EntitySnapshot.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Model;
  7. use Magento\Framework\EntityManager\MetadataPool;
  8. use Magento\Framework\Model\EntitySnapshot\AttributeProvider;
  9. /**
  10. * Class EntitySnapshot
  11. */
  12. class EntitySnapshot
  13. {
  14. /**
  15. * Array of snapshots of entities data
  16. *
  17. * @var array
  18. */
  19. protected $snapshotData = [];
  20. /**
  21. * @var MetadataPool
  22. */
  23. protected $metadataPool;
  24. /**
  25. * @var AttributeProvider
  26. */
  27. protected $attributeProvider;
  28. /**
  29. * @param MetadataPool $metadataPool
  30. * @param AttributeProvider $attributeProvider
  31. */
  32. public function __construct(
  33. MetadataPool $metadataPool,
  34. AttributeProvider $attributeProvider
  35. ) {
  36. $this->metadataPool = $metadataPool;
  37. $this->attributeProvider = $attributeProvider;
  38. }
  39. /**
  40. * @param string $entityType
  41. * @param object $entity
  42. * @return void
  43. */
  44. public function registerSnapshot($entityType, $entity)
  45. {
  46. $metadata = $this->metadataPool->getMetadata($entityType);
  47. $hydrator = $this->metadataPool->getHydrator($entityType);
  48. $entityData = $hydrator->extract($entity);
  49. $attributes = $this->attributeProvider->getAttributes($entityType);
  50. $this->snapshotData[$entityType][$entityData[$metadata->getIdentifierField()]]
  51. = array_intersect_key($entityData, $attributes);
  52. }
  53. /**
  54. * Check is current entity has changes, by comparing current object state with stored snapshot
  55. *
  56. * @param string $entityType
  57. * @param object $entity
  58. * @return bool
  59. */
  60. public function isModified($entityType, $entity)
  61. {
  62. $metadata = $this->metadataPool->getMetadata($entityType);
  63. $hydrator = $this->metadataPool->getHydrator($entityType);
  64. $entityData = $hydrator->extract($entity);
  65. if (empty($entityData[$metadata->getIdentifierField()])) {
  66. return true;
  67. }
  68. $identifier = $entityData[$metadata->getIdentifierField()];
  69. if (!isset($this->snapshotData[$entityType][$identifier])) {
  70. return true;
  71. }
  72. foreach ($this->snapshotData[$entityType][$identifier] as $field => $value) {
  73. if (isset($entityData[$field]) && $entityData[$field] != $value) {
  74. return true;
  75. }
  76. }
  77. return false;
  78. }
  79. }