media-cloud-sync
/
includes
/
sdk
/
google
/
ramsey
/
collection
/
src
/
Tool
/
ValueExtractorTrait.php
ValueExtractorTrait.php in Media Cloud Sync 1.1.1, at includes/sdk/google/ramsey/collection/src/Tool/ValueExtractorTrait.php
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * This file is part of the ramsey/collection library |
| 5 | * |
| 6 | * For the full copyright and license information, please view the LICENSE |
| 7 | * file that was distributed with this source code. |
| 8 | * |
| 9 | * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> |
| 10 | * @license http://opensource.org/licenses/MIT MIT |
| 11 | */ |
| 12 | declare (strict_types=1); |
| 13 | namespace Dudlewebs\WPMCS\Ramsey\Collection\Tool; |
| 14 | |
| 15 | use Dudlewebs\WPMCS\Ramsey\Collection\Exception\ValueExtractionException; |
| 16 | use function get_class; |
| 17 | use function is_object; |
| 18 | use function method_exists; |
| 19 | use function property_exists; |
| 20 | use function sprintf; |
| 21 | /** |
| 22 | * Provides functionality to extract the value of a property or method from an object. |
| 23 | */ |
| 24 | trait ValueExtractorTrait |
| 25 | { |
| 26 | /** |
| 27 | * Extracts the value of the given property or method from the object. |
| 28 | * |
| 29 | * @param mixed $object The object to extract the value from. |
| 30 | * @param string $propertyOrMethod The property or method for which the |
| 31 | * value should be extracted. |
| 32 | * |
| 33 | * @return mixed the value extracted from the specified property or method. |
| 34 | * |
| 35 | * @throws ValueExtractionException if the method or property is not defined. |
| 36 | */ |
| 37 | // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint |
| 38 | protected function extractValue($object, string $propertyOrMethod) |
| 39 | { |
| 40 | if (!is_object($object)) { |
| 41 | throw new ValueExtractionException('Unable to extract a value from a non-object'); |
| 42 | } |
| 43 | if (property_exists($object, $propertyOrMethod)) { |
| 44 | return $object->{$propertyOrMethod}; |
| 45 | } |
| 46 | if (method_exists($object, $propertyOrMethod)) { |
| 47 | return $object->{$propertyOrMethod}(); |
| 48 | } |
| 49 | throw new ValueExtractionException( |
| 50 | // phpcs:ignore SlevomatCodingStandard.Classes.ModernClassNameReference.ClassNameReferencedViaFunctionCall |
| 51 | sprintf('Method or property "%s" not defined in %s', $propertyOrMethod, get_class($object)) |
| 52 | ); |
| 53 | } |
| 54 | } |
| 55 |