Post.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <?php
  2. /**
  3. * Copyright © 2016 Ihor Vansach (ihor@magefan.com). All rights reserved.
  4. * See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).
  5. *
  6. * Glory to Ukraine! Glory to the heroes!
  7. */
  8. namespace Magefan\Blog\Model\ResourceModel;
  9. /**
  10. * Blog category resource model
  11. */
  12. class Post extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
  13. {
  14. /**
  15. * @var \Magento\Framework\Stdlib\DateTime\DateTime
  16. */
  17. protected $_date;
  18. /**
  19. * @var \Magento\Framework\Stdlib\DateTime
  20. */
  21. protected $dateTime;
  22. /**
  23. * Construct
  24. *
  25. * @param \Magento\Framework\Model\ResourceModel\Db\Context $context
  26. * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
  27. * @param \Magento\Framework\Stdlib\DateTime $dateTime
  28. * @param string|null $resourcePrefix
  29. */
  30. public function __construct(
  31. \Magento\Framework\Model\ResourceModel\Db\Context $context,
  32. \Magento\Framework\Stdlib\DateTime\DateTime $date,
  33. \Magento\Framework\Stdlib\DateTime $dateTime,
  34. $resourcePrefix = null
  35. ) {
  36. parent::__construct($context, $resourcePrefix);
  37. $this->_date = $date;
  38. $this->dateTime = $dateTime;
  39. }
  40. /**
  41. * Initialize resource model
  42. * Get tablename from config
  43. *
  44. * @return void
  45. */
  46. protected function _construct()
  47. {
  48. $this->_init('magefan_blog_post', 'post_id');
  49. }
  50. /**
  51. * Retrieve date object
  52. * @return \Magento\Framework\Stdlib\DateTime
  53. */
  54. public function getDate()
  55. {
  56. return $this->_date;
  57. }
  58. /**
  59. * Process post data before deleting
  60. *
  61. * @param \Magento\Framework\Model\AbstractModel $object
  62. * @return $this
  63. */
  64. protected function _beforeDelete(
  65. \Magento\Framework\Model\AbstractModel $object
  66. ){
  67. $condition = ['post_id = ?' => (int)$object->getId()];
  68. $tableSufixs = [
  69. 'store',
  70. 'category',
  71. 'tag',
  72. 'relatedproduct',
  73. 'relatedpost',
  74. 'relatedpost',
  75. ];
  76. foreach ($tableSufixs as $sufix) {
  77. $this->getConnection()->delete(
  78. $this->getTable('magefan_blog_post_' . $sufix),
  79. ($sufix == 'relatedpost')
  80. ? ['related_id = ?' => (int)$object->getId()]
  81. : $condition
  82. );
  83. }
  84. return parent::_beforeDelete($object);
  85. }
  86. /**
  87. * Process post data before saving
  88. *
  89. * @param \Magento\Framework\Model\AbstractModel $object
  90. * @return $this
  91. * @throws \Magento\Framework\Exception\LocalizedException
  92. */
  93. protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
  94. {
  95. foreach (['publish_time', 'custom_theme_from', 'custom_theme_to'] as $field) {
  96. $value = $object->getData($field) ?: null;
  97. $object->setData($field, $this->dateTime->formatDate($value));
  98. }
  99. $identifierGenerator = \Magento\Framework\App\ObjectManager::getInstance()
  100. ->create('Magefan\Blog\Model\ResourceModel\PageIdentifierGenerator');
  101. $identifierGenerator->generate($object);
  102. if (!$this->isValidPageIdentifier($object)) {
  103. throw new \Magento\Framework\Exception\LocalizedException(
  104. __('The post URL key contains capital letters or disallowed symbols.')
  105. );
  106. }
  107. if ($this->isNumericPageIdentifier($object)) {
  108. throw new \Magento\Framework\Exception\LocalizedException(
  109. __('The post URL key cannot be made of only numbers.')
  110. );
  111. }
  112. $gmtDate = $this->_date->gmtDate();
  113. if ($object->isObjectNew() && !$object->getCreationTime()) {
  114. $object->setCreationTime($gmtDate);
  115. }
  116. if (!$object->getPublishTime()) {
  117. $object->setPublishTime($object->getCreationTime());
  118. }
  119. $object->setUpdateTime($gmtDate);
  120. return parent::_beforeSave($object);
  121. }
  122. /**
  123. * Assign post to store views, categories, related posts, etc.
  124. *
  125. * @param \Magento\Framework\Model\AbstractModel $object
  126. * @return $this
  127. */
  128. protected function _afterSave(\Magento\Framework\Model\AbstractModel $object)
  129. {
  130. $oldIds = $this->lookupStoreIds($object->getId());
  131. $newIds = (array)$object->getStoreIds();
  132. if (!$newIds) {
  133. $newIds = [0];
  134. }
  135. $this->_updateLinks($object, $newIds, $oldIds, 'magefan_blog_post_store', 'store_id');
  136. /* Save category & tag links */
  137. foreach (['category' => 'categories', 'tag' => 'tags'] as $linkType => $dataKey) {
  138. $newIds = (array)$object->getData($dataKey);
  139. foreach($newIds as $key => $id) {
  140. if (!$id) { // e.g.: zero
  141. unset($newIds[$key]);
  142. }
  143. }
  144. if (is_array($newIds)) {
  145. $lookup = 'lookup' . ucfirst($linkType) . 'Ids';
  146. $oldIds = $this->$lookup($object->getId());
  147. $this->_updateLinks(
  148. $object,
  149. $newIds,
  150. $oldIds,
  151. 'magefan_blog_post_' . $linkType,
  152. $linkType . '_id'
  153. );
  154. }
  155. }
  156. /* Save tags links */
  157. $newIds = (array)$object->getTags();
  158. foreach($newIds as $key => $id) {
  159. if (!$id) { // e.g.: zero
  160. unset($newIds[$key]);
  161. }
  162. }
  163. if (is_array($newIds)) {
  164. $oldIds = $this->lookupTagIds($object->getId());
  165. $this->_updateLinks($object, $newIds, $oldIds, 'magefan_blog_post_tag', 'tag_id');
  166. }
  167. /* Save related post & product links */
  168. if ($links = $object->getData('links')) {
  169. if (is_array($links)) {
  170. foreach (['post', 'product'] as $linkType) {
  171. if (isset($links[$linkType]) && is_array($links[$linkType])) {
  172. $linksData = $links[$linkType];
  173. $lookup = 'lookupRelated' . ucfirst($linkType) . 'Ids';
  174. $oldIds = $this->$lookup($object->getId());
  175. $this->_updateLinks(
  176. $object,
  177. array_keys($linksData),
  178. $oldIds,
  179. 'magefan_blog_post_related' . $linkType,
  180. 'related_id',
  181. $linksData
  182. );
  183. }
  184. }
  185. }
  186. }
  187. return parent::_afterSave($object);
  188. }
  189. /**
  190. * Update post connections
  191. * @param \Magento\Framework\Model\AbstractModel $object
  192. * @param Array $newRelatedIds
  193. * @param Array $oldRelatedIds
  194. * @param String $tableName
  195. * @param String $field
  196. * @param Array $rowData
  197. * @return void
  198. */
  199. protected function _updateLinks(
  200. \Magento\Framework\Model\AbstractModel $object,
  201. Array $newRelatedIds,
  202. Array $oldRelatedIds,
  203. $tableName,
  204. $field,
  205. $rowData = []
  206. ) {
  207. $table = $this->getTable($tableName);
  208. $insert = $newRelatedIds;
  209. $delete = $oldRelatedIds;
  210. if ($delete) {
  211. $where = ['post_id = ?' => (int)$object->getId(), $field.' IN (?)' => $delete];
  212. $this->getConnection()->delete($table, $where);
  213. }
  214. if ($insert) {
  215. $data = [];
  216. foreach ($insert as $id) {
  217. $id = (int)$id;
  218. $data[] = array_merge(['post_id' => (int)$object->getId(), $field => $id],
  219. (isset($rowData[$id]) && is_array($rowData[$id])) ? $rowData[$id] : []
  220. );
  221. }
  222. $this->getConnection()->insertMultiple($table, $data);
  223. }
  224. }
  225. /**
  226. * Load an object using 'identifier' field if there's no field specified and value is not numeric
  227. *
  228. * @param \Magento\Framework\Model\AbstractModel $object
  229. * @param mixed $value
  230. * @param string $field
  231. * @return $this
  232. */
  233. public function load(\Magento\Framework\Model\AbstractModel $object, $value, $field = null)
  234. {
  235. if (!is_numeric($value) && is_null($field)) {
  236. $field = 'identifier';
  237. }
  238. return parent::load($object, $value, $field);
  239. }
  240. /**
  241. * Perform operations after object load
  242. *
  243. * @param \Magento\Framework\Model\AbstractModel $object
  244. * @return $this
  245. */
  246. protected function _afterLoad(\Magento\Framework\Model\AbstractModel $object)
  247. {
  248. if ($object->getId()) {
  249. $storeIds = $this->lookupStoreIds($object->getId());
  250. $object->setData('store_ids', $storeIds);
  251. $categories = $this->lookupCategoryIds($object->getId());
  252. $object->setCategories($categories);
  253. $tags = $this->lookupTagIds($object->getId());
  254. $object->setTags($tags);
  255. }
  256. return parent::_afterLoad($object);
  257. }
  258. /**
  259. * Check if post identifier exist for specific store
  260. * return post id if post exists
  261. *
  262. * @param string $identifier
  263. * @param int $storeId
  264. * @return int
  265. */
  266. protected function _getLoadByIdentifierSelect($identifier, $storeIds)
  267. {
  268. $select = $this->getConnection()->select()->from(
  269. ['cp' => $this->getMainTable()]
  270. )->join(
  271. ['cps' => $this->getTable('magefan_blog_post_store')],
  272. 'cp.post_id = cps.post_id',
  273. []
  274. )->where(
  275. 'cp.identifier = ?',
  276. $identifier
  277. )->where(
  278. 'cps.store_id IN (?)',
  279. $storeIds
  280. );
  281. return $select;
  282. }
  283. /**
  284. * Check whether post identifier is numeric
  285. *
  286. * @param \Magento\Framework\Model\AbstractModel $object
  287. * @return bool
  288. */
  289. protected function isNumericPageIdentifier(\Magento\Framework\Model\AbstractModel $object)
  290. {
  291. return preg_match('/^[0-9]+$/', $object->getData('identifier'));
  292. }
  293. /**
  294. * Check whether post identifier is valid
  295. *
  296. * @param \Magento\Framework\Model\AbstractModel $object
  297. * @return bool
  298. */
  299. protected function isValidPageIdentifier(\Magento\Framework\Model\AbstractModel $object)
  300. {
  301. return preg_match('/^[a-z0-9][a-z0-9_\/-]+(\.[a-z0-9_-]+)?$/', $object->getData('identifier'));
  302. }
  303. /**
  304. * Check if post identifier exist for specific store
  305. * return post id if post exists
  306. *
  307. * @param string $identifier
  308. * @param int|array $storeId
  309. * @return int
  310. */
  311. public function checkIdentifier($identifier, $storeIds)
  312. {
  313. if (!is_array($storeIds)) {
  314. $storeIds = [$storeIds];
  315. }
  316. $storeIds[] = \Magento\Store\Model\Store::DEFAULT_STORE_ID;
  317. $select = $this->_getLoadByIdentifierSelect($identifier, $storeIds);
  318. $select->reset(\Zend_Db_Select::COLUMNS)->columns('cp.post_id')->order('cps.store_id DESC')->limit(1);
  319. return $this->getConnection()->fetchOne($select);
  320. }
  321. /**
  322. * Get store ids to which specified item is assigned
  323. *
  324. * @param int $postId
  325. * @return array
  326. */
  327. public function lookupStoreIds($postId)
  328. {
  329. return $this->_lookupIds($postId, 'magefan_blog_post_store', 'store_id');
  330. }
  331. /**
  332. * Get category ids to which specified item is assigned
  333. *
  334. * @param int $postId
  335. * @return array
  336. */
  337. public function lookupCategoryIds($postId)
  338. {
  339. return $this->_lookupIds($postId, 'magefan_blog_post_category', 'category_id');
  340. }
  341. /**
  342. * Get tag ids to which specified item is assigned
  343. *
  344. * @param int $postId
  345. * @return array
  346. */
  347. public function lookupTagIds($postId)
  348. {
  349. return $this->_lookupIds($postId, 'magefan_blog_post_tag', 'tag_id');
  350. }
  351. /**
  352. * Get related post ids to which specified item is assigned
  353. *
  354. * @param int $postId
  355. * @return array
  356. */
  357. public function lookupRelatedPostIds($postId)
  358. {
  359. return $this->_lookupIds($postId, 'magefan_blog_post_relatedpost', 'related_id');
  360. }
  361. /**
  362. * Get related product ids to which specified item is assigned
  363. *
  364. * @param int $postId
  365. * @return array
  366. */
  367. public function lookupRelatedProductIds($postId)
  368. {
  369. return $this->_lookupIds($postId, 'magefan_blog_post_relatedproduct', 'related_id');
  370. }
  371. /**
  372. * Get ids to which specified item is assigned
  373. * @param int $postId
  374. * @param string $tableName
  375. * @param string $field
  376. * @return array
  377. */
  378. protected function _lookupIds($postId, $tableName, $field)
  379. {
  380. $adapter = $this->getConnection();
  381. $select = $adapter->select()->from(
  382. $this->getTable($tableName),
  383. $field
  384. )->where(
  385. 'post_id = ?',
  386. (int)$postId
  387. );
  388. return $adapter->fetchCol($select);
  389. }
  390. }