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

  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.     public function collect(Request $requestResponse $response\Throwable $exception null)
  25.     {
  26.         $this->updateMemoryUsage();
  27.     }
  28.     public function reset()
  29.     {
  30.         $this->data = [
  31.             'memory' => 0,
  32.             'memory_limit' => $this->convertToBytes(\ini_get('memory_limit')),
  33.         ];
  34.     }
  35.     public function lateCollect()
  36.     {
  37.         $this->updateMemoryUsage();
  38.     }
  39.     public function getMemory(): int
  40.     {
  41.         return $this->data['memory'];
  42.     }
  43.     public function getMemoryLimit(): int|float
  44.     {
  45.         return $this->data['memory_limit'];
  46.     }
  47.     public function updateMemoryUsage()
  48.     {
  49.         $this->data['memory'] = memory_get_peak_usage(true);
  50.     }
  51.     public function getName(): string
  52.     {
  53.         return 'memory';
  54.     }
  55.     private function convertToBytes(string $memoryLimit): int|float
  56.     {
  57.         if ('-1' === $memoryLimit) {
  58.             return -1;
  59.         }
  60.         $memoryLimit strtolower($memoryLimit);
  61.         $max strtolower(ltrim($memoryLimit'+'));
  62.         if (str_starts_with($max'0x')) {
  63.             $max \intval($max16);
  64.         } elseif (str_starts_with($max'0')) {
  65.             $max \intval($max8);
  66.         } else {
  67.             $max = (int) $max;
  68.         }
  69.         switch (substr($memoryLimit, -1)) {
  70.             case 't'$max *= 1024;
  71.                 // no break
  72.             case 'g'$max *= 1024;
  73.                 // no break
  74.             case 'm'$max *= 1024;
  75.                 // no break
  76.             case 'k'$max *= 1024;
  77.         }
  78.         return $max;
  79.     }
  80. }