PostManagement.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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;
  9. /**
  10. * Post management model
  11. */
  12. class PostManagement extends AbstractManagement
  13. {
  14. /**
  15. * @var \Magefan\Blog\Model\PostFactory
  16. */
  17. protected $_itemFactory;
  18. /**
  19. * Initialize dependencies.
  20. *
  21. * @param \Magefan\Blog\Model\PostFactory $postFactory
  22. */
  23. public function __construct(
  24. \Magefan\Blog\Model\PostFactory $postFactory
  25. ) {
  26. $this->_itemFactory = $postFactory;
  27. }
  28. /**
  29. * Retrieve list of post by page type, term, store, etc
  30. *
  31. * @param string $type
  32. * @param string $term
  33. * @param int $storeId
  34. * @param int $page
  35. * @param int $limit
  36. * @return bool
  37. */
  38. public function getList($type, $term, $storeId, $page, $limit)
  39. {
  40. try {
  41. $collection = $this->_itemFactory->create()->getCollection();
  42. $collection
  43. ->addActiveFilter()
  44. ->addStoreFilter($storeId)
  45. ->setOrder('publish_time', 'DESC')
  46. ->setCurPage($page)
  47. ->setPageSize($limit);
  48. $type = strtolower($type);
  49. switch ($type) {
  50. case 'archive' :
  51. $term = explode('-', $term);
  52. if (count($term) < 2) {
  53. return false;
  54. }
  55. list($year, $month) = $term;
  56. $year = (int) $year;
  57. $month = (int) $month;
  58. if ($year < 1970) {
  59. return false;
  60. }
  61. if ($month < 1 || $month > 12) {
  62. return false;
  63. }
  64. $collection->addArchiveFilter($year, $month);
  65. break;
  66. case 'author' :
  67. $collection->addAuthorFilter($term);
  68. break;
  69. case 'category' :
  70. $collection->addCategoryFilter($term);
  71. break;
  72. case 'search' :
  73. $collection->addSearchFilter($term);
  74. break;
  75. case 'tag' :
  76. $collection->addTagFilter($term);
  77. break;
  78. }
  79. $posts = [];
  80. foreach ($collection as $item) {
  81. $item->initDinamicData();
  82. $posts[] = $item->getData();
  83. }
  84. $result = [
  85. 'posts' => $posts,
  86. 'total_number' => $collection->getSize(),
  87. 'current_page' => $collection->getCurPage(),
  88. 'last_page' => $collection->getLastPageNumber(),
  89. ];
  90. return json_encode($result);
  91. } catch (\Exception $e) {
  92. return false;
  93. }
  94. }
  95. }