StatePlugin.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\NewRelicReporting\Plugin;
  8. use Magento\Framework\App\State;
  9. use Magento\Framework\Exception\LocalizedException;
  10. use Magento\NewRelicReporting\Model\Config;
  11. use Magento\NewRelicReporting\Model\NewRelicWrapper;
  12. use Psr\Log\LoggerInterface;
  13. /**
  14. * Handles setting which, when enabled, reports frontend and adminhtml as separate apps to New Relic.
  15. */
  16. class StatePlugin
  17. {
  18. /**
  19. * @var Config
  20. */
  21. private $config;
  22. /**
  23. * @var NewRelicWrapper
  24. */
  25. private $newRelicWrapper;
  26. /**
  27. * @var LoggerInterface
  28. */
  29. private $logger;
  30. /**
  31. * @param Config $config
  32. * @param NewRelicWrapper $newRelicWrapper
  33. * @param LoggerInterface $logger
  34. */
  35. public function __construct(
  36. Config $config,
  37. NewRelicWrapper $newRelicWrapper,
  38. LoggerInterface $logger
  39. ) {
  40. $this->config = $config;
  41. $this->newRelicWrapper = $newRelicWrapper;
  42. $this->logger = $logger;
  43. }
  44. /**
  45. * Set separate appname
  46. *
  47. * @param State $subject
  48. * @param mixed $result
  49. * @return mixed
  50. */
  51. public function afterSetAreaCode(State $subject, $result)
  52. {
  53. if (!$this->shouldSetAppName()) {
  54. return $result;
  55. }
  56. try {
  57. $this->newRelicWrapper->setAppName($this->appName($subject));
  58. } catch (LocalizedException $e) {
  59. $this->logger->critical($e);
  60. return $result;
  61. }
  62. return $result;
  63. }
  64. /**
  65. * Format appName.
  66. *
  67. * @param State $state
  68. * @return string
  69. * @throws LocalizedException
  70. */
  71. private function appName(State $state): string
  72. {
  73. $code = $state->getAreaCode();
  74. $current = $this->config->getNewRelicAppName();
  75. return $current . ';' . $current . '_' . $code;
  76. }
  77. /**
  78. * Check if app name should be set.
  79. *
  80. * @return bool
  81. */
  82. private function shouldSetAppName(): bool
  83. {
  84. return (
  85. $this->config->isSeparateApps() &&
  86. $this->config->getNewRelicAppName() &&
  87. $this->config->isNewRelicEnabled()
  88. );
  89. }
  90. }