class-wc-meta-data.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. /**
  3. * Wraps an array (meta data for now) and tells if there was any changes.
  4. *
  5. * The main idea behind this class is to avoid doing unneeded
  6. * SQL updates if nothing changed.
  7. *
  8. * @version 3.2.0
  9. * @package WooCommerce
  10. */
  11. defined( 'ABSPATH' ) || exit;
  12. /**
  13. * Meta data class.
  14. */
  15. class WC_Meta_Data implements JsonSerializable {
  16. /**
  17. * Current data for metadata
  18. *
  19. * @since 3.2.0
  20. * @var array
  21. */
  22. protected $current_data;
  23. /**
  24. * Metadata data
  25. *
  26. * @since 3.2.0
  27. * @var array
  28. */
  29. protected $data;
  30. /**
  31. * Constructor.
  32. *
  33. * @param array $meta Data to wrap behind this function.
  34. */
  35. public function __construct( $meta = array() ) {
  36. $this->current_data = $meta;
  37. $this->apply_changes();
  38. }
  39. /**
  40. * When converted to JSON.
  41. *
  42. * @return object
  43. */
  44. public function jsonSerialize() {
  45. return $this->get_data();
  46. }
  47. /**
  48. * Merge changes with data and clear.
  49. */
  50. public function apply_changes() {
  51. $this->data = $this->current_data;
  52. }
  53. /**
  54. * Creates or updates a property in the metadata object.
  55. *
  56. * @param string $key Key to set.
  57. * @param mixed $value Value to set.
  58. */
  59. public function __set( $key, $value ) {
  60. $this->current_data[ $key ] = $value;
  61. }
  62. /**
  63. * Checks if a given key exists in our data. This is called internally
  64. * by `empty` and `isset`.
  65. *
  66. * @param string $key Key to check if set.
  67. */
  68. public function __isset( $key ) {
  69. return array_key_exists( $key, $this->current_data );
  70. }
  71. /**
  72. * Returns the value of any property.
  73. *
  74. * @param string $key Key to get.
  75. * @return mixed Property value or NULL if it does not exists
  76. */
  77. public function __get( $key ) {
  78. if ( array_key_exists( $key, $this->current_data ) ) {
  79. return $this->current_data[ $key ];
  80. }
  81. return null;
  82. }
  83. /**
  84. * Return data changes only.
  85. *
  86. * @return array
  87. */
  88. public function get_changes() {
  89. $changes = array();
  90. foreach ( $this->current_data as $id => $value ) {
  91. if ( ! array_key_exists( $id, $this->data ) || $value !== $this->data[ $id ] ) {
  92. $changes[ $id ] = $value;
  93. }
  94. }
  95. return $changes;
  96. }
  97. /**
  98. * Return all data as an array.
  99. *
  100. * @return array
  101. */
  102. public function get_data() {
  103. return $this->data;
  104. }
  105. }