1 | <?php |
||
13 | trait Boxable |
||
14 | { |
||
15 | /** |
||
16 | * Address to pointer in Memory::collection. |
||
17 | * |
||
18 | * @var string |
||
19 | */ |
||
20 | private $memoryAddress = null; |
||
21 | |||
22 | /** |
||
23 | * Boxes a variable to a specific type, including future reassignment as a primitive. |
||
24 | * Optionally takes value or instance of the variable. |
||
25 | * If more than one argument should be passed to constructor, then an instance should be passed explicitly instead |
||
26 | * of a primitive for $value argument. |
||
27 | * |
||
28 | * For examples please view the example.php file. |
||
29 | * |
||
30 | * @param null &$pointer Anmpty variable to box (the pointer) |
||
31 | * @param mixed $value the primitive value to pass the constructor OR an instance of the type |
||
32 | * |
||
33 | * @throws \LogicException when the pointer has previously been declared |
||
34 | * @throws \LogicException when the pointer has previously been declared |
||
35 | * @throws \TypeError when an invalid argument is passed as value or assigned to pointer |
||
36 | */ |
||
37 | 58 | final public static function box(&$pointer, $value = null) |
|
38 | { |
||
39 | 58 | if ($pointer !== null) { |
|
40 | 6 | throw new \LogicException( |
|
41 | 6 | sprintf( |
|
42 | 'The identifier of type %s is defined more than once. '. |
||
43 | 6 | 'First argument of %s() must be null or undefined.', |
|
44 | 6 | gettype($pointer), |
|
45 | 6 | __METHOD__ |
|
46 | ) |
||
47 | ); |
||
48 | } |
||
49 | |||
50 | try { |
||
51 | 52 | if ($value instanceof static) { |
|
52 | 9 | $pointer = clone $value; |
|
53 | } else { |
||
54 | 52 | $pointer = $value !== null ? new static($value) : new static(); |
|
55 | } |
||
56 | 17 | } catch (\TypeError $e) { |
|
57 | 17 | $message = sprintf( |
|
58 | 17 | '%s. Argument can be instance of %s or scalar equivalent.', |
|
59 | 17 | $e->getMessage(), |
|
60 | 17 | static::class |
|
61 | ); |
||
62 | |||
63 | 17 | throw new \TypeError($message, $e->getCode(), $e); |
|
64 | } |
||
65 | |||
66 | 41 | $pointer->memoryAddress = Memory::getNewAddress($pointer); |
|
67 | 41 | } |
|
68 | |||
69 | /** |
||
70 | * Runs when a variable is reassigned or destroyed with $pointer = null;. |
||
71 | * Basically overloads the assignment operator when a specific pointer has been boxed to return a new instance |
||
72 | * of the previous type with the new assigned value. |
||
73 | */ |
||
74 | 148 | final public function __destruct() |
|
99 | |||
100 | /** |
||
101 | * Translates type to cast front int to string representation. |
||
102 | * |
||
103 | * @param int|null $type |
||
104 | * |
||
105 | * @return string |
||
106 | */ |
||
107 | 21 | protected function getTranslatedType(int $type = null): string |
|
125 | } |
||
126 |