|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Common abstract for the common classes package (last modified: 2024.09.20). |
| 4 | + * |
| 5 | + * This file is a part of the "common classes package", utilised by a number of |
| 6 | + * packages and projects, including CIDRAM and phpMussel. |
| 7 | + * @link https://github.com/Maikuolan/Common |
| 8 | + * |
| 9 | + * License: GNU/GPLv2 |
| 10 | + * @see LICENSE.txt |
| 11 | + * |
| 12 | + * "COMMON CLASSES PACKAGE" COPYRIGHT 2019 and beyond by Caleb Mazalevskis. |
| 13 | + */ |
| 14 | + |
| 15 | +namespace Maikuolan\Common; |
| 16 | + |
| 17 | +abstract class CommonAbstract |
| 18 | +{ |
| 19 | + /** |
| 20 | + * @var string Common Classes Package tag/release version. |
| 21 | + * @link https://github.com/Maikuolan/Common/tags |
| 22 | + */ |
| 23 | + public const VERSION = '2.12.3'; |
| 24 | + |
| 25 | + /** |
| 26 | + * Traverse data path. |
| 27 | + * |
| 28 | + * @param mixed $Data The data to traverse. |
| 29 | + * @param string|array $Path The path to traverse. |
| 30 | + * @param bool $AllowNonScalar Whether to allow non-scalar returns. |
| 31 | + * @param bool $AllowMethodCalls Whether to allow method calls. |
| 32 | + * @return mixed The traversed data, or an empty string on failure. |
| 33 | + */ |
| 34 | + public function dataTraverse(&$Data, $Path = [], bool $AllowNonScalar = false, bool $AllowMethodCalls = false) |
| 35 | + { |
| 36 | + if (!is_array($Path)) { |
| 37 | + $Path = preg_split('~(?<!\\\\)\\.~', $Path) ?: []; |
| 38 | + } |
| 39 | + $Segment = array_shift($Path); |
| 40 | + if ($Segment === null || strlen($Segment) === 0) { |
| 41 | + return $AllowNonScalar || is_scalar($Data) ? $Data : ''; |
| 42 | + } |
| 43 | + $Segment = str_replace('\.', '.', $Segment); |
| 44 | + if (is_array($Data)) { |
| 45 | + return isset($Data[$Segment]) ? $this->dataTraverse($Data[$Segment], $Path, $AllowNonScalar, $AllowMethodCalls) : ''; |
| 46 | + } |
| 47 | + if (is_object($Data)) { |
| 48 | + if (property_exists($Data, $Segment)) { |
| 49 | + return $this->dataTraverse($Data->$Segment, $Path, $AllowNonScalar, $AllowMethodCalls); |
| 50 | + } |
| 51 | + if ($AllowMethodCalls && method_exists($Data, $Segment)) { |
| 52 | + $Working = $Data->{$Segment}(...$Path); |
| 53 | + return $this->dataTraverse($Working, [], $AllowNonScalar); |
| 54 | + } |
| 55 | + } |
| 56 | + if (is_string($Data)) { |
| 57 | + if (preg_match('~^(?:trim|str(?:tolower|toupper|len))\\(\\)~i', $Segment)) { |
| 58 | + $Segment = substr($Segment, 0, -2); |
| 59 | + $Data = $Segment($Data); |
| 60 | + } |
| 61 | + } |
| 62 | + return $this->dataTraverse($Data, $Path, $AllowNonScalar, $AllowMethodCalls); |
| 63 | + } |
| 64 | +} |
0 commit comments