fork download
  1. <?php
  2. namespace Valid;
  3.  
  4. class ArgumentException extends \Exception
  5. {
  6. public function __invoke() {
  7. throw $this;
  8. }
  9. }
  10.  
  11. class CouldBeAnyObjectForExampleLogger
  12. {
  13. public function __construct($argument) {
  14. $this->argument = $argument;
  15. }
  16. public function __invoke() {
  17. // log something to file
  18. }
  19. }
  20.  
  21. class Email
  22. {
  23. public function __construct($email) {
  24. new Is(new Same($email, 'ya@ty.sobaka'), new CouldBeAnyObjectForExampleLogger($email), new ArgumentException($email));
  25. }
  26. }
  27.  
  28. class Is
  29. {
  30. public function __construct($expression, $do, $not) {
  31. $this->expression = $expression;
  32. $this->do = $do;
  33. $this->not = $not;
  34.  
  35. $this();
  36. }
  37.  
  38. public function __invoke() {
  39. $this->expression->__invoke() ? $this->do->__invoke() : $this->not->__invoke();
  40. }
  41.  
  42. public function __toString() {
  43. throw new \TypeException(); //Can't stringify expression!
  44. }
  45. }
  46.  
  47. class Same
  48. {
  49. public function __construct($one, $two) {
  50. $this->one = $one;
  51. $this->two = $two;
  52. }
  53. public function __invoke() {
  54. return $this->one === $this->two;
  55. }
  56. public function __toString() {
  57. return (string)$this();
  58. }
  59. }
  60.  
  61. print "first try is ok \n";
  62.  
  63. try {
  64. new \Valid\Email('ya@ty.sobaka');
  65. } catch (\Exception $e) {
  66. print $e->getMessage() . " is not a valid login";
  67. }
  68.  
  69. print "\nsecond try should throw exception\n";
  70.  
  71. try {
  72. new \Valid\Email('ya@ty.kowaka');
  73. } catch (\Exception $e) {
  74. print $e->getMessage() . " is not a valid login";
  75. }
Success #stdin #stdout 0s 82880KB
stdin
Standard input is empty
stdout
first try is ok 

second try should throw exception
ya@ty.kowaka is not a valid login