Aucune description

class-wc-meta-data.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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|array
  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. * @return bool
  69. */
  70. public function __isset( $key ) {
  71. return array_key_exists( $key, $this->current_data );
  72. }
  73. /**
  74. * Returns the value of any property.
  75. *
  76. * @param string $key Key to get.
  77. * @return mixed Property value or NULL if it does not exists
  78. */
  79. public function __get( $key ) {
  80. if ( array_key_exists( $key, $this->current_data ) ) {
  81. return $this->current_data[ $key ];
  82. }
  83. return null;
  84. }
  85. /**
  86. * Return data changes only.
  87. *
  88. * @return array
  89. */
  90. public function get_changes() {
  91. $changes = array();
  92. foreach ( $this->current_data as $id => $value ) {
  93. if ( ! array_key_exists( $id, $this->data ) || $value !== $this->data[ $id ] ) {
  94. $changes[ $id ] = $value;
  95. }
  96. }
  97. return $changes;
  98. }
  99. /**
  100. * Return all data as an array.
  101. *
  102. * @return array
  103. */
  104. public function get_data() {
  105. return $this->data;
  106. }
  107. }