ClassStub.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\Component\VarDumper\Caster;
  11. /**
  12. * Represents a PHP class identifier.
  13. *
  14. * @author Nicolas Grekas <p@tchwork.com>
  15. */
  16. class ClassStub extends ConstStub
  17. {
  18. /**
  19. * @param string A PHP identifier, e.g. a class, method, interface, etc. name
  20. * @param callable The callable targeted by the identifier when it is ambiguous or not a real PHP identifier
  21. */
  22. public function __construct($identifier, $callable = null)
  23. {
  24. $this->value = $identifier;
  25. if (0 < $i = strrpos($identifier, '\\')) {
  26. $this->attr['ellipsis'] = \strlen($identifier) - $i;
  27. $this->attr['ellipsis-type'] = 'class';
  28. $this->attr['ellipsis-tail'] = 1;
  29. }
  30. try {
  31. if (null !== $callable) {
  32. if ($callable instanceof \Closure) {
  33. $r = new \ReflectionFunction($callable);
  34. } elseif (\is_object($callable)) {
  35. $r = array($callable, '__invoke');
  36. } elseif (\is_array($callable)) {
  37. $r = $callable;
  38. } elseif (false !== $i = strpos($callable, '::')) {
  39. $r = array(substr($callable, 0, $i), substr($callable, 2 + $i));
  40. } else {
  41. $r = new \ReflectionFunction($callable);
  42. }
  43. } elseif (0 < $i = strpos($identifier, '::') ?: strpos($identifier, '->')) {
  44. $r = array(substr($identifier, 0, $i), substr($identifier, 2 + $i));
  45. } else {
  46. $r = new \ReflectionClass($identifier);
  47. }
  48. if (\is_array($r)) {
  49. try {
  50. $r = new \ReflectionMethod($r[0], $r[1]);
  51. } catch (\ReflectionException $e) {
  52. $r = new \ReflectionClass($r[0]);
  53. }
  54. }
  55. } catch (\ReflectionException $e) {
  56. return;
  57. }
  58. if ($f = $r->getFileName()) {
  59. $this->attr['file'] = $f;
  60. $this->attr['line'] = $r->getStartLine();
  61. }
  62. }
  63. public static function wrapCallable($callable)
  64. {
  65. if (\is_object($callable) || !\is_callable($callable)) {
  66. return $callable;
  67. }
  68. if (!\is_array($callable)) {
  69. $callable = new static($callable);
  70. } elseif (\is_string($callable[0])) {
  71. $callable[0] = new static($callable[0]);
  72. } else {
  73. $callable[1] = new static($callable[1], $callable);
  74. }
  75. return $callable;
  76. }
  77. }