菜谱项目

MemoryDataCollector.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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->data = array(
  23. 'memory' => 0,
  24. 'memory_limit' => $this->convertToBytes(ini_get('memory_limit')),
  25. );
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function collect(Request $request, Response $response, \Exception $exception = null)
  31. {
  32. $this->updateMemoryUsage();
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function lateCollect()
  38. {
  39. $this->updateMemoryUsage();
  40. }
  41. /**
  42. * Gets the memory.
  43. *
  44. * @return int The memory
  45. */
  46. public function getMemory()
  47. {
  48. return $this->data['memory'];
  49. }
  50. /**
  51. * Gets the PHP memory limit.
  52. *
  53. * @return int The memory limit
  54. */
  55. public function getMemoryLimit()
  56. {
  57. return $this->data['memory_limit'];
  58. }
  59. /**
  60. * Updates the memory usage data.
  61. */
  62. public function updateMemoryUsage()
  63. {
  64. $this->data['memory'] = memory_get_peak_usage(true);
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function getName()
  70. {
  71. return 'memory';
  72. }
  73. private function convertToBytes($memoryLimit)
  74. {
  75. if ('-1' === $memoryLimit) {
  76. return -1;
  77. }
  78. $memoryLimit = strtolower($memoryLimit);
  79. $max = strtolower(ltrim($memoryLimit, '+'));
  80. if (0 === strpos($max, '0x')) {
  81. $max = intval($max, 16);
  82. } elseif (0 === strpos($max, '0')) {
  83. $max = intval($max, 8);
  84. } else {
  85. $max = (int) $max;
  86. }
  87. switch (substr($memoryLimit, -1)) {
  88. case 't': $max *= 1024;
  89. // no break
  90. case 'g': $max *= 1024;
  91. // no break
  92. case 'm': $max *= 1024;
  93. // no break
  94. case 'k': $max *= 1024;
  95. }
  96. return $max;
  97. }
  98. }