Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CronEvent.php
Go to the documentation of this file.
1 <?php
7 
8 use \Magento\Framework\HTTP\ZendClient;
9 
10 class CronEvent
11 {
15  protected $request;
16 
22  protected $eventsUrl = '';
23 
29  protected $customParameters = [];
30 
34  protected $config;
35 
39  protected $jsonEncoder;
40 
44  protected $clientFactory;
45 
53  public function __construct(
54  \Magento\NewRelicReporting\Model\Config $config,
55  \Magento\Framework\Json\EncoderInterface $jsonEncoder,
56  \Magento\Framework\HTTP\ZendClientFactory $clientFactory
57  ) {
58  $this->config = $config;
59  $this->jsonEncoder = $jsonEncoder;
60  $this->clientFactory = $clientFactory;
61  }
62 
69  protected function getEventsUrl()
70  {
71  if (empty($this->eventsUrl)) {
72  $accountId = $this->config->getNewRelicAccountId();
73  if (empty($accountId)) {
74  throw new \Magento\Framework\Exception\LocalizedException(__(
75  'No New Relic Application ID configured, cannot continue with Cron Event reporting'
76  ));
77  }
78  $this->eventsUrl = sprintf(
79  $this->config->getInsightsApiUrl(),
80  $accountId
81  );
82  }
83  return $this->eventsUrl;
84  }
85 
91  protected function getRequest()
92  {
93  if (!isset($this->request)) {
94  $this->request = $this->clientFactory->create();
95  $this->request->setUri($this->getEventsUrl());
96  $insertKey = $this->config->getInsightsInsertKey();
97 
98  $this->request->setMethod(ZendClient::POST);
99  $this->request->setHeaders(
100  [
101  'X-Insert-Key' => $insertKey,
102  'Content-Type' => 'application/json',
103  ]
104  );
105  }
106  return $this->request;
107  }
108 
114  protected function getJsonForResponse()
115  {
116  $json = [
117  'eventType' => 'Cron',
118  'appName' => $this->config->getNewRelicAppName(),
119  'appId' => $this->config->getNewRelicAppId(),
120  ];
121  $jsonArrayKeys = array_keys($json);
122 
123  foreach ($jsonArrayKeys as $jsonKey) {
124  if (array_key_exists($jsonKey, $this->customParameters)) {
125  unset($this->customParameters[$jsonKey]);
126  }
127  }
128 
129  $json = array_merge($json, $this->customParameters);
130 
131  return $this->jsonEncoder->encode($json);
132  }
133 
140  public function addData(array $data)
141  {
142  $this->customParameters = array_merge($this->customParameters, $data);
143  return $this;
144  }
145 
151  public function sendRequest()
152  {
153  $response = $this->getRequest()
154  ->setRawData($this->getJsonForResponse())
155  ->request();
156 
157  if ($response->getStatus() >= 200 && $response->getStatus() < 300) {
158  return true;
159  }
160  return false;
161  }
162 }
$response
Definition: 404.php:11
__construct(\Magento\NewRelicReporting\Model\Config $config, \Magento\Framework\Json\EncoderInterface $jsonEncoder, \Magento\Framework\HTTP\ZendClientFactory $clientFactory)
Definition: CronEvent.php:53
__()
Definition: __.php:13