DataCollector.php 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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\Cloner\ClonerInterface;
  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, \Serializable
  25. {
  26. protected $data = array();
  27. /**
  28. * @var ClonerInterface
  29. */
  30. private $cloner;
  31. public function serialize()
  32. {
  33. return serialize($this->data);
  34. }
  35. public function unserialize($data)
  36. {
  37. $this->data = unserialize($data);
  38. }
  39. /**
  40. * Converts the variable into a serializable Data instance.
  41. *
  42. * This array can be displayed in the template using
  43. * the VarDumper component.
  44. *
  45. * @param mixed $var
  46. *
  47. * @return Data
  48. */
  49. protected function cloneVar($var)
  50. {
  51. if ($var instanceof Data) {
  52. return $var;
  53. }
  54. if (null === $this->cloner) {
  55. if (!class_exists(CutStub::class)) {
  56. throw new \LogicException(sprintf('The VarDumper component is needed for the %s() method. Install symfony/var-dumper version 3.4 or above.', __METHOD__));
  57. }
  58. $this->cloner = new VarCloner();
  59. $this->cloner->setMaxItems(-1);
  60. $this->cloner->addCasters($this->getCasters());
  61. }
  62. return $this->cloner->cloneVar($var);
  63. }
  64. /**
  65. * @return callable[] The casters to add to the cloner
  66. */
  67. protected function getCasters()
  68. {
  69. return array(
  70. '*' => function ($v, array $a, Stub $s, $isNested) {
  71. if (!$v instanceof Stub) {
  72. foreach ($a as $k => $v) {
  73. if (is_object($v) && !$v instanceof \DateTimeInterface && !$v instanceof Stub) {
  74. $a[$k] = new CutStub($v);
  75. }
  76. }
  77. }
  78. return $a;
  79. },
  80. );
  81. }
  82. }