Created
September 16, 2015 07:56
-
-
Save jamesBan/dcc40108139b3413cff4 to your computer and use it in GitHub Desktop.
php tuple splfixArray
This file contains hidden or 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 | |
| class Tuple extends SplFixedArray | |
| { | |
| protected $prototype; | |
| public function __construct(array $prototype, array $data = []) | |
| { | |
| echo __METHOD__ . "\r\n"; | |
| parent::__construct(count($prototype)); | |
| $this->prototype = $prototype; | |
| foreach ($data as $offset => $value) { | |
| $this->offSet($offset, $value); | |
| } | |
| } | |
| public function offSet($offset, $value) | |
| { | |
| echo __METHOD__ . "\r\n"; | |
| if(!$this->isValid($offset, $value)) { | |
| throw new RuntimeException; | |
| } | |
| return parent::offsetSet($offset, $value); | |
| } | |
| public function isValid($offset, $value) | |
| { | |
| echo __METHOD__ . "\r\n"; | |
| $type = $this->prototype[$offset]; | |
| if( | |
| $type === 'mixed' || | |
| gettype($value) === $type || | |
| $value instanceof $type | |
| ) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| public function __toString() | |
| { | |
| echo __METHOD__ . "\r\n"; | |
| return get_class($this) . '('.implode(', ', $this->toArray()) . ')'; | |
| } | |
| public static function create() | |
| { | |
| echo __METHOD__ . "\r\n"; | |
| $prototype = func_get_args(); | |
| return function() use($prototype) { | |
| return new self($prototype, func_get_args()); | |
| }; | |
| } | |
| public static function type($name, array $prototype) | |
| { | |
| echo __METHOD__ . "\r\n"; | |
| if(class_exists($name) || function_exists($name)) { | |
| throw new RuntimeException; | |
| } | |
| $eval = sprintf( | |
| 'class %s extends Tuple {'. | |
| 'public function __construct(array $data){'. | |
| 'return parent::__construct(%s, $data);'. | |
| '}'. | |
| '}', | |
| $name, "['" . implode("','", $prototype) . "']" | |
| ); | |
| $eval .= sprintf( | |
| 'function %s() { return new %s(func_get_args()); }', | |
| $name, $name | |
| ); | |
| eval($eval); | |
| } | |
| } | |
| $point = Tuple::create('double', 'double'); | |
| var_dump($point(1.0, 2.5)[1]); | |
| Tuple::type('Point', [ 'double', 'double' ]); | |
| Point(1.0, 2.5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment