Snapshot.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Model\ResourceModel\Db\VersionControl;
  7. /**
  8. * Class Snapshot register snapshot of entity data, for tracking changes
  9. */
  10. class Snapshot
  11. {
  12. /**
  13. * Array of snapshots of entities data
  14. *
  15. * @var array
  16. */
  17. protected $snapshotData = [];
  18. /**
  19. * @var Metadata
  20. */
  21. protected $metadata;
  22. /**
  23. * Initialization
  24. *
  25. * @param Metadata $metadata
  26. */
  27. public function __construct(
  28. Metadata $metadata
  29. ) {
  30. $this->metadata = $metadata;
  31. }
  32. /**
  33. * Register snapshot of entity data, for tracking changes
  34. *
  35. * @param \Magento\Framework\DataObject $entity
  36. * @return void
  37. * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  38. */
  39. public function registerSnapshot(\Magento\Framework\DataObject $entity)
  40. {
  41. $metaData = $this->metadata->getFields($entity);
  42. $filteredData = array_intersect_key($entity->getData(), $metaData);
  43. $data = array_merge($metaData, $filteredData);
  44. $this->snapshotData[get_class($entity)][$entity->getId()] = $data;
  45. }
  46. /**
  47. * Check is current entity has changes, by comparing current object state with stored snapshot
  48. *
  49. * @param \Magento\Framework\DataObject $entity
  50. * @return bool
  51. */
  52. public function isModified(\Magento\Framework\DataObject $entity)
  53. {
  54. if (!$entity->getId()) {
  55. return true;
  56. }
  57. $entityClass = get_class($entity);
  58. if (!isset($this->snapshotData[$entityClass][$entity->getId()])) {
  59. return true;
  60. }
  61. foreach ($this->snapshotData[$entityClass][$entity->getId()] as $field => $value) {
  62. if ($entity->getDataByKey($field) != $value) {
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. }