ClassExistsMock.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\PhpUnit;
  11. /**
  12. * @author Roland Franssen <franssen.roland@gmail.com>
  13. */
  14. class ClassExistsMock
  15. {
  16. private static $classes = [];
  17. /**
  18. * Configures the classes to be checked upon existence.
  19. *
  20. * @param array $classes Mocked class names as keys (case sensitive, without leading root namespace slash) and booleans as values
  21. */
  22. public static function withMockedClasses(array $classes)
  23. {
  24. self::$classes = $classes;
  25. }
  26. public static function class_exists($name, $autoload = true)
  27. {
  28. $name = ltrim($name, '\\');
  29. return isset(self::$classes[$name]) ? (bool) self::$classes[$name] : \class_exists($name, $autoload);
  30. }
  31. public static function interface_exists($name, $autoload = true)
  32. {
  33. $name = ltrim($name, '\\');
  34. return isset(self::$classes[$name]) ? (bool) self::$classes[$name] : \interface_exists($name, $autoload);
  35. }
  36. public static function trait_exists($name, $autoload = true)
  37. {
  38. $name = ltrim($name, '\\');
  39. return isset(self::$classes[$name]) ? (bool) self::$classes[$name] : \trait_exists($name, $autoload);
  40. }
  41. public static function register($class)
  42. {
  43. $self = \get_called_class();
  44. $mockedNs = [substr($class, 0, strrpos($class, '\\'))];
  45. if (0 < strpos($class, '\\Tests\\')) {
  46. $ns = str_replace('\\Tests\\', '\\', $class);
  47. $mockedNs[] = substr($ns, 0, strrpos($ns, '\\'));
  48. } elseif (0 === strpos($class, 'Tests\\')) {
  49. $mockedNs[] = substr($class, 6, strrpos($class, '\\') - 6);
  50. }
  51. foreach ($mockedNs as $ns) {
  52. foreach (['class', 'interface', 'trait'] as $type) {
  53. if (\function_exists($ns.'\\'.$type.'_exists')) {
  54. continue;
  55. }
  56. eval(<<<EOPHP
  57. namespace $ns;
  58. function {$type}_exists(\$name, \$autoload = true)
  59. {
  60. return \\$self::{$type}_exists(\$name, \$autoload);
  61. }
  62. EOPHP
  63. );
  64. }
  65. }
  66. }
  67. }