vendor/symfony/http-kernel/DataCollector/MemoryDataCollector.php line 32

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\DataCollector;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. /**
  14.  * @author Fabien Potencier <fabien@symfony.com>
  15.  *
  16.  * @final
  17.  */
  18. class MemoryDataCollector extends DataCollector implements LateDataCollectorInterface
  19. {
  20.     public function __construct()
  21.     {
  22.         $this->reset();
  23.     }
  24.     /**
  25.      * {@inheritdoc}
  26.      */
  27.     public function collect(Request $request, Response $response, \Throwable $exception = null)
  28.     {
  29.         $this->updateMemoryUsage();
  30.     }
  31.     /**
  32.      * {@inheritdoc}
  33.      */
  34.     public function reset()
  35.     {
  36.         $this->data = [
  37.             'memory' => 0,
  38.             'memory_limit' => $this->convertToBytes(ini_get('memory_limit')),
  39.         ];
  40.     }
  41.     /**
  42.      * {@inheritdoc}
  43.      */
  44.     public function lateCollect()
  45.     {
  46.         $this->updateMemoryUsage();
  47.     }
  48.     public function getMemory(): int
  49.     {
  50.         return $this->data['memory'];
  51.     }
  52.     public function getMemoryLimit(): int
  53.     {
  54.         return $this->data['memory_limit'];
  55.     }
  56.     public function updateMemoryUsage()
  57.     {
  58.         $this->data['memory'] = memory_get_peak_usage(true);
  59.     }
  60.     /**
  61.      * {@inheritdoc}
  62.      */
  63.     public function getName(): string
  64.     {
  65.         return 'memory';
  66.     }
  67.     private function convertToBytes(string $memoryLimit): int|float
  68.     {
  69.         if ('-1' === $memoryLimit) {
  70.             return -1;
  71.         }
  72.         $memoryLimit = strtolower($memoryLimit);
  73.         $max = strtolower(ltrim($memoryLimit, '+'));
  74.         if (str_starts_with($max, '0x')) {
  75.             $max = \intval($max, 16);
  76.         } elseif (str_starts_with($max, '0')) {
  77.             $max = \intval($max, 8);
  78.         } else {
  79.             $max = (int) $max;
  80.         }
  81.         switch (substr($memoryLimit, -1)) {
  82.             case 't': $max *= 1024;
  83.             // no break
  84.             case 'g': $max *= 1024;
  85.             // no break
  86.             case 'm': $max *= 1024;
  87.             // no break
  88.             case 'k': $max *= 1024;
  89.         }
  90.         return $max;
  91.     }
  92. }