Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AbstractSave.php
Go to the documentation of this file.
1 <?php
9 
12 
17 abstract class AbstractSave implements ObserverInterface
18 {
22  protected $_helper;
23 
27  protected $_modelCode;
28 
32  protected $_request;
33 
37  protected $_params;
38 
44  public function __construct(
45  \Magento\GoogleOptimizer\Helper\Data $helper,
46  \Magento\GoogleOptimizer\Model\Code $modelCode,
47  \Magento\Framework\App\RequestInterface $request
48  ) {
49  $this->_helper = $helper;
50  $this->_modelCode = $modelCode;
51  $this->_request = $request;
52  }
53 
60  public function execute(Observer $observer)
61  {
62  $this->_initEntity($observer);
63 
64  if ($this->_isGoogleExperimentActive() && $this->isDataAvailable()) {
65  $this->_processCode();
66  }
67 
68  return $this;
69  }
70 
77  abstract protected function _initEntity($observer);
78 
84  protected function _isGoogleExperimentActive()
85  {
86  return $this->_helper->isGoogleExperimentActive();
87  }
88 
94  protected function _processCode()
95  {
96  $this->_initRequestParams();
97 
98  if ($this->_isNewCode()) {
99  $this->_saveCode();
100  } else {
101  $this->_loadCode();
102  if ($this->_isEmptyCode()) {
103  $this->_deleteCode();
104  } else {
105  $this->_saveCode();
106  }
107  }
108  }
109 
116  protected function _initRequestParams()
117  {
118  if (!$this->isDataAvailable()) {
119  throw new \InvalidArgumentException('Wrong request parameters');
120  }
121  $this->_params = $this->getRequestData();
122  }
123 
129  protected function _isNewCode()
130  {
131  return empty($this->_params['code_id']);
132  }
133 
139  protected function _saveCode()
140  {
141  $this->_modelCode->addData($this->_getCodeData());
142  $this->_modelCode->save();
143  }
144 
150  abstract protected function _getCodeData();
151 
158  protected function _loadCode()
159  {
160  $this->_modelCode->load($this->_params['code_id']);
161  if (!$this->_modelCode->getId()) {
162  throw new \InvalidArgumentException('Code does not exist');
163  }
164  }
165 
171  protected function _isEmptyCode()
172  {
173  return empty($this->_params['experiment_script']);
174  }
175 
182  protected function _deleteCode()
183  {
184  $this->_modelCode->delete();
185  }
186 
190  private function isDataAvailable()
191  {
192  $params = $this->getRequestData();
193  return is_array($params) && isset($params['experiment_script']) && isset($params['code_id']);
194  }
195 
199  private function getRequestData()
200  {
201  return $this->_request->getParam('google_experiment');
202  }
203 }
$helper
Definition: iframe.phtml:13
__construct(\Magento\GoogleOptimizer\Helper\Data $helper, \Magento\GoogleOptimizer\Model\Code $modelCode, \Magento\Framework\App\RequestInterface $request)
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18