Skip to content

Commit

Permalink
close #11
Browse files Browse the repository at this point in the history
  • Loading branch information
rodber committed Jan 18, 2025
1 parent 08343a8 commit 0bf31e9
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace Chevere\Parameter;

use ArrayAccess;
use BadMethodCallException;
use Chevere\Parameter\Attributes\ReturnAttr;
use Chevere\Parameter\Exceptions\AttributeNotFoundException;
use Chevere\Parameter\Exceptions\ParameterException;
Expand Down Expand Up @@ -41,8 +42,32 @@
use Throwable;
use function Chevere\Message\message;

function cast(mixed $argument): CastInterface
function cast(mixed $argument, string|int ...$key): CastInterface
{
if ($key !== []) {
if (! ($argument instanceof ArrayAccess || is_array($argument))) {
throw new BadMethodCallException(
(string) message(
'Argument must be array-accessible, %type% provided',
type: gettype($argument)
)
);
}
$fn = function ($carry, $item) {
if (array_key_exists($item, $carry)) {
return $carry[$item];
}

throw new InvalidArgumentException(
(string) message(
'Key `%key%` not found in array',
key: $item
)
);
};
$argument = array_reduce($key, $fn, $argument);
}

return new Cast($argument);
}

Expand Down
39 changes: 39 additions & 0 deletions tests/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace Chevere\Tests;

use BadMethodCallException;
use Chevere\Parameter\Exceptions\ParameterException;
use Chevere\Parameter\Exceptions\ReturnException;
use InvalidArgumentException;
Expand Down Expand Up @@ -370,6 +371,44 @@ public function testCast(): void
$this->assertSame($value, $cast->string());
}

public function testCastNested(): void
{
$value = [
'super' => [
'taldo' => null,
],
3 => 'co',
'agac',
];
$cast = cast($value);
$this->assertSame($value, $cast->array());
$cast = cast($value, 'super');
$this->assertSame($value['super'], $cast->array());
$cast = cast($value, 'super', 'taldo');
$this->assertSame($value['super']['taldo'], $cast->mixed());
$cast = cast($value, 3);
$this->assertSame($value[3], $cast->string());
$cast = cast($value, 4);
$this->assertSame($value[4], $cast->string());
}

public static function dataProviderCastNestedError(): array
{
return [
[1, BadMethodCallException::class],
[[], InvalidArgumentException::class],
];
}

/**
* @dataProvider dataProviderCastNestedError
*/
public function testCastNestedError(mixed $value, string $exception): void
{
$this->expectException($exception);
$cast = cast($value, 'foo');
}

public function testParameterAttr(): void
{
$caller = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
Expand Down

0 comments on commit 0bf31e9

Please sign in to comment.