vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Profiler/Profiler.php line 105

Open in your IDE?
  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\Profiler;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\Debug\Exception\FatalThrowableError;
  13. use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
  17. use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface;
  18. use Symfony\Contracts\Service\ResetInterface;
  19. /**
  20.  * Profiler.
  21.  *
  22.  * @author Fabien Potencier <fabien@symfony.com>
  23.  */
  24. class Profiler implements ResetInterface
  25. {
  26.     private $storage;
  27.     /**
  28.      * @var DataCollectorInterface[]
  29.      */
  30.     private $collectors = [];
  31.     private $logger;
  32.     private $initiallyEnabled true;
  33.     private $enabled true;
  34.     public function __construct(ProfilerStorageInterface $storageLoggerInterface $logger nullbool $enable true)
  35.     {
  36.         $this->storage $storage;
  37.         $this->logger $logger;
  38.         $this->initiallyEnabled $this->enabled $enable;
  39.     }
  40.     /**
  41.      * Disables the profiler.
  42.      */
  43.     public function disable()
  44.     {
  45.         $this->enabled false;
  46.     }
  47.     /**
  48.      * Enables the profiler.
  49.      */
  50.     public function enable()
  51.     {
  52.         $this->enabled true;
  53.     }
  54.     /**
  55.      * Loads the Profile for the given Response.
  56.      *
  57.      * @return Profile|null A Profile instance
  58.      */
  59.     public function loadProfileFromResponse(Response $response)
  60.     {
  61.         if (!$token $response->headers->get('X-Debug-Token')) {
  62.             return null;
  63.         }
  64.         return $this->loadProfile($token);
  65.     }
  66.     /**
  67.      * Loads the Profile for the given token.
  68.      *
  69.      * @param string $token A token
  70.      *
  71.      * @return Profile|null A Profile instance
  72.      */
  73.     public function loadProfile($token)
  74.     {
  75.         return $this->storage->read($token);
  76.     }
  77.     /**
  78.      * Saves a Profile.
  79.      *
  80.      * @return bool
  81.      */
  82.     public function saveProfile(Profile $profile)
  83.     {
  84.         // late collect
  85.         foreach ($profile->getCollectors() as $collector) {
  86.             if ($collector instanceof LateDataCollectorInterface) {
  87.                 $collector->lateCollect();
  88.             }
  89.         }
  90.         if (!($ret $this->storage->write($profile)) && null !== $this->logger) {
  91.             $this->logger->warning('Unable to store the profiler information.', ['configured_storage' => \get_class($this->storage)]);
  92.         }
  93.         return $ret;
  94.     }
  95.     /**
  96.      * Purges all data from the storage.
  97.      */
  98.     public function purge()
  99.     {
  100.         $this->storage->purge();
  101.     }
  102.     /**
  103.      * Finds profiler tokens for the given criteria.
  104.      *
  105.      * @param string $ip         The IP
  106.      * @param string $url        The URL
  107.      * @param string $limit      The maximum number of tokens to return
  108.      * @param string $method     The request method
  109.      * @param string $start      The start date to search from
  110.      * @param string $end        The end date to search to
  111.      * @param string $statusCode The request status code
  112.      *
  113.      * @return array An array of tokens
  114.      *
  115.      * @see https://php.net/datetime.formats for the supported date/time formats
  116.      */
  117.     public function find($ip$url$limit$method$start$end$statusCode null)
  118.     {
  119.         return $this->storage->find($ip$url$limit$method$this->getTimestamp($start), $this->getTimestamp($end), $statusCode);
  120.     }
  121.     /**
  122.      * Collects data for the given Response.
  123.      *
  124.      * @param \Throwable|null $exception
  125.      *
  126.      * @return Profile|null A Profile instance or null if the profiler is disabled
  127.      */
  128.     public function collect(Request $requestResponse $response/* , \Throwable $exception = null */)
  129.     {
  130.         $exception \func_num_args() ? func_get_arg(2) : null;
  131.         if (false === $this->enabled) {
  132.             return null;
  133.         }
  134.         $profile = new Profile(substr(hash('sha256'uniqid(mt_rand(), true)), 06));
  135.         $profile->setTime(time());
  136.         $profile->setUrl($request->getUri());
  137.         $profile->setMethod($request->getMethod());
  138.         $profile->setStatusCode($response->getStatusCode());
  139.         try {
  140.             $profile->setIp($request->getClientIp());
  141.         } catch (ConflictingHeadersException $e) {
  142.             $profile->setIp('Unknown');
  143.         }
  144.         if ($prevToken $response->headers->get('X-Debug-Token')) {
  145.             $response->headers->set('X-Previous-Debug-Token'$prevToken);
  146.         }
  147.         $response->headers->set('X-Debug-Token'$profile->getToken());
  148.         $wrappedException null;
  149.         foreach ($this->collectors as $collector) {
  150.             if (($e $exception) instanceof \Error) {
  151.                 $r = new \ReflectionMethod($collector'collect');
  152.                 $e >= $r->getNumberOfParameters() || !($p $r->getParameters()[2])->hasType() || \Exception::class !== $p->getType()->getName() ? $e : ($wrappedException ?? $wrappedException = new FatalThrowableError($e));
  153.             }
  154.             $collector->collect($request$response$e);
  155.             // we need to clone for sub-requests
  156.             $profile->addCollector(clone $collector);
  157.         }
  158.         return $profile;
  159.     }
  160.     public function reset()
  161.     {
  162.         foreach ($this->collectors as $collector) {
  163.             $collector->reset();
  164.         }
  165.         $this->enabled $this->initiallyEnabled;
  166.     }
  167.     /**
  168.      * Gets the Collectors associated with this profiler.
  169.      *
  170.      * @return array An array of collectors
  171.      */
  172.     public function all()
  173.     {
  174.         return $this->collectors;
  175.     }
  176.     /**
  177.      * Sets the Collectors associated with this profiler.
  178.      *
  179.      * @param DataCollectorInterface[] $collectors An array of collectors
  180.      */
  181.     public function set(array $collectors = [])
  182.     {
  183.         $this->collectors = [];
  184.         foreach ($collectors as $collector) {
  185.             $this->add($collector);
  186.         }
  187.     }
  188.     /**
  189.      * Adds a Collector.
  190.      */
  191.     public function add(DataCollectorInterface $collector)
  192.     {
  193.         $this->collectors[$collector->getName()] = $collector;
  194.     }
  195.     /**
  196.      * Returns true if a Collector for the given name exists.
  197.      *
  198.      * @param string $name A collector name
  199.      *
  200.      * @return bool
  201.      */
  202.     public function has($name)
  203.     {
  204.         return isset($this->collectors[$name]);
  205.     }
  206.     /**
  207.      * Gets a Collector by name.
  208.      *
  209.      * @param string $name A collector name
  210.      *
  211.      * @return DataCollectorInterface A DataCollectorInterface instance
  212.      *
  213.      * @throws \InvalidArgumentException if the collector does not exist
  214.      */
  215.     public function get($name)
  216.     {
  217.         if (!isset($this->collectors[$name])) {
  218.             throw new \InvalidArgumentException(sprintf('Collector "%s" does not exist.'$name));
  219.         }
  220.         return $this->collectors[$name];
  221.     }
  222.     private function getTimestamp(?string $value): ?int
  223.     {
  224.         if (null === $value || '' === $value) {
  225.             return null;
  226.         }
  227.         try {
  228.             $value = new \DateTime(is_numeric($value) ? '@'.$value $value);
  229.         } catch (\Exception $e) {
  230.             return null;
  231.         }
  232.         return $value->getTimestamp();
  233.     }
  234. }