LimeTesterFactory.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. /*
  3. * This file is part of the Lime framework.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. * (c) Bernhard Schussek <bernhard.schussek@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. class LimeTesterFactory
  12. {
  13. protected
  14. $testers = array(
  15. 'null' => 'LimeTesterScalar',
  16. 'integer' => 'LimeTesterInteger',
  17. 'boolean' => 'LimeTesterScalar',
  18. 'string' => 'LimeTesterString',
  19. 'double' => 'LimeTesterDouble',
  20. 'array' => 'LimeTesterArray',
  21. 'object' => 'LimeTesterObject',
  22. 'resource' => 'LimeTesterResource',
  23. 'Exception' => 'LimeTesterException',
  24. );
  25. public function create($value)
  26. {
  27. $type = null;
  28. if (is_null($value))
  29. {
  30. $type = 'null';
  31. }
  32. else if (is_object($value) && array_key_exists(get_class($value), $this->testers))
  33. {
  34. $type = get_class($value);
  35. }
  36. else if (is_object($value))
  37. {
  38. $class = new ReflectionClass($value);
  39. foreach ($class->getInterfaces() as $interface)
  40. {
  41. if (array_key_exists($interface->getName(), $this->testers))
  42. {
  43. $type = $interface->getName();
  44. break;
  45. }
  46. }
  47. $parentClass = $class;
  48. while ($parentClass = $parentClass->getParentClass())
  49. {
  50. if (array_key_exists($parentClass->getName(), $this->testers))
  51. {
  52. $type = $parentClass->getName();
  53. break;
  54. }
  55. }
  56. if (!empty($type))
  57. {
  58. // cache the tester
  59. $this->testers[$class->getName()] = $this->testers[$type];
  60. }
  61. }
  62. if (empty($type))
  63. {
  64. if (array_key_exists(gettype($value), $this->testers))
  65. {
  66. $type = gettype($value);
  67. }
  68. else
  69. {
  70. throw new InvalidArgumentException(sprintf('No tester is registered for type "%s"', gettype($value)));
  71. }
  72. }
  73. $class = $this->testers[$type];
  74. return new $class($value);
  75. }
  76. public function register($type, $tester)
  77. {
  78. if (!class_exists($tester))
  79. {
  80. throw new InvalidArgumentException(sprintf('The class "%s" does not exist', $tester));
  81. }
  82. $class = new ReflectionClass($tester);
  83. if (!$class->implementsInterface('LimeTesterInterface'))
  84. {
  85. throw new InvalidArgumentException('Testers must implement "LimeTesterInterface"');
  86. }
  87. $this->testers[$type] = $tester;
  88. }
  89. public function unregister($type)
  90. {
  91. if (array_key_exists($type, $this->testers))
  92. {
  93. unset($this->testers[$type]);
  94. }
  95. }
  96. }