123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422 |
- <?php
- namespace WebserviceBundle\tests;
- use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
- use Symfony\Component\BrowserKit\Cookie;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
- use Symfony\Bundle\FrameworkBundle\Client;
- use Doctrine\Common\Collections\ArrayCollection;
- use ReflectionClass;
- use Symfony\Component\Security\Core\User\User;
- use WebserviceBundle\Services\WebserviceMock;
- class WebTestCaseBase extends WebTestCase
- {
- /**
- * @var Client Cliente web.
- */
- private $client;
- /**
- * @var bool Me dice si estamos en el modulo base.
- */
- protected $isModuleBase;
- /**
- * @var int Contiene el id de usuario a simular
- */
- protected $idUser;
- /**
- * Funcion que crea un nuevo cliente para realizar consultas. Para cada consulta web necesito crear un nuevo cliente.
- * @param bool $new Me dice si tengo que crear un nuevo cliente.
- * @return Client Retorna el cliente.
- */
- protected function getClient($new = false)
- {
- if (!$this->client || $new) {
- // por defecto es environment=test y debug = true
- $this->client = static::createClient();
- }
- return $this->client;
- }
- /**
- * Funcion que busca un servicio dentro del container.
- * @param mixed $service Contiene el nombre del servicio.
- * @return mixed Retorna el servicio.
- */
- protected function get($service)
- {
- return $this->getClient()->getContainer()->get($service);
- }
- /**
- * @return mixed Retorna el manager de doctrine.
- */
- protected function getDoctrineManager()
- {
- return $this->get('doctrine')->getManager();
- }
- /**
- * @return bool Retorna TRUE si estoy en el modulo base.
- */
- public function isModuleBase()
- {
- if ($this->isModuleBase == null) {
- $em = $this->getDoctrineManager();
- if ($em == null) {
- $this->isModuleBase = false;
- } else {
- $this->isModuleBase = array_key_exists('BaseTenancyBundle', $this->getClient()->getContainer()->getParameter('kernel.bundles'));
- }
- }
- return $this->isModuleBase;
- }
- /**
- * Se creo este metodo para crear objeto desde un string para no tener conflictos en otros modulos.
- * @param string $repository Contiene el objeto del repositorio.
- * @return mixed Crea una instancia de una objeto.
- */
- public function getObject($repository)
- {
- $obj = $this->getDoctrineManager()->getMetadataFactory()->getMetadataFor($repository)->getName();
- $rc = new ReflectionClass($obj);
- return $rc->newInstance();
- }
- /**
- * Utiliza un mock del webservice original. Solo modifica el llamado de la url.
- * @param array $webServiceData Contiene los datos que debe retorna el webservice.
- */
- public function fakeWebservice($webServiceData = null)
- {
- if ($webServiceData != null && is_array($webServiceData)) {
- if ($this->getClient()->getContainer()->has('webservice')) {
- $original = $this->getClient()->getContainer()->get('webservice');
- $fake = new WebserviceMock(
- $original->getServiceContainer(),
- null, //$original->getSecurityTokenStorage(),
- null, //$original->getHttpClient(),
- $webServiceData);
- $this->setContainerObject('webservice', $fake);
- }
- }
- }
- /**
- * Funcion que crea el servicio de tenencias. Por defecto crea la tenencia base.
- * @param int $current Contiene la tenencia actual.
- * @param array $tenancies Contiene las tenencias. Ej. array(array('id'=>1,'name'=>'base'))
- */
- protected function fakeTenancyService($current = 1, $tenancies = array())
- {
- $service_tenancy = $this->get('base_tenancy.tenancy_service');
- if (count($tenancies) == 0) {
- $tenancies [] = array('id' => 1, 'name' => 'Tenencia Base');
- }
- if ($this->isModuleBase()) {
- // tengo que cargar las tenencias que no existan en la base de datos.
- $em = $this->getDoctrineManager();
- $user = $em->getRepository("BaseUserBundle:User")->findOneBy(array('id' => $this->idUser));
- if (!$user) {
- // el usuario no existe, entonces lo creo
- $user = $this->getObject("BaseUserBundle:User");
- $user->setUsername("adminpruebas");
- $user->setPassword("adminpass");
- $user->setEnabled(true);
- $user->setEmail("pepe@pepe.com");
- $em->persist($user);
- $em->flush();
- }
- $arrayTenancies = new ArrayCollection();
- foreach ($tenancies as $tenancyData) {
- $tenancy = $em->getRepository("BaseTenancyBundle:Tenancy")->findOneBy(array('id' => $tenancyData['id']));
- if (!$tenancy) {
- // la tenencia no existe, entonces la creo
- $tenancy = $this->getObject("BaseTenancyBundle:Tenancy");
- $tenancy->setId($tenancyData['id']);
- $tenancy->setName($tenancyData['name']);
- $tenancy->setEnabled(true);
- $em->persist($tenancy);
- $em->flush();
- }
- $ten_user = $em->createQueryBuilder()
- ->select('t')
- ->from('BaseTenancyBundle:Tenancy', 't')
- ->join('t.users', 'ut',
- \Doctrine\ORM\Query\Expr\Join::WITH,
- $em->getExpressionBuilder()->eq('ut.id', $this->idUser))
- ->where($em->getExpressionBuilder()->eq('t.id', $tenancyData['id']))
- ->getQuery()
- ->execute();
- if (!$ten_user) {
- $arrayTenancies[] = $tenancy;
- }
- }
- // actualizo las tenencias asociadas al usuario
- $user->setTenancies($arrayTenancies);
- $em->flush();
- } else {
- // seteo las tenencias como array en el usuario
- $this->get('security.token_storage')->getToken()->getUser()->setTenancies($tenancies);
- }
- $service_tenancy->setTenancy($current);
- }
- /**
- * Se crean los datos para hacer el fake al oauth
- * @param int $idUser Contiene el id de usuario a simular.
- * @throws \ErrorException Lanza una excepcion durante las distintas validaciones.
- */
- protected function FakeLogin($idUser = 1)
- {
- $this->idUser = $idUser;
- // obtengo la session
- $session = $this->get('session');
- if ($session != null) {
- // busco el usuario logueado
- $em = $this->getDoctrineManager();
- if ($em != null) {
- // FOS\UserBundle\Model\UserManager
- // FOS\UserBundle\Doctrine\UserManager
- if ($this->isModuleBase()) {
- $userManager = $this->get('fos_user.user_manager');
- if ($userManager != null) {
- try {
- $user = $userManager->findUserBy(array('id' => $this->idUser));
- } catch (\Throwable $t) {
- $user = null;
- }
- if (!$user) {
- // el usuario no existe por lo tanto lo creo. Deberia ver el tema de las tenencias
- // no tengo la oportunidad de probarlo
- $user = $userManager->createUser();
- $cargo = false;
- try {
- $em = $this->getDoctrineManager();
- $userDB = $em->getRepository("BaseUserBundle:User")->findOneBy(array('id' => $this->idUser));
- if ($userDB) {
- $cargo = true;
- $user->setEmail($userDB->email);
- $user->Id = $idUser;
- $user->setUsername($userDB->username);
- $user->setPlainPassword($userDB->plainPassword);
- $user->setEnabled(true);
- $user->setRoles($userDB->getRoles());
- // este comando ademas se setear los datos, los persiste en la base de datos.
- $userManager->updateUser($user);
- }
- } catch (\Throwable $t) {
- }
- if (!$cargo) {
- // no se cargo el usuario por algun error. Lo hago manual.
- $user->setEmail("pepe@pepe.com");
- $user->Id = $idUser;
- $user->setUsername('admin');
- $user->setPlainPassword('adminpass');
- $user->setEnabled(true);
- $user->setRoles(array("ROLE_USER"));
- $userManager->updateCanonicalFields($user);
- $userManager->updatePassword($user);
- }
- }
- // contiene el nombre de firewall a utilizar
- $firewall = 'main';
- // busco el token en el security
- $tokenStorage = $this->get('security.token_storage');
- if ($tokenStorage != null) {
- $token = null;
- if (!$tokenStorage->getToken()) {
- // no tengo el token, entonces lo creo
- $token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_SUPER_ADMIN'));
- } else {
- // utilizo el token que yo esta creado
- $token = $tokenStorage->getToken();
- }
- // seteo en la session el firewall que voy a utilizar y el token
- $session->set('_security_' . $firewall, serialize($token));
- $session->save();
- // creo una cookie con los datos de la session.
- $cookie = new Cookie($session->getName(), $session->getId());
- $this->getClient()->getCookieJar()->set($cookie);
- // seteo el token en el security.token_storage
- $tokenStorage->setToken($token);
- } else {
- throw new \ErrorException("Error al obtener el token storage.");
- }
- } else {
- throw new \ErrorException("Error al obtener el fos user manager.");
- }
- } else {
- // no estoy en el modulo base
- // creo la clase de esta forma para no utilizar el "use" porque va a traer conflicto en otros modulos
- $class = "Base\OAuthClientBundle\Security\Core\User\CustomOAuthUser";
- $user = new $class('admin');
- // no se cargo el usuario por algun error. Lo hago manual.
- $user->Id = $idUser;
- $user->setRoles(array("ROLE_USER"));
- // contiene el nombre de firewall a utilizar
- $firewall = 'main';
- // busco el token en el security
- $tokenStorage = $this->get('security.token_storage');
- if ($tokenStorage != null) {
- $token = null;
- // no tengo el token, entonces lo creo
- $token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_SUPER_ADMIN'));
- // seteo en la session el firewall que voy a utilizar y el token
- $session->set('_security_' . $firewall, serialize($token));
- $session->save();
- // creo una cookie con los datos de la session.
- $cookie = new Cookie($session->getName(), $session->getId());
- $this->getClient()->getCookieJar()->set($cookie);
- // seteo el token en el security.token_storage
- $tokenStorage->setToken($token);
- }
- }
- } else {
- throw new \ErrorException("Error al obtener doctrine.");
- }
- } else {
- throw new \ErrorException("Error al obtener la session.");
- }
- }
- /**
- * Crea las tenencias.
- * @param int $quantity Contiene la cantidad de tenencias a crear por defecto.
- * @return array Retorna una matriz con las tenencias a crear.
- * @throws \Exception Lanza un excepcion en caso de no poder crear las tenencias.
- */
- protected function generateTenancies($quantity = 0)
- {
- if ($quantity <= 0) {
- throw new \Exception("No se pasaron los argumentos de forma correcta.");
- } else {
- $resp = array();
- for ($i = 0; $i < $quantity; $i++) {
- if ($i == 1) {
- $resp[$i] = array('id' => $i, 'name' => 'Tenencia Base');
- } else {
- $resp[$i] = array('id' => $i, 'name' => 'Tenencia ' . $i);
- }
- }
- return $resp;
- }
- }
- /**
- * Cambia los datos para realizar una modificacion
- * @param array $original Contiene los datos originales.
- * @param array $newData Contiene los nuevos datos a setear.
- * @return array|string Retorna el array con los datos o el valor de la key pasada como parametro.
- * @throws \Exception Lanza un excepcion en caso de no encontrar la key.
- */
- protected function obtainDataChange($original, $newData)
- {
- foreach ($newData as $k => $v) {
- $original[$k] = $v;
- }
- return $original;
- }
- /**
- * Genera el filtro de busqueda filters
- * @param array $data Contiene los datos a buscar de la forma clave -> valor.
- * @param bool $qbcriteria Me dice si utiliza qb-criteria.
- * @return string Retorna el string generado.
- */
- protected function generateFilters($data, $qbcriteria = true)
- {
- $resp = '?';
- if ($qbcriteria) {
- $resp .= 'filters[qb-criteria]';
- }
- if ($data != null && count($data) > 0) {
- foreach ($data as $k => $v) {
- $resp .= '&filters[' . $k . ']=' . $v;
- }
- }
- return $resp;
- }
- /**
- * Funcion que busca el valor de una propiedad dentro del response.
- * @param Response $response Contiene el response.
- * @param string $property Contiene el nombre de la propiedad.
- * @param string $object Contiene el nombre del objeto del cual voy a obtener la propiedad.
- * @return null|mixed Retorna el valor de la propiedad.
- */
- protected function getProperty(Response $response, $property, $object = null)
- {
- $resp = json_decode($response->getContent(), true);
- if (count($resp) > 0) {
- if ($object != null) {
- // busco el objecto
- foreach ($resp as $k => $v) {
- if ($k == $object) {
- $resp = $v;
- break;
- }
- }
- }
- foreach ($resp as $v) {
- try {
- if (isset($v[$property])) {
- return $v[$property];
- }
- } catch (\Throwable $t) {
- }
- }
- return null;
- } else {
- if (isset($resp[$property])) {
- return $resp[$property];
- } else {
- return null;
- }
- }
- }
- /**
- * Funcion que inicializa por defecto las variables.
- * Crea el client para el request.
- * Hace el fake del login.
- * Crea 1 tenencia por defecto (TENENCIA BASE = 1).
- * @param array $webServiceData Contiene los datos que debe retorna el webservice.
- */
- protected function initDefault($webServiceData = null)
- {
- // creo un nuevo cliente para consultar. Lo tengo que crear para cada consulta.
- $this->getClient(true);
- // reemplaza el webservice por un mock
- $this->fakeWebservice($webServiceData);
- // hago fake del login
- $this->FakeLogin();
- // creo el servicio de tenencias
- $this->fakeTenancyService();
- }
- /**
- * Obtiene un objeto del container.
- * @param string $id Contiene el id que va a poseer en el container.
- * @return mixed Retorna el objeto seteado en el container.
- */
- protected function getContainerObject($id)
- {
- return static::$kernel->getContainer()->get($id);
- }
- /**
- * Setea un objeto en el container.
- * @param string $id Contiene el id que va a poseer en el container.
- * @param mixed $object Contiene el objeto a setear.
- */
- protected function setContainerObject($id, $object)
- {
- static::$kernel->getContainer()->set($id, $object);
- }
- }
|