WebTestCaseBase.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. namespace WebserviceBundle\tests;
  3. use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
  4. use Symfony\Component\BrowserKit\Cookie;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  7. use Symfony\Bundle\FrameworkBundle\Client;
  8. use Doctrine\Common\Collections\ArrayCollection;
  9. use ReflectionClass;
  10. class WebTestCaseBase extends WebTestCase
  11. {
  12. /**
  13. * @var Client Cliente web.
  14. */
  15. private $client;
  16. /**
  17. * @var bool Me dice si estamos en el modulo base.
  18. */
  19. protected $isModuleBase;
  20. /**
  21. * @var int Contiene el id de usuario a simular
  22. */
  23. protected $idUser;
  24. /**
  25. * Funcion que crea un nuevo cliente para realizar consultas. Para cada consulta web necesito crear un nuevo cliente.
  26. * @param bool $new Me dice si tengo que crear un nuevo cliente.
  27. * @return Client Retorna el cliente.
  28. */
  29. protected function getClient($new = false)
  30. {
  31. if (!$this->client || $new) {
  32. // por defecto es environment=test y debug = true
  33. $this->client = static::createClient();
  34. }
  35. return $this->client;
  36. }
  37. /**
  38. * Funcion que busca un servicio dentro del container.
  39. * @param mixed $service Contiene el nombre del servicio.
  40. * @return mixed Retorna el servicio.
  41. */
  42. protected function get($service)
  43. {
  44. return $this->getClient()->getContainer()->get($service);
  45. }
  46. /**
  47. * @return mixed Retorna el manager de doctrine.
  48. */
  49. protected function getDoctrineManager()
  50. {
  51. return $this->get('doctrine')->getManager();
  52. }
  53. /**
  54. * @return bool Retorna TRUE si estoy en el modulo base.
  55. */
  56. public function isModuleBase()
  57. {
  58. if ($this->isModuleBase == null) {
  59. $em = $this->getDoctrineManager();
  60. if ($em == null) {
  61. $this->isModuleBase = false;
  62. } else {
  63. $this->isModuleBase = array_key_exists('BaseTenancyBundle', $this->getClient()->getContainer()->getParameter('kernel.bundles'));
  64. }
  65. }
  66. return $this->isModuleBase;
  67. }
  68. /**
  69. * Se creo este metodo para crear objeto desde un string para no tener conflictos en otros modulos.
  70. * @param string $repository Contiene el objeto del repositorio.
  71. * @return mixed Crea una instancia de una objeto.
  72. */
  73. public function getObject($repository)
  74. {
  75. $obj = $this->getDoctrineManager()->getMetadataFactory()->getMetadataFor($repository)->getName();
  76. $rc = new ReflectionClass($obj);
  77. return $rc->newInstance();
  78. }
  79. /**
  80. * Funcion que crea el servicio de tenencias. Por defecto crea la tenencia base.
  81. * @param int $current Contiene la tenencia actual.
  82. * @param array $tenancies Contiene las tenencias. Ej. array(array('id'=>1,'name'=>'base'))
  83. */
  84. protected function fakeTenancyService($current = 1, $tenancies = array())
  85. {
  86. $service_tenancy = $this->get('base_tenancy.tenancy_service');
  87. if (count($tenancies) == 0) {
  88. $tenancies [] = array('id' => 1, 'name' => 'Tenencia Base');
  89. }
  90. if ($this->isModuleBase()) {
  91. // tengo que cargar las tenencias que no existan en la base de datos.
  92. $em = $this->getDoctrineManager();
  93. $user = $em->getRepository("BaseUserBundle:User")->findOneBy(array('id' => $this->idUser));
  94. if (!$user) {
  95. // el usuario no existe, entonces lo creo
  96. $user = $this->getObject("BaseUserBundle:User");
  97. $user->setUsername("adminpruebas");
  98. $user->setPassword("adminpass");
  99. $user->setEnabled(true);
  100. $user->setEmail("pepe@pepe.com");
  101. $em->persist($user);
  102. $em->flush();
  103. }
  104. $arrayTenancies = new ArrayCollection();
  105. foreach ($tenancies as $tenancyData) {
  106. $tenancy = $em->getRepository("BaseTenancyBundle:Tenancy")->findOneBy(array('id' => $tenancyData['id']));
  107. if (!$tenancy) {
  108. // la tenencia no existe, entonces la creo
  109. $tenancy = $this->getObject("BaseTenancyBundle:Tenancy");
  110. $tenancy->setId($tenancyData['id']);
  111. $tenancy->setName($tenancyData['name']);
  112. $tenancy->setEnabled(true);
  113. $em->persist($tenancy);
  114. $em->flush();
  115. }
  116. $ten_user = $em->createQueryBuilder()
  117. ->select('t')
  118. ->from('BaseTenancyBundle:Tenancy', 't')
  119. ->join('t.users', 'ut',
  120. \Doctrine\ORM\Query\Expr\Join::WITH,
  121. $em->getExpressionBuilder()->eq('ut.id', $this->idUser))
  122. ->where($em->getExpressionBuilder()->eq('t.id', $tenancyData['id']))
  123. ->getQuery()
  124. ->execute();
  125. if (!$ten_user) {
  126. $arrayTenancies[] = $tenancy;
  127. }
  128. }
  129. // actualizo las tenencias asociadas al usuario
  130. $user->setTenancies($arrayTenancies);
  131. $em->flush();
  132. }
  133. $service_tenancy->setTenancy($current);
  134. }
  135. /**
  136. * Se crean los datos para hacer el fake al oauth
  137. * @param int $idUser Contiene el id de usuario a simular.
  138. * @throws \ErrorException Lanza una excepcion durante las distintas validaciones.
  139. */
  140. protected function FakeLogin($idUser = 1)
  141. {
  142. $this->idUser = $idUser;
  143. // obtengo la session
  144. $session = $this->get('session');
  145. if ($session != null) {
  146. // busco el usuario logueado
  147. $em = $this->getDoctrineManager();
  148. if ($em != null) {
  149. // FOS\UserBundle\Model\UserManager
  150. // FOS\UserBundle\Doctrine\UserManager
  151. $userManager = $this->get('fos_user.user_manager');
  152. if ($userManager != null) {
  153. try {
  154. $user = $userManager->findUserBy(array('id' => $this->idUser));
  155. } catch (\Throwable $t) {
  156. $user = null;
  157. }
  158. if (!$user) {
  159. // el usuario no existe por lo tanto lo creo. Deberia ver el tema de las tenencias
  160. // no tengo la oportunidad de probarlo
  161. $user = $userManager->createUser();
  162. $cargo = false;
  163. try {
  164. $em = $this->getDoctrineManager();
  165. $userDB = $em->getRepository("BaseUserBundle:User")->findOneBy(array('id' => $this->idUser));
  166. if ($userDB) {
  167. $cargo = true;
  168. $user->setEmail($userDB->email);
  169. $user->Id = $idUser;
  170. $user->setUsername($userDB->username);
  171. $user->setPlainPassword($userDB->plainPassword);
  172. $user->setEnabled(true);
  173. $user->setRoles($userDB->getRoles());
  174. // este comando ademas se setear los datos, los persiste en la base de datos.
  175. $userManager->updateUser($user);
  176. }
  177. } catch (\Throwable $t) {
  178. }
  179. if (!$cargo) {
  180. // no se cargo el usuario por algun error. Lo hago manual.
  181. $user->setEmail("pepe@pepe.com");
  182. $user->Id = $idUser;
  183. $user->setUsername('admin');
  184. $user->setPlainPassword('adminpass');
  185. $user->setEnabled(true);
  186. $user->setRoles(array("ROLE_USER"));
  187. $userManager->updateCanonicalFields($user);
  188. $userManager->updatePassword($user);
  189. }
  190. }
  191. // contiene el nombre de firewall a utilizar
  192. $firewall = 'main';
  193. // busco el token en el security
  194. $tokenStorage = $this->get('security.token_storage');
  195. if ($tokenStorage != null) {
  196. $token = null;
  197. if (!$tokenStorage->getToken()) {
  198. // no tengo el token, entonces lo creo
  199. $token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_SUPER_ADMIN'));
  200. } else {
  201. // utilizo el token que yo esta creado
  202. $token = $tokenStorage->getToken();
  203. }
  204. // seteo en la session el firewall que voy a utilizar y el token
  205. $session->set('_security_' . $firewall, serialize($token));
  206. $session->save();
  207. // creo una cookie con los datos de la session.
  208. $cookie = new Cookie($session->getName(), $session->getId());
  209. $this->getClient()->getCookieJar()->set($cookie);
  210. // seteo el token en el security.token_storage
  211. $tokenStorage->setToken($token);
  212. } else {
  213. throw new \ErrorException("Error al obtener el token storage.");
  214. }
  215. } else {
  216. throw new \ErrorException("Error al obtener el fos user manager.");
  217. }
  218. } else {
  219. throw new \ErrorException("Error al obtener doctrine.");
  220. }
  221. } else {
  222. throw new \ErrorException("Error al obtener la session.");
  223. }
  224. }
  225. /**
  226. * Crea las tenencias.
  227. * @param int $quantity Contiene la cantidad de tenencias a crear por defecto.
  228. * @return array Retorna una matriz con las tenencias a crear.
  229. * @throws \Exception Lanza un excepcion en caso de no poder crear las tenencias.
  230. */
  231. protected function generateTenancies($quantity = 0)
  232. {
  233. if ($quantity <= 0) {
  234. throw new \Exception("No se pasaron los argumentos de forma correcta.");
  235. } else {
  236. $resp = array();
  237. for ($i = 0; $i < $quantity; $i++) {
  238. if ($i == 1) {
  239. $resp[$i] = array('id' => $i, 'name' => 'Tenencia Base');
  240. } else {
  241. $resp[$i] = array('id' => $i, 'name' => 'Tenencia ' . $i);
  242. }
  243. }
  244. return $resp;
  245. }
  246. }
  247. /**
  248. * Cambia los datos para realizar una modificacion
  249. * @param array $original Contiene los datos originales.
  250. * @param array $newData Contiene los nuevos datos a setear.
  251. * @return array|string Retorna el array con los datos o el valor de la key pasada como parametro.
  252. * @throws \Exception Lanza un excepcion en caso de no encontrar la key.
  253. */
  254. protected function obtainDataChange($original, $newData)
  255. {
  256. foreach ($newData as $k => $v) {
  257. $original[$k] = $v;
  258. }
  259. return $original;
  260. }
  261. /**
  262. * Genera el filtro de busqueda filters
  263. * @param array $data Contiene los datos a buscar de la forma clave -> valor.
  264. * @param bool $qbcriteria Me dice si utiliza qb-criteria.
  265. * @return string Retorna el string generado.
  266. */
  267. protected function generateFilters($data, $qbcriteria = true)
  268. {
  269. $resp = '?';
  270. if ($qbcriteria) {
  271. $resp .= 'filters[qb-criteria]';
  272. }
  273. if ($data != null && count($data) > 0) {
  274. foreach ($data as $k => $v) {
  275. $resp .= '&filters[' . $k . ']=' . $v;
  276. }
  277. }
  278. return $resp;
  279. }
  280. /**
  281. * Funcion que busca el valor de una propiedad dentro del response.
  282. * @param Response $response Contiene el response.
  283. * @param string $property Contiene el nombre de la propiedad.
  284. * @param string $object Contiene el nombre del objeto del cual voy a obtener la propiedad.
  285. * @return null|mixed Retorna el valor de la propiedad.
  286. */
  287. protected function getProperty(Response $response, $property, $object = null)
  288. {
  289. $resp = json_decode($response->getContent(), true);
  290. if (count($resp) > 0) {
  291. if ($object != null) {
  292. // busco el objecto
  293. foreach ($resp as $k => $v) {
  294. if ($k == $object) {
  295. $resp = $v;
  296. break;
  297. }
  298. }
  299. }
  300. foreach ($resp as $v) {
  301. try {
  302. if (isset($v[$property])) {
  303. return $v[$property];
  304. }
  305. } catch (\Throwable $t) {
  306. }
  307. }
  308. return null;
  309. } else {
  310. if (isset($resp[$property])) {
  311. return $resp[$property];
  312. } else {
  313. return null;
  314. }
  315. }
  316. }
  317. /**
  318. * Funcion que inicializa por defecto las variables.
  319. * Crea el client para el request.
  320. * Hace el fake del login.
  321. * Crea 1 tenencia por defecto (TENENCIA BASE = 1).
  322. */
  323. protected function initDefault()
  324. {
  325. // creo un nuevo cliente para consultar. Lo tengo que crear para cada consulta.
  326. $this->getClient(true);
  327. // hago fake del login
  328. $this->FakeLogin();
  329. // creo el servicio de tenencias
  330. $this->fakeTenancyService();
  331. }
  332. }