Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
13
declare(strict_types=1);
14
 
15
namespace Ramsey\Collection\Tool;
16
 
17
use Ramsey\Collection\Exception\InvalidPropertyOrMethod;
18
use Ramsey\Collection\Exception\UnsupportedOperationException;
19
 
20
use function is_array;
21
use function is_object;
22
use function method_exists;
23
use function property_exists;
24
use function sprintf;
25
 
26
/**
27
 * Provides functionality to extract the value of a property or method from an object.
28
 */
29
trait ValueExtractorTrait
30
{
31
    /**
32
     * Extracts the value of the given property, method, or array key from the
33
     * element.
34
     *
35
     * If `$propertyOrMethod` is `null`, we return the element as-is.
36
     *
37
     * @param mixed $element The element to extract the value from.
38
     * @param string | null $propertyOrMethod The property or method for which the
39
     *     value should be extracted.
40
     *
41
     * @return mixed the value extracted from the specified property, method,
42
     *     or array key, or the element itself.
43
     *
44
     * @throws InvalidPropertyOrMethod
45
     * @throws UnsupportedOperationException
46
     */
47
    protected function extractValue(mixed $element, ?string $propertyOrMethod): mixed
48
    {
49
        if ($propertyOrMethod === null) {
50
            return $element;
51
        }
52
 
53
        if (!is_object($element) && !is_array($element)) {
54
            throw new UnsupportedOperationException(sprintf(
55
                'The collection type "%s" does not support the $propertyOrMethod parameter',
56
                $this->getType(),
57
            ));
58
        }
59
 
60
        if (is_array($element)) {
61
            return $element[$propertyOrMethod] ?? throw new InvalidPropertyOrMethod(sprintf(
62
                'Key or index "%s" not found in collection elements',
63
                $propertyOrMethod,
64
            ));
65
        }
66
 
67
        if (property_exists($element, $propertyOrMethod)) {
68
            return $element->$propertyOrMethod;
69
        }
70
 
71
        if (method_exists($element, $propertyOrMethod)) {
72
            return $element->{$propertyOrMethod}();
73
        }
74
 
75
        throw new InvalidPropertyOrMethod(sprintf(
76
            'Method or property "%s" not defined in %s',
77
            $propertyOrMethod,
78
            $element::class,
79
        ));
80
    }
81
}