lib/composer/LisaBundle/src/VisualMedia/LisaBundle/Component/Manager.php line 313

Open in your IDE?
  1. <?php
  2. /**
  3. * Manager
  4. *
  5. * @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
  6. */
  7. namespace VisualMedia\LisaBundle\Component;
  8. use Exception;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Doctrine\ORM\Event\LifecycleEventArgs;
  11. use Doctrine\ORM\Tools\Pagination\Paginator;
  12. use Doctrine\ORM\QueryBuilder;
  13. use Doctrine\ORM\Query;
  14. use Doctrine\ORM\Query\ResultSetMapping;
  15. use VisualMedia\LisaBundle\Component\Interfaces\EntityInterface;
  16. use VisualMedia\LisaBundle\Component\Interfaces\ManagerInterface;
  17. use VisualMedia\LisaBundle\Doctrine\Arguments\GetResultsEventArgs;
  18. use VisualMedia\LisaBundle\Doctrine\Arguments\ProcessConditionsEventArgs;
  19. use VisualMedia\LisaBundle\Doctrine\Arguments\MoveEventArgs;
  20. /**
  21. * Manager
  22. */
  23. abstract class Manager implements ManagerInterface
  24. {
  25. /**
  26. * @var EntityManagerInterface
  27. */
  28. protected $entityManager;
  29. /**
  30. * @var EventManager
  31. */
  32. protected $eventManager;
  33. /**
  34. * @var string
  35. */
  36. protected $entityName;
  37. /**
  38. * @var string
  39. */
  40. protected $alias;
  41. /**
  42. * @var array
  43. */
  44. protected $identifiers;
  45. /**
  46. * @var string
  47. */
  48. public $querytype;
  49. /**
  50. * @param EntityManagerInterface $entityManager
  51. */
  52. public function __construct(EntityManagerInterface $entityManager)
  53. {
  54. $this->entityManager = $entityManager;
  55. $this->eventManager = $entityManager->getEventManager();
  56. $metaData = $entityManager->getClassMetadata(static::getEntityName());
  57. $this->entityName = $metaData->getReflectionClass()->getName();
  58. $explodedEntityName = explode('\\', $this->entityName);
  59. $this->alias = sprintf('_%s', strtolower(end($explodedEntityName)));
  60. $this->identifiers = $metaData->getIdentifier();
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function getAlias(): string
  66. {
  67. return $this->alias;
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. public function getFullFieldName($field): string
  73. {
  74. if (strpos($field, '.') !== false) {
  75. return $field;
  76. }
  77. else {
  78. return sprintf('%s.%s', $this->alias, $field);
  79. }
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function getEntityManager(): EntityManagerInterface
  85. {
  86. if ($this->entityManager === null) {
  87. throw new Exception(sprintf('The entity manager has not been set for Manager "%s". Please make sure the constructor is called.', get_class($this)));
  88. }
  89. return $this->entityManager;
  90. }
  91. /**
  92. * {@inheritdoc}
  93. */
  94. public function initializeQueryBuilder($querytype = ManagerInterface::QUERYTYPE_MULTIPLE): QueryBuilder
  95. {
  96. $this->querytype = $querytype;
  97. $qb = $this->getEntityManager()->createQueryBuilder();
  98. $alias = $this->alias;
  99. $identifier = $this->getFullFieldName($this->identifiers[0]);
  100. if ($querytype === static::QUERYTYPE_SINGLE || $querytype === static::QUERYTYPE_MULTIPLE) {
  101. $qb->select($alias);
  102. $qb->from($this->entityName, $alias);
  103. $qb->groupBy($identifier);
  104. }
  105. elseif ($querytype === static::QUERYTYPE_COUNT) {
  106. $qb->select(sprintf('count(distinct %s)', $alias));
  107. $qb->from($this->entityName, $alias);
  108. }
  109. elseif ($querytype === static::QUERYTYPE_DISTINCT) {
  110. $qb->select(sprintf('DISTINCT %s', $identifier));
  111. $qb->from($this->entityName, $alias);
  112. }
  113. elseif ($querytype === static::QUERYTYPE_MIN) {
  114. $qb->select(sprintf('%s, MIN(%s)', $alias, $identifier));
  115. $qb->from($this->entityName, $alias);
  116. }
  117. elseif ($querytype === static::QUERYTYPE_MAX) {
  118. $qb->select(sprintf('%s, MAX(%s)', $alias, $identifier));
  119. $qb->from($this->entityName, $alias);
  120. }
  121. return $qb;
  122. }
  123. /**
  124. * {@inheritdoc}
  125. */
  126. public function getQB(string $querytype, ManagerData $data = null): QueryBuilder
  127. {
  128. $data = $data ?? new ManagerData();
  129. $data->setQuerytype($querytype);
  130. $qb = $this->initializeQueryBuilder($data->getQuerytype(), $data->getConditions());
  131. $this->processConditions($qb, $data->getConditions());
  132. $this->eventManager->dispatchEvent('processConditions', new ProcessConditionsEventArgs($this, $qb, $data->getConditions()));
  133. if ($data->getQuerytype() === static::QUERYTYPE_MULTIPLE) {
  134. $this->processOrdering($qb, $data->getConditions(), $data->getOrdering());
  135. }
  136. return $qb;
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function getQuery(QueryBuilder $qb, array $conditions = array()): Query
  142. {
  143. $query = $qb->getQuery();
  144. return $query;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function getResults(Query $query, ManagerData $data = null): array
  150. {
  151. $result = array();
  152. if ($this->querytype === static::QUERYTYPE_MULTIPLE) {
  153. $paginator = new Paginator($query, $fetchJoinCollection = true);
  154. foreach ($paginator as $row) {
  155. $result[] = $row;
  156. }
  157. }
  158. else {
  159. $result = $query->getResult();
  160. }
  161. $this->eventManager->dispatchEvent('getResults', new GetResultsEventArgs($this, $result, $data ?? new ManagerData()));
  162. return $result;
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. public function find($id, $lockMode = null, $lockVersion = null)
  168. {
  169. return $this->getEntityManager()->find(static::getEntityName(), $id, $lockMode, $lockVersion);
  170. }
  171. /**
  172. * {@inheritdoc}
  173. */
  174. public function findAll()
  175. {
  176. return $this->getIndex();
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null)
  182. {
  183. return $this->getIndex(new ManagerData($criteria, $orderBy, $limit, $offset));
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function findOneBy(array $criteria = array(), array $orderBy = array()): ?EntityInterface
  189. {
  190. return $this->getFirst(new ManagerData($criteria, $orderBy));
  191. }
  192. /**
  193. * {@inheritdoc}
  194. */
  195. public function getIndex(ManagerData $data = null): array
  196. {
  197. $data = $data ?? new ManagerData();
  198. $qb = $this->getQB(static::QUERYTYPE_MULTIPLE, $data);
  199. $query = $this->getQuery($qb, $data->getConditions());
  200. if (null !== $limit = $data->getLimit()) {
  201. $query->setMaxResults($limit);
  202. $query->setFirstResult($data->getOffset());
  203. }
  204. $result = $this->getResults($query, $data);
  205. return $result;
  206. }
  207. /**
  208. * {@inheritdoc}
  209. */
  210. public function getFirst(ManagerData $data = null): ?EntityInterface
  211. {
  212. $data = $data ?? new ManagerData();
  213. $qb = $this->getQB(static::QUERYTYPE_SINGLE, $data);
  214. $query = $this->getQuery($qb, $data->getConditions());
  215. $result = $this->getResults($query, $data);
  216. if (count($result) == 0) {
  217. return null;
  218. }
  219. return $result[0];
  220. }
  221. /**
  222. * {@inheritdoc}
  223. */
  224. public function getCount(ManagerData $data = null): int
  225. {
  226. $data = $data ?? new ManagerData();
  227. $qb = $this->getQB(static::QUERYTYPE_COUNT, $data);
  228. $query = $this->getQuery($qb, $data->getConditions());
  229. @list($entity, $count) = $query->getOneOrNullResult();
  230. return (int)$count;
  231. }
  232. /**
  233. * {@inheritdoc}
  234. */
  235. public function getDistinct($field, ManagerData $data = null): array
  236. {
  237. $data = $data ?? new ManagerData();
  238. $originalIdentifiers = $this->identifiers;
  239. $this->identifiers = array($field);
  240. $qb = $this->getQB(static::QUERYTYPE_DISTINCT, $data);
  241. $query = $this->getQuery($qb, $data->getConditions());
  242. $result = $this->getResults($query, $data);
  243. $this->identifiers = $originalIdentifiers;
  244. @list($field, $alias) = array_reverse(explode('.', $field));
  245. $processed = array();
  246. foreach ($result as $index=>$row) {
  247. $processed[$index] = $row[$field] ?? null;
  248. }
  249. return $processed;
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function getMin($field, ManagerData $data = null): int
  255. {
  256. $data = $data ?? new ManagerData();
  257. $originalIdentifiers = $this->identifiers;
  258. $this->identifiers = array($field);
  259. $qb = $this->getQB(static::QUERYTYPE_MIN, $data);
  260. $query = $this->getQuery($qb, $data->getConditions());
  261. @list($entity, $min) = $query->getOneOrNullResult();
  262. $this->identifiers = $originalIdentifiers;
  263. return (int)$min;
  264. }
  265. /**
  266. * {@inheritdoc}
  267. */
  268. public function getMax($field, ManagerData $data = null): int
  269. {
  270. $data = $data ?? new ManagerData();
  271. $originalIdentifiers = $this->identifiers;
  272. $this->identifiers = array($field);
  273. $qb = $this->getQB(static::QUERYTYPE_MAX, $data);
  274. $query = $this->getQuery($qb, $data->getConditions());
  275. @list($entity, $max) = $query->getOneOrNullResult();
  276. $this->identifiers = $originalIdentifiers;
  277. return (int)$max;
  278. }
  279. /**
  280. * {@inheritdoc}
  281. */
  282. public function processOrdering(QueryBuilder &$qb, array $options, ?array $ordering = null): void
  283. {
  284. if($ordering !== null) {
  285. foreach ($ordering as $key=>$value) {
  286. if (!empty($key) && is_string($key) && in_array($value, array(static::ORDER_DIR_ASC, static::ORDER_DIR_DESC))) {
  287. $qb->addOrderBy($this->getFullFieldName($key), $value);
  288. }
  289. }
  290. }
  291. }
  292. /**
  293. * {@inheritdoc}
  294. */
  295. public function persist(EntityInterface $entity): void
  296. {
  297. $this->eventManager->dispatchEvent('persist', new LifecycleEventArgs($entity, $this->getEntityManager()));
  298. $this->getEntityManager()->persist($entity);
  299. }
  300. /**
  301. * {@inheritdoc}
  302. */
  303. public function remove(EntityInterface $entity): void
  304. {
  305. $this->getEntityManager()->remove($entity);
  306. }
  307. /**
  308. * {@inheritdoc}
  309. */
  310. public function flush(): void
  311. {
  312. $this->getEntityManager()->flush();
  313. }
  314. /**
  315. * {@inheritdoc}
  316. */
  317. public function execute(string $sql, array $parameters = array(), ResultSetMapping $rsm = null)
  318. {
  319. $sql = trim(preg_replace('/\s+/', ' ', $sql));
  320. // Set parameters on sql.
  321. foreach ($parameters as $key=>$value) {
  322. if (is_array($value)) {
  323. $value = sprintf('(%s)', implode(',', array_map(function($v) {
  324. return preg_match("/[a-z]/i", $v) ? sprintf('\'%s\'', $v) : $v;
  325. }, $value)));
  326. }
  327. elseif (preg_match("/[a-z]/i", $value)) {
  328. $value = sprintf('\'%s\'', $value);
  329. }
  330. $sql = str_replace(sprintf(':%s', $key), $value, $sql);
  331. }
  332. // Get connection.
  333. $connection = $this->getEntityManager()->getConnection();
  334. // Execute select query through a native query.
  335. if ((true === $select = strpos($sql, 'SELECT') !== false) && (true === $native = $parameters['native'] ?? true)) {
  336. $rsm = $rsm ?: new ResultSetMapping();
  337. $query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
  338. return $query->getResult();
  339. }
  340. // Execute query through the connection.
  341. if ($select) {
  342. return $connection->executeQuery($sql)->fetchAllAssociative();
  343. }
  344. else {
  345. $connection->executeStatement($sql);
  346. }
  347. }
  348. /**
  349. * {@inheritdoc}
  350. */
  351. public function moveDown(EntityInterface $entity = null): void
  352. {
  353. $this->eventManager->dispatchEvent('move', new MoveEventArgs($this, 'down', $entity));
  354. }
  355. /**
  356. * {@inheritdoc}
  357. */
  358. public function moveUp(EntityInterface $entity = null): void
  359. {
  360. $this->eventManager->dispatchEvent('move', new MoveEventArgs($this, 'up', $entity));
  361. }
  362. /**
  363. * {@inheritdoc}
  364. */
  365. public function getOrderingQueryBuilder(EntityInterface $entity = null): QueryBuilder
  366. {
  367. $qb = $this->getEntityManager()->createQueryBuilder();
  368. $qb->select('e');
  369. $qb->from($this->getEntityName(), 'e');
  370. if ($entity !== null && property_exists($entity, 'parent')) {
  371. if ($entity->parent) {
  372. $qb->andWhere(sprintf('e.parent = %d', $entity->parent->id));
  373. }
  374. else {
  375. $qb->andWhere(sprintf('e.parent IS NULL'));
  376. }
  377. }
  378. return $qb;
  379. }
  380. /**
  381. * {@inheritdoc}
  382. */
  383. public function getClassName()
  384. {
  385. return static::getEntityName();
  386. }
  387. }