vendor/shopware/core/Profiling/Profiler.php line 59

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Profiling;
  3. use Shopware\Core\Framework\Log\Package;
  4. use Shopware\Core\Profiling\Integration\ProfilerInterface;
  5. /**
  6. * @internal experimental atm
  7. */
  8. #[Package('core')]
  9. class Profiler
  10. {
  11. /**
  12. * Profilers will be activated over the shopware.yaml file
  13. *
  14. * All enabled profilers will be added here
  15. *
  16. * @var ProfilerInterface[]
  17. */
  18. private static array $profilers = [];
  19. /**
  20. * Tags will be added to each trace
  21. *
  22. * @var array<string>
  23. */
  24. private static array $tags = [];
  25. /**
  26. * @var array<string>
  27. */
  28. private static array $openTraces = [];
  29. /**
  30. * @param array<string> $activeProfilers
  31. */
  32. public function __construct(\Traversable $profilers, array $activeProfilers)
  33. {
  34. $profilers = iterator_to_array($profilers);
  35. self::$profilers = array_intersect_key($profilers, array_flip($activeProfilers));
  36. self::$tags = [];
  37. register_shutdown_function(fn () => self::cleanup());
  38. }
  39. /**
  40. * @return mixed
  41. */
  42. public static function trace(string $name, \Closure $closure, string $category = 'shopware', array $tags = [])
  43. {
  44. $tags = array_merge(self::$tags, $tags);
  45. try {
  46. foreach (self::$profilers as $profiler) {
  47. $profiler->start($name, $category, $tags);
  48. }
  49. $result = $closure();
  50. } finally {
  51. foreach (self::$profilers as $profiler) {
  52. $profiler->stop($name);
  53. }
  54. }
  55. return $result;
  56. }
  57. public static function start(string $title, string $category, array $tags): void
  58. {
  59. self::$openTraces[] = $title;
  60. $tags = array_merge(self::$tags, $tags);
  61. foreach (self::$profilers as $profiler) {
  62. $profiler->start($title, $category, $tags);
  63. }
  64. }
  65. public static function stop(string $title): void
  66. {
  67. foreach (self::$profilers as $profiler) {
  68. $profiler->stop($title);
  69. }
  70. unset(self::$openTraces[$title]);
  71. }
  72. public static function cleanup(): void
  73. {
  74. foreach (self::$openTraces as $name) {
  75. foreach (self::$profilers as $profiler) {
  76. $profiler->stop($name);
  77. }
  78. }
  79. self::$openTraces = [];
  80. }
  81. public static function addTag(string $key, string $value): void
  82. {
  83. self::$tags[$key] = $value;
  84. }
  85. public static function removeTag(string $key): void
  86. {
  87. unset(self::$tags[$key]);
  88. }
  89. }