ArrayColumn.php
1 year ago
ArrayFlatten.php
1 year ago
ArrayKeys.php
1 year ago
ArraySearch.php
1 year ago
ArrayValues.php
1 year ago
Count.php
1 year ago
DotNotation.php
1 year ago
PrepareUrl.php
1 year ago
TransformerInterface.php
1 year ago
TransformerService.php
1 year ago
DotNotation.php
80 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Automattic\WooCommerce\Admin\RemoteSpecs\RuleProcessors\Transformers; |
| 4 | |
| 5 | use Automattic\WooCommerce\Admin\RemoteSpecs\RuleProcessors\Transformers\TransformerInterface; |
| 6 | use InvalidArgumentException; |
| 7 | use stdClass; |
| 8 | |
| 9 | /** |
| 10 | * Find an array value by dot notation. |
| 11 | * |
| 12 | * @package Automattic\WooCommerce\Admin\RemoteSpecs\RuleProcessors\Transformers |
| 13 | */ |
| 14 | class DotNotation implements TransformerInterface { |
| 15 | |
| 16 | /** |
| 17 | * Find given path from the given value. |
| 18 | * |
| 19 | * @param mixed $value a value to transform. |
| 20 | * @param stdClass|null $arguments required argument 'path'. |
| 21 | * @param string|null $default_value default value. |
| 22 | * |
| 23 | * @throws InvalidArgumentException Throws when the required 'path' is missing. |
| 24 | * |
| 25 | * @return mixed |
| 26 | */ |
| 27 | public function transform( $value, ?stdclass $arguments = null, $default_value = null ) { |
| 28 | if ( is_object( $value ) ) { |
| 29 | // if the value is an object, convert it to an array. |
| 30 | $value = json_decode( wp_json_encode( $value ), true ); |
| 31 | } |
| 32 | |
| 33 | return $this->get( $value, $arguments->path, $default_value ); |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Find the given $path in $array_to_search by dot notation. |
| 38 | * |
| 39 | * @param array $array_to_search an array to search in. |
| 40 | * @param string $path a path in the given array. |
| 41 | * @param null $default_value default value to return if $path was not found. |
| 42 | * |
| 43 | * @return mixed|null |
| 44 | */ |
| 45 | public function get( $array_to_search, $path, $default_value = null ) { |
| 46 | if ( ! is_array( $array_to_search ) ) { |
| 47 | return $default_value; |
| 48 | } |
| 49 | |
| 50 | if ( isset( $array_to_search[ $path ] ) ) { |
| 51 | return $array_to_search[ $path ]; |
| 52 | } |
| 53 | |
| 54 | foreach ( explode( '.', $path ) as $segment ) { |
| 55 | if ( ! is_array( $array_to_search ) || ! array_key_exists( $segment, $array_to_search ) ) { |
| 56 | return $default_value; |
| 57 | } |
| 58 | |
| 59 | $array_to_search = $array_to_search[ $segment ]; |
| 60 | } |
| 61 | |
| 62 | return $array_to_search; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Validate Transformer arguments. |
| 67 | * |
| 68 | * @param stdClass|null $arguments arguments to validate. |
| 69 | * |
| 70 | * @return mixed |
| 71 | */ |
| 72 | public function validate( ?stdClass $arguments = null ) { |
| 73 | if ( ! isset( $arguments->path ) ) { |
| 74 | return false; |
| 75 | } |
| 76 | |
| 77 | return true; |
| 78 | } |
| 79 | } |
| 80 |