diff --git a/README.md b/README.md index d7c4cec..f395e9e 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ use Bakame\Http\StructuredFields\OuterList; $fieldValue = 'text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8'; $container = OuterList::fromRfc9651($fieldValue); $container[1]->value()->toString(); // returns 'application/xhtml+xml' -$container[1]->parameterByKey(key: 'q', default: 1.0); // returns 1.0 if the parameter is not defined +$container[1]->parameterByName(key: 'q', default: 1.0); // returns 1.0 if the parameter is not defined ``` ## System Requirements diff --git a/docs/00-intro.md b/docs/00-intro.md index 8e82489..c4a018a 100644 --- a/docs/00-intro.md +++ b/docs/00-intro.md @@ -16,7 +16,7 @@ use Bakame\Http\StructuredFields\DataType; $fieldValue = 'text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8'; $container = DataType::List->parse($fieldValue); $container[1]->value()->toString(); // returns 'application/xhtml+xml' -$container[1]->parameterByKey(key: 'q', default: 1.0); // returns 1.0 if the parameter is not defined +$container[1]->parameterByName(key: 'q', default: 1.0); // returns 1.0 if the parameter is not defined ``` ## Motivation diff --git a/docs/02-parsing-serializing.md b/docs/02-parsing-serializing.md index 02ded9a..a035551 100644 --- a/docs/02-parsing-serializing.md +++ b/docs/02-parsing-serializing.md @@ -128,9 +128,9 @@ The following field is an example from the Accept header which is already struct $fieldValue = 'text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8'; $field = DataType::List->parse($fieldValue); $field[2]->value()->toString(); // returns 'application/xml' -$field[2]->parameterByKey('q'); // returns (float) 0.9 +$field[2]->parameterByName('q'); // returns (float) 0.9 $field[0]->value()->toString(); // returns 'text/html' -$field[0]->parameterByKey('q'); // returns null +$field[0]->parameterByName('q'); // returns null ``` - The Accept header is an `List` field made of `Item` only. diff --git a/docs/04-item.md b/docs/04-item.md index fd4c147..7ff9e41 100644 --- a/docs/04-item.md +++ b/docs/04-item.md @@ -64,7 +64,7 @@ They can be accessed by their indices **but also** by their required key attache $item = Item::fromHttpValue('application/xml;q=0.9;foobar'); $item->value()->toString(); // returns 'application/xhtml+xml' -$item->parameterByKey(key: 'q', default: 1.0); // returns 1.0 if the parameter is not defined +$item->parameterByName(key: 'q', default: 1.0); // returns 1.0 if the parameter is not defined $item->parameterByIndex(index: 1, default: ['toto', false]); // returns ['foobar', true] because there's a parameter at index 1 $item->parameters(); // returns a Parameters instance. ``` @@ -72,7 +72,7 @@ $item->parameters(); // returns a Parameters instance. By default, you can access the member `Item` of a parameters using the following methods: - `Item::parameters` returns a `Parameters` instance; -- `Item::parameterByKey` returns the value of the bare item instance attached to the supplied `key`; +- `Item::parameterByName` returns the value of the bare item instance attached to the supplied `key`; - `Item::parameterByIndex` returns the value of the bare item instance attached to the supplied `index`; It is possible to alter and modify the `Parameters` attached to an `Item` but this section diff --git a/docs/05-containers.md b/docs/05-containers.md index 5affec5..89d4b2d 100644 --- a/docs/05-containers.md +++ b/docs/05-containers.md @@ -57,27 +57,27 @@ unset($permissions['a']); // triggers a ForbiddenOperation exception The `Dictionary` and `Parameters` classes also allow accessing its members as value using their key: ```php -$permissions->hasKey('picture-in-picture'); // returns true -$permissions->hasKey('picture-in-picture', 'foobar'); // returns false +$permissions->hasName('picture-in-picture'); // returns true +$permissions->hasName('picture-in-picture', 'foobar'); // returns false // 'foobar' is not a valid key or at least it is not present -$permissions->getByKey('camera'); // returns Item::fromToken('*'); +$permissions->getByName('camera'); // returns Item::fromToken('*'); $permissions->toAssociative(); // returns an iterator // the iterator key is the member key and the value is the member value // the offset is "lost" -$permissions->keyByIndex(42); // returns null because there's no member with the offset 42 -$permissions->keyByIndex(2); // returns 'camera' +$permissions->nameByIndex(42); // returns null because there's no member with the offset 42 +$permissions->nameByIndex(2); // returns 'camera' -$permissions->indexByKey('foobar'): // returns null because there's no member with the key 'foobar' -$permissions->indexByKey('geolocation'): // returns 1 +$permissions->indexByName('foobar'): // returns null because there's no member with the key 'foobar' +$permissions->indexByName('geolocation'): // returns 1 ``` > [!IMPORTANT] -> The `getByKey` method will throw an `InvalidOffset` exception if no member exists for the given `$offset`. +> The `getByName` method will throw an `InvalidOffset` exception if no member exists for the given `$offset`. > [!TIP] > The `ArrayAccess` interface proxy the result from `getByIndex` in list. -> The `ArrayAccess` interface proxy the result from `getByKey` in ordered map. +> The `ArrayAccess` interface proxy the result from `getByName` in ordered map. ### Accessing the parameters values @@ -85,11 +85,11 @@ As we have already seen, it is possible to access the `Parameters` values direct from the `Item` instance. The same public API is used from the `InnerList`. On the other hand if you already have a `Parameters` instance you can use the -`valueByKey` and `valueByIndex` methods to directly access the value from a single +`valueByName` and `valueByIndex` methods to directly access the value from a single parameter. > [!TIP] -> The `parameterByKey` proxy the result from `valueByKey`. +> The `parameterByKey` proxy the result from `valueByName`. > The `parameterByIndex` proxy the result from `valueByIndex`. ## Building and Updating Structured Fields Values @@ -138,11 +138,11 @@ following steps. You, first, create a `Parameters` or a `Dictionary` instance us use any of the following modifying methods to populate it. ```php -$map->add(string $key, $value): static; -$map->append(string $key, $value): static; -$map->prepend(string $key, $value): static; +$map->add(string $name, $value): static; +$map->append(string $name, $value): static; +$map->prepend(string $name, $value): static; $map->mergeAssociative(...$others): static; -$map->removeByKeys(string ...$keys): static; +$map->removeByKeys(string ...$names): static; ``` As shown below: @@ -384,9 +384,9 @@ Both objects provide additional modifying methods to help deal with parameters. You can attach and update the associated `Parameters` instance using the following methods. ```php -$field->addParameter(string $key, mixed $value): static; -$field->appendParameter(string $key, mixed $value): static; -$field->prependParameter(string $key, mixed $value): static; +$field->addParameter(string $name, mixed $value): static; +$field->appendParameter(string $name, mixed $value): static; +$field->prependParameter(string $name, mixed $value): static; $field->withoutParameters(string ...$keys): static; // this method is deprecated as of version 1.1 use withoutParametersByKeys instead $field->withoutAnyParameter(): static; $field->withParameters(Parameters $parameters): static; diff --git a/docs/06-validation.md b/docs/06-validation.md index 2acd867..78515ba 100644 --- a/docs/06-validation.md +++ b/docs/06-validation.md @@ -172,7 +172,7 @@ Because parameters are optional by default and the `longitude` parameter is requ require its presence. So to fully validate the parameter we need to do the following ```php -$member->parameterBykey( +$member->parameterByName( key: 'longitude', validate: fn (mixed $value) => match (true) { Type::Decimal->supports($value) => true, @@ -257,9 +257,9 @@ use Bakame\Http\StructuredFields\Validation\ParametersValidator; $parametersValidator = ParametersValidator::new() ->filterByCriteria( fn (Parameters $parameters): bool|string => $parameters - ->allowedKeys(['location', 'longitude', 'latitude', 'date']) + ->allowedNames(['location', 'longitude', 'latitude', 'date']) ) - ->filterByKeys([ + ->filterByNames([ 'location' => [ 'validate' => fn (mixed $value) => Type::fromVariable($value)->isOneOf(Type::String, Type::DisplayString), ], diff --git a/src/Dictionary.php b/src/Dictionary.php index d3ef672..dc09796 100644 --- a/src/Dictionary.php +++ b/src/Dictionary.php @@ -42,8 +42,8 @@ final class Dictionary implements ArrayAccess, Countable, IteratorAggregate, Str private function __construct(iterable $members = []) { $filteredMembers = []; - foreach ($members as $key => $member) { - $filteredMembers[MapKey::from($key)->value] = self::filterMember($member); + foreach ($members as $name => $member) { + $filteredMembers[MapKey::from($name)->value] = self::filterMember($member); } $this->members = $filteredMembers; @@ -148,8 +148,8 @@ public static function fromPairs(StructuredFieldProvider|iterable $pairs): self $pairs instanceof Dictionary, $pairs instanceof Parameters => new self($pairs->toAssociative()), default => new self((function (iterable $pairs) use ($converter) { - foreach ($pairs as [$key, $member]) { - yield $key => $converter($member); + foreach ($pairs as [$name, $member]) { + yield $name => $converter($member); } })($pairs)), }; @@ -213,10 +213,10 @@ public function toHttpValue(?Ietf $rfc = null): string { $rfc ??= Ietf::Rfc9651; $members = []; - foreach ($this->members as $key => $member) { + foreach ($this->members as $name => $member) { $members[] = match (true) { - $member instanceof Item && true === $member->value() => $key.$member->parameters()->toHttpValue($rfc), - default => $key.'='.$member->toHttpValue($rfc), + $member instanceof Item && true === $member->value() => $name.$member->parameters()->toHttpValue($rfc), + default => $name.'='.$member->toHttpValue($rfc), }; } @@ -275,11 +275,11 @@ public function getIterator(): Iterator } /** - * Returns an ordered list of the instance keys. + * Returns an ordered list of the instance names. * * @return array */ - public function keys(): array + public function names(): array { return array_keys($this->members); } @@ -289,37 +289,37 @@ public function keys(): array */ public function indices(): array { - return array_keys($this->keys()); + return array_keys($this->names()); } /** * Tells whether the instance contain a members at the specified offsets. */ - public function hasKeys(string ...$keys): bool + public function hasNames(string ...$names): bool { - foreach ($keys as $key) { - if (!array_key_exists($key, $this->members)) { + foreach ($names as $name) { + if (!array_key_exists($name, $this->members)) { return false; } } - return [] !== $keys; + return [] !== $names; } /** * Returns true only if the instance only contains the listed keys, false otherwise. * - * @param array $keys + * @param array $names */ - public function allowedKeys(array $keys): bool + public function allowedNames(array $names): bool { - foreach ($this->members as $key => $member) { - if (!in_array($key, $keys, true)) { + foreach ($this->members as $name => $member) { + if (!in_array($name, $names, true)) { return false; } } - return [] !== $keys; + return [] !== $names; } /** @@ -327,9 +327,9 @@ public function allowedKeys(array $keys): bool * * @throws InvalidOffset|Violation|StructuredFieldError */ - public function getByKey(string $key, ?callable $validate = null): Item|InnerList + public function getByName(string $name, ?callable $validate = null): Item|InnerList { - $value = $this->members[$key] ?? throw InvalidOffset::dueToKeyNotFound($key); + $value = $this->members[$name] ?? throw InvalidOffset::dueToNameNotFound($name); if (null === $validate) { return $value; } @@ -339,10 +339,10 @@ public function getByKey(string $key, ?callable $validate = null): Item|InnerLis } if (!is_string($exceptionMessage) || '' === trim($exceptionMessage)) { - $exceptionMessage = "The parameter '{key}' whose value is '{value}' failed validation."; + $exceptionMessage = "The parameter '{name}' whose value is '{value}' failed validation."; } - throw new Violation(strtr($exceptionMessage, ['{key}' => $key, '{value}' => $value->toHttpValue()])); + throw new Violation(strtr($exceptionMessage, ['{name}' => $name, '{value}' => $value->toHttpValue()])); } /** @@ -390,16 +390,16 @@ public function getByIndex(int $index, ?callable $validate = null): array { $foundOffset = $this->filterIndex($index) ?? throw InvalidOffset::dueToIndexNotFound($index); - $validator = function (Item|InnerList $value, string $key, int $index, callable $validate): array { - if (true === ($exceptionMessage = $validate($value, $key))) { - return [$key, $value]; + $validator = function (Item|InnerList $value, string $name, int $index, callable $validate): array { + if (true === ($exceptionMessage = $validate($value, $name))) { + return [$name, $value]; } if (!is_string($exceptionMessage) || '' === trim($exceptionMessage)) { - $exceptionMessage = "The member at position '{index}' whose name is '{key}' with the value '{value}' failed validation."; + $exceptionMessage = "The member at position '{index}' whose name is '{name}' with the value '{value}' failed validation."; } - throw new Violation(strtr($exceptionMessage, ['{index}' => $index, '{key}' => $key, '{value}' => $value->toHttpValue()])); + throw new Violation(strtr($exceptionMessage, ['{index}' => $index, '{name}' => $name, '{value}' => $value->toHttpValue()])); }; foreach ($this as $offset => $pair) { @@ -417,10 +417,10 @@ public function getByIndex(int $index, ?callable $validate = null): array /** * Returns the key associated with the given index or null otherwise. */ - public function indexByKey(string $key): ?int + public function indexByName(string $name): ?int { foreach ($this as $index => $member) { - if ($key === $member[0]) { + if ($name === $member[0]) { return $index; } } @@ -431,7 +431,7 @@ public function indexByKey(string $key): ?int /** * Returns the index associated with the given key or null otherwise. */ - public function keyByIndex(int $index): ?string + public function nameByIndex(int $index): ?string { $index = $this->filterIndex($index); if (null === $index) { @@ -488,14 +488,14 @@ public function last(): array * @throws SyntaxError If the string key is not a valid */ public function add( - string $key, + string $name, iterable|StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): self { if (null === $member) { return $this; } $members = $this->members; - $members[MapKey::from($key)->value] = self::filterMember($member); + $members[MapKey::from($name)->value] = self::filterMember($member); return $this->newInstance($members); } @@ -517,21 +517,21 @@ private function newInstance(array $members): self * This method MUST retain the state of the current instance, and return * an instance that contains the specified changes. */ - private function remove(string|int ...$keys): self + private function remove(string|int ...$names): self { - if ([] === $this->members || [] === $keys) { + if ([] === $this->members || [] === $names) { return $this; } $offsets = array_keys($this->members); $max = count($offsets); - $reducer = fn (array $carry, string|int $key): array => match (true) { - is_string($key) && (false !== ($position = array_search($key, $offsets, true))), - is_int($key) && (null !== ($position = $this->filterIndex($key, $max))) => [$position => true] + $carry, + $reducer = fn (array $carry, string|int $name): array => match (true) { + is_string($name) && (false !== ($position = array_search($name, $offsets, true))), + is_int($name) && (null !== ($position = $this->filterIndex($name, $max))) => [$position => true] + $carry, default => $carry, }; - $indices = array_reduce($keys, $reducer, []); + $indices = array_reduce($names, $reducer, []); return match (true) { [] === $indices => $this, @@ -563,9 +563,9 @@ public function removeByIndices(int ...$indices): self * This method MUST retain the state of the current instance, and return * an instance that contains the specified changes. */ - public function removeByKeys(string ...$keys): self + public function removeByNames(string ...$names): self { - return $this->remove(...$keys); + return $this->remove(...$names); } /** @@ -578,16 +578,16 @@ public function removeByKeys(string ...$keys): self * @throws SyntaxError If the string key is not a valid */ public function append( - string $key, + string $name, iterable|StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): self { if (null === $member) { return $this; } $members = $this->members; - unset($members[$key]); + unset($members[$name]); - return $this->newInstance([...$members, MapKey::from($key)->value => self::filterMember($member)]); + return $this->newInstance([...$members, MapKey::from($name)->value => self::filterMember($member)]); } /** @@ -601,16 +601,16 @@ public function append( * @throws SyntaxError If the string key is not a valid */ public function prepend( - string $key, + string $name, iterable|StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): self { if (null === $member) { return $this; } $members = $this->members; - unset($members[$key]); + unset($members[$name]); - return $this->newInstance([MapKey::from($key)->value => self::filterMember($member), ...$members]); + return $this->newInstance([MapKey::from($name)->value => self::filterMember($member), ...$members]); } /** @@ -719,8 +719,8 @@ public function mergeAssociative(StructuredFieldProvider|iterable ...$others): s $other = $other->toAssociative(); } - foreach ($other as $key => $value) { - $members[$key] = $value; + foreach ($other as $name => $value) { + $members[$name] = $value; } } @@ -742,8 +742,8 @@ public function mergePairs(StructuredFieldProvider|Dictionary|Parameters|iterabl if (!$other instanceof self) { $other = self::fromPairs($other); } - foreach ($other->toAssociative() as $key => $value) { - $members[$key] = $value; + foreach ($other->toAssociative() as $name => $value) { + $members[$name] = $value; } } @@ -755,7 +755,7 @@ public function mergePairs(StructuredFieldProvider|Dictionary|Parameters|iterabl */ public function offsetExists(mixed $offset): bool { - return $this->hasKeys($offset); + return $this->hasNames($offset); } /** @@ -763,7 +763,7 @@ public function offsetExists(mixed $offset): bool */ public function offsetGet(mixed $offset): InnerList|Item { - return $this->getByKey($offset); + return $this->getByName($offset); } public function offsetUnset(mixed $offset): void diff --git a/src/InvalidOffset.php b/src/InvalidOffset.php index 91136db..7376430 100644 --- a/src/InvalidOffset.php +++ b/src/InvalidOffset.php @@ -22,17 +22,17 @@ public static function dueToIndexNotFound(string|int $index): self return new self('No member exists with the index "'.$index.'".'); } - public static function dueToKeyNotFound(string|int $key): self + public static function dueToNameNotFound(string|int $name): self { - if (is_int($key)) { - return new self('The member key can not be the integer "'.$key.'".'); + if (is_int($name)) { + return new self('The member key can not be the integer "'.$name.'".'); } - return new self('No member exists with the key "'.$key.'".'); + return new self('No member exists with the key "'.$name.'".'); } - public static function dueToMemberNotFound(string|int $key): self + public static function dueToMemberNotFound(string|int $offset): self { - return new self('No member exists with the '.(is_int($key) ? 'index' : 'key').' "'.$key.'".'); + return new self('No member exists with the '.(is_int($offset) ? 'index' : 'name').' "'.$offset.'".'); } } diff --git a/src/ParameterAccess.php b/src/ParameterAccess.php index b66be43..f184317 100644 --- a/src/ParameterAccess.php +++ b/src/ParameterAccess.php @@ -34,13 +34,13 @@ public function parameters(): Parameters * * @return SfType|null */ - public function parameterByKey( - string $key, + public function parameterByName( + string $name, ?callable $validate = null, bool|string $required = false, ByteSequence|Token|DisplayString|DateTimeImmutable|string|int|float|bool|null $default = null ): ByteSequence|Token|DisplayString|DateTimeImmutable|string|int|float|bool|null { - return $this->parameters->valueByKey($key, $validate, $required, $default); + return $this->parameters->valueByName($name, $validate, $required, $default); } /** @@ -81,10 +81,10 @@ abstract public function withParameters(Parameters $parameters): static; * @throws SyntaxError If the string key is not a valid */ public function addParameter( - string $key, + string $name, StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): static { - return $this->withParameters($this->parameters()->add($key, $member)); + return $this->withParameters($this->parameters()->add($name, $member)); } /** @@ -98,10 +98,10 @@ public function addParameter( * @throws SyntaxError If the string key is not a valid */ public function prependParameter( - string $key, + string $name, StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): static { - return $this->withParameters($this->parameters()->prepend($key, $member)); + return $this->withParameters($this->parameters()->prepend($name, $member)); } /** @@ -115,10 +115,10 @@ public function prependParameter( * @throws SyntaxError If the string key is not a valid */ public function appendParameter( - string $key, + string $name, StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): static { - return $this->withParameters($this->parameters()->append($key, $member)); + return $this->withParameters($this->parameters()->append($name, $member)); } /** @@ -164,9 +164,9 @@ public function unshiftParameters(array ...$pairs): static * This method MUST retain the state of the current instance, and return * an instance that contains the specified parameter change. */ - public function withoutParameterByKeys(string ...$keys): static + public function withoutParameterByNames(string ...$names): static { - return $this->withParameters($this->parameters()->removeByKeys(...$keys)); + return $this->withParameters($this->parameters()->removeByKeys(...$names)); } /** diff --git a/src/Parameters.php b/src/Parameters.php index f8a17a0..03c90c6 100644 --- a/src/Parameters.php +++ b/src/Parameters.php @@ -43,8 +43,8 @@ final class Parameters implements ArrayAccess, Countable, IteratorAggregate, Str private function __construct(iterable $members = []) { $filteredMembers = []; - foreach ($members as $key => $member) { - $filteredMembers[MapKey::from($key)->value] = self::filterMember($member); + foreach ($members as $name => $member) { + $filteredMembers[MapKey::from($name)->value] = self::filterMember($member); } $this->members = $filteredMembers; @@ -118,8 +118,8 @@ public static function fromPairs(StructuredFieldProvider|iterable $pairs): self $pairs instanceof Parameters, $pairs instanceof Dictionary => new self($pairs->toAssociative()), default => new self((function (iterable $pairs) { - foreach ($pairs as [$key, $member]) { - yield $key => $member; + foreach ($pairs as [$name, $member]) { + yield $name => $member; } })($pairs)), }; @@ -214,7 +214,7 @@ public function getIterator(): Iterator /** * @return array */ - public function keys(): array + public function names(): array { return array_keys($this->members); } @@ -222,15 +222,15 @@ public function keys(): array /** * Tells whether the instance contain a members at the specified offsets. */ - public function hasKeys(string ...$keys): bool + public function hasNames(string ...$names): bool { - foreach ($keys as $key) { - if (!array_key_exists($key, $this->members)) { + foreach ($names as $name) { + if (!array_key_exists($name, $this->members)) { return false; } } - return [] !== $keys; + return [] !== $names; } /** @@ -238,9 +238,9 @@ public function hasKeys(string ...$keys): bool * * @throws Violation|InvalidOffset */ - public function getByKey(string $key, ?callable $validate = null): Item + public function getByName(string $name, ?callable $validate = null): Item { - $value = $this->members[$key] ?? throw InvalidOffset::dueToKeyNotFound($key); + $value = $this->members[$name] ?? throw InvalidOffset::dueToNameNotFound($name); if (null === $validate) { return $value; } @@ -250,10 +250,10 @@ public function getByKey(string $key, ?callable $validate = null): Item } if (!is_string($exceptionMessage) || '' === trim($exceptionMessage)) { - $exceptionMessage = "The parameter '{key}' whose value is '{value}' failed validation."; + $exceptionMessage = "The parameter '{name}' whose value is '{value}' failed validation."; } - throw new Violation(strtr($exceptionMessage, ['{key}' => $key, '{value}' => $value->toHttpValue()])); + throw new Violation(strtr($exceptionMessage, ['{name}' => $name, '{value}' => $value->toHttpValue()])); } /** @@ -261,7 +261,7 @@ public function getByKey(string $key, ?callable $validate = null): Item */ public function indices(): array { - return array_keys($this->keys()); + return array_keys($this->names()); } public function hasIndices(int ...$indices): bool @@ -303,16 +303,16 @@ public function getByIndex(int $index, ?callable $validate = null): array { $foundOffset = $this->filterIndex($index) ?? throw InvalidOffset::dueToIndexNotFound($index); - $validator = function (Item $value, string $key, int $index, callable $validate): array { - if (true === ($exceptionMessage = $validate($value->value(), $key))) { - return [$key, $value]; + $validator = function (Item $value, string $name, int $index, callable $validate): array { + if (true === ($exceptionMessage = $validate($value->value(), $name))) { + return [$name, $value]; } if (!is_string($exceptionMessage) || '' === trim($exceptionMessage)) { - $exceptionMessage = "The parameter at position '{index}' whose name is '{key}' with the value '{value}' failed validation."; + $exceptionMessage = "The parameter at position '{index}' whose name is '{name}' with the value '{value}' failed validation."; } - throw new Violation(strtr($exceptionMessage, ['{index}' => $index, '{key}' => $key, '{value}' => $value->toHttpValue()])); + throw new Violation(strtr($exceptionMessage, ['{index}' => $index, '{name}' => $name, '{value}' => $value->toHttpValue()])); }; foreach ($this as $offset => $pair) { @@ -330,10 +330,10 @@ public function getByIndex(int $index, ?callable $validate = null): array /** * Returns the key associated with the given index or null otherwise. */ - public function indexByKey(string $key): ?int + public function indexByName(string $name): ?int { foreach ($this as $index => $member) { - if ($key === $member[0]) { + if ($name === $member[0]) { return $index; } } @@ -344,7 +344,7 @@ public function indexByKey(string $key): ?int /** * Returns the index associated with the given key or null otherwise. */ - public function keyByIndex(int $index): ?string + public function nameByIndex(int $index): ?string { $index = $this->filterIndex($index); if (null === $index) { @@ -387,17 +387,17 @@ public function last(): array /** * Returns true only if the instance only contains the listed keys, false otherwise. * - * @param array $keys + * @param array $names */ - public function allowedKeys(array $keys): bool + public function allowedNames(array $names): bool { - foreach ($this->members as $key => $member) { - if (!in_array($key, $keys, true)) { + foreach ($this->members as $name => $member) { + if (!in_array($name, $names, true)) { return false; } } - return [] !== $keys; + return [] !== $names; } /** @@ -409,14 +409,14 @@ public function allowedKeys(array $keys): bool * * @return SfType|null */ - public function valueByKey( - string $key, + public function valueByName( + string $name, ?callable $validate = null, bool|string $required = false, ByteSequence|Token|DisplayString|DateTimeImmutable|string|int|float|bool|null $default = null ): ByteSequence|Token|DisplayString|DateTimeImmutable|string|int|float|bool|null { try { - return $this->getByKey($key, $validate)->value(); + return $this->getByName($name, $validate)->value(); } catch (InvalidOffset $exception) { if (false === $required) { return $default; @@ -424,10 +424,10 @@ public function valueByKey( $message = $required; if (!is_string($message) || '' === trim($message)) { - $message = "The required parameter '{key}' is missing."; + $message = "The required parameter '{name}' is missing."; } - throw new Violation(strtr($message, ['{key}' => $key]), previous: $exception); + throw new Violation(strtr($message, ['{name}' => $name]), previous: $exception); } } @@ -447,9 +447,9 @@ public function valueByIndex(int $index, ?callable $validate = null, bool|string [] === $default => [], !array_is_list($default) => throw new SyntaxError('The pair must be represented by an array as a list.'), /* @phpstan-ignore-line */ 2 !== count($default) => throw new SyntaxError('The pair first member is the name; its second member is its value.'), /* @phpstan-ignore-line */ - null === ($key = MapKey::tryFrom($default[0])?->value) => throw new SyntaxError('The pair first member is invalid.'), + null === ($name = MapKey::tryFrom($default[0])?->value) => throw new SyntaxError('The pair first member is invalid.'), null === ($value = Item::tryNew($default[1])?->value()) => throw new SyntaxError('The pair second member is invalid.'), - default => [$key, $value], + default => [$name, $value], }; try { @@ -474,14 +474,14 @@ public function valueByIndex(int $index, ?callable $validate = null, bool|string * @param StructuredFieldProvider|StructuredField|SfType|null $member */ public function add( - string $key, + string $name, StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): self { if (null === $member) { return $this; } $members = $this->members; - $members[MapKey::from($key)->value] = self::filterMember($member); + $members[MapKey::from($name)->value] = self::filterMember($member); return $this->newInstance($members); } @@ -497,21 +497,21 @@ private function newInstance(array $members): self }; } - private function remove(string|int ...$keys): self + private function remove(string|int ...$names): self { - if ([] === $this->members || [] === $keys) { + if ([] === $this->members || [] === $names) { return $this; } $offsets = array_keys($this->members); $max = count($offsets); - $reducer = fn (array $carry, string|int $key): array => match (true) { - is_string($key) && (false !== ($position = array_search($key, $offsets, true))), - is_int($key) && (null !== ($position = $this->filterIndex($key, $max))) => [$position => true] + $carry, + $reducer = fn (array $carry, string|int $name): array => match (true) { + is_string($name) && (false !== ($position = array_search($name, $offsets, true))), + is_int($name) && (null !== ($position = $this->filterIndex($name, $max))) => [$position => true] + $carry, default => $carry, }; - $indices = array_reduce($keys, $reducer, []); + $indices = array_reduce($names, $reducer, []); return match (true) { [] === $indices => $this, @@ -531,16 +531,16 @@ public function removeByIndices(int ...$indices): self return $this->remove(...$indices); } - public function removeByKeys(string ...$keys): self + public function removeByKeys(string ...$names): self { - return $this->remove(...$keys); + return $this->remove(...$names); } /** * @param StructuredFieldProvider|StructuredField|SfType|null $member */ public function append( - string $key, + string $name, StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): self { if (null === $member) { @@ -548,25 +548,25 @@ public function append( } $members = $this->members; - unset($members[$key]); + unset($members[$name]); - return $this->newInstance([...$members, MapKey::from($key)->value => self::filterMember($member)]); + return $this->newInstance([...$members, MapKey::from($name)->value => self::filterMember($member)]); } /** * @param StructuredFieldProvider|StructuredField|SfType|null $member */ public function prepend( - string $key, + string $name, StructuredFieldProvider|StructuredField|Token|ByteSequence|DisplayString|DateTimeInterface|string|int|float|bool|null $member ): self { if (null === $member) { return $this; } $members = $this->members; - unset($members[$key]); + unset($members[$name]); - return $this->newInstance([MapKey::from($key)->value => self::filterMember($member), ...$members]); + return $this->newInstance([MapKey::from($name)->value => self::filterMember($member), ...$members]); } /** @@ -650,8 +650,8 @@ public function mergeAssociative(StructuredFieldProvider|iterable ...$others): s $other = $other->toAssociative(); } - foreach ($other as $key => $value) { - $members[$key] = $value; + foreach ($other as $name => $value) { + $members[$name] = $value; } } @@ -668,8 +668,8 @@ public function mergePairs(Dictionary|Parameters|StructuredFieldProvider|iterabl if (!$other instanceof self) { $other = self::fromPairs($other); } - foreach ($other->toAssociative() as $key => $value) { - $members[$key] = $value; + foreach ($other->toAssociative() as $name => $value) { + $members[$name] = $value; } } @@ -681,7 +681,7 @@ public function mergePairs(Dictionary|Parameters|StructuredFieldProvider|iterabl */ public function offsetExists(mixed $offset): bool { - return $this->hasKeys($offset); + return $this->hasNames($offset); } /** @@ -689,7 +689,7 @@ public function offsetExists(mixed $offset): bool */ public function offsetGet(mixed $offset): Item { - return $this->getByKey($offset); + return $this->getByName($offset); } public function offsetUnset(mixed $offset): void diff --git a/src/Parser.php b/src/Parser.php index 882d95c..b3ae30b 100644 --- a/src/Parser.php +++ b/src/Parser.php @@ -161,13 +161,13 @@ public function parseDictionary(Stringable|string $httpValue): array $map = []; $remainder = ltrim((string) $httpValue, ' '); while ('' !== $remainder) { - $key = MapKey::fromStringBeginning($remainder)->value; - $remainder = substr($remainder, strlen($key)); + $name = MapKey::fromStringBeginning($remainder)->value; + $remainder = substr($remainder, strlen($name)); if ('' === $remainder || '=' !== $remainder[0]) { $remainder = '=?1'.$remainder; } - [$map[$key], $offset] = $this->extractItemOrInnerList(substr($remainder, 1)); + [$map[$name], $offset] = $this->extractItemOrInnerList(substr($remainder, 1)); $remainder = self::removeCommaSeparatedWhiteSpaces($remainder, ++$offset); } @@ -343,12 +343,12 @@ private function extractParametersValues(Stringable|string $httpValue): array $remainder = $httpValue; while ('' !== $remainder && ';' === $remainder[0]) { $remainder = ltrim(substr($remainder, 1), ' '); - $key = MapKey::fromStringBeginning($remainder)->value; - $map[$key] = true; - $remainder = substr($remainder, strlen($key)); + $name = MapKey::fromStringBeginning($remainder)->value; + $map[$name] = true; + $remainder = substr($remainder, strlen($name)); if ('' !== $remainder && '=' === $remainder[0]) { $remainder = substr($remainder, 1); - [$map[$key], $offset] = $this->extractValue($remainder); + [$map[$name], $offset] = $this->extractValue($remainder); $remainder = substr($remainder, $offset); } } diff --git a/src/Validation/ParametersValidator.php b/src/Validation/ParametersValidator.php index 76c0d07..7d03edc 100644 --- a/src/Validation/ParametersValidator.php +++ b/src/Validation/ParametersValidator.php @@ -116,7 +116,7 @@ public function validate(Parameters|Stringable|string $parameters): Result if ([] !== $this->filterConstraints) { $parsedParameters = match ($this->type) { self::USE_INDICES => $this->validateByIndices($parameters), - default => $this->validateByKeys($parameters), + default => $this->validateByNames($parameters), }; if ($parsedParameters->isFailed()) { @@ -169,19 +169,19 @@ private function validateByCriteria(Parameters $parameters): bool|string * * @return Result|Result */ - private function validateByKeys(Parameters $parameters): Result /* @phpstan-ignore-line */ + private function validateByNames(Parameters $parameters): Result /* @phpstan-ignore-line */ { $data = []; $violations = new ViolationList(); /** - * @var string $key + * @var string $name * @var SfParameterKeyRule $rule */ - foreach ($this->filterConstraints as $key => $rule) { + foreach ($this->filterConstraints as $name => $rule) { try { - $data[$key] = $parameters->valueByKey($key, $rule['validate'] ?? null, $rule['required'] ?? false, $rule['default'] ?? null); + $data[$name] = $parameters->valueByName($name, $rule['validate'] ?? null, $rule['required'] ?? false, $rule['default'] ?? null); } catch (Violation $exception) { - $violations[$key] = $exception; + $violations[$name] = $exception; } } diff --git a/tests/DictionaryTest.php b/tests/DictionaryTest.php index 1745bdd..d4eeada 100644 --- a/tests/DictionaryTest.php +++ b/tests/DictionaryTest.php @@ -24,9 +24,9 @@ public function it_can_be_instantiated_with_an_collection_of_item_or_inner_list( self::assertSame(['string', $stringItem], $instance->getByIndex(0)); - self::assertSame($stringItem, $instance->getByKey('string')); - self::assertTrue($instance->hasKeys('string', 'string')); - self::assertFalse($instance->hasKeys('string', 'no-present')); + self::assertSame($stringItem, $instance->getByName('string')); + self::assertTrue($instance->hasNames('string', 'string')); + self::assertFalse($instance->hasNames('string', 'no-present')); self::assertEquals([['string', $stringItem], ['boolean', $booleanItem]], [...$instance->getIterator()]); self::assertEquals($arrayParams, [...$instance->toAssociative()]); } @@ -40,8 +40,8 @@ public function it_can_be_instantiated_with_key_value_pairs(): void $instance = Dictionary::fromPairs($arrayParams); self::assertSame(['string', $stringItem], $instance->getByIndex(0)); - self::assertSame($stringItem, $instance->getByKey('string')); - self::assertTrue($instance->hasKeys('string')); + self::assertSame($stringItem, $instance->getByName('string')); + self::assertTrue($instance->hasNames('string')); self::assertEquals($arrayParams, [...$instance->getIterator()]); self::assertEquals(['string' => $stringItem, 'boolean' => $booleanItem], [...$instance->toAssociative()]); } @@ -58,10 +58,10 @@ public function it_can_add_or_remove_members(): void self::assertTrue($instance->isNotEmpty()); self::assertFalse($instance->isEmpty()); - $deletedInstance = $instance->removeByKeys('boolean'); + $deletedInstance = $instance->removeByNames('boolean'); self::assertCount(1, $deletedInstance); - self::assertFalse($deletedInstance->hasKeys('boolean')); + self::assertFalse($deletedInstance->hasNames('boolean')); self::assertFalse($deletedInstance->hasIndices(1)); $appendInstance = $deletedInstance->append('foobar', Item::new('BarBaz')); @@ -75,7 +75,7 @@ public function it_can_add_or_remove_members(): void self::assertIsString($foundItem[1]->value()); self::assertStringContainsString('BarBaz', $foundItem[1]->value()); - $deleteAgain = $appendInstance->removeByKeys('foobar', 'string'); + $deleteAgain = $appendInstance->removeByNames('foobar', 'string'); self::assertCount(0, $deleteAgain); self::assertFalse($deleteAgain->isNotEmpty()); @@ -86,7 +86,7 @@ public function it_returns_the_same_object_if_no_member_is_removed(): void { $instance = Dictionary::new(); - self::assertSame($instance, $instance->removeByKeys('foo', 'bar', 'baz')); + self::assertSame($instance, $instance->removeByNames('foo', 'bar', 'baz')); } #[Test] @@ -94,11 +94,11 @@ public function it_fails_to_return_an_member_with_invalid_key(): void { $instance = Dictionary::new(); - self::assertFalse($instance->hasKeys('foobar')); + self::assertFalse($instance->hasNames('foobar')); $this->expectException(InvalidOffset::class); - $instance->getByKey('foobar'); + $instance->getByName('foobar'); } #[Test] @@ -154,13 +154,13 @@ public function it_can_returns_the_container_member_keys(): void { $instance = Dictionary::new(); - self::assertSame([], $instance->keys()); + self::assertSame([], $instance->names()); $newInstance = $instance ->append('a', Item::false()) ->prepend('b', Item::true()); - self::assertSame(['b', 'a'], $newInstance->keys()); + self::assertSame(['b', 'a'], $newInstance->names()); } #[Test] @@ -173,8 +173,8 @@ public function it_can_merge_one_or_more_instances_using_associative(): void $instance4 = $instance1->mergeAssociative($instance2, $instance3); self::assertCount(2, $instance4); - self::assertEquals(Item::new(42), $instance4->getByKey('a')); - self::assertEquals(Item::true(), $instance4->getByKey('b')); + self::assertEquals(Item::new(42), $instance4->getByName('a')); + self::assertEquals(Item::true(), $instance4->getByName('b')); } #[Test] @@ -187,8 +187,8 @@ public function it_can_merge_two_or_more_instances_to_yield_different_result(): $instance4 = $instance3->mergeAssociative($instance2, $instance1); self::assertCount(2, $instance4); - self::assertEquals(Item::false(), $instance4->getByKey('a')); - self::assertEquals(Item::true(), $instance4->getByKey('b')); + self::assertEquals(Item::false(), $instance4->getByName('a')); + self::assertEquals(Item::true(), $instance4->getByName('b')); } #[Test] @@ -208,8 +208,8 @@ public function it_can_merge_one_or_more_instances_using_pairs(): void self::assertCount(2, $instance4); - self::assertEquals(Item::false(), $instance4->getByKey('a')); - self::assertEquals(Item::true(), $instance4->getByKey('b')); + self::assertEquals(Item::false(), $instance4->getByName('a')); + self::assertEquals(Item::true(), $instance4->getByName('b')); } #[Test] @@ -257,8 +257,8 @@ public function it_can_delete_a_member_via_remove_method(): void self::assertCount(1, $newInstance2); self::assertSame($newInstance, $newInstance2); - self::assertFalse($newInstance->removeByKeys('foo')->isNotEmpty()); - self::assertSame($newInstance, $newInstance->removeByKeys('baz', 'bar', 'yolo-not-there')); + self::assertFalse($newInstance->removeByNames('foo')->isNotEmpty()); + self::assertSame($newInstance, $newInstance->removeByNames('baz', 'bar', 'yolo-not-there')); self::assertSame($newInstance, $newInstance->removeByIndices(325)); $instanceWithoutMember = Dictionary::new(); @@ -277,8 +277,8 @@ public function it_can_access_the_item_value(): void ['token', $token], ]); - self::assertInstanceOf(Item::class, $structuredField->getByKey('false')); - self::assertFalse($structuredField->getByKey('false')->value()); + self::assertInstanceOf(Item::class, $structuredField->getByName('false')); + self::assertFalse($structuredField->getByName('false')->value()); } #[Test] @@ -293,10 +293,10 @@ public function it_implements_the_array_access_interface(): void ['token', $token], ]); - self::assertInstanceOf(Item::class, $structuredField->getByKey('false')); + self::assertInstanceOf(Item::class, $structuredField->getByName('false')); self::assertInstanceOf(Item::class, $structuredField['false']); - self::assertFalse($structuredField->getByKey('false')->value()); + self::assertFalse($structuredField->getByName('false')->value()); self::assertFalse($structuredField['false']->value()); self::assertFalse(isset($structuredField['toto'])); } @@ -322,8 +322,8 @@ public function it_can_returns_the_container_member_keys_with_pairs(): void { $instance = Dictionary::new(); - self::assertSame([], $instance->keys()); - self::assertSame(['a', 'b'], $instance->push(['a', false], ['b', true])->keys()); + self::assertSame([], $instance->names()); + self::assertSame(['a', 'b'], $instance->push(['a', false], ['b', true])->names()); $container = Dictionary::new() ->unshift(['a', '42']) @@ -331,7 +331,7 @@ public function it_can_returns_the_container_member_keys_with_pairs(): void ->insert(1, ['c', 42.0]) ->replace(0, ['d', 'forty-two']); - self::assertSame(['d', 'c', 'b'], $container->keys()); + self::assertSame(['d', 'c', 'b'], $container->names()); self::assertSame('d="forty-two", c=42.0, b=42', $container->toHttpValue()); } @@ -391,7 +391,7 @@ public function toStructuredField(): Item ->push(['a', true], ['v', ByteSequence::fromDecoded('I will be removed')], ['c', 'true']) ->unshift(['b', $instance]) ->replace(1, ['a', 'false']) - ->removeByKeys('toto') + ->removeByNames('toto') ->removeByIndices(-2) ->insert(1, ['d', Token::fromString('*/*')]); @@ -412,10 +412,10 @@ public function it_can_detect_the_member_keys_and_indices(): void ->prepend('b', Item::true()) ->push(['c', Item::fromToken('blablabla')]); - self::assertSame(2, $instance->indexByKey('c')); - self::assertSame(0, $instance->indexByKey('b')); - self::assertNull($instance->indexByKey('foobar')); - self::assertSame('c', $instance->keyByIndex(-1)); - self::assertNull($instance->keyByIndex(23)); + self::assertSame(2, $instance->indexByName('c')); + self::assertSame(0, $instance->indexByName('b')); + self::assertNull($instance->indexByName('foobar')); + self::assertSame('c', $instance->nameByIndex(-1)); + self::assertNull($instance->nameByIndex(23)); } } diff --git a/tests/InnerListTest.php b/tests/InnerListTest.php index c3a925b..57b3b72 100644 --- a/tests/InnerListTest.php +++ b/tests/InnerListTest.php @@ -130,10 +130,10 @@ public function it_can_access_its_parameter_values(): void { $instance = InnerList::fromAssociative([false], ['foo' => 'bar']); - self::assertSame('bar', $instance->parameters()->getByKey('foo')->value()); - self::assertSame('bar', $instance->parameterByKey('foo')); + self::assertSame('bar', $instance->parameters()->getByName('foo')->value()); + self::assertSame('bar', $instance->parameterByName('foo')); self::assertSame(['foo', 'bar'], $instance->parameterByIndex(0)); - self::assertNull($instance->parameterByKey('non-existing-key')); + self::assertNull($instance->parameterByName('non-existing-key')); self::assertSame([], $instance->parameterByIndex(42)); } @@ -142,7 +142,7 @@ public function it_fails_to_access_unknown_parameter_values(): void { $this->expectException(StructuredFieldError::class); - InnerList::new(false)->parameters()->getByKey('bar')->value(); + InnerList::new(false)->parameters()->getByName('bar')->value(); } #[Test] @@ -152,11 +152,11 @@ public function it_successfully_parse_a_http_field(): void self::assertCount(3, $instance); self::assertCount(1, $instance->parameters()); - self::assertSame('bar(', $instance->parameters()->getByKey('foo')->value()); + self::assertSame('bar(', $instance->parameters()->getByName('foo')->value()); self::assertSame('hello)world', $instance->getByIndex(0)->value()); self::assertSame(42, $instance->getByIndex(1)->value()); self::assertSame(42.0, $instance->getByIndex(2)->value()); - self::assertEquals(Token::fromString('doe'), $instance->getByIndex(2)->parameters()->getByKey('john')->value()); + self::assertEquals(Token::fromString('doe'), $instance->getByIndex(2)->parameters()->getByName('john')->value()); } #[Test] @@ -254,8 +254,8 @@ public function it_can_create_via_parameters_access_methods_a_new_object(): void $instance2 = $instance1->appendParameter('a', true); $instance7 = $instance1->addParameter('a', true); $instance3 = $instance1->prependParameter('a', false); - $instance4 = $instance1->withoutParameterByKeys('b'); - $instance5 = $instance1->withoutParameterByKeys('a'); + $instance4 = $instance1->withoutParameterByNames('b'); + $instance5 = $instance1->withoutParameterByNames('a'); $instance6 = $instance1->withoutAnyParameter(); self::assertSame($instance1, $instance2); @@ -265,8 +265,8 @@ public function it_can_create_via_parameters_access_methods_a_new_object(): void self::assertSame($instance1, $instance4); self::assertFalse($instance5->parameters()->isNotEmpty()); self::assertTrue($instance6->parameters()->isEmpty()); - self::assertTrue($instance1->parameterByKey('a')); - self::assertNull($instance5->parameterByKey('a')); + self::assertTrue($instance1->parameterByName('a')); + self::assertNull($instance5->parameterByName('a')); } #[Test] diff --git a/tests/ItemTest.php b/tests/ItemTest.php index 343937c..a5e8acb 100644 --- a/tests/ItemTest.php +++ b/tests/ItemTest.php @@ -342,8 +342,8 @@ public function it_can_access_its_parameter_values(): void { $instance = Item::fromHttpValue('1; a; b=?0'); - self::assertTrue($instance->parameters()->getByKey('a')->value()); - self::assertFalse($instance->parameters()->getByKey('b')->value()); + self::assertTrue($instance->parameters()->getByName('a')->value()); + self::assertFalse($instance->parameters()->getByName('b')->value()); } #[Test] @@ -351,7 +351,7 @@ public function it_fails_to_access_unknown_parameter_values(): void { $this->expectException(StructuredFieldError::class); - Item::fromHttpValue('1; a; b=?0')->parameters()->getByKey('bar')->value(); + Item::fromHttpValue('1; a; b=?0')->parameters()->getByName('bar')->value(); } #[Test] @@ -434,8 +434,8 @@ public function it_can_create_via_parameters_access_methods_a_new_object(): void $instance7 = $instance1->addParameter('a', true); $instance2 = $instance1->appendParameter('a', true); $instance3 = $instance1->prependParameter('a', false); - $instance4 = $instance1->withoutParameterByKeys('b'); - $instance5 = $instance1->withoutParameterByKeys('a'); + $instance4 = $instance1->withoutParameterByNames('b'); + $instance5 = $instance1->withoutParameterByNames('a'); $instance6 = $instance1->withoutAnyParameter(); self::assertSame($instance1, $instance2); @@ -443,12 +443,12 @@ public function it_can_create_via_parameters_access_methods_a_new_object(): void self::assertNotSame($instance1, $instance3); self::assertEquals($instance1->value(), $instance3->value()); self::assertSame($instance1, $instance4); - self::assertTrue($instance1->parameterByKey('a')); + self::assertTrue($instance1->parameterByName('a')); self::assertSame(['a', true], $instance1->parameterByIndex(0)); - self::assertNull($instance5->parameterByKey('a')); + self::assertNull($instance5->parameterByName('a')); self::assertTrue($instance5->parameters()->isEmpty()); self::assertTrue($instance6->parameters()->isEmpty()); - self::assertNull($instance1->parameterByKey('non-existing-key')); + self::assertNull($instance1->parameterByName('non-existing-key')); self::assertSame([], $instance1->parameterByIndex(42)); } @@ -504,9 +504,9 @@ public function it_can_validate_and_trigger_a_default_message_on_error(): void public function it_can_validate_the_item_parameter_value(): void { $item = Item::fromAssociative(Token::fromString('babayaga'), ['a' => true]); - self::assertTrue($item->parameterByKey('a')); - self::assertTrue($item->parameterByKey('a', fn (mixed $value) => true)); - self::assertFalse($item->parameterByKey(key: 'b', default: false)); + self::assertTrue($item->parameterByName('a')); + self::assertTrue($item->parameterByName('a', fn (mixed $value) => true)); + self::assertFalse($item->parameterByName(name: 'b', default: false)); } #[Test] @@ -516,7 +516,7 @@ public function it_can_validate_and_trigger_a_custom_error_message(): void $this->expectExceptionObject(new Violation('The exception has been triggered')); - $item->parameterByKey(key: 'a', validate:fn (mixed $value): string => 'The exception has been triggered'); + $item->parameterByName(name: 'a', validate:fn (mixed $value): string => 'The exception has been triggered'); } #[Test] @@ -526,7 +526,7 @@ public function it_can_validate_and_trigger_an_error_message_for_missing_paramet $this->expectExceptionObject(new Violation("The required parameter 'b' is missing.")); - $item->parameterByKey(key: 'b', required: true); + $item->parameterByName(name: 'b', required: true); } #[Test] @@ -536,7 +536,7 @@ public function it_can_validate_and_trigger_a_default_error_message(): void $this->expectExceptionObject(new Violation("The parameter 'a' whose value is '?1' failed validation.")); - $item->parameterByKey(key: 'a', validate:fn (mixed $value): bool => false); + $item->parameterByName(name: 'a', validate:fn (mixed $value): bool => false); } #[Test] diff --git a/tests/ParametersTest.php b/tests/ParametersTest.php index 221142c..9414293 100644 --- a/tests/ParametersTest.php +++ b/tests/ParametersTest.php @@ -26,9 +26,9 @@ public function it_can_be_instantiated_with_an_collection_of_item(): void $instance = Parameters::fromAssociative($arrayParams); self::assertSame(['string', $stringItem], $instance->getByIndex(0)); - self::assertTrue($instance->hasKeys('string', 'string')); - self::assertSame($stringItem, $instance->getByKey('string')); - self::assertTrue($instance->hasKeys('string')); + self::assertTrue($instance->hasNames('string', 'string')); + self::assertSame($stringItem, $instance->getByName('string')); + self::assertTrue($instance->hasNames('string')); self::assertEquals(['string' => $stringItem, 'boolean' => $booleanItem], [...$instance->toAssociative()]); } @@ -42,8 +42,8 @@ public function test_it_can_be_instantiated_with_key_value_pairs(): void $instance = Parameters::fromPairs($arrayParams); self::assertSame(['string', $stringItem], $instance->getByIndex(0)); - self::assertSame($stringItem, $instance->getByKey('string')); - self::assertTrue($instance->hasKeys('string')); + self::assertSame($stringItem, $instance->getByName('string')); + self::assertTrue($instance->hasNames('string')); self::assertEquals( [['string', $stringItem], ['boolean', $booleanItem]], [...$instance] @@ -96,7 +96,7 @@ public function it_can_add_or_remove_members(): void $deletedInstance = $instance->removeByKeys('boolean'); self::assertCount(1, $deletedInstance); - self::assertFalse($deletedInstance->hasKeys('boolean')); + self::assertFalse($deletedInstance->hasNames('boolean')); self::assertFalse($deletedInstance->hasIndices(1)); $instance = new class () implements StructuredFieldProvider { @@ -151,10 +151,10 @@ public function it_fails_to_return_an_member_with_invalid_key(): void $instance = Parameters::new(); - self::assertFalse($instance->hasKeys('foobar', 'barbaz')); - self::assertFalse($instance->hasKeys()); + self::assertFalse($instance->hasNames('foobar', 'barbaz')); + self::assertFalse($instance->hasNames()); - $instance->getByKey('foobar'); + $instance->getByName('foobar'); } #[Test] @@ -204,8 +204,8 @@ public function it_can_returns_the_container_member_keys_with_pairs(): void { $instance = Parameters::new(); - self::assertSame([], $instance->keys()); - self::assertSame(['a', 'b'], $instance->push(['a', false], ['b', true])->keys()); + self::assertSame([], $instance->names()); + self::assertSame(['a', 'b'], $instance->push(['a', false], ['b', true])->names()); $container = Parameters::new() ->unshift(['a', '42']) @@ -213,7 +213,7 @@ public function it_can_returns_the_container_member_keys_with_pairs(): void ->insert(1, ['c', 42.0]) ->replace(0, ['d', 'forty-two']); - self::assertSame(['d', 'c', 'b'], $container->keys()); + self::assertSame(['d', 'c', 'b'], $container->names()); self::assertSame(';d="forty-two";c=42.0;b=42', $container->toHttpValue()); } @@ -244,13 +244,13 @@ public function it_can_returns_the_container_member_keys(): void { $instance = Parameters::new(); - self::assertSame([], $instance->keys()); + self::assertSame([], $instance->names()); $newInstance = Parameters::new() ->append('a', Item::false()) ->prepend('b', Item::true()); - self::assertSame(['b', 'a'], $newInstance->keys()); + self::assertSame(['b', 'a'], $newInstance->names()); } #[Test] @@ -262,8 +262,8 @@ public function it_can_merge_one_or_more_instances(): void $instance4 = $instance1->mergeAssociative($instance2, $instance3); - self::assertEquals(Item::fromInteger(42), $instance4->getByKey('a')); - self::assertEquals(Item::true(), $instance4->getByKey('b')); + self::assertEquals(Item::fromInteger(42), $instance4->getByName('a')); + self::assertEquals(Item::true(), $instance4->getByName('b')); } #[Test] @@ -275,8 +275,8 @@ public function it_can_merge_two_or_more_dictionaries_different_result(): void $instance4 = $instance3->mergeAssociative($instance2, $instance1); - self::assertEquals(Item::false(), $instance4->getByKey('a')); - self::assertEquals(Item::true(), $instance4->getByKey('b')); + self::assertEquals(Item::false(), $instance4->getByName('a')); + self::assertEquals(Item::true(), $instance4->getByName('b')); } #[Test] @@ -297,8 +297,8 @@ public function it_can_merge_one_or_more_instances_using_pairs(): void $instance4 = $instance3->mergePairs($instance2, $instance1); self::assertCount(2, $instance4); - self::assertEquals(Item::false(), $instance4->getByKey('a')); - self::assertEquals(Item::true(), $instance4->getByKey('b')); + self::assertEquals(Item::false(), $instance4->getByName('a')); + self::assertEquals(Item::true(), $instance4->getByName('b')); } #[Test] @@ -327,7 +327,7 @@ public function it_can_return_bare_items_values(): void 'boolean' => Item::true(), ]); - self::assertSame('helloWorld', $instance->getByKey('string')->value()); + self::assertSame('helloWorld', $instance->getByName('string')->value()); } #[Test] @@ -380,9 +380,9 @@ public function it_implements_the_array_access_interface(): void ['token', $token], ]); - self::assertSame($structuredField->getByKey('false'), $structuredField['false']); + self::assertSame($structuredField->getByName('false'), $structuredField['false']); - self::assertFalse($structuredField->getByKey('false')->value()); + self::assertFalse($structuredField->getByName('false')->value()); self::assertFalse($structuredField['false']->value()); self::assertFalse(isset($structuredField['toto'])); } @@ -411,10 +411,10 @@ public function it_can_detect_the_member_keys_and_indices(): void ->prepend('b', Item::true()) ->push(['c', Item::fromToken('blablabla')]); - self::assertSame(2, $instance->indexByKey('c')); - self::assertSame(0, $instance->indexByKey('b')); - self::assertNull($instance->indexByKey('foobar')); - self::assertSame('c', $instance->keyByIndex(-1)); - self::assertNull($instance->keyByIndex(23)); + self::assertSame(2, $instance->indexByName('c')); + self::assertSame(0, $instance->indexByName('b')); + self::assertNull($instance->indexByName('foobar')); + self::assertSame('c', $instance->nameByIndex(-1)); + self::assertNull($instance->nameByIndex(23)); } } diff --git a/tests/Validation/ItemValidatorTest.php b/tests/Validation/ItemValidatorTest.php index 675c67a..5c36e26 100644 --- a/tests/Validation/ItemValidatorTest.php +++ b/tests/Validation/ItemValidatorTest.php @@ -52,7 +52,7 @@ public function it_will_fail_validating_missing_parameters_when_the_item_has_som $item = Item::fromString('foo')->addParameter('foo', 'bar'); $validation = $this->validator ->value(fn (mixed $value): bool => true) - ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedKeys(ErrorCode::list()))) + ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedNames(ErrorCode::list()))) ->validate($item); self::assertTrue($validation->isFailed()); @@ -66,7 +66,7 @@ public function it_will_successfully_validating_missing_parameters_when_the_item $item = Item::fromString('foo'); $validation = $this->validator ->value(fn (mixed $value): bool => true) - ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedKeys(ErrorCode::list()))) + ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedNames(ErrorCode::list()))) ->validate($item); self::assertTrue($validation->isSuccess()); @@ -78,7 +78,7 @@ public function it_will_succeed_validating_allowed_parameters_and_returns_all_pa $item = Item::fromPair(['foo', [['foo', 1], ['bar', 2]]]); $validation = $this->validator ->value(fn (mixed $value): bool => true) - ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedKeys(['foo', 'bar']))) + ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedNames(['foo', 'bar']))) ->validate($item); self::assertFalse($validation->isFailed()); @@ -93,7 +93,7 @@ public function it_will_succeed_validating_allowed_parameters_and_returns_all_pa $item = Item::fromPair(['foo', [['foo', 1], ['bar', 2]]]); $validation = $this->validator ->value(fn (mixed $value): bool => true) - ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedKeys(['foo', 'bar']), ParametersValidator::USE_INDICES)) + ->parameters(ParametersValidator::new()->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedNames(['foo', 'bar']), ParametersValidator::USE_INDICES)) ->validate($item); self::assertTrue($validation->isSuccess()); @@ -106,7 +106,7 @@ public function it_will_succeed_validating_allowed_parameters_and_returns_all_pa public function it_will_fail_validating_parameters_by_keys(): void { $parametersValidator = ParametersValidator::new() - ->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedKeys(['foo', 'bar']), ParametersValidator::USE_INDICES) + ->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedNames(['foo', 'bar']), ParametersValidator::USE_INDICES) ->filterByKeys([ 'foo' => ['validate' => fn (mixed $value): bool => false], 'bar' => ['validate' => fn (mixed $value): bool => true], @@ -127,7 +127,7 @@ public function it_will_fail_validating_parameters_by_keys(): void public function it_will_succeed_validating_parameters_by_keys_and_override_parameters_validator_return(): void { $parametersValidator = ParametersValidator::new() - ->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedKeys(['foo', 'bar']), ParametersValidator::USE_INDICES) + ->filterByCriteria(fn (Parameters $parameters) => $parameters->allowedNames(['foo', 'bar']), ParametersValidator::USE_INDICES) ->filterByIndices([ 1 => ['validate' => fn (mixed $value, string $key): bool => true], ]);