CallbackHandler.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\EntityManager;
  7. use Magento\Framework\Model\CallbackPool;
  8. use Psr\Log\LoggerInterface;
  9. /**
  10. * Class CallbackHandler
  11. */
  12. class CallbackHandler
  13. {
  14. /**
  15. * @var MetadataPool
  16. */
  17. protected $metadataPool;
  18. /**
  19. * @var LoggerInterface
  20. */
  21. protected $logger;
  22. /**
  23. * CallbackHandler constructor.
  24. *
  25. * @param MetadataPool $metadataPool
  26. * @param LoggerInterface $logger
  27. */
  28. public function __construct(
  29. MetadataPool $metadataPool,
  30. LoggerInterface $logger
  31. ) {
  32. $this->metadataPool = $metadataPool;
  33. $this->logger = $logger;
  34. }
  35. /**
  36. * @param string $entityType
  37. * @throws \Exception
  38. * @return void
  39. */
  40. public function process($entityType)
  41. {
  42. $metadata = $this->metadataPool->getMetadata($entityType);
  43. $connection = $metadata->getEntityConnection();
  44. $hash = spl_object_hash($connection);
  45. if ($connection->getTransactionLevel() === 0) {
  46. $callbacks = CallbackPool::get($hash);
  47. try {
  48. foreach ($callbacks as $callback) {
  49. call_user_func($callback);
  50. }
  51. } catch (\Exception $e) {
  52. $this->logger->error($e->getMessage(), $e->getTrace());
  53. throw $e;
  54. }
  55. }
  56. }
  57. /**
  58. * @param string $entityType
  59. * @param array $callback
  60. * @throws \Exception
  61. * @return void
  62. */
  63. public function attach($entityType, $callback)
  64. {
  65. $metadata = $this->metadataPool->getMetadata($entityType);
  66. CallbackPool::attach(spl_object_hash($metadata->getEntityConnection()), $callback);
  67. }
  68. /**
  69. * @param string $entityType
  70. * @throws \Exception
  71. * @return void
  72. */
  73. public function clear($entityType)
  74. {
  75. $metadata = $this->metadataPool->getMetadata($entityType);
  76. CallbackPool::clear(spl_object_hash($metadata->getEntityConnection()));
  77. }
  78. }