src/Repository/WebServices/AbstractWsRepository.php line 115

Open in your IDE?
  1. <?php
  2. namespace App\Repository\WebServices;
  3. use App\Serializer\Normalizer\CrossSystemIdMapper;
  4. use App\Services\ApiConsumerService;
  5. use App\Services\CriteriaToRequest;
  6. use Doctrine\Common\Collections\ArrayCollection;
  7. use Doctrine\Common\Collections\Criteria;
  8. use Psr\EventDispatcher\EventDispatcherInterface;
  9. use Symfony\Component\EventDispatcher\EventDispatcher;
  10. use Symfony\Component\HttpFoundation\RequestStack;
  11. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  12. use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
  13. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  14. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  15. use Symfony\Component\Serializer\SerializerInterface;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. abstract class AbstractWsRepository
  18. {
  19. protected $ruta;
  20. protected $entidad;
  21. protected $cache;
  22. protected $global;
  23. protected $expire;
  24. public function getEntityClass()
  25. {
  26. return $this->entidad;
  27. }
  28. // Forzar la extensión de clase para definir este método
  29. // abstract protected function getValor();
  30. // abstract protected function valorPrefijo($prefijo);
  31. public function __construct(
  32. protected ApiConsumerService $apiConsumerService,
  33. protected CriteriaToRequest $criteriaToRequest,
  34. protected SerializerInterface $serializer,
  35. protected TranslatorInterface $translator,
  36. protected SessionInterface $session,
  37. protected CrossSystemIdMapper $crossSystemIdMapper,
  38. protected RequestStack $requestStack,
  39. protected EventDispatcherInterface $eventDispatcher
  40. )
  41. {
  42. // Extraer el nombre de la clase sin "Repository"
  43. $className = (new \ReflectionClass($this))->getShortName();
  44. $entityName = str_replace('Repository', '', $className);
  45. // ejemplo: "cms/" Ojo a la barra final
  46. $this->ruta = $this->ruta ?: strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $entityName)) . '/';
  47. // metemos aquí la ruta por si cambia no cambiar abajo
  48. $this->entidad = $this->entidad ? "App\Entity\\{$this->entidad}" : "App\Entity\\{$entityName}";
  49. }
  50. protected function preSave($object)
  51. {
  52. return $object;
  53. }
  54. protected function postSave($object)
  55. {
  56. return $object;
  57. }
  58. // Métodos comunes
  59. public function save($object)
  60. {
  61. $this->preSave($object);
  62. $clase = $this->serializer->serialize($object, 'json', [
  63. ObjectNormalizer::SKIP_NULL_VALUES => true,
  64. 'normalizer_type' => 'hermes',
  65. AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object) {
  66. if (method_exists($object, 'getId') && $object->getId() !== null) {
  67. return ['id' => $object->getId()];
  68. }
  69. return ['_circular_reference' => get_class($object)];
  70. },
  71. AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT => 3,
  72. ]);
  73. // WORKAROUND para Evento: filtrar campos que causan problemas en Hermes
  74. if ($object instanceof \App\Entity\Evento) {
  75. $data = json_decode($clase, true);
  76. $camposProblematicos = ['pacientes', 'responsables', 'pacientes_filter', 'grupos_pacientes_filter', 'organigramas_filter', 'lista_espera', 'sesiones', 'listaespera', 'formulario_respuestas'];
  77. foreach ($camposProblematicos as $campo) {
  78. unset($data[$campo]);
  79. }
  80. // Filtrar TODOS los campos null restantes
  81. $data = array_filter($data, function($value) {
  82. return $value !== null;
  83. });
  84. $clase = json_encode($data);
  85. }
  86. $response = $this->apiConsumerService->postData($this->ruta . $object->getId(), $clase);
  87. $idSourceSystem = json_decode($response, true)['id'];
  88. $object->setId($idSourceSystem);
  89. $this->postSave($object);
  90. }
  91. public function all($subParameters = '', $cachear = null): ?ArrayCollection
  92. {
  93. $cachear = $cachear ?? $this->cache ?? true;
  94. $queryParams = [];
  95. try {
  96. $data = $this->apiConsumerService->getData($this->ruta . $subParameters, $queryParams, $cachear, $this->global, $this->expire);
  97. } catch (NotAcceptableHttpException $e) {
  98. return null;
  99. }
  100. if (!class_exists($this->entidad)) throw new \Exception("API consumer class no exist $this->entidad");
  101. if (!$data) return null;
  102. $valores = $this->serializer->deserialize($data, $this->entidad . '[]', 'json',
  103. ['normalizer_type' => 'hermes']);
  104. $valores = new ArrayCollection($valores);
  105. return $valores;
  106. }
  107. public function findById(int $id, $cachear = null, $extraparams = [])
  108. {
  109. $cachear = $cachear ?? $this->cache ?? true;
  110. $queryParams = [];
  111. if (!empty($extraparams)) {
  112. foreach ($extraparams as $key => $value) {
  113. $queryParams[$key] = $value;
  114. }
  115. }
  116. try {
  117. $data = $this->apiConsumerService->getData($this->ruta . $id, $queryParams, $cachear, $this->global, $this->expire);
  118. } catch (NotAcceptableHttpException $e) {
  119. return null;
  120. }
  121. if (!class_exists($this->entidad)) return null;
  122. if (!$data) return null;
  123. $valor = $this->serializer->deserialize($data, $this->entidad, 'json',
  124. ['normalizer_type' => 'hermes']);
  125. return $valor;
  126. }
  127. public function findOne(Criteria $criteria, $cachear = null, $extraparams = [])
  128. {
  129. $cachear = $cachear ?? $this->cache ?? true;
  130. $valoreS = $this->find($criteria, $cachear, $extraparams);
  131. if ($valoreS and $valoreS->count()) return $valoreS->first();
  132. return null;
  133. }
  134. public function find(Criteria $criteria, $cachear = null, $extraparams = []): ?ArrayCollection
  135. {
  136. $cachear = $cachear ?? $this->cache ?? true;
  137. if (!empty($extraparams)) {
  138. foreach ($extraparams as $key => $value) {
  139. $queryParams[$key] = $value;
  140. }
  141. }
  142. $queryParams['criteria'] = ($this->criteriaToRequest)($criteria);
  143. try {
  144. $data = $this->apiConsumerService->getData($this->ruta, $queryParams, $cachear, $this->global, $this->expire);
  145. } catch (NotAcceptableHttpException $e) {
  146. return new ArrayCollection([]);
  147. }
  148. if (!class_exists($this->entidad)) return new ArrayCollection([]);
  149. if (!$data) return new ArrayCollection([]);
  150. $valores = $this->serializer->deserialize($data, $this->entidad . '[]', 'json', ['normalizer_type' => 'hermes']);
  151. $valores = new ArrayCollection($valores);
  152. return $valores;
  153. }
  154. public function delete($object, bool $force = false): void
  155. {
  156. }//function
  157. public function saveAndGet($object, $queryParams = [])
  158. {
  159. $clase = $this->serializer->serialize($object, 'json', [
  160. ObjectNormalizer::SKIP_NULL_VALUES => true,
  161. AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object) {
  162. if (method_exists($object, 'getId') && $object->getId() !== null) {
  163. return ['id' => $object->getId()];
  164. }
  165. return ['_circular_reference' => get_class($object)];
  166. },
  167. ]);
  168. $id = $object->getId() ?: '';
  169. $response = $this->apiConsumerService->postData($this->ruta . $id, $clase, $queryParams);
  170. return $this->serializer->deserialize($response, $this->entidad, 'json',
  171. ['normalizer_type' => 'hermes']);
  172. }
  173. public function setGlobal($global)
  174. {
  175. $this->global = $global;
  176. return $this;
  177. }
  178. public function setExpire($expire)
  179. {
  180. $this->expire = $expire;
  181. return $this;
  182. }
  183. public function setCache($cache)
  184. {
  185. $this->cache = $cache;
  186. return $this;
  187. }
  188. public function getClass()
  189. {
  190. return get_called_class();
  191. }
  192. }