On Thu, Jan 25, 2018 at 9:52 AM, Derick Rethans <der...@php.net> wrote:

> On Wed, 24 Jan 2018, Michael Morris wrote:
>
> > Ok, here's another idea I've been mulling over. This I know is possible
> > because I've done it using user land code, specifically Drupal 8's
> > Assertion\Inspector class.
> >
> > https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Comp
> onent%21Assertion%21Inspector.php/class/Inspector/8.5.x
> >
> > These methods provide a means to inspect collections - arrays usually but
> > also Traversables. They fill a hole in the PHP library - the ability to
> > check collection integrity.
>
> IMO, it makes a lot more sense to check integrity when creating the
> "array" structure. Instead, I would suggest to add a native Collection
> type, that takes a "type" as argument. They aren't quite full generics,
> but it does 1. fix something; 2. isn't really complicated.
>
> What I am suggesting is to add a new syntax "Collection<$type>",
> mimicking a class, but having a type as "argument":
>
> $a = new Collection<integer>;
>
> And then $a can act as if you'd use an ArrayAccess'ed class.
> Upon each set or update, the type of the value can then be checked
> against the type.
>

Agreed, and we can get *almost* there today with:

$collection = collection_of('is_int', [ 1, 2 ]);
$collection[] = M_PI; // exception thrown

given:

function collection_of(callable $validator, $input = []) {
    $collection = new class($input) extends \ArrayObject {
        public function offsetSet($index, $value) {
            if (($this->validator)($value)) return
parent::offsetSet($index, $value);
            throw new \DomainException;
        }
    };
    $collection->validator = $validator;
    foreach ($input as $key => $value) $collection[$key] = $value;
    return $collection;
}



> Consequently, this would also mean you can type hint on Collection<type>
> instead of for example an earlier suggested array of type, where upon
> passing in the array each member was checked for its type (slow).
>

Regrettably, class_alias cannot quite work here, because the validator is
passed at run-time, so making this part of the language seems a good place
to go.

Cheers,
bishop

Reply via email to