Skip to content

Commit

Permalink
FEATURE: Add getAccessorByPath to Neos\Utility\Arrays for type sa…
Browse files Browse the repository at this point in the history
…fe access to array values

The array utility allows to create an accessor for a path of an array by calling `getAccessorByPath($arrayValue, 'your.path')`
The accessor provides the following methods that will either return the requested type or throw a TypeError.

* `int()`
* `float()`
* `number()`
* `string()`
* `classString()`
* `array()`
* `object(string $className)`
* `intOrNull()`
* `floatOrNull()`
* `numberOrNull()`
* `stringOrNull()`
* `classStringOrNull()`
* `arrayOrNull()`
* `objectOrNull(string $className)`
  • Loading branch information
mficzel committed Sep 3, 2023
1 parent dc72146 commit 9cec4b5
Show file tree
Hide file tree
Showing 4 changed files with 408 additions and 17 deletions.
43 changes: 27 additions & 16 deletions Neos.Utility.Arrays/Classes/Arrays.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Neos\Utility;

/*
Expand Down Expand Up @@ -194,28 +195,38 @@ public static function array_reduce(array $array, string $function, $initial = n
/**
* Returns the value of a nested array by following the specifed path.
*
* @param array &$array The array to traverse as a reference
* @param array $array The array to traverse
* @param array|string $path The path to follow. Either a simple array of keys or a string in the format 'foo.bar.baz'
* @return mixed The value found, NULL if the path didn't exist (note there is no way to distinguish between a found NULL value and "path not found")
* @throws \InvalidArgumentException
*/
public static function getValueByPath(array &$array, $path)
public static function getValueByPath(array $array, array|string $path): mixed
{
if (is_string($path)) {
$path = explode('.', $path);
} elseif (!is_array($path)) {
throw new \InvalidArgumentException('getValueByPath() expects $path to be string or array, "' . gettype($path) . '" given.', 1304950007);
}
$key = array_shift($path);
if (isset($array[$key])) {
if (count($path) > 0) {
return (is_array($array[$key])) ? self::getValueByPath($array[$key], $path) : null;
} else {
return $array[$key];
}
} else {
$pathSegments = is_string($path) ? explode('.', $path) : $path;
$pathSegment = array_shift($pathSegments);

if (!isset($array[$pathSegment])) {
return null;
}
if ($pathSegments === []) {
return $array[$pathSegment];
}
return is_array($array[$pathSegment])
? self::getValueByPath($array[$pathSegment], $pathSegments)
: null;
}

/**
* Returns a type safe accessor for a value in a nested array by following the specifed path.
*
* @param array $array The array to traverse
* @param array|string $path The path to follow. Either a simple array of keys or a string in the format 'foo.bar.baz'
* @return ValueAccessor
*/
public static function getAccessorByPath(array $array, array|string $path): ValueAccessor
{
$pathinfo = is_array($path) ? implode('.', $path) : $path;
$value = self::getValueByPath($array, $path);
return new ValueAccessor($value, $pathinfo);
}

/**
Expand Down
158 changes: 158 additions & 0 deletions Neos.Utility.Arrays/Classes/ValueAccessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
<?php

namespace Neos\Utility;

/*
* This file is part of the Neos.Utility.Arrays package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/

/**
* Type safe accessing of values from nested arrays
*/
class ValueAccessor
{
public function __construct(
public readonly mixed $value,
public readonly ?string $pathinfo = null
) {
}

private function createTypeError($message): \TypeError
{
return new \TypeError(get_debug_type($this->value) . ' ' . $message . ($this->pathinfo ? ' in path ' . $this->pathinfo : ''));
}

public function int(): int
{
if (is_int($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not an integer");
}

public function float(): float
{
if (is_float($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a float");
}

public function number(): int|float
{
if (is_int($this->value) || is_float($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a number");
}

public function string(): string
{
if (is_string($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a string");
}

/**
* @return class-string
*/
public function classString(): string
{
if (is_string($this->value) && class_exists($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a class-string");
}

public function array(): array
{
if (is_array($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not an array");
}

/**
* @template T
* @param class-string<T> $type
* @return object&T
*/
public function object(string $type): object
{
if (is_a($this->value, $type, false)) {
return $this->value;
}
throw $this->createTypeError(sprintf('is not of type class %s', $type));
}

public function intOrNull(): ?int
{
if (is_int($this->value) || is_null($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not an integer or null");
}

public function floatOrNull(): ?float
{
if (is_float($this->value) || is_null($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a float or null");
}

public function numberOrNull(): null|int|float
{
if (is_int($this->value) || is_float($this->value) || is_null($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a number or null");
}

public function stringOrNull(): ?string
{
if (is_string($this->value) || is_null($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a string or null");
}

/**
* @return class-string|null
*/
public function classStringOrNull(): ?string
{
if ((is_string($this->value) && class_exists($this->value)) || is_null($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not a class-string");
}

public function arrayOrNull(): ?array
{
if (is_array($this->value) || is_null($this->value)) {
return $this->value;
}
throw $this->createTypeError("is not an array or null");
}

/**
* @template T
* @param class-string<T> $type
* @return (object&T)|null
*/
public function objectOrNull(string $type): ?object
{
if (is_a($this->value, $type, false) || is_null($this->value)) {
return $this->value;
}
throw $this->createTypeError(sprintf('is not of type class %s or null', $type));
}
}
90 changes: 89 additions & 1 deletion Neos.Utility.Arrays/Tests/Unit/ArraysTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function getValueByPathReturnsTheValueOfANestedArrayByFollowingTheGivenPa
*/
public function getValueByPathThrowsExceptionIfPathIsNoArrayOrString()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectException(\TypeError::class);
$array = ['Foo' => ['Bar' => ['Baz' => [2 => 'the value']]]];
Arrays::getValueByPath($array, null);
}
Expand All @@ -108,6 +108,94 @@ public function getValueByPathReturnsNullIfThePathHasMoreSegmentsThanTheGivenArr
self::assertNull(Arrays::getValueByPath($array, ['Foo', 'Bar', 'Baz', 'Bux']));
}

/**
* @test
*/
public function getAccessorByPathReturnsTheValueOfANestedArrayByFollowingTheGivenSimplePath()
{
$array = ['Foo' => 'the value'];
self::assertSame('the value', Arrays::getAccessorByPath($array, ['Foo'])->string());
}

/**
* @test
*/
public function getAccessorByPathReturnsTheValueOfANestedArrayByFollowingTheGivenPath()
{
$array = ['Foo' => ['Bar' => ['Baz' => [2 => 'the value']]]];
self::assertSame('the value', Arrays::getAccessorByPath($array, ['Foo', 'Bar', 'Baz', 2])->string());
}

/**
* @test
*/
public function getAccessorByPathReturnsTheValueOfANestedArrayByFollowingTheGivenPathIfPathIsString()
{
$array = ['Foo' => ['Bar' => ['Baz' => [2 => 'the value']]]];
self::assertSame('the value', Arrays::getAccessorByPath($array, 'Foo.Bar.Baz.2')->string());
}

/**
* @test
*/
public function getAccessorByPathThrowsTypeErrorIfPathIsNoArrayOrString()
{
$this->expectException(\TypeError::class);
$array = ['Foo' => ['Bar' => ['Baz' => [2 => 'the value']]]];
Arrays::getAccessorByPath($array, null);
}

/**
* @test
*/
public function getAccessorByPathReturnsNullIfTheSegementsOfThePathDontExist()
{
$array = ['Foo' => ['Bar' => ['Baz' => [2 => 'the value']]]];
self::assertNull(Arrays::getAccessorByPath($array, ['Foo', 'Bar', 'Bax', 2])->intOrNull());
}

/**
* @test
*/
public function getAccessorByPathReturnsNullIfThePathHasMoreSegmentsThanTheGivenArray()
{
$array = ['Foo' => ['Bar' => ['Baz' => 'the value']]];
self::assertNull(Arrays::getAccessorByPath($array, ['Foo', 'Bar', 'Baz', 'Bux'])->intOrNull());
}

/**
* @test
*/
public function getAccessorByPathTypeErrorContainsPathForNonMatchingTypes()
{
$array = ['Foo' => ['Bar' => ['Baz' => 'the value']]];
$this->expectException(\TypeError::class);
$this->expectExceptionMessage('in path Foo.Bar.Baz');
Arrays::getAccessorByPath($array, ['Foo', 'Bar', 'Baz'])->int();
}

/**
* @test
*/
public function getAccessorByPathTypeErrorContainsPathForNonMatchingTypesOnRoot()
{
$array = ['Foo' => 'string'];
$this->expectException(\TypeError::class);
$this->expectExceptionMessage('in path Foo');
Arrays::getAccessorByPath($array, ['Foo'])->int();
}

/**
* @test
*/
public function getAccessorByPathTypeErrorContainsPathForNonExistingPathes()
{
$array = ['Foo' => ['Bar' => ['Baz' => 'the value']]];
$this->expectException(\TypeError::class);
$this->expectExceptionMessage('in path Foo.Bar.Bax');
Arrays::getAccessorByPath($array, ['Foo', 'Bar', 'Bax'])->int();
}

/**
* @test
*/
Expand Down
Loading

0 comments on commit 9cec4b5

Please sign in to comment.