MemoryDataCollector.php 2.5 KB

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