AbstractModel.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Rule\Model;
  7. use Magento\Framework\Api\AttributeValueFactory;
  8. use Magento\Framework\Api\ExtensionAttributesFactory;
  9. /**
  10. * Abstract Rule entity data model
  11. *
  12. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  13. * @api
  14. * @since 100.0.2
  15. */
  16. abstract class AbstractModel extends \Magento\Framework\Model\AbstractExtensibleModel
  17. {
  18. /**
  19. * Store rule combine conditions model
  20. *
  21. * @var \Magento\Rule\Model\Condition\Combine
  22. */
  23. protected $_conditions;
  24. /**
  25. * Store rule actions model
  26. *
  27. * @var \Magento\Rule\Model\Action\Collection
  28. */
  29. protected $_actions;
  30. /**
  31. * Store rule form instance
  32. *
  33. * @var \Magento\Framework\Data\Form
  34. */
  35. protected $_form;
  36. /**
  37. * Is model can be deleted flag
  38. *
  39. * @var bool
  40. */
  41. protected $_isDeleteable = true;
  42. /**
  43. * Is model readonly
  44. *
  45. * @var bool
  46. */
  47. protected $_isReadonly = false;
  48. /**
  49. * @var \Magento\Framework\Serialize\Serializer\Json
  50. * @since 100.2.0
  51. */
  52. protected $serializer;
  53. /**
  54. * Getter for rule combine conditions instance
  55. *
  56. * @return \Magento\Rule\Model\Condition\Combine
  57. */
  58. abstract public function getConditionsInstance();
  59. /**
  60. * Getter for rule actions collection instance
  61. *
  62. * @return \Magento\Rule\Model\Action\Collection
  63. */
  64. abstract public function getActionsInstance();
  65. /**
  66. * Form factory
  67. *
  68. * @var \Magento\Framework\Data\FormFactory
  69. */
  70. protected $_formFactory;
  71. /**
  72. * Timezone instance
  73. *
  74. * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
  75. */
  76. protected $_localeDate;
  77. /**
  78. * AbstractModel constructor
  79. *
  80. * @param \Magento\Framework\Model\Context $context
  81. * @param \Magento\Framework\Registry $registry
  82. * @param \Magento\Framework\Data\FormFactory $formFactory
  83. * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  84. * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
  85. * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
  86. * @param array $data
  87. * @param ExtensionAttributesFactory|null $extensionFactory
  88. * @param AttributeValueFactory|null $customAttributeFactory
  89. * @param \Magento\Framework\Serialize\Serializer\Json $serializer
  90. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  91. */
  92. public function __construct(
  93. \Magento\Framework\Model\Context $context,
  94. \Magento\Framework\Registry $registry,
  95. \Magento\Framework\Data\FormFactory $formFactory,
  96. \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
  97. \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
  98. \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
  99. array $data = [],
  100. ExtensionAttributesFactory $extensionFactory = null,
  101. AttributeValueFactory $customAttributeFactory = null,
  102. \Magento\Framework\Serialize\Serializer\Json $serializer = null
  103. ) {
  104. $this->_formFactory = $formFactory;
  105. $this->_localeDate = $localeDate;
  106. $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()->get(
  107. \Magento\Framework\Serialize\Serializer\Json::class
  108. );
  109. parent::__construct(
  110. $context,
  111. $registry,
  112. $extensionFactory ?: $this->getExtensionFactory(),
  113. $customAttributeFactory ?: $this->getCustomAttributeFactory(),
  114. $resource,
  115. $resourceCollection,
  116. $data
  117. );
  118. }
  119. /**
  120. * Prepare data before saving
  121. *
  122. * @return $this
  123. * @throws \Magento\Framework\Exception\LocalizedException
  124. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  125. */
  126. public function beforeSave()
  127. {
  128. // Check if discount amount not negative
  129. if ($this->hasDiscountAmount()) {
  130. if ((int)$this->getDiscountAmount() < 0) {
  131. throw new \Magento\Framework\Exception\LocalizedException(__('Please choose a valid discount amount.'));
  132. }
  133. }
  134. // Serialize conditions
  135. if ($this->getConditions()) {
  136. $this->setConditionsSerialized($this->serializer->serialize($this->getConditions()->asArray()));
  137. $this->_conditions = null;
  138. }
  139. // Serialize actions
  140. if ($this->getActions()) {
  141. $this->setActionsSerialized($this->serializer->serialize($this->getActions()->asArray()));
  142. $this->_actions = null;
  143. }
  144. /**
  145. * Prepare website Ids if applicable and if they were set as string in comma separated format.
  146. * Backwards compatibility.
  147. */
  148. if ($this->hasWebsiteIds()) {
  149. $websiteIds = $this->getWebsiteIds();
  150. if (is_string($websiteIds) && !empty($websiteIds)) {
  151. $this->setWebsiteIds(explode(',', $websiteIds));
  152. }
  153. }
  154. /**
  155. * Prepare customer group Ids if applicable and if they were set as string in comma separated format.
  156. * Backwards compatibility.
  157. */
  158. if ($this->hasCustomerGroupIds()) {
  159. $groupIds = $this->getCustomerGroupIds();
  160. if (is_string($groupIds) && !empty($groupIds)) {
  161. $this->setCustomerGroupIds(explode(',', $groupIds));
  162. }
  163. }
  164. parent::beforeSave();
  165. return $this;
  166. }
  167. /**
  168. * Set rule combine conditions model
  169. *
  170. * @param \Magento\Rule\Model\Condition\Combine $conditions
  171. * @return $this
  172. */
  173. public function setConditions($conditions)
  174. {
  175. $this->_conditions = $conditions;
  176. return $this;
  177. }
  178. /**
  179. * Retrieve rule combine conditions model
  180. *
  181. * @return \Magento\Rule\Model\Condition\Combine
  182. */
  183. public function getConditions()
  184. {
  185. if (empty($this->_conditions)) {
  186. $this->_resetConditions();
  187. }
  188. // Load rule conditions if it is applicable
  189. if ($this->hasConditionsSerialized()) {
  190. $conditions = $this->getConditionsSerialized();
  191. if (!empty($conditions)) {
  192. $conditions = $this->serializer->unserialize($conditions);
  193. if (is_array($conditions) && !empty($conditions)) {
  194. $this->_conditions->loadArray($conditions);
  195. }
  196. }
  197. $this->unsConditionsSerialized();
  198. }
  199. return $this->_conditions;
  200. }
  201. /**
  202. * Set rule actions model
  203. *
  204. * @param \Magento\Rule\Model\Action\Collection $actions
  205. * @return $this
  206. */
  207. public function setActions($actions)
  208. {
  209. $this->_actions = $actions;
  210. return $this;
  211. }
  212. /**
  213. * Retrieve rule actions model
  214. *
  215. * @return \Magento\Rule\Model\Action\Collection
  216. */
  217. public function getActions()
  218. {
  219. if (!$this->_actions) {
  220. $this->_resetActions();
  221. }
  222. // Load rule actions if it is applicable
  223. if ($this->hasActionsSerialized()) {
  224. $actions = $this->getActionsSerialized();
  225. if (!empty($actions)) {
  226. $actions = $this->serializer->unserialize($actions);
  227. if (is_array($actions) && !empty($actions)) {
  228. $this->_actions->loadArray($actions);
  229. }
  230. }
  231. $this->unsActionsSerialized();
  232. }
  233. return $this->_actions;
  234. }
  235. /**
  236. * Reset rule combine conditions
  237. *
  238. * @param null|\Magento\Rule\Model\Condition\Combine $conditions
  239. * @return $this
  240. */
  241. protected function _resetConditions($conditions = null)
  242. {
  243. if (null === $conditions) {
  244. $conditions = $this->getConditionsInstance();
  245. }
  246. $conditions->setRule($this)->setId('1')->setPrefix('conditions');
  247. $this->setConditions($conditions);
  248. return $this;
  249. }
  250. /**
  251. * Reset rule actions
  252. *
  253. * @param null|\Magento\Rule\Model\Action\Collection $actions
  254. * @return $this
  255. */
  256. protected function _resetActions($actions = null)
  257. {
  258. if (null === $actions) {
  259. $actions = $this->getActionsInstance();
  260. }
  261. $actions->setRule($this)->setId('1')->setPrefix('actions');
  262. $this->setActions($actions);
  263. return $this;
  264. }
  265. /**
  266. * Rule form getter
  267. *
  268. * @return \Magento\Framework\Data\Form
  269. */
  270. public function getForm()
  271. {
  272. if (!$this->_form) {
  273. $this->_form = $this->_formFactory->create();
  274. }
  275. return $this->_form;
  276. }
  277. /**
  278. * Initialize rule model data from array
  279. *
  280. * @param array $data
  281. * @return $this
  282. */
  283. public function loadPost(array $data)
  284. {
  285. $arr = $this->_convertFlatToRecursive($data);
  286. if (isset($arr['conditions'])) {
  287. $this->getConditions()->setConditions([])->loadArray($arr['conditions'][1]);
  288. }
  289. if (isset($arr['actions'])) {
  290. $this->getActions()->setActions([])->loadArray($arr['actions'][1], 'actions');
  291. }
  292. return $this;
  293. }
  294. /**
  295. * Set specified data to current rule.
  296. * Set conditions and actions recursively.
  297. * Convert dates into \DateTime.
  298. *
  299. * @param array $data
  300. * @return array
  301. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  302. */
  303. protected function _convertFlatToRecursive(array $data)
  304. {
  305. $arr = [];
  306. foreach ($data as $key => $value) {
  307. if (($key === 'conditions' || $key === 'actions') && is_array($value)) {
  308. foreach ($value as $id => $data) {
  309. $path = explode('--', $id);
  310. $node = & $arr;
  311. for ($i = 0, $l = sizeof($path); $i < $l; $i++) {
  312. if (!isset($node[$key][$path[$i]])) {
  313. $node[$key][$path[$i]] = [];
  314. }
  315. $node = & $node[$key][$path[$i]];
  316. }
  317. foreach ($data as $k => $v) {
  318. $node[$k] = $v;
  319. }
  320. }
  321. } else {
  322. /**
  323. * Convert dates into \DateTime
  324. */
  325. if (in_array($key, ['from_date', 'to_date'], true) && $value) {
  326. $value = new \DateTime($value);
  327. }
  328. $this->setData($key, $value);
  329. }
  330. }
  331. return $arr;
  332. }
  333. /**
  334. * Validate rule conditions to determine if rule can run
  335. *
  336. * @param \Magento\Framework\DataObject $object
  337. * @return bool
  338. */
  339. public function validate(\Magento\Framework\DataObject $object)
  340. {
  341. return $this->getConditions()->validate($object);
  342. }
  343. /**
  344. * Validate rule data
  345. *
  346. * @param \Magento\Framework\DataObject $dataObject
  347. * @return bool|string[] - return true if validation passed successfully. Array with errors description otherwise
  348. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  349. * @SuppressWarnings(PHPMD.NPathComplexity)
  350. */
  351. public function validateData(\Magento\Framework\DataObject $dataObject)
  352. {
  353. $result = [];
  354. $fromDate = $toDate = null;
  355. if ($dataObject->hasFromDate() && $dataObject->hasToDate()) {
  356. $fromDate = $dataObject->getFromDate();
  357. $toDate = $dataObject->getToDate();
  358. }
  359. if ($fromDate && $toDate) {
  360. $fromDate = new \DateTime($fromDate);
  361. $toDate = new \DateTime($toDate);
  362. if ($fromDate > $toDate) {
  363. $result[] = __('End Date must follow Start Date.');
  364. }
  365. }
  366. if ($dataObject->hasWebsiteIds()) {
  367. $websiteIds = $dataObject->getWebsiteIds();
  368. if (empty($websiteIds)) {
  369. $result[] = __('Please specify a website.');
  370. }
  371. }
  372. if ($dataObject->hasCustomerGroupIds()) {
  373. $customerGroupIds = $dataObject->getCustomerGroupIds();
  374. if (empty($customerGroupIds)) {
  375. $result[] = __('Please specify Customer Groups.');
  376. }
  377. }
  378. return !empty($result) ? $result : true;
  379. }
  380. /**
  381. * Check availability to delete rule
  382. *
  383. * @return bool
  384. * @codeCoverageIgnore
  385. */
  386. public function isDeleteable()
  387. {
  388. return $this->_isDeleteable;
  389. }
  390. /**
  391. * Set is rule can be deleted flag
  392. *
  393. * @param bool $value
  394. * @return $this
  395. * @codeCoverageIgnore
  396. */
  397. public function setIsDeleteable($value)
  398. {
  399. $this->_isDeleteable = (bool)$value;
  400. return $this;
  401. }
  402. /**
  403. * Check if rule is readonly
  404. *
  405. * @return bool
  406. * @codeCoverageIgnore
  407. */
  408. public function isReadonly()
  409. {
  410. return $this->_isReadonly;
  411. }
  412. /**
  413. * Set is readonly flag to rule
  414. *
  415. * @param bool $value
  416. * @return $this
  417. * @codeCoverageIgnore
  418. */
  419. public function setIsReadonly($value)
  420. {
  421. $this->_isReadonly = (bool)$value;
  422. return $this;
  423. }
  424. /**
  425. * Get rule associated website Ids
  426. *
  427. * @return array
  428. */
  429. public function getWebsiteIds()
  430. {
  431. if (!$this->hasWebsiteIds()) {
  432. $websiteIds = $this->_getResource()->getWebsiteIds($this->getId());
  433. $this->setData('website_ids', (array)$websiteIds);
  434. }
  435. return $this->_getData('website_ids');
  436. }
  437. /**
  438. * @return \Magento\Framework\Api\ExtensionAttributesFactory
  439. * @deprecated 100.1.0
  440. */
  441. private function getExtensionFactory()
  442. {
  443. return \Magento\Framework\App\ObjectManager::getInstance()
  444. ->get(\Magento\Framework\Api\ExtensionAttributesFactory::class);
  445. }
  446. /**
  447. * @return \Magento\Framework\Api\AttributeValueFactory
  448. * @deprecated 100.1.0
  449. */
  450. private function getCustomAttributeFactory()
  451. {
  452. return \Magento\Framework\App\ObjectManager::getInstance()
  453. ->get(\Magento\Framework\Api\AttributeValueFactory::class);
  454. }
  455. }