MemoryDataCollector.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. 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, \Exception $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. /**
  49. * Gets the memory.
  50. *
  51. * @return int The memory
  52. */
  53. public function getMemory()
  54. {
  55. return $this->data['memory'];
  56. }
  57. /**
  58. * Gets the PHP memory limit.
  59. *
  60. * @return int The memory limit
  61. */
  62. public function getMemoryLimit()
  63. {
  64. return $this->data['memory_limit'];
  65. }
  66. /**
  67. * Updates the memory usage data.
  68. */
  69. public function updateMemoryUsage()
  70. {
  71. $this->data['memory'] = memory_get_peak_usage(true);
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function getName()
  77. {
  78. return 'memory';
  79. }
  80. private function convertToBytes($memoryLimit)
  81. {
  82. if ('-1' === $memoryLimit) {
  83. return -1;
  84. }
  85. $memoryLimit = strtolower($memoryLimit);
  86. $max = strtolower(ltrim($memoryLimit, '+'));
  87. if (0 === strpos($max, '0x')) {
  88. $max = \intval($max, 16);
  89. } elseif (0 === strpos($max, '0')) {
  90. $max = \intval($max, 8);
  91. } else {
  92. $max = (int) $max;
  93. }
  94. switch (substr($memoryLimit, -1)) {
  95. case 't': $max *= 1024;
  96. // no break
  97. case 'g': $max *= 1024;
  98. // no break
  99. case 'm': $max *= 1024;
  100. // no break
  101. case 'k': $max *= 1024;
  102. }
  103. return $max;
  104. }
  105. }