DataCollector.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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\HttpKernel\DataCollector;
  11. use Symfony\Component\VarDumper\Caster\CutStub;
  12. use Symfony\Component\VarDumper\Caster\ReflectionCaster;
  13. use Symfony\Component\VarDumper\Cloner\Data;
  14. use Symfony\Component\VarDumper\Cloner\Stub;
  15. use Symfony\Component\VarDumper\Cloner\VarCloner;
  16. /**
  17. * DataCollector.
  18. *
  19. * Children of this class must store the collected data in the data property.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. * @author Bernhard Schussek <bschussek@symfony.com>
  23. */
  24. abstract class DataCollector implements DataCollectorInterface
  25. {
  26. /**
  27. * @var array|Data
  28. */
  29. protected $data = [];
  30. private $cloner;
  31. /**
  32. * Converts the variable into a serializable Data instance.
  33. *
  34. * This array can be displayed in the template using
  35. * the VarDumper component.
  36. */
  37. protected function cloneVar(mixed $var): Data
  38. {
  39. if ($var instanceof Data) {
  40. return $var;
  41. }
  42. if (!isset($this->cloner)) {
  43. $this->cloner = new VarCloner();
  44. $this->cloner->setMaxItems(-1);
  45. $this->cloner->addCasters($this->getCasters());
  46. }
  47. return $this->cloner->cloneVar($var);
  48. }
  49. /**
  50. * @return callable[] The casters to add to the cloner
  51. */
  52. protected function getCasters()
  53. {
  54. $casters = [
  55. '*' => function ($v, array $a, Stub $s, $isNested) {
  56. if (!$v instanceof Stub) {
  57. foreach ($a as $k => $v) {
  58. if (\is_object($v) && !$v instanceof \DateTimeInterface && !$v instanceof Stub) {
  59. $a[$k] = new CutStub($v);
  60. }
  61. }
  62. }
  63. return $a;
  64. },
  65. ] + ReflectionCaster::UNSET_CLOSURE_FILE_INFO;
  66. return $casters;
  67. }
  68. public function __sleep(): array
  69. {
  70. return ['data'];
  71. }
  72. public function __wakeup()
  73. {
  74. }
  75. /**
  76. * @internal to prevent implementing \Serializable
  77. */
  78. final protected function serialize()
  79. {
  80. }
  81. /**
  82. * @internal to prevent implementing \Serializable
  83. */
  84. final protected function unserialize(string $data)
  85. {
  86. }
  87. }