MemoryDataCollector.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 $request, Response $response, ?\Throwable $exception = null): void
  25. {
  26. $this->updateMemoryUsage();
  27. }
  28. public function reset(): void
  29. {
  30. $this->data = [
  31. 'memory' => 0,
  32. 'memory_limit' => $this->convertToBytes(\ini_get('memory_limit')),
  33. ];
  34. }
  35. public function lateCollect(): void
  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(): void
  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($max, 16);
  64. } elseif (str_starts_with($max, '0')) {
  65. $max = \intval($max, 8);
  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. }