Created
August 3, 2022 14:41
-
-
Save Shipu/b37a10fdf598e326a51e4f66c5c6fe1d to your computer and use it in GitHub Desktop.
Support TypedArrayObject in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Tinker away! | |
Class YourClassName | |
{ | |
public string $name; | |
} | |
abstract class TypedArrayObject extends ArrayObject | |
{ | |
abstract public function className(): string; | |
public function __construct(array $array = []) | |
{ | |
if(!empty($array) && count(array_filter($array, function ($entry) { | |
$className = $this->className(); | |
return !($entry instanceof $className); | |
})) > 0) { | |
throw new \InvalidArgumentException('Value must be an instance of '.(string) $this->className()); | |
} | |
parent::__construct($array, \ArrayObject::ARRAY_AS_PROPS); | |
} | |
public function offsetSet($key, $value): void | |
{ | |
if (!($value instanceof YourClassName)) { | |
throw new \InvalidArgumentException('Value must be an instance of YourClassName'); | |
} | |
parent::offsetSet($key, $value); | |
} | |
} | |
Class ArrayOfYourClassName extends TypedArrayObject | |
{ | |
public function className(): string | |
{ | |
return YourClassName::class; | |
} | |
} | |
Class AnotherClassWhereImplementingArrayOfClassA | |
{ | |
public ArrayOfYourClassName $arrayOfClassA; | |
} | |
// Valid Case | |
$a = new YourClassName(); | |
$a->name = "John Doe"; | |
$b = new AnotherClassWhereImplementingArrayOfClassA(); | |
// style one | |
$b->arrayOfClassA = new ArrayOfYourClassName([$a]); | |
// style two | |
$c = new ArrayOfYourClassName(); | |
$c[] = $a; | |
$b->arrayOfClassA = $c; | |
var_dump($b->arrayOfClassA[0]->name); | |
// Invalid Case | |
$a = new YourClassName(); | |
$a->name = "John Doe"; | |
$b = new AnotherClassWhereImplementingArrayOfClassA(); | |
// style one | |
$b->arrayOfClassA = new ArrayOfYourClassName([$a, "ok"]); | |
// style two | |
$c = new ArrayOfYourClassName(); | |
$c[] = $a; | |
$c[] = "ok"; | |
$b->arrayOfClassA = $c; | |
var_dump($b->arrayOfClassA[0]->name); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment