ClassStub.php 2.7 KB

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