Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active February 28, 2016 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/dc3d24eba8d13a650cc6 to your computer and use it in GitHub Desktop.
Save mindplay-dk/dc3d24eba8d13a650cc6 to your computer and use it in GitHub Desktop.
<?php
// pseudo-code:
class ReflectionClass
{
// ...
/**
* @return ReflectionTypeParam[]
*/
public function getTypeParams()
{
// ...
}
/**
* @return bool
*/
public function isGeneric()
{
return count($this->getTemplates()) > 0;
}
}
/**
* This class represents a template type (type parameter) of a generic class
*/
class ReflectionTypeParam
{
/**
* @var ReflectionClass owner class reference
*/
protected $class;
/**
* @var string template name, e.g. "T"
*/
protected $name;
public function __construct(ReflectionClass $class, $name)
{
$this->class = $class;
$this->name = $name;
}
/**
* @return ReflectionTypeArg
*/
public function getTypeArg($object)
{
// return
}
public function __toString() {
return $this->name;
}
}
/**
* This class represents a type provided as a type argument
* for an individual template type of a generic object
*/
class ReflectionTypeArg
{
/**
* @return bool
*/
public function check($value)
{
// return true, if the given value passes a type-check for this type-argument
}
/**
* @return bool
*/
public function isBuiltIn()
{
// return true, if the type being checked is a built-in type (int, bool, string, etc.)
}
public function __toString()
{
// return e.g. "User" or "int" etc.
}
}
// usage:
class Box<T> {
/**
* @var T
*/
private $value;
public function get() : T {
return $this->value;
}
public function set(T $value) {
$this->value = $value;
}
}
class Hat {}
$box = new Box<Hat>();
$box_class = new ReflectionClass("Box");
var_dump($box_class->getTypeParams()[0]->getTypeArg($box)->__toString()); // "Hat"
var_dump($box_class->getTypeParams()[0]->getTypeArg($box)->check(new Hat())); // true
// case with structured type argument:
$boxed_box = new Box<Box<Hat>>();
var_dump($box_class->getTypeParams()[0]->getTypeArg($boxed_box)->__toString()); // "Box<Hat>"
var_dump($box_class->getTypeParams()[0]->getTypeArg($box)->check(new Box<Hat>())); // true
// case with type argument defined via extends clause:
class HatBox extends Box<Hat> {}
$hat_box = new HatBox();
var_dump($box_class->getTypeParams()[0]->getTypeArg($hat_box)->__toString()); // "Hat"
var_dump($box_class->getTypeParams()[0]->getTypeArg($hat_box)->check(new Hat())); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment