fork download
  1. <?php
  2. class DomainValidator {
  3. const DOMAIN_TAG = '@domain';
  4.  
  5. private $object;
  6.  
  7. public function __construct($object) {
  8. $this->object = $object;
  9. }
  10.  
  11. public function __call($function, $arguments) {
  12. if (!$this->verify_domain($function, $arguments)) {
  13. throw new \DomainException('Bad domain!');
  14. }
  15.  
  16. array($this->object, $function),
  17. $arguments
  18. );
  19. }
  20.  
  21. public function __get($name) {
  22. return $this->object->name;
  23. }
  24.  
  25. public function __set($name, $value) {
  26. $this->object->name = $value;
  27. }
  28.  
  29. private function verify_domain($function, $arguments) {
  30. // Get reference to method
  31. $method = new \ReflectionMethod($this->object, $function);
  32. $domains = $this->get_domains($method->getDocComment());
  33. $arguments = $this->parse_arguments(
  34. $method->getParameters(),
  35. $arguments
  36. );
  37. foreach ($domains as $domain) {
  38. $domain['name'],
  39. $arguments[$domain['parameter']]
  40. )) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46.  
  47. private function get_domains($doc_block) {
  48. $lines = explode("\n", $doc_block);
  49. $domains = array();
  50. $domain_tag = DomainValidator::DOMAIN_TAG . ' ';
  51. foreach ($lines as $line) {
  52. $has_domain = stristr($line, $domain_tag) !== false;
  53. if ($has_domain) {
  54. $domain_info = explode($domain_tag, $line);
  55. $domain_info = explode(' ', $domain_info[1]);
  56. $domains[] = array(
  57. 'name' => $domain_info[0],
  58. 'parameter' => $domain_info[1],
  59. );
  60. }
  61. }
  62. return $domains;
  63. }
  64.  
  65. private function parse_arguments($parameters, $values) {
  66. $ret = array();
  67. for ($i = 0, $size = sizeof($values); $i < $size; $i++) {
  68. $ret[$parameters[$i]->name] = $values[$i];
  69. }
  70. return $ret;
  71. }
  72. }
  73.  
  74. class FooDomain {
  75. public static function is_not_empty($input) {
  76. return !empty($input);
  77. }
  78. }
  79.  
  80. class Foo {
  81. /**
  82.   * @domain FooDomain::is_not_empty my_string
  83.   */
  84. public function print_string($my_string) {
  85. echo $my_string . PHP_EOL;
  86. }
  87. }
  88.  
  89. $foo = new DomainValidator(new Foo());
  90. $foo->print_string('Hello, world!');
  91. try {
  92. $foo->print_string(''); // throws a DomainException
  93. } catch (\DomainException $e) {
  94. echo 'Could not print an empty string...' . PHP_EOL;
  95. }
  96.  
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
Hello, world!
Could not print an empty string...