This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
+962
View File
@@ -0,0 +1,962 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Api;
use Exception;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection as SalesAbstractCollection;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Blog\Api\BlogRepositoryInterface;
use Mageplaza\Blog\Api\Data\AuthorInterface;
use Mageplaza\Blog\Api\Data\CategoryInterface;
use Mageplaza\Blog\Api\Data\PostInterface;
use Mageplaza\Blog\Api\Data\TagInterface;
use Mageplaza\Blog\Api\Data\TopicInterface;
use Mageplaza\Blog\Helper\Data;
use Mageplaza\Blog\Model\CommentFactory;
use Mageplaza\Blog\Model\Config\General;
use Mageplaza\Blog\Model\Config\Sidebar;
use Mageplaza\Blog\Model\Config\Seo;
use Mageplaza\Blog\Model\BlogConfig;
use Mageplaza\Blog\Model\MonthlyArchive;
use Mageplaza\Blog\Block\MonthlyArchive\Widget as MonthlyWidget;
use Mageplaza\Blog\Model\PostLikeFactory;
/**
* Class BlogRepository
* @package Mageplaza\Blog\Model\Api
*/
class BlogRepository implements BlogRepositoryInterface
{
/**
* @var Data
*/
protected $_helperData;
/**
* @var DateTime
*/
protected $date;
/**
* @var CustomerRepositoryInterface
*/
protected $_customerRepositoryInterface;
/**
* @var CollectionProcessorInterface
*/
protected $collectionProcessor;
/**
* @var CommentFactory
*/
protected $_commentFactory;
/**
* @var PostLikeFactory
*/
protected $_likeFactory;
/**
* @var RequestInterface
*/
protected $_request;
/**
* @var BlogConfig
*/
protected $blogConfig;
/**
* @var MonthlyWidget
*/
protected $monthlyWidget;
/**
* BlogRepository constructor.
*
* @param Data $helperData
* @param CustomerRepositoryInterface $customerRepositoryInterface
* @param CollectionProcessorInterface $collectionProcessor
* @param CommentFactory $commentFactory
* @param PostLikeFactory $likeFactory
* @param RequestInterface $request
* @param BlogConfig $blogConfig
* @param MonthlyWidget $monthlyWidget
* @param DateTime $date
*/
public function __construct(
Data $helperData,
CustomerRepositoryInterface $customerRepositoryInterface,
CollectionProcessorInterface $collectionProcessor,
CommentFactory $commentFactory,
PostLikeFactory $likeFactory,
RequestInterface $request,
BlogConfig $blogConfig,
MonthlyWidget $monthlyWidget,
DateTime $date
) {
$this->_request = $request;
$this->_helperData = $helperData;
$this->_customerRepositoryInterface = $customerRepositoryInterface;
$this->date = $date;
$this->_commentFactory = $commentFactory;
$this->_likeFactory = $likeFactory;
$this->collectionProcessor = $collectionProcessor;
$this->blogConfig = $blogConfig;
$this->monthlyWidget = $monthlyWidget;
}
/**
* @inheritDoc
*/
public function getAllPost()
{
$collection = $this->_helperData->getFactoryByType()->create()->getCollection();
return $this->getAllItem($collection);
}
/**
* @inheritDoc
*/
public function getMonthlyArchive()
{
$dateArrayCount = $this->monthlyWidget->getDateArrayCount();
$dateArrayUnique = $this->monthlyWidget->getDateArrayUnique();
$dateLabel = $this->monthlyWidget->getDateLabel();
$monthlyAr = [];
// phpcs:disable Generic.CodeAnalysis.ForLoopWithTestFunctionCall
for ($i = 0; $i < $this->monthlyWidget->getDateCount(); $i++) {
$monthly = new MonthlyArchive();
$monthly->setLabel($dateLabel[$i])->setPostCount((int) $dateArrayCount[$i])
->setLink(
$this->_helperData->getBlogUrl(
date('Y-m', $this->date->timestamp($dateArrayUnique[$i])),
Data::TYPE_MONTHLY
)
);
$monthlyAr[] = $monthly;
}
return $monthlyAr;
}
/**
* @param string $monthly
* @param string $year
*
* @return PostInterface[]
* @throws NoSuchEntityException
*/
public function getPostMonthlyArchive($monthly, $year)
{
return $this->_helperData->getPostCollection(Data::TYPE_MONTHLY, $year . '-' . $monthly)->getItems();
}
/**
* @inheritDoc
*/
public function getPostView($postId)
{
$post = $this->_helperData->getFactoryByType()->create()->load($postId);
$post->updateViewTraffic();
return $post;
}
/**
* @inheritDoc
*/
public function getPostViewByAuthorName($authorName)
{
$author = $this->_helperData->getFactoryByType('author')->create()->getAuthorByName($authorName);
return $this->_helperData->getFactoryByType()->create()->getCollection()
->addFieldToFilter('author_id', $author->getId())->getItems();
}
/**
* @inheritDoc
*/
public function getPostViewByAuthorId($authorId)
{
return $this->_helperData->getFactoryByType()->create()->getCollection()
->addFieldToFilter('author_id', $authorId)->getItems();
}
/**
* @inheritDoc
*/
public function getPostComment($postId)
{
return $this->_commentFactory->create()->getCollection()
->addFieldToFilter('post_id', $postId)->getItems();
}
/**
* @inheritDoc
*/
public function getAllComment()
{
$collection = $this->_commentFactory->create()->getCollection();
return $this->getAllItem($collection);
}
/**
* @inheritDoc
*/
public function getCommentView($commentId)
{
return $this->_commentFactory->create()->load($commentId);
}
/**
* @inheritDoc
*/
public function getCommentList(SearchCriteriaInterface $searchCriteria)
{
$collection = $this->_commentFactory->create()->getCollection();
return $this->getListEntity($collection, $searchCriteria);
}
/**
* @inheritDoc
*/
public function getPostByTagName($tagName)
{
$tag = $this->_helperData->getFactoryByType('tag')->create()->getCollection()
->addFieldToFilter('name', $tagName)->getFirstItem();
return $tag->getSelectedPostsCollection()->getItems();
}
/**
* @inheritDoc
*/
public function getProductByPost($postId)
{
$post = $this->_helperData->getFactoryByType()->create()->load($postId);
return $post->getSelectedProductsCollection()->getItems();
}
/**
* @inheritDoc
*/
public function getPostRelated($postId)
{
$post = $this->_helperData->getFactoryByType()->create()->load($postId);
return $post->getRelatedPostsCollection() ? $post->getRelatedPostsCollection()->getItems() : [];
}
/**
* @inheritDoc
*/
public function addCommentInPost($postId, $commentData)
{
$comment = $this->_commentFactory->create();
$commentData->setPostId($postId);
$commentData->setIsReply(0);
$commentData->setReplyId(0);
$commentData->setCreatedAt($this->date->date());
$comment->setData($commentData->getData())->save();
return $comment;
}
/**
* @inheritDoc
*/
public function getPostLike($postId)
{
return $this->_likeFactory->create()->getCollection()
->addFieldToFilter('post_id', $postId)->count();
}
/**
* @inheritDoc
*/
public function getPostList(SearchCriteriaInterface $searchCriteria)
{
$collection = $this->_helperData->getPostCollection();
return $this->getListEntity($collection, $searchCriteria);
}
/**
* @param PostInterface $post
*
* @return PostInterface
*/
public function createPost($post)
{
$data = $post->getData();
if ($this->checkPostData($data)) {
$this->prepareData($data);
$post->addData($data);
$post->save();
}
return $post;
}
/**
* @param string $postId
*
* @return string|null
* @throws Exception
*/
public function deletePost($postId)
{
$post = $this->_helperData->getFactoryByType()->create()->load($postId);
if ($post) {
$post->delete();
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function updatePost($postId, $post)
{
if (empty($postId)) {
throw new InputException(__('Invalid post id %1', $postId));
}
$subPost = $this->_helperData->getFactoryByType()->create()->load($postId);
if (!$subPost->getId()) {
throw new NoSuchEntityException(
__(
'The "%1" Post doesn\'t exist.',
$postId
)
);
}
$subPost->addData($post->getData())->save();
return $subPost;
}
/**
* @inheritDoc
*/
public function getAllTag()
{
$collection = $this->_helperData->getFactoryByType('tag')->create()->getCollection();
return $this->getAllItem($collection);
}
/**
* @inheritDoc
*/
public function getTagList(SearchCriteriaInterface $searchCriteria)
{
$collection = $this->_helperData->getFactoryByType('tag')->create()->getCollection();
return $this->getListEntity($collection, $searchCriteria);
}
/**
* @inheritDoc
*/
public function getTagView($tagId)
{
return $this->_helperData->getFactoryByType('tag')->create()->load($tagId);
}
/**
* @param TagInterface $tag
*
* @return TagInterface
*/
public function createTag($tag)
{
if (!empty($tag->getName())) {
if (empty($tag->getStoreIds())) {
$tag->setStoreIds(0);
}
if (empty($tag->getEnabled())) {
$tag->setEnabled(1);
}
if (empty($tag->getCreatedAt())) {
$tag->setCreatedAt($this->date->date());
}
if (empty($tag->getMetaRobots())) {
$tag->setMetaRobots('INDEX,FOLLOW');
}
$tag->save();
}
return $tag;
}
/**
* @param string $tagId
*
* @return bool|string
* @throws Exception
*/
public function deleteTag($tagId)
{
$tag = $this->_helperData->getFactoryByType('tag')->create()->load($tagId);
if ($tag) {
$tag->delete();
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function updateTag($tagId, $tag)
{
if (empty($tagId)) {
throw new InputException(__('Invalid tag id %1', $tagId));
}
$subTag = $this->_helperData->getFactoryByType('tag')->create()->load($tagId);
if (!$subTag->getId()) {
throw new NoSuchEntityException(
__(
'The "%1" Tag doesn\'t exist.',
$tagId
)
);
}
$subTag->addData($tag->getData())->save();
return $subTag;
}
/**
* @inheritDoc
*/
public function getAllTopic()
{
$collection = $this->_helperData->getFactoryByType('topic')->create()->getCollection();
return $this->getAllItem($collection);
}
/**
* @inheritDoc
*/
public function getTopicView($topicId)
{
return $this->_helperData->getFactoryByType('topic')->create()->load($topicId);
}
/**
* @inheritDoc
*/
public function getTopicList(SearchCriteriaInterface $searchCriteria)
{
$collection = $this->_helperData->getFactoryByType('topic')->create()->getCollection();
return $this->getListEntity($collection, $searchCriteria);
}
/**
* @inheritDoc
*/
public function getPostsByTopic($topicId)
{
$topic = $this->_helperData->getFactoryByType('topic')->create()->load($topicId);
return $topic->getSelectedPostsCollection()->getItems();
}
/**
* @param TopicInterface $topic
*
* @return TopicInterface
*/
public function createTopic($topic)
{
if (!empty($topic->getName())) {
if (empty($topic->getStoreIds())) {
$topic->setStoreIds(0);
}
if (empty($topic->getEnabled())) {
$topic->setEnabled(1);
}
if (empty($topic->getCreatedAt())) {
$topic->setCreatedAt($this->date->date());
}
if (empty($topic->getMetaRobots())) {
$topic->setMetaRobots('INDEX,FOLLOW');
}
$topic->save();
}
return $topic;
}
/**
* @param string $topicId
*
* @return bool|string
* @throws Exception
*/
public function deleteTopic($topicId)
{
$topic = $this->_helperData->getFactoryByType('topic')->create()->load($topicId);
if ($topic) {
$topic->delete();
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function updateTopic($topicId, $topic)
{
if (empty($topicId)) {
throw new InputException(__('Invalid topic id %1', $topicId));
}
$subTopic = $this->_helperData->getFactoryByType('topic')->create()->load($topicId);
if (!$subTopic->getId()) {
throw new NoSuchEntityException(
__(
'The "%1" Topic doesn\'t exist.',
$topicId
)
);
}
$subTopic->addData($topic->getData())->save();
return $subTopic;
}
/**
* @inheritDoc
*/
public function getCategoryList(SearchCriteriaInterface $searchCriteria)
{
$collection = $this->_helperData->getFactoryByType('category')->create()->getCollection();
return $this->getListEntity($collection, $searchCriteria);
}
/**
* @inheritDoc
*/
public function getAllCategory()
{
$collection = $this->_helperData->getFactoryByType('category')->create()->getCollection();
return $this->getAllItem($collection);
}
/**
* @inheritDoc
*/
public function getPostsByCategoryId($categoryId)
{
$category = $this->_helperData->getFactoryByType('category')->create()->load($categoryId);
return $category->getSelectedPostsCollection()->getItems();
}
/**
* @inheritDoc
*/
public function getPostsByCategory($categoryKey)
{
$category = $this->_helperData->getFactoryByType('category')->create()->getCollection()
->addFieldToFilter('url_key', $categoryKey)->getFirstItem();
return $category->getSelectedPostsCollection()->getItems();
}
/**
* @inheritDoc
*/
public function getCategoriesByPostId($postId)
{
$post = $this->_helperData->getFactoryByType()->create()->load($postId);
return $post->getSelectedCategoriesCollection()->getItems();
}
/**
* @inheritDoc
*/
public function getCategoryView($categoryId)
{
return $this->_helperData->getFactoryByType('category')->create()->load($categoryId);
}
/**
* @param CategoryInterface $category
*
* @return CategoryInterface
*/
public function createCategory($category)
{
if (!empty($category->getName())) {
if (empty($category->getStoreIds())) {
$category->setStoreIds(0);
}
if (empty($category->getEnabled())) {
$category->setEnabled(1);
}
if (empty($category->getCreatedAt())) {
$category->setCreatedAt($this->date->date());
}
if (empty($category->getMetaRobots())) {
$category->setMetaRobots('INDEX,FOLLOW');
}
if (empty($category->getParentId())) {
$category->setParentId(1);
}
$category->save();
}
return $category;
}
/**
* @param string $categoryId
*
* @return bool|string
* @throws Exception
*/
public function deleteCategory($categoryId)
{
$category = $this->_helperData->getFactoryByType('category')->create()->load($categoryId);
if ($categoryId === '1') {
throw new NoSuchEntityException(
__('The ROOT Category can not remove.')
);
}
if ($category) {
$category->delete();
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function updateCategory($categoryId, $category)
{
if (empty($categoryId)) {
throw new InputException(__('Invalid category id %1', $categoryId));
}
$subCategory = $this->_helperData->getFactoryByType('category')->create()->load($categoryId);
if (!$subCategory->getId()) {
throw new NoSuchEntityException(
__(
'The "%1" Category doesn\'t exist.',
$categoryId
)
);
}
$subCategory->addData($category->getData())->save();
return $subCategory;
}
/**
* @return DataObject[]|BlogRepositoryInterface[]
*/
public function getAuthorList()
{
$collection = $this->_helperData->getFactoryByType('author')->create()->getCollection();
return $collection->getItems();
}
/**
* @param AuthorInterface $author
*
* @return AuthorInterface
* @throws NoSuchEntityException
* @throws LocalizedException
*/
public function createAuthor($author)
{
$collection = $this->_helperData->getFactoryByType('author')->create()->getCollection();
if (!empty($author->getCustomerId())) {
$customerId = $author->getCustomerId();
$collection->addFieldToFilter('customer_id', $customerId);
$customer = $this->_customerRepositoryInterface->getById($customerId);
if (!$customer || $collection->count() > 0) {
return null;
}
}
if (!empty($author->getName())) {
if (empty($author->getType())) {
$author->setType(0);
}
if (empty($author->getStatus())) {
$author->setStatus(0);
}
if (empty($author->getCreatedAt())) {
$author->setCreatedAt($this->date->date());
}
$author->save();
}
return $author;
}
/**
* @param string $authorId
*
* @return bool|string
* @throws Exception
*/
public function deleteAuthor($authorId)
{
$author = $this->_helperData->getFactoryByType('author')->create()->load($authorId);
if ($author) {
$author->delete();
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function updateAuthor($authorId, $author)
{
if (empty($authorId)) {
throw new InputException(__('Invalid author id %1', $authorId));
}
$subAuthor = $this->_helperData->getFactoryByType('author')->create()->load($authorId);
if (!$subAuthor->getId()) {
throw new NoSuchEntityException(
__(
'The "%1" Author doesn\'t exist.',
$authorId
)
);
}
$subAuthor->addData($author->getData())->save();
return $subAuthor;
}
/**
* @inheritDoc
*/
public function getConfig()
{
if (!$this->_helperData->isEnabled()) {
throw new InputException(__('Module Blog is disabled'));
}
$blogConfig = $this->_helperData->getConfigValue(Data::CONFIG_MODULE_PATH);
$general = new General();
$general->setBlogName($blogConfig['display']['name']);
$general->setIsLinkInMenu($blogConfig['display']['toplinks']);
$general->setIsDisplayAuthor($blogConfig['post_view_page']['display_author']);
$general->setBlogMode($blogConfig['post_view_page']['display_style']);
$general->setBlogColor($blogConfig['index_page']['font_color']);
$sidebar = new Sidebar();
$sidebar->setNumberMostView($blogConfig['sidebar']['recent_post']['number_recent_posts']);
$sidebar->setNumberRecent($blogConfig['sidebar']['recent_post']['number_mostview_posts']);
$seo = new Seo();
if (isset($blogConfig['seo']['meta_title'])) {
$seo->setMetaTitle($blogConfig['seo']['meta_title']);
}
if (isset($blogConfig['seo']['meta_description'])) {
$seo->setMetaDescription($blogConfig['seo']['meta_description']);
}
$this->blogConfig->setGeneral($general)->setSidebar($sidebar)->setSeo($seo);
return $this->blogConfig;
}
/**
* @param array $data
*/
protected function prepareData(&$data)
{
if (!empty($data['categories_ids'])) {
$data['categories_ids'] = explode(',', $data['categories_ids'] ?? '');
}
if (!empty($data['tags_ids'])) {
$data['tags_ids'] = explode(',', $data['tags_ids'] ?? '');
}
if (!empty($data['topics_ids'])) {
$data['topics_ids'] = explode(',', $data['topics_ids'] ?? '');
}
if (empty($data['enabled'])) {
$data['enabled'] = 0;
}
if (empty($data['allow_comment'])) {
$data['allow_comment'] = 0;
}
if (empty($data['store_ids'])) {
$data['store_ids'] = 0;
}
if (empty($data['in_rss'])) {
$data['in_rss'] = 0;
}
if (empty($data['meta_robots'])) {
$data['meta_robots'] = 'INDEX,FOLLOW';
}
if (empty($data['layout'])) {
$data['layout'] = 'empty';
}
$data['created_at'] = $this->date->date();
if (empty($data['publish_date'])) {
$data['publish_date'] = $this->date->date();
}
}
/**
* @param array $data
*
* @return bool
*/
protected function checkPostData($data)
{
if (empty($data['name']) || empty($data['author_id']) || !$this->checkAuthor($data['author_id'])) {
return false;
}
if (!empty($data['categories_ids'])) {
$collection = $this->_helperData->getFactoryByType('category')->create()->getCollection();
foreach (explode(',', $data['categories_ids']) as $id) {
if ($collection->addFieldToFilter('category_id', $id)->count() < 1) {
return false;
}
}
}
if (!empty($data['tags_ids'])) {
$collection = $this->_helperData->getFactoryByType('tag')->create()->getCollection();
foreach (explode(',', $data['tags_ids']) as $id) {
if ($collection->addFieldToFilter('tag_id', $id)->count() < 1) {
return false;
}
}
}
if (!empty($data['topics_ids'])) {
$collection = $this->_helperData->getFactoryByType('topic')->create()->getCollection();
foreach (explode(',', $data['topics_ids']) as $id) {
if ($collection->addFieldToFilter('topic_id', $id)->count() < 1) {
return false;
}
}
}
return true;
}
/**
* @param string $authorId
*
* @return bool
*/
protected function checkAuthor($authorId)
{
$collection = $this->_helperData->getFactoryByType('author')->create()->getCollection()
->addFieldToFilter('user_id', $authorId);
return $collection->count() > 0;
}
/**
* @param SalesAbstractCollection|AbstractCollection $searchResult
* @param SearchCriteriaInterface $searchCriteria
*
* @return mixed
*/
protected function getListEntity($searchResult, $searchCriteria)
{
$this->collectionProcessor->process($searchCriteria, $searchResult);
$searchResult->setSearchCriteria($searchCriteria);
return $searchResult;
}
/**
* @param AbstractCollection $collection
*
* @return mixed
*/
protected function getAllItem($collection)
{
$page = $this->_request->getParam('page', 1);
$limit = $this->_request->getParam('limit', 10);
$collection->getSelect()->limitPage($page, $limit);
return $collection->getItems();
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Mageplaza\Blog\Helper\Data;
/**
* Class Author
* @package Mageplaza\Blog\Model
*/
class Author extends AbstractModel
{
/**
* @inheritdoc
*/
const CACHE_TAG = 'mageplaza_blog_author';
/**
* @var Data
*/
protected $helperData;
/**
* Author constructor.
*
* @param Context $context
* @param Registry $registry
* @param Data $helperData
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
Data $helperData,
?AbstractResource $resource = null,
?AbstractDb $resourceCollection = null,
array $data = []
) {
$this->helperData = $helperData;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* Constructor
*/
protected function _construct()
{
$this->_init(ResourceModel\Author::class);
}
/**
* @param $name
*
* @return DataObject
*/
public function getAuthorByName($name)
{
return $this->getCollection()->addFieldToFilter('name', $name)->getFirstItem();
}
/**
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* @return string
*/
public function getUrl()
{
return $this->helperData->getBlogUrl($this, Data::TYPE_AUTHOR);
}
/**
* @return bool
*/
public function hasPost()
{
try {
return (bool)count($this->_getResource()->getPostIds($this));
} catch (LocalizedException $exception) {
return false;
}
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\DataObject;
use Mageplaza\Blog\Api\Data\BlogConfigInterface;
/**
* Class BlogConfig
* @package Mageplaza\Blog\Model
*/
class BlogConfig extends DataObject implements BlogConfigInterface
{
/**
* {@inheritdoc}
*/
public function getGeneral()
{
return $this->getData(self::GENERAL);
}
/**
* {@inheritdoc}
*/
public function setGeneral($value)
{
$this->setData(self::GENERAL, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getSidebar()
{
return $this->getData(self::SIDEBAR);
}
/**
* {@inheritdoc}
*/
public function setSidebar($value)
{
$this->setData(self::SIDEBAR, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getSeo()
{
return $this->getData(self::SEO);
}
/**
* {@inheritdoc}
*/
public function setSeo($value)
{
$this->setData(self::SEO, $value);
return $this;
}
}
+309
View File
@@ -0,0 +1,309 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Exception;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Mageplaza\Blog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
use Mageplaza\Blog\Model\ResourceModel\Post\CollectionFactory;
/**
* @method Category setName($name)
* @method Category setDescription($description)
* @method Category setUrlKey($urlKey)
* @method Category setEnabled($enabled)
* @method Category setMetaTitle($metaTitle)
* @method Category setMetaDescription($metaDescription)
* @method Category setMetaKeywords($metaKeywords)
* @method Category setMetaRobots($metaRobots)
* @method mixed getName()
* @method mixed getDescription()
* @method mixed getUrlKey()
* @method mixed getEnabled()
* @method mixed getMetaTitle()
* @method mixed getMetaDescription()
* @method mixed getMetaKeywords()
* @method mixed getMetaRobots()
* @method Category setParentId(int $parentId)
* @method int getParentId()
* @method Category setPath(string $path)
* @method string getPath()
* @method Category setPosition(int $path)
* @method int getPosition()
* @method Category setChildrenCount(int $path)
* @method int getChildrenCount()
* @method Category setCreatedAt(string $createdAt)
* @method string getCreatedAt()
* @method Category setUpdatedAt(string $updatedAt)
* @method string getUpdatedAt()
* @method Category setMovedCategoryId(string $id)
* @method Category setAffectedCategoryIds(array $ids)
* @method Category setPostsData(array $data)
* @method array getPostsData()
* @method Category setIsChangedPostList(bool $flag)
* @method bool getIsChangedPostList()
* @method Category setAffectedPostIds(array $ids)
* @method bool getAffectedPostIds()
*/
class Category extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_category';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_category';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_category';
/**
* Post Collection
*
* @var Collection
*/
public $postCollection;
/**
* Blog Category Factory
*
* @var CategoryFactory
*/
public $categoryFactory;
/**
* Post Collection Factory
*
* @var CollectionFactory
*/
public $postCollectionFactory;
/**
* @var CategoryCollectionFactory
*/
public $categoryCollectionFactory;
/**
* Category constructor.
*
* @param Context $context
* @param Registry $registry
* @param CategoryFactory $categoryFactory
* @param CollectionFactory $postCollectionFactory
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
CategoryFactory $categoryFactory,
CollectionFactory $postCollectionFactory,
CategoryCollectionFactory $categoryCollectionFactory,
?AbstractResource $resource = null,
?AbstractDb $resourceCollection = null,
array $data = []
) {
$this->categoryFactory = $categoryFactory;
$this->postCollectionFactory = $postCollectionFactory;
$this->categoryCollectionFactory = $categoryCollectionFactory;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(ResourceModel\Category::class);
}
/**
* Get identities
*
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* get entity default values
*
* @return array
*/
public function getDefaultValues()
{
$values = [];
$values['store_ids'] = '1';
$values['enabled'] = '1';
return $values;
}
/**
* get tree path ids
*
* @return array
*/
public function getPathIds()
{
$ids = $this->getData('path_ids');
if ($ids === null) {
$ids = explode('/', (string) $this->getPath());
$this->setData('path_ids', $ids);
}
return $ids;
}
/**
* get all parent ids
*
* @return array
*/
public function getParentIds()
{
return array_diff($this->getPathIds(), [$this->getId()]);
}
/**
* move Blog Category in tree
*
* @param $parentId
* @param $afterCategoryId
*
* @return $this
* @throws LocalizedException
* @throws Exception
*/
public function move($parentId, $afterCategoryId)
{
try {
$parent = $this->categoryFactory->create()->load($parentId);
} catch (NoSuchEntityException $e) {
throw new LocalizedException(
__('Sorry, but we can\'t move the Blog Category because we can\'t find the new parent Blog Category you selected.'),
$e
);
}
if (!$this->getId()) {
throw new LocalizedException(
__('Sorry, but we can\'t move the Blog Category because we can\'t find the new parent Blog Category you selected.')
);
}
if ($parent->getId() == $this->getId()) {
throw new LocalizedException(
__('We can\'t perform this Blog Category move operation because the parent Blog Category matches the child Blog Category.')
);
}
$this->setMovedCategoryId($this->getId());
$oldParentId = $this->getParentId();
$eventParams = [
$this->_eventObject => $this,
'parent' => $parent,
'category_id' => $this->getId(),
'prev_parent_id' => $oldParentId,
'parent_id' => $parentId,
];
$this->_getResource()->beginTransaction();
try {
$this->_eventManager->dispatch($this->_eventPrefix . '_move_before', $eventParams);
$this->getResource()->changeParent($this, $parent, $afterCategoryId);
$this->_eventManager->dispatch($this->_eventPrefix . '_move_after', $eventParams);
$this->_getResource()->commit();
// Set data for indexer
$this->setAffectedCategoryIds([$this->getId(), $oldParentId, $parentId]);
} catch (Exception $e) {
$this->_getResource()->rollBack();
throw $e;
}
$this->_eventManager->dispatch($this->_eventPrefix . '_move', $eventParams);
$this->_cacheManager->clean([self::CACHE_TAG]);
return $this;
}
/**
* @return array|mixed
*/
public function getPostsPosition()
{
if (!$this->getId()) {
return [];
}
$array = $this->getData('posts_position');
if ($array === null) {
$array = $this->getResource()->getPostsPosition($this);
$this->setData('posts_position', $array);
}
return $array;
}
/**
* @return Collection
*/
public function getSelectedPostsCollection()
{
if (!$this->postCollection) {
$collection = $this->postCollectionFactory->create();
$collection->join(
['cat' => $this->getResource()->getTable('mageplaza_blog_post_category')],
'main_table.post_id=cat.post_id AND cat.category_id=' . (int) $this->getId(),
['position']
);
$collection->setOrder('post_id','DESC');
$this->postCollection = $collection;
}
return $this->postCollection;
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Mageplaza\Blog\Model\ResourceModel\Comment\CollectionFactory as CommentCollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Post\CollectionFactory;
/**
* Class Comment
* @package Mageplaza\Blog\Model
*/
class Comment extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_comment';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_comment';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_comment';
/**
* @var string
*/
protected $_idFieldName = 'comment_id';
/**
* Post Collection Factory
*
* @var CollectionFactory
*/
public $postCollectionFactory;
/**
* @var CommentCollectionFactory
*/
public $commentCollectionFactory;
/**
* Comment constructor.
*
* @param Context $context
* @param Registry $registry
* @param CollectionFactory $postCollectionFactory
* @param CommentCollectionFactory $commentCollectionFactory
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
CollectionFactory $postCollectionFactory,
CommentCollectionFactory $commentCollectionFactory,
?AbstractResource $resource = null,
?AbstractDb $resourceCollection = null,
array $data = []
) {
$this->postCollectionFactory = $postCollectionFactory;
$this->commentCollectionFactory = $commentCollectionFactory;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* @inheritdoc
*/
protected function _construct()
{
$this->_init(ResourceModel\Comment::class);
}
/**
* @inheritdoc
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
}
@@ -0,0 +1,49 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Backend;
use Magento\Framework\App\Config\Value;
use Magento\Framework\Exception\ValidatorException;
/**
* Class Author
* @package Mageplaza\Blog\Model\Config\Backend
*/
class Pagination extends Value
{
/**
* @return Value|void
* @throws ValidatorException
*/
public function beforeSave()
{
if (!empty($this->getValue())) {
$valueArray = explode(',', $this->getValue());
foreach ($valueArray as $value) {
if (!is_numeric($value) || $value < 1) {
throw new ValidatorException(__('Pagination value must be a positive integer.'));
}
}
}
parent::beforeSave(); // TODO: Change the autogenerated stub
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config;
use Magento\Framework\DataObject;
use Mageplaza\Blog\Api\Data\Config\GeneralInterface;
/**
* Class General
* @package Mageplaza\Blog\Model\Config
*/
class General extends DataObject implements GeneralInterface
{
/**
* {@inheritdoc}
*/
public function getBlogName()
{
return $this->getData(self::BLOG_NAME);
}
/**
* {@inheritdoc}
*/
public function setBlogName($value)
{
$this->setData(self::BLOG_NAME, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getIsLinkInMenu()
{
return $this->getData(self::IS_LINK_IN_MENU);
}
/**
* {@inheritdoc}
*/
public function setIsLinkInMenu($value)
{
$this->setData(self::IS_LINK_IN_MENU, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getIsDisplayAuthor()
{
return $this->getData(self::IS_DISPLAY_AUTHOR);
}
/**
* {@inheritdoc}
*/
public function setIsDisplayAuthor($value)
{
$this->setData(self::IS_DISPLAY_AUTHOR, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getBlogMode()
{
return $this->getData(self::BLOG_MODE);
}
/**
* {@inheritdoc}
*/
public function setBlogMode($value)
{
$this->setData(self::BLOG_MODE, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getBlogColor()
{
return $this->getData(self::BLOG_COLOR);
}
/**
* {@inheritdoc}
*/
public function setBlogColor($value)
{
$this->setData(self::BLOG_COLOR, $value);
return $this;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config;
use Magento\Framework\DataObject;
use Mageplaza\Blog\Api\Data\Config\SeoInterface;
/**
* Class Seo
* @package Mageplaza\Blog\Model\Config
*/
class Seo extends DataObject implements SeoInterface
{
/**
* {@inheritdoc}
*/
public function getMetaTitle()
{
return $this->getData(self::META_TITLE);
}
/**
* {@inheritdoc}
*/
public function setMetaTitle($value)
{
$this->setData(self::META_TITLE, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getMetaDescription()
{
return $this->getData(self::META_DESCRIPTION);
}
/**
* {@inheritdoc}
*/
public function setMetaDescription($value)
{
$this->setData(self::META_DESCRIPTION, $value);
return $this;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config;
use Magento\Framework\DataObject;
use Mageplaza\Blog\Api\Data\Config\SidebarInterface;
/**
* Class Sidebar
* @package Mageplaza\Blog\Model\Config
*/
class Sidebar extends DataObject implements SidebarInterface
{
/**
* {@inheritdoc}
*/
public function getNumberRecent()
{
return $this->getData(self::NUMBER_RECENT);
}
/**
* {@inheritdoc}
*/
public function setNumberRecent($value)
{
$this->setData(self::NUMBER_RECENT, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getNumberMostView()
{
return $this->getData(self::NUMBER_MOST_VIEW);
}
/**
* {@inheritdoc}
*/
public function setNumberMostView($value)
{
$this->setData(self::NUMBER_MOST_VIEW, $value);
return $this;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Faqs
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Framework\Option\ArrayInterface;
use Mageplaza\Blog\Model\AuthorFactory;
/**
* Class Author
* @package Mageplaza\Faqs\Model\Config\Source
*/
class Author implements ArrayInterface
{
/**
* @var AuthorFactory
*/
public $_authorFactory;
public function __construct(
AuthorFactory $authorFactory
) {
$this->_authorFactory = $authorFactory;
}
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->getAuthors() as $value => $author) {
$options[] = [
'value' => $value,
'label' => $author->getName()
];
}
return $options;
}
/**
* @return AbstractCollection
*/
public function getAuthors()
{
return $this->_authorFactory->create()->getCollection()->addFieldToFilter('status', '1');
}
}
@@ -0,0 +1,66 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Faqs
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class AuthorStatus
* @package Mageplaza\Faqs\Model\Config\Source
*/
class AuthorStatus implements ArrayInterface
{
const PENDING = '0';
const APPROVED = '1';
const DISAPPROVED = '2';
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [
self::PENDING => __('Pending'),
self::APPROVED => __('Approved'),
self::DISAPPROVED => __('Disapproved')
];
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Faqs
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class AuthorStatus
* @package Mageplaza\Faqs\Model\Config\Source
*/
class AuthorType implements ArrayInterface
{
const ADMIN = '0';
const CUSTOMER = '1';
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [
self::ADMIN => __('Created by Admin'),
self::CUSTOMER => __('Customer Register')
];
}
}
@@ -0,0 +1,68 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\Comments\Facebook;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Colorscheme
* @package Mageplaza\Blog\Model\Config\Source\Comments\Facebook
*/
class Colorscheme implements ArrayInterface
{
const LIGHT = 'light';
const DARK = 'dark';
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [self::LIGHT => __('Light'), self::DARK => __('Dark')];
}
/**
* @return array
*/
public function getAllOptions()
{
return $this->toOptionArray();
}
}
@@ -0,0 +1,69 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\Comments\Facebook;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Orderby
* @package Mageplaza\Blog\Model\Config\Source\Comments\Facebook
*/
class Orderby implements ArrayInterface
{
const SOCIAL = 'social';
const REVERSE_TIME = 'reverse_time';
const TIME = 'time';
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [self::SOCIAL => __('Social'), self::REVERSE_TIME => __('Reverse time'), self::TIME => __('Time')];
}
/**
* @return array
*/
public function getAllOptions()
{
return $this->toOptionArray();
}
}
@@ -0,0 +1,65 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\Comments;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Status
* @package Mageplaza\Blog\Model\Config\Source\Comments
*/
class Status implements ArrayInterface
{
const APPROVED = 1;
const SPAM = 2;
const PENDING = 3;
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [
self::APPROVED => __('Approved'),
self::PENDING => __('Pending'),
self::SPAM => __('Spam')
];
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\Comments;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Type
* @package Mageplaza\Blog\Model\Config\Source\Comments
*/
class Type implements ArrayInterface
{
const DEFAULT_COMMENT = 1;
const FACEBOOK = 2;
const DISQUS = 3;
const DISABLE = 4;
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [
self::DEFAULT_COMMENT => __('Default Comment'),
self::DISQUS => __('Disqus Comment'),
self::FACEBOOK => __('Facebook Comment'),
self::DISABLE => __('Disable Completely')
];
}
}
@@ -0,0 +1,64 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\DateFormat;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Type
* @package Mageplaza\Blog\Model\Config\Source\DateFormat
*/
class Type implements ArrayInterface
{
/**
* Options getter
*
* @return array
*/
public function toOptionArray()
{
$dateArray = [];
$type = [
'F j, Y',
'Y-m-d',
'm/d/Y',
'd/m/Y',
'F j, Y g:i a',
'F j, Y g:i A',
'Y-m-d g:i a',
'Y-m-d g:i A',
'd/m/Y g:i a',
'd/m/Y g:i A',
'm/d/Y H:i',
'd/m/Y H:i',
];
foreach ($type as $item) {
$dateArray[] = [
'value' => $item,
'label' => $item . ' (' . date($item) . ')'
];
}
return $dateArray;
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\DateFormat;
use Magento\Framework\Option\ArrayInterface;
/**
* Class TypeMonth
* @package Mageplaza\Blog\Model\Config\Source\DateFormat
*/
class TypeMonth implements ArrayInterface
{
/**
* Options getter
*
* @return array
*/
public function toOptionArray()
{
$dateArray = [];
$type = ['F , Y', 'Y - m', 'm / Y', 'M Y'];
foreach ($type as $item) {
$dateArray [] = [
'value' => $item,
'label' => $item . ' (' . date($item) . ')'
];
}
return $dateArray;
}
}
@@ -0,0 +1,60 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Display
* @package Mageplaza\Blog\Model\Config\Source\Blogview
*/
class DisplayType implements ArrayInterface
{
const LIST_VIEW = 1;
const GRID = 2;
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [self::LIST_VIEW => __('List View'), self::GRID => __('Grid View')];
}
}
@@ -0,0 +1,65 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\Import;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Behaviour
* @package Mageplaza\Blog\Model\Config\Source\Import
*/
class Behaviour implements ArrayInterface
{
const UPDATE = "update";
const REPLACE = "replace";
const DELETE = "delete";
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [
self::UPDATE => __('Add / Update'),
self::REPLACE => __('Replace'),
self::DELETE => __('Delete')
];
}
}
@@ -0,0 +1,66 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source\Import;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Type
* @package Mageplaza\Blog\Model\Config\Source\Import
*/
class Type implements ArrayInterface
{
const WORDPRESS = "wordpress";
const AHEADWORK = "aheadworksm1";
const MAGEFAN = "magefan";
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [
"" => __('-- Please Select --'),
self::WORDPRESS => __('Wordpress'),
self::AHEADWORK => __('AheadWorks Blog [Magento 1]'),
self::MAGEFAN => __('MageFan Blog [Magento 2]')
];
}
}
@@ -0,0 +1,60 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class Display
* @package Mageplaza\Blog\Model\Config\Source
*/
class RelatedMode implements ArrayInterface
{
const SLIDER = 1;
const GRID = 2;
/**
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [self::SLIDER => __('Slider'), self::GRID => __('Grid')];
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class SideBarLR
* @package Mageplaza\Blog\Model\Config\Source
*/
class SideBarLR implements ArrayInterface
{
const LEFT = '2columns-left';
const RIGHT = '2columns-right';
/**
* Options getter
*
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach ($this->toArray() as $value => $label) {
$options[] = [
'value' => $value,
'label' => $label
];
}
return $options;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return [
self::LEFT => __('Left'),
self::RIGHT => __('Right')
];
}
}
@@ -0,0 +1,65 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
use Mageplaza\Blog\Model\ResourceModel\Category\CollectionFactory;
/**
* Class WidgetCategory
* @package Mageplaza\Blog\Model\Config\Source\Widget
*/
class WidgetCategory implements ArrayInterface
{
/**
* @var CollectionFactory
*/
private $category;
/**
* WidgetCategory constructor.
*
* @param CollectionFactory $category
*/
public function __construct(
CollectionFactory $category
) {
$this->category = $category;
}
/**
* @return array
*/
public function toOptionArray()
{
$collection = $this->category->create();
$ar = [];
foreach ($collection->getItems() as $item) {
if ($item->getId() === '1') {
continue;
}
$ar[] = ['value' => $item->getId(), 'label' => $item->getName()];
}
return $ar;
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
/**
* Class ShowType
* @package Mageplaza\Blog\Model\Config\Source\Widget
*/
class WidgetShowType implements ArrayInterface
{
/**
* @return array
*/
public function toOptionArray()
{
return [
['value' => 'new', 'label' => __('New')],
['value' => 'category', 'label' => __('Category')]
];
}
}
+369
View File
@@ -0,0 +1,369 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Import;
use Magento\Backend\Model\Auth\Session;
use Magento\Customer\Model\CustomerFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Store\Model\StoreManagerInterface;
use Magento\User\Model\UserFactory;
use Mageplaza\Blog\Helper\Data as HelperData;
use Mageplaza\Blog\Helper\Image as HelperImage;
use Mageplaza\Blog\Model\CategoryFactory;
use Mageplaza\Blog\Model\CommentFactory;
use Mageplaza\Blog\Model\Config\Source\Import\Type;
use Mageplaza\Blog\Model\PostFactory;
use Mageplaza\Blog\Model\TagFactory;
use Mageplaza\Blog\Model\TopicFactory;
use Mageplaza\Blog\Model\AuthorFactory;
/**
* Class AbstractImport
* @package Mageplaza\Blog\Model\Import
*/
abstract class AbstractImport extends AbstractModel
{
/**
* @var DateTime
*/
public $date;
/**
* @var Type
*/
public $importType;
/**
* @var HelperData
*/
public $helperData;
/**
* @var PostFactory
*/
protected $_postFactory;
/**
* @var TagFactory
*/
protected $_tagFactory;
/**
* @var CategoryFactory
*/
protected $_categoryFactory;
/**
* @var TopicFactory
*/
protected $_topicFactory;
/**
* @var CommentFactory
*/
protected $_commentFactory;
/**
* @var UserFactory
*/
protected $_userFactory;
/**
* @var CustomerFactory
*/
protected $_customerFactory;
/**
* @var StoreManagerInterface
*/
protected $_storeManager;
/**
* @var HelperImage
*/
protected $_helperImage;
/**
* @var ObjectManagerInterface
*/
protected $_objectManager;
/**
* @var ResourceConnection
*/
protected $_resourceConnection;
/**
* @var Session
*/
protected $_authSession;
/**
* Error Count Statistic
* @var int
*/
protected $_errorCount = 0;
/**
* Success Count Statistic
* @var int
*/
protected $_successCount = 0;
/**
* @var bool
*/
protected $_hasData = false;
/**
* @var array
*/
protected $_type;
/**
* @var AuthorFactory
*/
protected $authorFactory;
/**
* AbstractImport constructor.
*
* @param Context $context
* @param Registry $registry
* @param PostFactory $postFactory
* @param TagFactory $tagFactory
* @param CategoryFactory $categoryFactory
* @param TopicFactory $topicFactory
* @param CommentFactory $commentFactory
* @param AuthorFactory $authorFactory
* @param UserFactory $userFactory
* @param CustomerFactory $customerFactory
* @param ObjectManagerInterface $objectManager
* @param Session $authSession
* @param ResourceConnection $resourceConnection
* @param DateTime $date
* @param Type $importType
* @param HelperData $helperData
* @param StoreManagerInterface $storeManager
* @param HelperImage $helperImage
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
PostFactory $postFactory,
TagFactory $tagFactory,
CategoryFactory $categoryFactory,
TopicFactory $topicFactory,
CommentFactory $commentFactory,
AuthorFactory $authorFactory,
UserFactory $userFactory,
CustomerFactory $customerFactory,
ObjectManagerInterface $objectManager,
Session $authSession,
ResourceConnection $resourceConnection,
DateTime $date,
Type $importType,
HelperData $helperData,
StoreManagerInterface $storeManager,
HelperImage $helperImage,
?AbstractResource $resource = null,
?AbstractDb $resourceCollection = null,
array $data = []
) {
$this->date = $date;
$this->importType = $importType;
$this->_type = $this->_getImportType();
$this->helperData = $helperData;
$this->_postFactory = $postFactory;
$this->_tagFactory = $tagFactory;
$this->_categoryFactory = $categoryFactory;
$this->_topicFactory = $topicFactory;
$this->_commentFactory = $commentFactory;
$this->_userFactory = $userFactory;
$this->_customerFactory = $customerFactory;
$this->_objectManager = $objectManager;
$this->_resourceConnection = $resourceConnection;
$this->_authSession = $authSession;
$this->_storeManager = $storeManager;
$this->_helperImage = $helperImage;
$this->authorFactory = $authorFactory;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* Import Post Function
*
* @param array $data
* @param null $connection
*
* @return mixed
*/
abstract protected function _importPosts($data, $connection);
/**
* Import Tag Function
*
* @param array $data
* @param null $connection
*
* @return mixed
*/
abstract protected function _importTags($data, $connection);
/**
* Import Category Function
*
* @param array $data
* @param null $connection
*
* @return mixed
*/
abstract protected function _importCategories($data, $connection);
/**
* Import Comment Function
*
* @param array $data
* @param null $connection
*
* @return mixed
*/
abstract protected function _importComments($data, $connection);
/**
* Import Author Function
*
* @param array $data
* @param null $connection
*
* @return mixed
*/
abstract protected function _importAuthors($data, $connection);
/**
* Get import statistics
*
* @param string $type
* @param int $successCount
* @param int $errorCount
* @param bool $hasData
*
* @return array
*/
protected function _getStatistics($type, $successCount, $errorCount, $hasData)
{
$statistics = [
'type' => $type,
'success_count' => $successCount,
'error_count' => $errorCount,
'has_data' => $hasData
];
return $statistics;
}
/**
* Reset statistic record
*/
protected function _resetRecords()
{
$this->_errorCount = 0;
$this->_successCount = 0;
$this->_hasData = false;
}
/**
* Auto generate password
*
* @param int $length
* @param bool $add_dashes
* @param string $available_sets
*
* @return bool|string
*/
protected function _generatePassword($length = 9, $add_dashes = false, $available_sets = 'luds')
{
$sets = [];
if (strpos($available_sets, 'l') !== false) {
$sets[] = 'abcdefghjkmnpqrstuvwxyz';
}
if (strpos($available_sets, 'u') !== false) {
$sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
}
if (strpos($available_sets, 'd') !== false) {
$sets[] = '23456789';
}
if (strpos($available_sets, 's') !== false) {
$sets[] = '!@#$%&*?';
}
$all = '';
$password = '';
foreach ($sets as $set) {
$password .= $set[array_rand(str_split($set))];
$all .= $set;
}
$all = str_split($all);
// phpcs:disable Generic.CodeAnalysis
for ($i = 0; $i < $length - count($sets); $i++) {
$password .= $all[array_rand($all)];
}
$password = str_shuffle($password);
if (!$add_dashes) {
return $password;
}
$dash_len = floor(sqrt($length));
$dash_str = '';
while (strlen($password) > $dash_len) {
$dash_str .= substr($password, 0, $dash_len) . '-';
$password = substr($password, $dash_len);
}
$dash_str .= $password;
return $dash_str;
}
/**
* Get import types
*
* @return array
*/
protected function _getImportType()
{
$types = [];
foreach ($this->importType->toOptionArray() as $item) {
$types[$item['value']] = $item['value'];
}
return $types;
}
}
+854
View File
@@ -0,0 +1,854 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\Import;
use Exception;
use Magento\Customer\Model\AccountManagement;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Mageplaza\Blog\Model\CategoryFactory;
use Mageplaza\Blog\Model\CommentFactory;
use Mageplaza\Blog\Model\Config\Source\Comments\Status;
use Mageplaza\Blog\Model\PostFactory;
use Mageplaza\Blog\Model\TagFactory;
/**
* Class AheadWorksM1
* @package Mageplaza\Blog\Model\Import
*/
class AheadWorksM1 extends AbstractImport
{
/**
* AheadworksM1 Post table name
*
* @var string
*/
const TABLE_POST = 'aw_blog';
/**
* AheadworksM1 Tag table name
*
* @var string
*/
const TABLE_TAG = 'aw_blog_tags';
/**
* AheadworksM1 Category table name
*
* @var string
*/
const TABLE_CATEGORY = 'aw_blog_cat';
/**
* AheadworksM1 Comment table name
*
* @var string
*/
const TABLE_COMMENT = 'aw_blog_comment';
/**
* AheadworksM1 Category-Post Relationship table name
*
* @var string
*/
const TABLE_CATEGORY_POST = 'aw_blog_post_cat';
/**
* Run imports
*
* @param array $data
* @param null $connection
*
* @return bool
* @throws LocalizedException
*/
public function run($data, $connection)
{
// phpcs:disable Magento2.Functions.DiscouragedFunction
mysqli_query($connection, 'SET NAMES "utf8"');
if ($this->_importPosts($data, $connection) && $data['type'] == $this->_type['aheadworksm1']) {
$this->_importTags($data, $connection);
$this->_importCategories($data, $connection);
$this->_importComments($data, $connection);
return true;
}
return false;
}
/**
* @param array $data
* @param null $connection
*
* @return bool|mixed
* @throws LocalizedException
*/
protected function _importPosts($data, $connection)
{
// phpcs:disable Magento2.SQL.RawQuery
$sqlString = "SELECT * FROM `" . $data['table_prefix'] . self::TABLE_POST . "`";
$result = mysqli_query($connection, $sqlString);
$isReplace = true;
if (!$result) {
return false;
}
$this->_resetRecords();
/** @var PostFactory $postModel */
$postModel = $this->_postFactory->create();
$oldPostIds = [];
$tags = [];
$importSource = $data['type'] . '-' . $data['database'];
/** delete behaviour action */
if ($data['behaviour'] == 'delete' || $data['behaviour'] == 'replace') {
$postModel->getResource()->deleteImportItems($data['type']);
$this->_hasData = true;
if ($data['behaviour'] == 'delete') {
$isReplace = false;
} else {
$isReplace = true;
}
}
/** fetch all items from import source */
while ($post = mysqli_fetch_assoc($result)) {
/** store the source item */
$sourceItems[] = [
'is_imported' => $postModel->getResource()->isImported($importSource, $post['post_id']),
'is_duplicated_url' => $postModel->getResource()->isDuplicateUrlKey($post['identifier']),
'id' => $post['post_id'],
'name' => $post['title'],
'short_description' => $post['short_content'],
'post_content' => $post['post_content'],
'url_key' => $this->helperData->generateUrlKey(
$postModel->getResource(),
$postModel,
$post['identifier']
),
'created_at' => ($post['created_time'] > $this->date->date() || !$post['created_time'])
? ($this->date->date()) : ($post['created_time']),
'updated_at' => ($post['update_time']) ?: $this->date->date(),
'publish_date' => ($post['created_time']) ?: $this->date->date(),
'enabled' => 1,
'in_rss' => 0,
'allow_comment' => 1,
'store_ids' => $this->_storeManager->getStore()->getId(),
'meta_robots' => 'INDEX,FOLLOW', //Default value
'meta_keywords' => $post['meta_keywords'],
'meta_description' => $post['meta_description'],
'author_id' => 1,
'import_source' => $importSource . '-' . $post['post_id'],
'tags' => $post['tags']
];
}
/** update and replace behaviour action */
if ($isReplace && isset($sourceItems)) {
foreach ($sourceItems as $post) {
$postTag = $post['tags'];
if ($post['is_imported']) {
/** update post that has duplicate URK key */
if ($post['is_duplicated_url'] != null || $data['expand_behaviour'] == '1') {
$where = ['post_id = ?' => (int) $post['is_imported']];
$this->_updatePosts($post, $where);
$this->_successCount++;
$this->_hasData = true;
} else {
/** Add new posts */
$postModel->load($post['is_imported'])->setImportSource('')->save();
try {
$this->_addPosts($postModel, $post);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
}
} else {
/**
* check the posts isn't imported
* Update posts
*/
if ($data['behaviour'] == 'update' && $data['expand_behaviour'] == '1'
&& $post['is_duplicated_url'] != null) {
$where = ['post_id = ?' => (int) $post['is_duplicated_url']];
$this->_updatePosts($post, $where);
$this->_successCount++;
$this->_hasData = true;
} else {
/**
* Add new posts
*/
try {
$this->_addPosts($postModel, $post);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
}
}
/**
* Store post-tags
*/
if (!empty($postTag)) {
$tagNames = explode(',', $postTag);
$id = [];
foreach ($tagNames as $name) {
// phpcs:disable Magento2.Files.LineLength
$tagTableSql = "SELECT * FROM `" . $data['table_prefix'] . self::TABLE_TAG . "` WHERE `tag` = '" . $name . "'";
$tagResult = mysqli_query($connection, $tagTableSql);
$tag = mysqli_fetch_assoc($tagResult);
$id [] = $tag['id'];
}
if ($post['is_imported']) {
$tags[$post['is_imported']] = $id;
}
}
}
/**
* Get old post ids
*/
foreach ($postModel->getCollection() as $item) {
if ($item->getImportSource() != null) {
$postImportSource = explode('-', $item->getImportSource());
$importType = array_shift($postImportSource);
if ($importType == $this->_type['aheadworksm1']) {
$oldPostId = array_pop($postImportSource);
$oldPostIds[$item->getId()] = $oldPostId;
}
}
}
mysqli_free_result($result);
}
$statistics = $this->_getStatistics('posts', $this->_successCount, $this->_errorCount, $this->_hasData);
$this->_registry->register('mageplaza_import_post_ids_collection', $oldPostIds);
$this->_registry->register('mageplaza_import_post_tags_collection', $tags);
$this->_registry->register('mageplaza_import_post_statistic', $statistics);
return true;
}
/**
* @param array $data
* @param null $connection
*
* @return mixed|void
* @throws NoSuchEntityException
*/
protected function _importTags($data, $connection)
{
$sqlString = "SELECT * FROM `" . $data['table_prefix'] . self::TABLE_TAG . "`";
$result = mysqli_query($connection, $sqlString);
$this->_resetRecords();
$isReplace = true;
$oldTagIds = [];
/** @var TagFactory $tagModel */
$tagModel = $this->_tagFactory->create();
$importSource = $data['type'] . '-' . $data['database'];
/** delete behaviour action */
if ($data['behaviour'] == 'delete' || $data['behaviour'] == 'replace') {
$tagModel->getResource()->deleteImportItems($data['type']);
$this->_hasData = true;
if ($data['behaviour'] == 'delete') {
$isReplace = false;
} else {
$isReplace = true;
}
}
/** fetch all items from import source */
while ($tag = mysqli_fetch_assoc($result)) {
/** store the source item */
$sourceItems[] = [
'is_imported' => $tagModel->getResource()->isImported($importSource, $tag['id']),
'is_duplicated_url' => $tagModel->getResource()->isDuplicateUrlKey($tag['tag']),
'id' => $tag['id'],
'name' => $tag['tag'],
'meta_robots' => 'INDEX,FOLLOW',
'store_ids' => $this->_storeManager->getStore()->getId(),
'enabled' => 1,
'import_source' => $importSource . '-' . $tag['id']
];
}
/** update and replace behaviour action */
if ($isReplace && isset($sourceItems)) {
foreach ($sourceItems as $tag) {
if ($tag['is_imported']) {
/** update tag that has duplicate URK key */
if ($tag['is_duplicated_url'] != null || $data['expand_behaviour'] == '1') {
try {
$where = ['tag_id = ?' => (int) $tag['is_imported']];
$this->_updateTags($tag, $where);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
} else {
/** Add new tags */
$tagModel->load($tag['is_imported'])->setImportSource('')->save();
try {
$this->_addTags($tagModel, $tag);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
}
} else {
/** Update tags */
if ($data['behaviour'] == 'update'
&& $data['expand_behaviour'] == '1'
&& $tag['is_duplicated_url'] != null) {
try {
$where = ['tag_id = ?' => (int) $tag['is_duplicated_url']];
$this->_updateTags($tag, $where);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
} else {
/** Add new tags */
try {
$this->_addTags($tagModel, $tag);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
}
}
}
mysqli_free_result($result);
/** Store old tag ids */
foreach ($tagModel->getCollection() as $item) {
if ($item->getImportSource() != null) {
$tagImportSource = explode('-', $item->getImportSource());
$importType = array_shift($tagImportSource);
if ($importType == $this->_type['aheadworksm1']) {
$oldTagId = array_pop($tagImportSource);
$oldTagIds[$item->getId()] = $oldTagId;
}
}
}
$tags = $this->_registry->registry('mageplaza_import_post_tags_collection');
/** Insert post tag relations */
foreach ($tags as $postId => $tagIds) {
foreach ($tagIds as $id) {
try {
$newTagId = array_search($id, $oldTagIds);
$this->_resourceConnection->getConnection()
->insert(
$this->_resourceConnection->getTableName('mageplaza_blog_post_tag'),
['tag_id' => $newTagId, 'post_id' => $postId, 'position' => 0]
);
} catch (Exception $e) {
continue;
}
}
}
}
$statistics = $this->_getStatistics('tags', $this->_successCount, $this->_errorCount, $this->_hasData);
$this->_registry->register('mageplaza_import_tag_statistic', $statistics);
}
/**
* @param array $data
* @param null $connection
*
* @return mixed|void
* @throws LocalizedException
*/
protected function _importCategories($data, $connection)
{
$sqlString = "SELECT * FROM `" . $data["table_prefix"] . self::TABLE_CATEGORY . "`";
$result = mysqli_query($connection, $sqlString);
$isReplace = true;
/** @var CategoryFactory $categoryModel */
$categoryModel = $this->_categoryFactory->create();
$oldCategoryIds = [];
$this->_resetRecords();
$importSource = $data['type'] . '-' . $data['database'];
/** delete behaviour action */
if ($data['behaviour'] === 'delete' || $data['behaviour'] === 'replace') {
$categoryModel->getResource()->deleteImportItems($data['type']);
$this->_hasData = true;
$isReplace = !($data['behaviour'] === 'delete');
}
/** fetch all items from import source */
while ($category = mysqli_fetch_assoc($result)) {
/** store the source item */
$sourceItems[] = [
'is_imported' => $categoryModel->getResource()->isImported($importSource, $category['cat_id']),
'is_duplicated_url' => $categoryModel->getResource()->isDuplicateUrlKey($category['identifier']),
'id' => $category['cat_id'],
'name' => $category['title'],
'url_key' => $this->helperData->generateUrlKey(
$categoryModel->getResource(),
$categoryModel,
$category['identifier']
),
'meta_robots' => 'INDEX,FOLLOW',
'store_ids' => $this->_storeManager->getStore()->getId(),
'enabled' => 1,
'path' => '1',
'meta_description' => $category['meta_description'],
'meta_keywords' => $category['meta_keywords'],
'import_source' => $importSource . '-' . $category['cat_id']
];
}
/** update and replace behaviour action */
if ($isReplace && isset($sourceItems)) {
foreach ($sourceItems as $category) {
if ($category['is_imported']) {
/** update category that has duplicate URK key */
if (($category['is_duplicated_url'] != null || $data['expand_behaviour'] == '1')
&& $category['url_key'] != 'root') {
try {
$where = ['category_id = ?' => (int) $category['is_imported']];
$this->_updateCategories($category, $where);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
} else {
/** Add new categories */
$categoryModel->load($category['is_imported'])->setImportSource('')->save();
try {
$this->_addCategories($categoryModel, $category);
$newCategories[$categoryModel->getId()] = $category;
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
}
} else {
/**
* Update categories
*/
if ($data['behaviour'] == 'update'
&& $data['expand_behaviour'] == '1'
&& $category['is_duplicated_url'] != null
&& $category['url_key'] != 'root') {
try {
$where = ['category_id = ?' => (int) $category['is_duplicated_url']];
$this->_updateCategories($category, $where);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
} else {
/**
* Add new categories
*/
try {
$this->_addCategories($categoryModel, $category);
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
}
}
}
/** Store old category ids */
foreach ($categoryModel->getCollection() as $item) {
if ($item->getImportSource() != null) {
$catImportSource = explode('-', $item->getImportSource());
$importType = array_shift($catImportSource);
if ($importType == $this->_type['aheadworksm1']) {
$oldCategoryId = array_pop($catImportSource);
$oldCategoryIds[$item->getId()] = $oldCategoryId;
}
}
}
mysqli_free_result($result);
$this->_importCategoryPost($data, $connection, $oldCategoryIds, 'mageplaza_blog_post_category');
}
$statistics = $this->_getStatistics("categories", $this->_successCount, $this->_errorCount, $this->_hasData);
$this->_registry->register('mageplaza_import_category_statistic', $statistics);
}
/**
* Import comments
*
* @param array $data
* @param null $connection
*
* @throws LocalizedException
*/
protected function _importComments($data, $connection)
{
$accountManage = $this->_objectManager->create(AccountManagement::class);
$sqlString = "SELECT * FROM `" . $data["table_prefix"] . self::TABLE_COMMENT . "`";
$result = mysqli_query($connection, $sqlString);
$this->_resetRecords();
$isReplace = true;
/** @var CommentFactory $commentModel */
$commentModel = $this->_commentFactory->create();
$customerModel = $this->_customerFactory->create();
$websiteId = $this->_storeManager->getWebsite()->getId();
$oldPostIds = $this->_registry->registry('mageplaza_import_post_ids_collection');
$importSource = $data['type'] . '-' . $data['database'];
/** delete behaviour action */
if ($data['behaviour'] === 'delete' || $data['behaviour'] === 'replace') {
$commentModel->getResource()->deleteImportItems($data['type']);
$this->_hasData = true;
$isReplace = !($data['behaviour'] === 'delete');
}
/** fetch all items from import source */
while ($comment = mysqli_fetch_assoc($result)) {
/** mapping status */
switch ($comment['status']) {
case '2':
$status = Status::APPROVED;
break;
case '1':
$status = Status::PENDING;
break;
default:
$status = Status::APPROVED;
}
/** search for new post id */
$newPostId = array_search($comment['post_id'], $oldPostIds);
/** check if comment author is customer */
if ($accountManage->isEmailAvailable($comment['email'], $websiteId)) {
$entityId = 0;
$userName = $comment['user'];
$userEmail = $comment['email'];
} else {
/** comment author is guest */
$customerModel->setWebsiteId($websiteId);
$customerModel->loadByEmail($comment['email']);
$entityId = $customerModel->getEntityId();
$userName = '';
$userEmail = '';
}
/** store the source item */
$sourceItems[] = [
'is_imported' => $commentModel->getResource()->isImported($importSource, $comment['comment_id']),
'id' => $comment['comment_id'],
'post_id' => $newPostId,
'entity_id' => $entityId,
'has_reply' => 0,
'is_reply' => 0,
'reply_id' => 0,
'content' => $comment['comment'],
'created_at' => ($comment['created_time']) ?: $this->date->date(),
'status' => $status,
'store_ids' => $this->_storeManager->getStore()->getId(),
'user_name' => $userName,
'user_email' => $userEmail,
'import_source' => $importSource . '-' . $comment['comment_id']
];
}
/** update and replace behaviour action */
if ($isReplace && isset($sourceItems)) {
foreach ($sourceItems as $comment) {
/** import actions */
if ($comment['is_imported']) {
/** update comments */
$where = ['comment_id = ?' => (int) $comment['is_imported']];
$this->_resourceConnection->getConnection()
->update(
$this->_resourceConnection->getTableName('mageplaza_blog_comment'),
[
'post_id' => $comment['post_id'],
'entity_id' => $comment['entity_id'],
'has_reply' => $comment['has_reply'],
'is_reply' => $comment['is_reply'],
'reply_id' => $comment['reply_id'],
'content' => $comment['content'],
'created_at' => $comment['created_at'],
'status' => $comment['status'],
'store_ids' => $comment['store_ids'],
'user_name' => $comment['user_name'],
'user_email' => $comment['user_email'],
'import_source' => $comment['import_source']
],
$where
);
$this->_successCount++;
$this->_hasData = true;
} else {
/** add new comments */
try {
$commentModel->setData([
'post_id' => $comment['post_id'],
'entity_id' => $comment['entity_id'],
'has_reply' => $comment['has_reply'],
'is_reply' => $comment['is_reply'],
'reply_id' => $comment['reply_id'],
'content' => $comment['content'],
'created_at' => $comment['created_at'],
'status' => $comment['status'],
'store_ids' => $comment['store_ids'],
'user_name' => $comment['user_name'],
'user_email' => $comment['user_email'],
'import_source' => $comment['import_source']
])->save();
$this->_successCount++;
$this->_hasData = true;
} catch (Exception $e) {
$this->_errorCount++;
$this->_hasData = true;
continue;
}
}
}
mysqli_free_result($result);
}
$statistics = $this->_getStatistics('comments', $this->_successCount, $this->_errorCount, $this->_hasData);
$this->_registry->register('mageplaza_import_comment_statistic', $statistics);
}
// phpcs:disable Magento2.CodeAnalysis.EmptyBlock
/**
* @param array $data
* @param null $connection
*
* @return mixed|void
*/
protected function _importAuthors($data, $connection)
{
// TODO: Implement _importAuthors() method.
}
/**
* Import category posts relationships
*
* @param array $data
* @param null $connection
* @param array $oldCatIds
* @param string $relationTable
*/
protected function _importCategoryPost($data, $connection, $oldCatIds, $relationTable)
{
$oldPostIds = $this->_registry->registry('mageplaza_import_post_ids_collection');
$categoryPostTable = $this->_resourceConnection->getTableName($relationTable);
foreach ($oldPostIds as $newPostId => $oldPostId) {
$sqlRelation = "SELECT * FROM `" . $data["table_prefix"]
. self::TABLE_CATEGORY_POST . "` WHERE `post_id` = " . $oldPostId;
$result = mysqli_query($connection, $sqlRelation);
while ($categoryPost = mysqli_fetch_assoc($result)) {
$newCategoryId = (array_search($categoryPost['cat_id'], $oldCatIds)) ?: '1';
try {
$this->_resourceConnection->getConnection()->insert($categoryPostTable, [
'category_id' => $newCategoryId,
'post_id' => $newPostId,
'position' => 0
]);
} catch (Exception $e) {
continue;
}
}
}
}
/**
* Add posts to database
*
* @param PostFactory $postModel
* @param array $post
*/
private function _addPosts($postModel, $post)
{
$postModel->setData([
'name' => $post['name'],
'short_description' => $post['short_description'],
'post_content' => $post['post_content'],
'url_key' => $post['url_key'],
'created_at' => $post['created_at'],
'updated_at' => $post['updated_at'],
'publish_date' => $post['publish_date'],
'enabled' => $post['enabled'],
'in_rss' => $post['in_rss'],
'allow_comment' => $post['allow_comment'],
'store_ids' => $post['store_ids'],
'meta_robots' => $post['meta_robots'],
'meta_keywords' => $post['meta_keywords'],
'meta_description' => $post['meta_description'],
'author_id' => $post['author_id'],
'import_source' => $post['import_source']
])->save();
}
/**
* Update posts to database
*
* @param array $post
* @param array $where
*/
private function _updatePosts($post, $where)
{
$this->_resourceConnection->getConnection()->update(
$this->_resourceConnection->getTableName('mageplaza_blog_post'),
[
'name' => $post['name'],
'short_description' => $post['short_description'],
'post_content' => $post['post_content'],
'url_key' => $post['url_key'],
'created_at' => $post['created_at'],
'updated_at' => $post['updated_at'],
'publish_date' => $post['publish_date'],
'enabled' => $post['enabled'],
'in_rss' => $post['in_rss'],
'allow_comment' => $post['allow_comment'],
'store_ids' => $post['store_ids'],
'meta_robots' => $post['meta_robots'],
'meta_keywords' => $post['meta_keywords'],
'meta_description' => $post['meta_description'],
'author_id' => $post['author_id'],
'import_source' => $post['import_source']
],
$where
);
$this->_resourceConnection->getConnection()
->delete($this->_resourceConnection
->getTableName('mageplaza_blog_post_category'), $where);
$this->_resourceConnection->getConnection()
->delete($this->_resourceConnection
->getTableName('mageplaza_blog_post_tag'), $where);
}
/**
* @param TagFactory $tagModel
* @param array $tag
*/
private function _addTags($tagModel, $tag)
{
$tagModel->setData([
'name' => $tag['name'],
'meta_robots' => $tag['meta_robots'],
'store_ids' => $tag['store_ids'],
'enabled' => $tag['enabled'],
'import_source' => $tag['import_source']
])->save();
}
/**
* @param array $tag
* @param array $where
*/
private function _updateTags($tag, $where)
{
$this->_resourceConnection->getConnection()->update(
$this->_resourceConnection->getTableName('mageplaza_blog_tag'),
[
'name' => $tag['name'],
'meta_robots' => $tag['meta_robots'],
'store_ids' => $tag['store_ids'],
'enabled' => $tag['enabled'],
'import_source' => $tag['import_source']
],
$where
);
}
/**
* @param CategoryFactory $categoryModel
* @param array $category
*/
private function _addCategories($categoryModel, $category)
{
$categoryModel->setData([
'name' => $category['name'],
'url_key' => $category['url_key'],
'meta_robots' => $category['meta_robots'],
'store_ids' => $category['store_ids'],
'enabled' => $category['enabled'],
'path' => $category['path'],
'meta_description' => $category['meta_description'],
'meta_keywords' => $category['meta_keywords'],
'import_source' => $category['import_source']
])->save();
}
/**
* @param array $category
* @param array $where
*/
private function _updateCategories($category, $where)
{
$this->_resourceConnection->getConnection()->update(
$this->_resourceConnection->getTableName('mageplaza_blog_category'),
[
'name' => $category['name'],
'url_key' => $category['url_key'],
'meta_robots' => $category['meta_robots'],
'store_ids' => $category['store_ids'],
'enabled' => $category['enabled'],
'meta_description' => $category['meta_description'],
'meta_keywords' => $category['meta_keywords'],
'import_source' => $category['import_source']
],
$where
);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Model\AbstractModel;
/**
* Class Like
* @package Mageplaza\Blog\Model
*/
class Like extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_comment_like';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_comment_like';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_comment_like';
/**
* @var string
*/
protected $_idFieldName = 'like_id';
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(ResourceModel\Like::class);
}
/**
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\DataObject;
use Mageplaza\Blog\Api\Data\MonthlyArchiveInterface;
/**
* Class MonthlyArchive
* @package Mageplaza\Blog\Model
*/
class MonthlyArchive extends DataObject implements MonthlyArchiveInterface
{
/**
* {@inheritdoc}
*/
public function getLabel()
{
return $this->getData(self::LABEL);
}
/**
* {@inheritdoc}
*/
public function setLabel($value)
{
$this->setData(self::LABEL, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getPostCount()
{
return $this->getData(self::POST_COUNT);
}
/**
* {@inheritdoc}
*/
public function setPostCount($value)
{
$this->setData(self::POST_COUNT, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function getLink()
{
return $this->getData(self::LINK);
}
/**
* {@inheritdoc}
*/
public function setLink($value)
{
$this->setData(self::LINK, $value);
return $this;
}
}
+640
View File
@@ -0,0 +1,640 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Exception;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\DateTime;
use Mageplaza\Blog\Helper\Data;
use Mageplaza\Blog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Post as PostResource;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
use Mageplaza\Blog\Model\ResourceModel\Post\CollectionFactory as PostCollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Tag\CollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Topic\CollectionFactory as TopicCollectionFactory;
/**
* @method Post setName($name)
* @method Post setShortDescription($shortDescription)
* @method Post setPostContent($postContent)
* @method Post setImage($image)
* @method Post setViews($views)
* @method Post setEnabled($enabled)
* @method Post setUrlKey($urlKey)
* @method Post setInRss($inRss)
* @method Post setAllowComment($allowComment)
* @method Post setMetaTitle($metaTitle)
* @method Post setMetaDescription($metaDescription)
* @method Post setMetaKeywords($metaKeywords)
* @method Post setMetaRobots($metaRobots)
* @method mixed getName()
* @method mixed getPostContent()
* @method mixed getImage()
* @method mixed getViews()
* @method mixed getEnabled()
* @method mixed getUrlKey()
* @method mixed getInRss()
* @method mixed getAllowComment()
* @method mixed getMetaTitle()
* @method mixed getMetaDescription()
* @method mixed getMetaKeywords()
* @method mixed getMetaRobots()
* @method Post setCreatedAt(string $createdAt)
* @method string getCreatedAt()
* @method Post setUpdatedAt(string $updatedAt)
* @method string getUpdatedAt()
* @method Post setTagsData(array $data)
* @method Post setTopicsData(array $data)
* @method Post setProductsData(array $data)
* @method array getTagsData()
* @method array getProductsData()
* @method array getTopicsData()
* @method Post setIsChangedTagList(bool $flag)
* @method Post setIsChangedProductList(bool $flag)
* @method Post setIsChangedTopicList(bool $flag)
* @method Post setIsChangedCategoryList(bool $flag)
* @method bool getIsChangedTagList()
* @method bool getIsChangedTopicList()
* @method bool getIsChangedCategoryList()
* @method Post setAffectedTagIds(array $ids)
* @method Post setAffectedEntityIds(array $ids)
* @method Post setAffectedTopicIds(array $ids)
* @method Post setAffectedCategoryIds(array $ids)
* @method bool getAffectedTagIds()
* @method bool getAffectedTopicIds()
* @method bool getAffectedCategoryIds()
* @method array getCategoriesIds()
* @method Post setCategoriesIds(array $categoryIds)
* @method array getTagsIds()
* @method Post setTagsIds(array $tagIds)
* @method array getTopicsIds()
* @method Post setTopicsIds(array $topicIds)
*/
class Post extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_post';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_post';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_post';
/**
* Tag Collection
*
* @var ResourceModel\Tag\Collection
*/
public $tagCollection;
/**
* Topic Collection
*
* @var ResourceModel\Topic\Collection
*/
public $topicCollection;
/**
* Blog Category Collection
*
* @var ResourceModel\Category\Collection
*/
public $categoryCollection;
/**
* Tag Collection Factory
*
* @var CollectionFactory
*/
public $tagCollectionFactory;
/**
* Topic Collection Factory
*
* @var TopicCollectionFactory
*/
public $topicCollectionFactory;
/**
* Blog Category Collection Factory
*
* @var CategoryCollectionFactory
*/
public $categoryCollectionFactory;
/**
* Post Collection Factory
*
* @var PostCollectionFactory
*/
public $postCollectionFactory;
/**
* Related Post Collection
*
* @var Collection
*/
public $relatedPostCollection;
/**
* Previous Post Collection
*
* @var Collection
*/
public $prevPostCollection;
/**
* Next Post Collection
*
* @var Collection
*/
public $nextPostCollection;
/**
* @var DateTime
*/
public $dateTime;
/**
* @var Data
*/
public $helperData;
/**
* @var ProductCollectionFactory
*/
public $productCollectionFactory;
/**
* @var ProductCollection
*/
public $productCollection;
/**
* @var TrafficFactory
*/
protected $trafficFactory;
/**
* Post constructor.
*
* @param Context $context
* @param Registry $registry
* @param DateTime $dateTime
* @param Data $helperData
* @param TrafficFactory $trafficFactory
* @param CollectionFactory $tagCollectionFactory
* @param TopicCollectionFactory $topicCollectionFactory
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param PostCollectionFactory $postCollectionFactory
* @param ProductCollectionFactory $productCollectionFactory
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
DateTime $dateTime,
Data $helperData,
TrafficFactory $trafficFactory,
CollectionFactory $tagCollectionFactory,
TopicCollectionFactory $topicCollectionFactory,
CategoryCollectionFactory $categoryCollectionFactory,
PostCollectionFactory $postCollectionFactory,
ProductCollectionFactory $productCollectionFactory,
?AbstractResource $resource = null,
?AbstractDb $resourceCollection = null,
array $data = []
) {
$this->tagCollectionFactory = $tagCollectionFactory;
$this->topicCollectionFactory = $topicCollectionFactory;
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->postCollectionFactory = $postCollectionFactory;
$this->productCollectionFactory = $productCollectionFactory;
$this->helperData = $helperData;
$this->dateTime = $dateTime;
$this->trafficFactory = $trafficFactory;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(PostResource::class);
}
/**
* @inheritdoc
*/
public function afterSave()
{
if ($this->isObjectNew()) {
$trafficModel = $this->trafficFactory->create()
->load($this->getId(), 'post_id');
if (!$trafficModel->getId()) {
$trafficModel->setData([
'post_id' => $this->getId(),
'numbers_view' => 0
])->save();
}
}
return parent::afterSave();
}
/**
* @param bool $shorten
*
* @return mixed|string
*/
public function getShortDescription($shorten = false)
{
$shortDescription = $this->getData('short_description');
$maxLength = 20;
$descArr = explode(' ', $shortDescription ?? '');
if ($shorten && count($descArr) > $maxLength) {
$descArr = array_slice($descArr, 0, $maxLength);
$shortDescription = implode(' ', $descArr) . '...';
}
return $shortDescription;
}
/**
* @param null $store
*
* @return string
*/
public function getUrl($store = null)
{
return $this->helperData->getBlogUrl($this, Data::TYPE_POST, $store);
}
/**
* Get identities
*
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* get entity default values
*
* @return array
*/
public function getDefaultValues()
{
$values = [];
$values['in_rss'] = '1';
$values['enabled'] = '1';
$values['allow_comment'] = '1';
$values['store_ids'] = '1';
return $values;
}
/**
* @return ResourceModel\Tag\Collection
*/
public function getSelectedTagsCollection()
{
if ($this->tagCollection === null) {
$collection = $this->tagCollectionFactory->create();
$collection->getSelect()->join(
$this->getResource()->getTable('mageplaza_blog_post_tag'),
'main_table.tag_id=' . $this->getResource()->getTable('mageplaza_blog_post_tag') . '.tag_id AND '
. $this->getResource()->getTable('mageplaza_blog_post_tag') . '.post_id=' . $this->getId(),
['position']
)->where("main_table.enabled='1'");
$this->tagCollection = $collection;
}
return $this->tagCollection;
}
/**
* @return ResourceModel\Topic\Collection
*/
public function getSelectedTopicsCollection()
{
if ($this->topicCollection === null) {
$collection = $this->topicCollectionFactory->create();
$collection->join(
$this->getResource()->getTable('mageplaza_blog_post_topic'),
'main_table.topic_id=' . $this->getResource()->getTable('mageplaza_blog_post_topic') . '.topic_id AND '
. $this->getResource()->getTable('mageplaza_blog_post_topic') . '.post_id=' . $this->getId(),
['position']
);
$this->topicCollection = $collection;
}
return $this->topicCollection;
}
/**
* @return ResourceModel\Category\Collection
*/
public function getSelectedCategoriesCollection()
{
if ($this->categoryCollection === null) {
$collection = $this->categoryCollectionFactory->create();
$collection->join(
$this->getResource()->getTable('mageplaza_blog_post_category'),
'main_table.category_id=' . $this->getResource()->getTable('mageplaza_blog_post_category') .
'.category_id AND ' . $this->getResource()->getTable('mageplaza_blog_post_category') . '.post_id="'
. $this->getId() . '"',
['position']
);
$this->categoryCollection = $collection;
}
return $this->categoryCollection;
}
/**
* @return array
* @throws LocalizedException
*/
public function getCategoryIds()
{
if (!$this->hasData('category_ids')) {
$ids = $this->_getResource()->getCategoryIds($this);
$this->setData('category_ids', $ids);
}
return (array) $this->_getData('category_ids');
}
/**
* @return array
* @throws LocalizedException
*/
public function getTagIds()
{
if (!$this->hasData('tag_ids')) {
$ids = $this->_getResource()->getTagIds($this);
$this->setData('tag_ids', $ids);
}
return (array) $this->_getData('tag_ids');
}
/**
* @return array
* @throws LocalizedException
*/
public function getTopicIds()
{
if (!$this->hasData('topic_ids')) {
$ids = $this->_getResource()->getTopicIds($this);
$this->setData('topic_ids', $ids);
}
return (array) $this->_getData('topic_ids');
}
/**
* @return int
* @throws LocalizedException
*/
public function getViewTraffic()
{
if (!$this->hasData('view_traffic')) {
$traffic = $this->_getResource()->getViewTraffic($this);
$this->setData('view_traffic', $traffic[0]);
}
return $this->_getData('view_traffic');
}
/**
* @return int
* @throws LocalizedException
*/
public function getAuthorName()
{
if (!$this->hasData('author_name')) {
$author = $this->_getResource()->getAuthor($this);
$this->setData('author_name', $author['name']);
}
return $this->_getData('author_name');
}
/**
* @return int
* @throws LocalizedException
*/
public function getAuthorUrl()
{
if (!$this->hasData('author_url')) {
$author = $this->_getResource()->getAuthor($this);
$this->setData('author_url', $this->helperData->getBlogUrl($author['url_key'], Data::TYPE_AUTHOR));
}
return $this->_getData('author_url');
}
/**
* @return int
* @throws LocalizedException
*/
public function getAuthorUrlKey()
{
if (!$this->hasData('author_url_key')) {
$author = $this->_getResource()->getAuthor($this);
$this->setData('author_url_key', $author['url_key']);
}
return $this->_getData('author_url_key');
}
/**
* @return mixed
* @throws NoSuchEntityException
*/
public function getUrlImage()
{
$imageHelper = $this->helperData->getImageHelper();
$imageFile = $this->getImage() ? $imageHelper->getMediaPath($this->getImage(), 'post') : '';
$imageUrl = $imageFile ? $this->helperData->getImageHelper()->getMediaUrl($imageFile) : '';
$this->setData('image', $imageUrl);
return $this->_getData('image');
}
/**
* @throws Exception
*/
public function updateViewTraffic()
{
if ($this->getId()) {
$trafficModel = $this->trafficFactory->create()->load($this->getId(), 'post_id');
if ($trafficModel->getId()) {
$trafficModel->setNumbersView($trafficModel->getNumbersView() + 1);
$trafficModel->save();
} else {
$traffic = $this->trafficFactory->create();
$traffic->addData(['post_id' => $this->getId(), 'numbers_view' => 1])->save();
}
}
}
/**
* @return Collection|null
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function getRelatedPostsCollection()
{
$topicIds = $this->_getResource()->getTopicIds($this);
if (count($topicIds)) {
$collection = $this->postCollectionFactory->create();
$collection->getSelect()
->join(
['topic' => $this->getResource()->getTable('mageplaza_blog_post_topic')],
'main_table.post_id=topic.post_id AND topic.post_id != "' . $this->getId()
. '" AND topic.topic_id IN (' . implode(',', $topicIds) . ')',
['position']
)->group('main_table.post_id')->order('topic.position');
if ($limit = (int) $this->helperData->getPostViewPageConfig('related_post')) {
$collection->getSelect()
->limit($limit);
}
$collection->addFieldToFilter('enabled', '1');
$this->helperData->addStoreFilter($collection);
return $collection;
}
return null;
}
/**
* @return ProductCollection
*/
public function getSelectedProductsCollection()
{
if ($this->productCollection === null) {
$collection = $this->productCollectionFactory->create();
$collection->getSelect()->join(
$this->getResource()->getTable('mageplaza_blog_post_product'),
'e.entity_id=' . $this->getResource()->getTable('mageplaza_blog_post_product')
. '.entity_id AND ' . $this->getResource()->getTable('mageplaza_blog_post_product') . '.post_id='
. $this->getId(),
['position']
);
$this->productCollection = $collection;
}
return $this->productCollection;
}
/**
* @return array|mixed
*/
public function getProductsPosition()
{
if (!$this->getId()) {
return [];
}
$array = $this->getData('products_position');
if ($array === null) {
$array = $this->getResource()->getProductsPosition($this);
$this->setData('products_position', $array);
}
return $array;
}
/**
* get previous post
* @return Collection
*/
public function getPrevPost()
{
if ($this->prevPostCollection === null) {
$collection = $this->postCollectionFactory->create();
$collection->addFieldToFilter('post_id', ['lt' => $this->getId()])
->setOrder('post_id', 'DESC')->setPageSize(1)->setCurPage(1);
$this->prevPostCollection = $collection;
}
return $this->prevPostCollection;
}
/**
* get next post
* @return Collection
*/
public function getNextPost()
{
if ($this->nextPostCollection === null) {
$collection = $this->postCollectionFactory->create();
$collection->addFieldToFilter('post_id', ['gt' => $this->getId()])
->setOrder('post_id', 'ASC')->setPageSize(1)->setCurPage(1);
$this->nextPostCollection = $collection;
}
return $this->nextPostCollection;
}
}
+110
View File
@@ -0,0 +1,110 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Model\AbstractModel;
use Mageplaza\Blog\Helper\Data;
/**
* Class PostLike
* @package Mageplaza\Blog\Model
*/
class PostHistory extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_post_history';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_post_history';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_post_history';
/**
* @var string
*/
protected $_idFieldName = 'like_id';
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(ResourceModel\PostHistory::class);
}
/**
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* @param $postId
*
* @return int
*/
public function getSumPostHistory($postId)
{
return $this->getCollection()->addFieldToFilter('post_id', $postId)->count();
}
/**
* @param $postId
*/
public function removeFirstHistory($postId)
{
$this->getCollection()->addFieldToFilter('post_id', $postId)->getFirstItem()->delete();
}
/**
* @return array|mixed
*/
public function getProductsPosition()
{
if (!$this->getId()) {
return [];
}
$data = [];
foreach (Data::jsonDecode($this->getProductIds()) as $key => $value) {
$data[$key] = $value['position'];
}
return $data;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Model\AbstractModel;
/**
* Class PostLike
* @package Mageplaza\Blog\Model
*/
class PostLike extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_post_like';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_post_like';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_post_like';
/**
* @var string
*/
protected $_idFieldName = 'like_id';
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(ResourceModel\PostLike::class);
}
/**
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Blog\Helper\Data;
/**
* Class Author
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Author extends AbstractDb
{
/**
* @var Data
*/
public $helperData;
/**
* @var DateTime
*/
public $dateTime;
/**
* @var string
*/
public $postTable;
/**
* Author constructor.
*
* @param Context $context
* @param Data $helperData
* @param DateTime $dateTime
*/
public function __construct(
Context $context,
Data $helperData,
DateTime $dateTime
) {
$this->helperData = $helperData;
$this->dateTime = $dateTime;
parent::__construct($context);
$this->postTable = $this->getTable('mageplaza_blog_post');
}
/**
* @inheritdoc
*/
protected function _construct()
{
$this->_init('mageplaza_blog_author', 'user_id');
}
/**
* @inheritdoc
* @throws LocalizedException
*/
protected function _beforeSave(AbstractModel $object)
{
$object->setUrlKey(
$this->helperData->generateUrlKey($this, $object, $object->getUrlKey() ?: $object->getName())
);
if (!$object->isObjectNew()) {
$timeStamp = $this->dateTime->gmtDate();
$object->setUpdatedAt($timeStamp);
}
return $this;
}
/**
* @param \Mageplaza\Blog\Model\Author $author
*
* @return array
*/
public function getPostIds(\Mageplaza\Blog\Model\Author $author)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from(
$this->postTable,
'post_id'
)
->where(
'author_id = ?',
(int)$author->getId()
);
return $adapter->fetchCol($select);
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Author;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Mageplaza\Blog\Model\Author;
use Mageplaza\Blog\Model\ResourceModel\Author as AuthorResourceModel;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Author
*/
class Collection extends AbstractCollection
{
/**
* @inheritdoc
*/
protected $_idFieldName = 'user_id';
/**
* Construct
*/
protected function _construct()
{
$this->_init(Author::class, AuthorResourceModel::class);
}
}
@@ -0,0 +1,110 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Author\Grid;
use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Author\Grid
*/
class Collection extends SearchResult
{
/**
* @return Collection
*/
protected function _initSelect(): Collection
{
parent::_initSelect();
$this->getSelect()->joinLeft(
['post' => $this->getTable('mageplaza_blog_post')],
'main_table.user_id = post.author_id',
['qty_post' => 'COUNT(post_id)']
)->group('main_table.user_id');
$this->addFilterToMap('name', 'main_table.name');
$this->addFilterToMap('url_key', 'main_table.url_key');
$this->addExpressionFieldToSelect(
'mp_created_at',
'main_table.created_at',
['mp_created_at' => 'created_at']
);
$this->addExpressionFieldToSelect(
'mp_updated_at',
'main_table.updated_at',
['mp_created_at' => 'created_at']
);
return $this;
}
/**
* @param array|string $field
* @param null $condition
*
* @return SearchResult
*/
public function addFieldToFilter($field, $condition = null)
{
switch ($field) {
case 'qty_post':
foreach ($condition as $key => $value) {
if ($key === 'like') {
$this->getSelect()->having('COUNT(post_id) LIKE ?', $value);
}
}
return $this;
case 'mp_created_at':
$field = 'main_table.created_at';
break;
case 'mp_updated_at':
$field = 'main_table.updated_at';
break;
}
return parent::addFieldToFilter($field, $condition);
}
/**
* @param string $field
* @param string $direction
*
* @return SearchResult
*/
public function setOrder($field, $direction = self::SORT_ORDER_DESC)
{
switch ($field) {
case 'customer_name':
return parent::setOrder('user_name', $direction);
case 'mp_updated_at':
$field = 'main_table.updated_at';
break;
case 'mp_created_at':
$field = 'main_table.updated_at';
break;
}
return parent::setOrder($field, $direction);
}
}
+600
View File
@@ -0,0 +1,600 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\DataObject;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Blog\Helper\Data;
use Mageplaza\Blog\Model\Category as CategoryModel;
use Zend_Db_Expr;
/**
* Class Category
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Category extends AbstractDb
{
/**
* Date model
*
* @var DateTime
*/
public $date;
/**
* Event Manager
*
* @var ManagerInterface
*/
public $eventManager;
/**
* Post relation model
*
* @var string
*/
public $categoryPostTable;
/**
* @var Data
*/
public $helperData;
/**
* Category constructor.
*
* @param Data $helperData
* @param DateTime $date
* @param ManagerInterface $eventManager
* @param Context $context
*/
public function __construct(
Context $context,
DateTime $date,
ManagerInterface $eventManager,
Data $helperData
) {
$this->helperData = $helperData;
$this->date = $date;
$this->eventManager = $eventManager;
parent::__construct($context);
$this->categoryPostTable = $this->getTable('mageplaza_blog_post_category');
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_category', 'category_id');
}
/**
* Retrieves Blog Category Name from DB by passed id.
*
* @param int $id
*
* @return string
* @throws LocalizedException
*/
public function getCategoryNameById($id)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'name')
->where('category_id = :category_id');
$binds = ['category_id' => (int) $id];
return $adapter->fetchOne($select, $binds);
}
/**
* Before save call back
*
* @param AbstractModel $object
*
* @return $this
* @throws LocalizedException
*/
protected function _beforeSave(AbstractModel $object)
{
$object->setUpdatedAt($this->date->date());
if ($object->isObjectNew()) {
$object->setCreatedAt($this->date->date());
}
/** @var CategoryModel $object */
parent::_beforeSave($object);
if (!$object->getChildrenCount()) {
$object->setChildrenCount(0);
}
if ($object->isObjectNew()) {
if ($object->getPosition() === null) {
$object->setPosition($this->getMaxPosition($object->getPath()) + 1);
}
$path = explode('/', $object->getPath());
$level = count($path) - ($object->getId() ? 1 : 0);
$toUpdateChild = array_diff($path, [$object->getId()]);
if (!$object->hasPosition()) {
$object->setPosition($this->getMaxPosition(implode('/', $toUpdateChild)) + 1);
}
if (!$object->hasLevel()) {
$object->setLevel($level);
}
if (!$object->hasParentId() && $level) {
$object->setParentId($path[$level - 1]);
}
if (!$object->getId()) {
$object->setPath($object->getPath() . '/');
}
$this->getConnection()->update(
$this->getMainTable(),
['children_count' => 'children_count+1'],
['category_id IN(?)' => $toUpdateChild]
);
}
if (is_array($object->getStoreIds())) {
$object->setStoreIds(implode(',', $object->getStoreIds()));
}
$object->setUrlKey(
$this->helperData->generateUrlKey($this, $object, $object->getUrlKey() ?: $object->getName())
);
return $this;
}
/**
* @param AbstractModel $object
*
* @return AbstractDb
* @throws LocalizedException
*/
protected function _afterSave(AbstractModel $object)
{
/** @var CategoryModel $object */
if (substr($object->getPath(), -1) === '/') {
$object->setPath($object->getPath() . $object->getId());
$this->savePath($object);
}
$this->savePostRelation($object);
return parent::_afterSave($object);
}
/**
* @param string $path
*
* @return int|string
*/
protected function getMaxPosition($path)
{
$adapter = $this->getConnection();
$positionField = $adapter->quoteIdentifier('position');
$level = count(explode('/', $path));
$bind = ['c_level' => $level, 'c_path' => $path . '/%'];
$select = $adapter->select()->from(
$this->getTable('mageplaza_blog_category'),
'MAX(' . $positionField . ')'
)->where(
$adapter->quoteIdentifier('path') . ' LIKE :c_path'
)->where(
$adapter->quoteIdentifier('level') . ' = :c_level'
);
$position = $adapter->fetchOne($select, $bind);
if (!$position) {
$position = 0;
}
return $position;
}
/**
* Check category url key is exists
*
* @param string $urlKey
*
* @return string
* @throws LocalizedException
*/
public function isDuplicateUrlKey($urlKey)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'category_id')
->where('url_key = :url_key');
$binds = ['url_key' => $urlKey];
return $adapter->fetchOne($select, $binds);
}
/**
* Check is imported category
*
* @param string $importSource
* @param int $oldId
*
* @return string
* @throws LocalizedException
*/
public function isImported($importSource, $oldId)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'category_id')
->where('import_source = :import_source');
$binds = ['import_source' => $importSource . '-' . $oldId];
return $adapter->fetchOne($select, $binds);
}
/**
* Update path field
*
* @param Object $object
*
* @return $this
* @throws LocalizedException
*/
public function savePath($object)
{
if ($object->getId()) {
$this->getConnection()->update(
$this->getMainTable(),
['path' => $object->getPath()],
['category_id = ?' => $object->getId()]
);
$object->unsetData('path_ids');
}
return $this;
}
/**
* @param AbstractModel $object
*
* @return $this
* @throws LocalizedException
*/
protected function _beforeDelete(AbstractModel $object)
{
parent::_beforeDelete($object);
/**
* Update children count for all parent Categories
*/
$parentIds = $object->getParentIds();
if ($parentIds) {
$childDecrease = $object->getChildrenCount() + 1;
// +1 is itself
$data = ['children_count' => 'children_count - ' . $childDecrease];
$where = ['category_id IN(?)' => $parentIds];
$this->getConnection()->update($this->getMainTable(), $data, $where);
}
$this->deleteChildren($object);
return $this;
}
/**
* @param DataObject $object
*
* @return $this
* @throws LocalizedException
*/
public function deleteChildren(DataObject $object)
{
$adapter = $this->getConnection();
$pathField = $adapter->quoteIdentifier('path');
$select = $adapter->select()->from(
$this->getMainTable(),
['category_id']
)->where(
$pathField . ' LIKE :c_path'
);
$childrenIds = $adapter->fetchCol($select, ['c_path' => $object->getPath() . '/%']);
if (!empty($childrenIds)) {
$adapter->delete($this->getMainTable(), ['category_id IN (?)' => $childrenIds]);
}
/**
* Add deleted children ids to object
* This data can be used in after delete event
*/
$object->setDeletedChildrenIds($childrenIds);
return $this;
}
/**
* @param CategoryModel $category
* @param CategoryModel $newParent
* @param null $afterCategoryId
*
* @return $this
* @throws LocalizedException
*/
public function changeParent(
CategoryModel $category,
CategoryModel $newParent,
$afterCategoryId = null
) {
$childrenCount = (int) $this->getChildrenCount($category->getId()) + 1;
$table = $this->getMainTable();
$adapter = $this->getConnection();
$levelField = $adapter->quoteIdentifier('level');
$pathField = $adapter->quoteIdentifier('path');
/**
* Decrease children count for all old Blog Category parent Categories
*/
$adapter->update(
$table,
['children_count' => new Zend_Db_Expr('children_count - ' . $childrenCount)],
['category_id IN(?)' => $category->getParentIds()]
);
/**
* Increase children count for new Blog Category parents
*/
$adapter->update(
$table,
['children_count' => new Zend_Db_Expr('children_count + ' . $childrenCount)],
['category_id IN(?)' => $newParent->getPathIds()]
);
$position = $this->processPositions($category, $newParent, $afterCategoryId);
$newPath = sprintf('%s/%s', $newParent->getPath(), $category->getId());
$newLevel = $newParent->getLevel() + 1;
$levelDisposition = $newLevel - $category->getLevel();
/**
* Update children nodes path
*/
$adapter->update(
$table,
[
'path' => new Zend_Db_Expr(
'REPLACE(' . $pathField . ',' . $adapter->quote(
$category->getPath() . '/'
) . ', ' . $adapter->quote(
$newPath . '/'
) . ')'
),
'level' => new Zend_Db_Expr($levelField . ' + ' . $levelDisposition)
],
[$pathField . ' LIKE ?' => $category->getPath() . '/%']
);
/**
* Update moved Blog Category data
*/
$data = [
'path' => $newPath,
'level' => $newLevel,
'position' => $position,
'parent_id' => $newParent->getId(),
];
$adapter->update($table, $data, ['category_id = ?' => $category->getId()]);
/** Update Blog Category object to new data */
$category->addData($data);
$category->unsetData('path_ids');
return $this;
}
/**
* @param CategoryModel $category
* @param CategoryModel $newParent
* @param int|null $afterCategoryId
*
* @return int|string
* @throws LocalizedException
*/
public function processPositions(
CategoryModel $category,
CategoryModel $newParent,
$afterCategoryId
) {
$table = $this->getMainTable();
$connect = $this->getConnection();
/** Get old category position */
$positionOld = $category->getPosition();
/** Get new category position */
if (empty($afterCategoryId)) {
$positionNew = 1;
} else {
$select = $connect->select()->from($table, 'position')->where('category_id = :category_id');
$positionNew = $connect->fetchOne($select, ['category_id' => $afterCategoryId]);
}
/** Update position when the item is moved */
/** Move to other category parent */
if ($category->getParentId() != $newParent->getId()) {
if ($afterCategoryId == 0) {
$positionNew = 0;
}
$positionNew++;
// phpcs:disable Magento2.SQL.RawQuery
$sql = "UPDATE `" . $table . "` SET `position`= (`position`-1) WHERE `parent_id`= "
. $category->getParentId() . " AND `position` >= " . $positionOld;
$connect->query($sql);
$sql = "UPDATE `" . $table . "` SET `position`= (`position`+1) WHERE `parent_id`= " . $newParent->getId()
. " AND `position` >= " . $positionNew;
$connect->query($sql);
} else {
/** Move in the same parent */
/** Move down */
if ($positionNew > $positionOld) {
$sql = "UPDATE `" . $table . "` SET `position`= (`position`-1) WHERE `parent_id`= "
. $newParent->getId() . " AND `position` <= " . $positionNew;
$connect->query($sql);
$sql = "UPDATE `" . $table . "` SET `position`= (`position`+1) WHERE `parent_id`= "
. $newParent->getId() . " AND `position` < " . $positionOld;
$connect->query($sql);
} else {
/** Move up */
$positionNew++;
if (empty($afterCategoryId)) {
$positionNew = 1;
}
$sql = "UPDATE `" . $table . "` SET `position`= (`position`+1) WHERE `parent_id`= "
. $newParent->getId() . " AND `position` >= " . $positionNew;
$connect->query($sql);
$sql = "UPDATE `" . $table . "` SET `position`= (`position`-1) WHERE `parent_id`= "
. $newParent->getId() . " AND `position` > " . $positionOld;
$connect->query($sql);
}
}
return $positionNew;
}
/**
* @param int $categoryId
*
* @return string
* @throws LocalizedException
*/
public function getChildrenCount($categoryId)
{
$select = $this->getConnection()->select()->from(
$this->getMainTable(),
'children_count'
)->where(
'category_id = :category_id'
);
$bind = ['category_id' => $categoryId];
return $this->getConnection()->fetchOne($select, $bind);
}
/**
* @param CategoryModel $category
*
* @return array
*/
public function getPostsPosition(CategoryModel $category)
{
$select = $this->getConnection()->select()->from(
$this->categoryPostTable,
['post_id', 'position']
)
->where(
'category_id = :category_id'
);
$bind = ['category_id' => (int) $category->getId()];
return $this->getConnection()->fetchPairs($select, $bind);
}
/**
* @param CategoryModel $category
*
* @return $this
*/
public function savePostRelation(CategoryModel $category)
{
$category->setIsChangedPostList(false);
$id = $category->getId();
$posts = $category->getPostsData();
if ($posts === null) {
return $this;
}
$oldPosts = $category->getPostsPosition();
$insert = array_diff_key($posts, $oldPosts);
$delete = array_diff_key($oldPosts, $posts);
$update = array_intersect_key($posts, $oldPosts);
$_update = [];
foreach ($update as $key => $position) {
if (isset($oldPosts[$key]) && $oldPosts[$key] != $position) {
$_update[$key] = $position;
}
}
$update = $_update;
$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = ['post_id IN(?)' => array_keys($delete), 'category_id=?' => $id];
$adapter->delete($this->categoryPostTable, $condition);
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $postId => $position) {
$data[] = [
'category_id' => (int) $id,
'post_id' => (int) $postId,
'position' => (int) $position
];
}
$adapter->insertMultiple($this->categoryPostTable, $data);
}
if (!empty($update)) {
foreach ($update as $postId => $position) {
$where = ['category_id = ?' => (int) $id, 'post_id = ?' => (int) $postId];
$bind = ['position' => (int) $position];
$adapter->update($this->categoryPostTable, $bind, $where);
}
}
if (!empty($insert) || !empty($delete)) {
$postIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'mageplaza_blog_category_change_posts',
['category' => $category, 'post_ids' => $postIds]
);
}
if (!empty($insert) || !empty($update) || !empty($delete)) {
$category->setIsChangedPostList(true);
$postIds = array_keys($insert + $delete + $update);
$category->setAffectedPostIds($postIds);
}
return $this;
}
/**
* @param string $importType
*
* @throws LocalizedException
*/
public function deleteImportItems($importType)
{
$adapter = $this->getConnection();
$adapter->delete($this->getMainTable(), "`import_source` LIKE '" . $importType . "%'");
}
}
@@ -0,0 +1,187 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Category;
use Magento\Eav\Model\Entity\Attribute;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\DB\Select;
use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection;
use Mageplaza\Blog\Api\Data\SearchResult\CategorySearchResultInterface;
use Mageplaza\Blog\Model\Category;
use Mageplaza\Blog\Model\ResourceModel\Category as CategoryResourceModel;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Category
*/
class Collection extends AbstractCollection implements CategorySearchResultInterface
{
/**
* ID Field Name
*
* @var string
*/
protected $_idFieldName = 'category_id';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_category_collection';
/**
* Event object
*
* @var string
*/
protected $_eventObject = 'category_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(Category::class, CategoryResourceModel::class);
}
/**
* @param Attribute|string $field
* @param null $condition
*
* @return AbstractDb|AbstractCollection
*/
public function addAttributeToFilter($field, $condition = null)
{
return $this->addFieldToFilter($field, $condition);
}
/**
* @inheritdoc
*/
public function addFieldToFilter($field, $condition = null)
{
if ($field === 'entity_id') {
$field = 'category_id';
}
return parent::addFieldToFilter($field, $condition);
}
/**
* @return $this
*/
public function setProductStoreId()
{
return $this;
}
/**
* @return $this
*/
public function setLoadProductCount()
{
return $this;
}
/**
* @return $this
*/
public function setStoreId()
{
return $this;
}
/**
* @param string $attribute
* @param bool $joinType
*
* @return $this
*/
public function addAttributeToSelect($attribute, $joinType = false)
{
return $this;
}
/**
* Get SQL for get record count.
* Extra GROUP BY strip added.
*
* @return Select
*/
public function getSelectCountSql()
{
$countSelect = parent::getSelectCountSql();
$countSelect->reset(Select::GROUP);
return $countSelect;
}
/**
* @param null $valueField
* @param string $labelField
* @param array $additional
*
* @return array
*/
protected function _toOptionArray($valueField = null, $labelField = 'name', $additional = [])
{
$valueField = 'category_id';
return parent::_toOptionArray($valueField, $labelField, $additional); // TODO: Change the autogenerated stub
}
/**
* Add if filter
*
* @param array|mixed $categoryIds
*
* @return $this
*/
public function addIdFilter($categoryIds)
{
$condition = '';
if (is_array($categoryIds)) {
if (!empty($categoryIds)) {
$condition = ['in' => $categoryIds];
}
} elseif (is_numeric($categoryIds)) {
$condition = $categoryIds;
} elseif (is_string($categoryIds)) {
$ids = explode(',', $categoryIds);
if (empty($ids)) {
$condition = $categoryIds;
} else {
$condition = ['in' => $ids];
}
}
if ($condition) {
$this->addFieldToFilter('category_id', $condition);
}
return $this;
}
}
@@ -0,0 +1,540 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Category;
use Exception;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Data\Tree\Dbp;
use Magento\Framework\Data\Tree\Node;
use Magento\Framework\DB\Select;
use Magento\Framework\Event\ManagerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Mageplaza\Blog\Model\ResourceModel\Category;
use Mageplaza\Blog\Model\Category as CategoryModel;
/**
* Class Tree
* @package Mageplaza\Blog\Model\ResourceModel\Category
*/
class Tree extends Dbp
{
/**
* ID field
*
* @var string
*/
const ID_FIELD = 'id';
/**
* Path field
*
* @var string
*/
const PATH_FIELD = 'path';
/**
* Order field
*
* @var string
*/
const ORDER_FIELD = 'order';
/**
* Level field
*
* @var string
*/
const LEVEL_FIELD = 'level';
/**
* Event manager
*
* @var ManagerInterface
*/
public $eventManager;
/**
* Collection factory
*
* @var CollectionFactory
*/
public $collectionFactory;
/**
* Blog Category Resource instance
*
* @var Category
*/
public $categoryResource;
/**
* Cache instance
*
* @var CacheInterface
*/
public $cache;
/**
* Store Manager instance
*
* @var StoreManagerInterface
*/
public $storeManager;
/**
* App resource
*
* @var ResourceConnection
*/
public $coreResource;
/**
* Blog Category Collection
*
* @var Collection
*/
public $collection;
/**
* Inactive Blog Category Ids
*
* @var array
*/
public $inactiveCategoryIds;
/**
* Tree constructor.
*
* @param ManagerInterface $eventManager
* @param CollectionFactory $collectionFactory
* @param Category $categoryResource
* @param CacheInterface $cache
* @param StoreManagerInterface $storeManager
* @param ResourceConnection $coreResource
*
* @throws Exception
*/
public function __construct(
ManagerInterface $eventManager,
CollectionFactory $collectionFactory,
Category $categoryResource,
CacheInterface $cache,
StoreManagerInterface $storeManager,
ResourceConnection $coreResource
) {
$this->eventManager = $eventManager;
$this->collectionFactory = $collectionFactory;
$this->categoryResource = $categoryResource;
$this->cache = $cache;
$this->storeManager = $storeManager;
$this->coreResource = $coreResource;
parent::__construct(
$coreResource->getConnection('mageplaza_blog_write'),
$coreResource->getTableName('mageplaza_blog_category'),
[
Dbp::ID_FIELD => 'category_id',
Dbp::PATH_FIELD => 'path',
Dbp::ORDER_FIELD => 'position',
Dbp::LEVEL_FIELD => 'level'
]
);
}
/**
* Add data to collection
*
* @param null $collection
* @param bool $sorted
* @param array $exclude
* @param bool $toLoad
* @param bool $onlyActive
*
* @return $this
*/
public function addCollectionData(
$collection = null,
$sorted = false,
$exclude = [],
$toLoad = true,
$onlyActive = false
) {
if ($collection === null) {
$collection = $this->getCollection($sorted);
} else {
$this->setCollection($collection);
}
if (!is_array($exclude)) {
$exclude = [$exclude];
}
$nodeIds = [];
foreach ($this->getNodes() as $node) {
if (!in_array($node->getId(), $exclude)) {
$nodeIds[] = $node->getId();
}
}
$collection->addIdFilter($nodeIds);
if ($onlyActive) {
$disabledIds = $this->getDisabledIds();
if ($disabledIds) {
$collection->addFieldToFilter('category_id', ['nin' => $disabledIds]);
}
}
if ($toLoad) {
$collection->load();
foreach ($collection as $category) {
if ($this->getNodeById($category->getId())) {
$this->getNodeById($category->getId())->addData($category->getData());
}
}
foreach ($this->getNodes() as $node) {
if (!$collection->getItemById($node->getId()) && $node->getParent()) {
$this->removeNode($node);
}
}
}
return $this;
}
/**
* Add inactive categories ids
*
* @param mixed $ids
*
* @return $this
*/
public function addInactiveCategoryIds($ids)
{
if (!is_array($this->inactiveCategoryIds)) {
$this->initInactiveCategoryIds();
}
$this->inactiveCategoryIds = array_merge($ids, $this->inactiveCategoryIds);
return $this;
}
/**
* Retrieve inactive Categories ids
*
* @return $this
*/
public function initInactiveCategoryIds()
{
$this->inactiveCategoryIds = [];
$this->eventManager->dispatch('mageplaza_blog_category_tree_init_inactive_category_ids', ['tree' => $this]);
return $this;
}
/**
* Retrieve inactive Categories ids
*
* @return array
*/
public function getInactiveCategoryIds()
{
if (!is_array($this->inactiveCategoryIds)) {
$this->initInactiveCategoryIds();
}
return $this->inactiveCategoryIds;
}
/**
* @return array
*/
public function getDisabledIds()
{
/* implement this for frontend */
return [];
}
/**
* Retrieve inactive Blog Category item ids
*
* @return array
*/
public function getInactiveItemIds()
{
/* implement this for frontend */
return [];
}
/**
* Check is Blog Category items active
*
* @return bool
*/
public function getItemIsActive()
{
//implement this for frontend
return false;
}
/**
* Get Categories collection
*
* @param boolean $sorted
*
* @return Collection
*/
public function getCollection($sorted = false)
{
if ($this->collection === null) {
$this->collection = $this->getDefaultCollection($sorted);
}
return $this->collection;
}
/**
* Clean unneeded collection
*
* @param Collection|array $object
*
* @return void
*/
public function clean($object)
{
if (is_array($object)) {
foreach ($object as $obj) {
$this->clean($obj);
}
}
unset($object);
}
/**
* Set collection
*
* @param Collection $collection
*
* @return $this
*/
public function setCollection($collection)
{
if ($this->collection !== null) {
$this->clean($this->collection);
}
$this->collection = $collection;
return $this;
}
/**
* Get default collection
*
* @param boolean $sorted
*
* @return Collection
*/
public function getDefaultCollection($sorted = false)
{
$collection = $this->collectionFactory->create();
if ($sorted) {
if (is_string($sorted)) {
// $sorted is supposed to be attribute name
$collection->addFieldToSort($sorted);
} else {
$collection->addFieldToSort('name');
}
}
return $collection;
}
/**
* Executing parents move method and cleaning cache after it
*
* @param Node $category
* @param Node $newParent
* @param null $prevNode
*
* @throws Exception
*/
public function move($category, $newParent, $prevNode = null)
{
$this->categoryResource->move($category->getId(), $newParent->getId());
parent::move($category, $newParent, $prevNode);
$this->afterMove();
}
/**
* Move tree after
*
* @return $this
*/
public function afterMove()
{
$this->cache->clean([CategoryModel::CACHE_TAG]);
return $this;
}
/**
* Load whole Blog Category tree, that will include specified Categories ids.
*
* @param array $ids
* @param bool $addCollectionData
*
* @return $this|bool
*/
public function loadByIds($ids, $addCollectionData = true)
{
$levelField = $this->_conn->quoteIdentifier('level');
$pathField = $this->_conn->quoteIdentifier('path');
// load first two levels, if no ids specified
if (empty($ids)) {
$select = $this->_conn
->select()
->from($this->_table, 'category_id')
->where($levelField . ' <= 2');
$ids = $this->_conn->fetchCol($select);
}
if (!is_array($ids)) {
$ids = [$ids];
}
foreach ($ids as $key => $id) {
$ids[$key] = (int) $id;
}
// collect paths of specified IDs and prepare to collect all their parents and neighbours
$select = $this->_conn
->select()
->from($this->_table, ['path', 'level'])
->where('category_id IN (?)', $ids);
$where = [$levelField . '=0' => true];
foreach ($this->_conn->fetchAll($select) as $item) {
$pathIds = explode('/', $item['path']);
$level = (int) $item['level'];
while ($level > 0) {
$lastId = end($pathIds);
$lastIndex = key($lastId);
$pathIds[$lastIndex] = '%';
$path = implode('/', $pathIds);
$where["{$levelField}={$level} AND {$pathField} LIKE '{$path}'"] = true;
array_pop($pathIds);
$level--;
}
}
$where = array_keys($where);
// get all required records
if ($addCollectionData) {
$select = $this->createCollectionDataSelect();
} else {
$select = clone $this->_select;
$select->order($this->_orderField . ' ' . Select::SQL_ASC);
}
$select->where(implode(' OR ', $where));
// get array of records and add them as nodes to the tree
$arrNodes = $this->_conn->fetchAll($select);
if (!$arrNodes) {
return false;
}
$childrenItems = [];
foreach ($arrNodes as $key => $nodeInfo) {
$pathToParent = explode('/', $nodeInfo[$this->_pathField]);
array_pop($pathToParent);
$pathToParent = implode('/', $pathToParent);
$childrenItems[$pathToParent][] = $nodeInfo;
}
$this->addChildNodes($childrenItems, '', null);
return $this;
}
/**
* Load array of category parents
*
* @param string $path
* @param bool $addCollectionData
* @param bool $withRootNode
*
* @return array
*/
public function loadBreadcrumbsArray($path, $addCollectionData = true, $withRootNode = false)
{
$pathIds = explode('/', $path);
if (!$withRootNode) {
array_shift($pathIds);
}
$result = [];
if (!empty($pathIds)) {
if ($addCollectionData) {
$select = $this->createCollectionDataSelect(false);
} else {
$select = clone $this->_select;
}
$select->where(
'e.category_id IN(?)',
$pathIds
)->order(
$this->_conn->getLengthSql('e.path') . ' ' . Select::SQL_ASC
);
$result = $this->_conn->fetchAll($select);
}
return $result;
}
/**
* @param bool $sorted
* @return Select
*/
public function createCollectionDataSelect($sorted = true)
{
$select = $this->getDefaultCollection($sorted ? $this->_orderField : false)->getSelect();
return $select;
}
/**
* Get real existing Blog Category ids by specified ids
*
* @param array $ids
*
* @return array
*/
public function getExistingCategoryIdsBySpecifiedIds($ids)
{
if (empty($ids)) {
return [];
}
if (!is_array($ids)) {
$ids = [$ids];
}
$select = $this->_conn
->select()
->from($this->_table, ['category_id'])
->where('category_id IN (?)', $ids);
return $this->_conn->fetchCol($select);
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
/**
* Class Comment
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Comment extends AbstractDb
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_comment', 'comment_id');
}
/**
* @param AbstractModel $object
*
* @return $this
*/
protected function _beforeSave(AbstractModel $object)
{
if (is_array($object->getStoreIds())) {
$object->setStoreIds(implode(',', $object->getStoreIds()));
}
return $this;
}
/**
* Check is imported category
*
* @param $importSource
* @param $oldId
*
* @return string
* @throws LocalizedException
*/
public function isImported($importSource, $oldId)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'comment_id')
->where('import_source = :import_source');
$binds = ['import_source' => $importSource . '-' . $oldId];
return $adapter->fetchOne($select, $binds);
}
/**
* @param $importType
*
* @throws LocalizedException
*/
public function deleteImportItems($importType)
{
$adapter = $this->getConnection();
$adapter->delete($this->getMainTable(), "`import_source` LIKE '" . $importType . "%'");
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Comment;
use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection;
use Mageplaza\Blog\Api\Data\SearchResult\CommentSearchResultInterface;
use Mageplaza\Blog\Model\Comment;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Comment
*/
class Collection extends AbstractCollection implements CommentSearchResultInterface
{
/**
* @var string
*/
protected $_idFieldName = 'comment_id';
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(Comment::class, \Mageplaza\Blog\Model\ResourceModel\Comment::class);
}
}
@@ -0,0 +1,150 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Comment\Grid;
use Magento\Framework\Data\Collection\Db\FetchStrategyInterface as FetchStrategy;
use Magento\Framework\Data\Collection\EntityFactoryInterface as EntityFactory;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;
use Mageplaza\Blog\Model\ResourceModel\Comment;
use Psr\Log\LoggerInterface as Logger;
use Zend_Db_Expr;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Comment\Grid
*/
class Collection extends SearchResult
{
/**
* Collection constructor.
*
* @param EntityFactory $entityFactory
* @param Logger $logger
* @param FetchStrategy $fetchStrategy
* @param EventManager $eventManager
* @param string $mainTable
* @param string $resourceModel
*
* @throws LocalizedException
*/
// phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
public function __construct(
EntityFactory $entityFactory,
Logger $logger,
FetchStrategy $fetchStrategy,
EventManager $eventManager,
$mainTable = 'mageplaza_blog_comment',
$resourceModel = Comment::class
) {
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $mainTable, $resourceModel);
}
/**
* @return $this
*/
protected function _initSelect()
{
parent::_initSelect();
$this->addPostName();
$this->addCustomerName();
$this->addExpressionFieldToSelect(
'mp_created_at',
'main_table.created_at',
['mp_created_at' => 'created_at']
);
return $this;
}
/**
* @param string $field
* @param string $direction
*
* @return SearchResult
*/
public function setOrder($field, $direction = self::SORT_ORDER_DESC)
{
switch ($field) {
case 'customer_name':
return parent::setOrder('user_name', $direction);
case 'mp_created_at':
return parent::setOrder('main_table.created_at', $direction);
}
return parent::setOrder($field, $direction);
}
/**
* @param array|string $field
* @param null $condition
*
* @return SearchResult
*/
public function addFieldToFilter($field, $condition = null)
{
if ($field === 'customer_name') {
return parent::addFieldToFilter('user_name', $condition);
}
if ($field === 'post_name') {
$field = 'mp.name';
} elseif ($field === 'mp_created_at') {
$field = 'main_table.created_at';
}
return parent::addFieldToFilter($field, $condition);
}
/**
* @return $this
*/
public function addPostName()
{
$this->getSelect()->joinLeft(
['mp' => $this->getTable('mageplaza_blog_post')],
'main_table.post_id = mp.post_id',
['post_name' => 'name']
);
return $this;
}
/**
* @return $this
*/
public function addCustomerName()
{
$this->getSelect()->joinLeft(
['ce' => $this->getTable('customer_entity')],
'main_table.entity_id = ce.entity_id',
['firstname', 'lastname']
)->columns([
'customer_name' => new Zend_Db_Expr("CONCAT(`ce`.`firstname`,' ',`ce`.`lastname`)")
]);
return $this;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
/**
* Class Like
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Like extends AbstractDb
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_comment_like', 'like_id');
}
}
@@ -0,0 +1,41 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Like;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Mageplaza\Blog\Model\Like;
use Mageplaza\Blog\Model\ResourceModel\Like as LikeResourceModel;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Like
*/
class Collection extends AbstractCollection
{
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(Like::class, LikeResourceModel::class);
}
}
+631
View File
@@ -0,0 +1,631 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Backend\Model\Auth;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Blog\Helper\Data;
use Mageplaza\Blog\Model\Author;
use Mageplaza\Blog\Model\AuthorFactory;
use Mageplaza\Blog\Model\Post as PostModel;
/**
* Class Post
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Post extends AbstractDb
{
/**
* Date model
*
* @var DateTime
*/
public $date;
/**
* Event Manager
*
* @var ManagerInterface
*/
public $eventManager;
/**
* Tag relation model
*
* @var string
*/
public $postTagTable;
/**
* Topic relation model
*
* @var string
*/
public $postTopicTable;
/**
* Blog Category relation model
*
* @var string
*/
public $postCategoryTable;
/**
* @var string
*/
public $postProductTable;
/**
* @var Data
*/
public $helperData;
/**
* @var AuthorFactory
*/
protected $_authorFactory;
/**
* @var Auth
*/
protected $_auth;
/**
* @var RequestInterface
*/
protected $_request;
/**
* @var string
*/
protected $postTrafficTable;
/**
* @var string
*/
protected $postAuthorTable;
/**
* Post constructor.
*
* @param Context $context
* @param DateTime $date
* @param ManagerInterface $eventManager
* @param Auth $auth
* @param Data $helperData
* @param RequestInterface $request
* @param AuthorFactory $authorFactory
*/
public function __construct(
Context $context,
DateTime $date,
ManagerInterface $eventManager,
Auth $auth,
Data $helperData,
RequestInterface $request,
AuthorFactory $authorFactory
) {
$this->date = $date;
$this->eventManager = $eventManager;
$this->_auth = $auth;
$this->helperData = $helperData;
$this->_request = $request;
$this->_authorFactory = $authorFactory;
parent::__construct($context);
$this->postTagTable = $this->getTable('mageplaza_blog_post_tag');
$this->postTopicTable = $this->getTable('mageplaza_blog_post_topic');
$this->postCategoryTable = $this->getTable('mageplaza_blog_post_category');
$this->postProductTable = $this->getTable('mageplaza_blog_post_product');
$this->postTrafficTable = $this->getTable('mageplaza_blog_post_traffic');
$this->postAuthorTable = $this->getTable('mageplaza_blog_author');
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_post', 'post_id');
}
/**
* Retrieves Post Name from DB by passed id.
*
* @param int $id
*
* @return string
* @throws LocalizedException
*/
public function getPostNameById($id)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'name')
->where('post_id = :post_id');
$binds = ['post_id' => (int) $id];
return $adapter->fetchOne($select, $binds);
}
/**
* before save callback
*
* @param AbstractModel $object
*
* @return $this
* @throws LocalizedException
*/
protected function _beforeSave(AbstractModel $object)
{
if (is_array($object->getStoreIds())) {
$object->setStoreIds(implode(',', $object->getStoreIds()));
}
if (is_array($object->getData('meta_title'))) {
$object->setData('meta_title', json_encode($object->getData('meta_title')));
}
if (is_array($object->getData('meta_description'))) {
$object->setData('meta_description', json_encode($object->getData('meta_description')));
}
if (is_array($object->getData('meta_keywords'))) {
$object->setData('meta_keywords', json_encode($object->getData('meta_keywords')));
}
if (is_array($object->getData('meta_robots'))) {
$object->setData('meta_robots', json_encode($object->getData('meta_robots')));
}
$object->setUrlKey(
$this->helperData->generateUrlKey($this, $object, $object->getUrlKey() ?: $object->getName())
);
return $this;
}
/**
* @param PostModel|AbstractModel $object
* @return AbstractDb
* @throws LocalizedException
*/
protected function _afterSave(AbstractModel $object)
{
$this->saveTagRelation($object);
$this->saveTopicRelation($object);
$this->saveCategoryRelation($object);
$this->saveProductRelation($object);
if ($this->_request->getActionName() !== 'manage') {
$this->saveAuthor();
}
return parent::_afterSave($object);
}
/**
* @param PostModel $post
*
* @return $this
* @throws LocalizedException
*/
public function saveTagRelation(PostModel $post)
{
$post->setIsChangedTagList(false);
$id = $post->getId();
$tags = $post->getTagsIds();
$oldTags = $post->getTagIds();
if ($tags === null) {
return $this;
}
$insert = array_diff($tags, $oldTags);
$delete = array_diff($oldTags, $tags);
$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = ['tag_id IN(?)' => $delete, 'post_id=?' => $id];
$adapter->delete($this->postTagTable, $condition);
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $tagId) {
$data[] = [
'post_id' => (int) $id,
'tag_id' => (int) $tagId,
'position' => 1
];
}
$adapter->insertMultiple($this->postTagTable, $data);
}
if (!empty($insert) || !empty($delete)) {
$tagIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'mageplaza_blog_post_change_tags',
['post' => $post, 'tag_ids' => $tagIds]
);
}
if (!empty($insert) || !empty($delete)) {
$post->setIsChangedTagList(true);
$tagIds = array_keys($insert + $delete);
$post->setAffectedTagIds($tagIds);
}
return $this;
}
/**
* @param PostModel $post
*
* @return $this
* @throws LocalizedException
*/
public function saveTopicRelation(PostModel $post)
{
$post->setIsChangedTopicList(false);
$id = $post->getId();
$topics = $post->getTopicsIds();
$oldTopics = $post->getTopicIds();
if ($topics === null) {
return $this;
}
$insert = array_diff($topics, $oldTopics);
$delete = array_diff($oldTopics, $topics);
$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = ['topic_id IN(?)' => $delete, 'post_id=?' => $id];
$adapter->delete($this->postTopicTable, $condition);
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $topicId) {
$data[] = [
'post_id' => (int) $id,
'topic_id' => (int) $topicId,
'position' => 1
];
}
$adapter->insertMultiple($this->postTopicTable, $data);
}
if (!empty($insert) || !empty($delete)) {
$topicIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'mageplaza_blog_post_change_topics',
['post' => $post, 'topic_ids' => $topicIds]
);
}
if (!empty($insert) || !empty($delete)) {
$post->setIsChangedTopicList(true);
$topicIds = array_keys($insert + $delete);
$post->setAffectedTopicIds($topicIds);
}
return $this;
}
/**
* @param PostModel $post
*
* @return $this
* @throws LocalizedException
*/
public function saveCategoryRelation(PostModel $post)
{
$post->setIsChangedCategoryList(false);
$id = $post->getId();
$categories = $post->getCategoriesIds();
$oldCategoryIds = $post->getCategoryIds();
if ($categories === null) {
return $this;
}
$insert = array_diff($categories, $oldCategoryIds);
$delete = array_diff($oldCategoryIds, $categories);
$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = ['category_id IN(?)' => $delete, 'post_id=?' => $id];
$adapter->delete($this->postCategoryTable, $condition);
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $categoryId) {
$data[] = [
'post_id' => (int) $id,
'category_id' => (int) $categoryId,
'position' => 1
];
}
$adapter->insertMultiple($this->postCategoryTable, $data);
}
if (!empty($insert) || !empty($delete)) {
$categoryIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'mageplaza_blog_post_change_categories',
['post' => $post, 'category_ids' => $categoryIds]
);
}
if (!empty($insert) || !empty($delete)) {
$post->setIsChangedCategoryList(true);
$categoryIds = array_keys($insert + $delete);
$post->setAffectedCategoryIds($categoryIds);
}
return $this;
}
/**
* @param PostModel $post
*
* @return array
*/
public function getCategoryIds(PostModel $post)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from(
$this->postCategoryTable,
'category_id'
)
->where(
'post_id = ?',
(int) $post->getId()
);
return $adapter->fetchCol($select);
}
/**
* @param PostModel $post
*
* @return array
*/
public function getTagIds(PostModel $post)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from(
$this->postTagTable,
'tag_id'
)
->where(
'post_id = ?',
(int) $post->getId()
);
return $adapter->fetchCol($select);
}
/**
* @param PostModel $post
*
* @return array
*/
public function getTopicIds(PostModel $post)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from($this->postTopicTable, 'topic_id')
->where('post_id = ?', (int) $post->getId());
return $adapter->fetchCol($select);
}
/**
* @param PostModel $post
* @return array
*/
public function getAuthor(PostModel $post)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from($this->postAuthorTable, '*')
->where('user_id = ?', (int) $post->getAuthorId());
return $adapter->fetchRow($select);
}
/**
* @param PostModel $post
*
* @return array
*/
public function getViewTraffic(PostModel $post)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from($this->postTrafficTable, 'numbers_view')
->where('post_id = ?', (int) $post->getId());
return $adapter->fetchCol($select);
}
/**
* @param PostModel $post
*
* @return $this
*/
public function saveProductRelation(PostModel $post)
{
$post->setIsChangedProductList(false);
$id = $post->getId();
$products = $post->getProductsData();
$oldProducts = $post->getProductsPosition();
if (is_array($products)) {
$insert = array_diff_key($products, $oldProducts);
$delete = array_diff_key($oldProducts, $products);
$update = array_intersect_key($products, $oldProducts);
$_update = [];
foreach ($update as $key => $settings) {
if (isset($oldProducts[$key]) && $oldProducts[$key] != $settings['position']) {
$_update[$key] = $settings;
}
}
$update = $_update;
}
$adapter = $this->getConnection();
if ($products === null && $this->_request->getActionName() === 'save') {
foreach (array_keys($oldProducts) as $value) {
$condition = ['entity_id =?' => (int) $value, 'post_id=?' => (int) $id];
$adapter->delete($this->postProductTable, $condition);
}
return $this;
}
if (!empty($delete)) {
foreach (array_keys($delete) as $value) {
$condition = ['entity_id =?' => (int) $value, 'post_id=?' => (int) $id];
$adapter->delete($this->postProductTable, $condition);
}
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $entityId => $position) {
$data[] = [
'post_id' => (int) $id,
'entity_id' => (int) $entityId,
'position' => (int) $position['position']
];
}
$adapter->insertMultiple($this->postProductTable, $data);
}
if (!empty($update)) {
foreach ($update as $entityId => $position) {
$where = ['post_id = ?' => (int) $id, 'entity_id = ?' => (int) $entityId];
$bind = ['position' => (int) $position['position']];
$adapter->update($this->postProductTable, $bind, $where);
}
}
if (!empty($insert) || !empty($delete)) {
$entityIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'mageplaza_blog_post_change_products',
['post' => $post, 'entity_ids' => $entityIds]
);
}
if (!empty($insert) || !empty($update) || !empty($delete)) {
$post->setIsChangedProductList(true);
$entityIds = array_keys($insert + $delete + $update);
$post->setAffectedEntityIds($entityIds);
}
return $this;
}
/**
* @param PostModel $post
*
* @return array
*/
public function getProductsPosition(PostModel $post)
{
$select = $this->getConnection()->select()->from(
$this->postProductTable,
['entity_id', 'position']
)
->where(
'post_id = :post_id'
);
$bind = ['post_id' => (int) $post->getId()];
return $this->getConnection()->fetchPairs($select, $bind);
}
/**
* Check post url key is exists
*
* @param string $urlKey
*
* @return string
* @throws LocalizedException
*/
public function isDuplicateUrlKey($urlKey)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'post_id')
->where('url_key = :url_key');
$binds = ['url_key' => $urlKey];
return $adapter->fetchOne($select, $binds);
}
/**
* Save the post author when creating post
*/
public function saveAuthor()
{
$currentUser = $this->_auth->getUser();
if ($currentUser) {
$currentUserId = $currentUser->getId();
/** @var Author $author */
$author = $this->_authorFactory->create()->load($currentUserId);
/** Create the new author if that author isn't exist */
if (!$author->getId()) {
$author->setId($currentUserId)
->setName($currentUser->getName())->save();
}
}
}
/**
* Check is imported post
*
* @param string $importSource
* @param string $oldId
*
* @return string
* @throws LocalizedException
*/
public function isImported($importSource, $oldId)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'post_id')
->where('import_source = :import_source');
$binds = ['import_source' => $importSource . '-' . $oldId];
return $adapter->fetchOne($select, $binds);
}
/**
* @param string $importType
*
* @return int
* @throws LocalizedException
*/
public function deleteImportItems($importType)
{
$adapter = $this->getConnection();
return $adapter->delete($this->getMainTable(), "`import_source` LIKE '" . $importType . "%'");
}
}
@@ -0,0 +1,93 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Post;
use Magento\Framework\DB\Select;
use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection;
use Mageplaza\Blog\Api\Data\SearchResult\PostSearchResultInterface;
use Mageplaza\Blog\Model\Post;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Post
*/
class Collection extends AbstractCollection implements PostSearchResultInterface
{
/**
* ID Field Name
*
* @var string
*/
protected $_idFieldName = 'post_id';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_post_collection';
/**
* Event object
*
* @var string
*/
protected $_eventObject = 'post_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(Post::class, \Mageplaza\Blog\Model\ResourceModel\Post::class);
}
/**
* Get SQL for get record count.
* Extra GROUP BY strip added.
*
* @return Select
*/
public function getSelectCountSql()
{
$countSelect = parent::getSelectCountSql();
$countSelect->reset(Select::GROUP);
return $countSelect;
}
/**
* @param null $valueField
* @param string $labelField
* @param array $additional
*
* @return array
*/
protected function _toOptionArray($valueField = null, $labelField = 'name', $additional = [])
{
$valueField = 'post_id';
return parent::_toOptionArray($valueField, $labelField, $additional); // TODO: Change the autogenerated stub
}
}
@@ -0,0 +1,86 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Mageplaza\Blog\Helper\Data;
/**
* Class PostLike
* @package Mageplaza\Blog\Model\ResourceModel
*/
class PostHistory extends AbstractDb
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_post_history', 'history_id');
}
/**
* @param AbstractModel $object
*
* @return AbstractDb
*/
protected function _beforeSave(AbstractModel $object)
{
if (is_array($object->getData('store_ids'))) {
$object->setData('store_ids', implode(',', $object->getData('store_ids')));
}
if (is_array($object->getData('categories_ids'))) {
$object->setData('category_ids', implode(',', $object->getData('categories_ids')));
}
if (is_array($object->getData('topics_ids'))) {
$object->setData('topic_ids', implode(',', $object->getData('topics_ids')));
}
if (is_array($object->getData('tags_ids'))) {
$object->setData('tag_ids', implode(',', $object->getData('tags_ids')));
}
if (is_array($object->getData('products_data'))) {
$data = $object->getData('products_data');
foreach ($data as $key => $datum) {
$data[$key]['position'] = $datum['position'] ?: '0';
}
$object->setData('product_ids', Data::jsonEncode($data));
}
return parent::_beforeSave($object);
}
/**
* {@inheritdoc}
*/
protected function _afterLoad(AbstractModel $object)
{
$object->setData('categories_ids', explode(',', $object->getCategoryIds() ?? ''));
$object->setData('tags_ids', explode(',', $object->getTagIds() ?? ''));
$object->setData('topics_ids', explode(',', $object->getTopicIds() ?? ''));
return parent::_afterLoad($object);
}
}
@@ -0,0 +1,136 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\PostHistory;
use DateTime;
use DateTimeZone;
use Exception;
use Magento\Framework\Data\Collection\Db\FetchStrategyInterface;
use Magento\Framework\Data\Collection\EntityFactoryInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\DB\Select;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Mageplaza\Blog\Model\PostHistory;
use Psr\Log\LoggerInterface;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\PostLike
*/
class Collection extends AbstractCollection
{
/**
* @var TimezoneInterface
*/
private $localeDate;
/**
* @var string
*/
private $locale;
/**
* Collection constructor.
*
* @param TimezoneInterface $localeDate
* @param ResolverInterface $localeResolver
* @param EntityFactoryInterface $entityFactory
* @param LoggerInterface $logger
* @param FetchStrategyInterface $fetchStrategy
* @param ManagerInterface $eventManager
* @param AdapterInterface|null $connection
* @param AbstractDb|null $resource
*/
public function __construct(
TimezoneInterface $localeDate,
ResolverInterface $localeResolver,
EntityFactoryInterface $entityFactory,
LoggerInterface $logger,
FetchStrategyInterface $fetchStrategy,
ManagerInterface $eventManager,
?AdapterInterface $connection = null,
?AbstractDb $resource = null
) {
$this->localeDate = $localeDate;
$this->locale = $localeResolver->getLocale();
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
}
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(PostHistory::class, \Mageplaza\Blog\Model\ResourceModel\PostHistory::class);
}
/**
* Add field filter to collection
*
* @param string|array $field
* @param null|string|array $condition
*
* @return \Magento\Framework\Data\Collection\AbstractDb
* @see self::_getConditionSql for $condition
*
*/
public function addFieldToFilter($field, $condition = null)
{
if (is_array($field)) {
$conditions = [];
foreach ($field as $key => $value) {
$conditions[] = $this->_translateCondition($value, isset($condition[$key]) ? $condition[$key] : null);
}
$resultCondition = '(' . implode(') ' . \Magento\Framework\DB\Select::SQL_OR . ' (', $conditions) . ')';
} else {
$resultCondition = $this->_translateCondition($field, $condition);
}
$this->_select->where($resultCondition, null, Select::TYPE_CONDITION);
return $this;
}
/**
* @return Collection
* @throws Exception
*/
protected function _afterLoad()
{
foreach ($this->getItems() as $item) {
$convertedDate = $this->localeDate->date(
new DateTime($item->getData('updated_at'), new DateTimeZone('UTC')),
$this->locale,
true
);
$item->setData('updated_at', $convertedDate->format('M j, Y h:i:s A'));
}
return parent::_afterLoad();
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
/**
* Class PostLike
* @package Mageplaza\Blog\Model\ResourceModel
*/
class PostLike extends AbstractDb
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_post_like', 'like_id');
}
}
@@ -0,0 +1,40 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\PostLike;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Mageplaza\Blog\Model\PostLike;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\PostLike
*/
class Collection extends AbstractCollection
{
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(PostLike::class, \Mageplaza\Blog\Model\ResourceModel\PostLike::class);
}
}
+293
View File
@@ -0,0 +1,293 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Blog\Helper\Data;
/**
* Class Tag
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Tag extends AbstractDb
{
/**
* Date model
*
* @var DateTime
*/
public $date;
/**
* Event Manager
*
* @var ManagerInterface
*/
public $eventManager;
/**
* Post relation model
*
* @var string
*/
public $tagPostTable;
/**
* @var Data
*/
public $helperData;
/**
* @var RequestInterface
*/
private $request;
/**
* Tag constructor.
*
* @param Context $context
* @param ManagerInterface $eventManager
* @param DateTime $date
* @param RequestInterface $request
* @param Data $helperData
*/
public function __construct(
Context $context,
ManagerInterface $eventManager,
DateTime $date,
RequestInterface $request,
Data $helperData
) {
$this->helperData = $helperData;
$this->date = $date;
$this->eventManager = $eventManager;
$this->request = $request;
parent::__construct($context);
$this->tagPostTable = $this->getTable('mageplaza_blog_post_tag');
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_tag', 'tag_id');
}
/**
* Retrieves Tag Name from DB by passed id.
*
* @param $id
*
* @return string
* @throws LocalizedException
*/
public function getTagNameById($id)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'name')
->where('tag_id = :tag_id');
$binds = ['tag_id' => (int)$id];
return $adapter->fetchOne($select, $binds);
}
/**
* @inheritdoc
*/
protected function _beforeSave(AbstractModel $object)
{
$object->setUpdatedAt($this->date->date());
if ($object->isObjectNew()) {
$object->setCreatedAt($this->date->date());
}
if (is_array($object->getStoreIds())) {
$object->setStoreIds(implode(',', $object->getStoreIds()));
}
$object->setUrlKey(
$this->helperData->generateUrlKey($this, $object, $object->getUrlKey() ?: $object->getName())
);
return parent::_beforeSave($object);
}
/**
* @inheritdoc
*/
protected function _afterSave(AbstractModel $object)
{
$this->savePostRelation($object);
return parent::_afterSave($object);
}
/**
* @param \Mageplaza\Blog\Model\Tag $tag
*
* @return array
*/
public function getPostsPosition(\Mageplaza\Blog\Model\Tag $tag)
{
$select = $this->getConnection()->select()
->from($this->tagPostTable, ['post_id', 'position'])
->where('tag_id = :tag_id');
$bind = ['tag_id' => (int)$tag->getId()];
return $this->getConnection()->fetchPairs($select, $bind);
}
/**
* @param \Mageplaza\Blog\Model\Tag $tag
*
* @return $this
*/
protected function savePostRelation(\Mageplaza\Blog\Model\Tag $tag)
{
$tag->setIsChangedPostList(false);
$id = $tag->getId();
$posts = $tag->getPostsData();
$oldPosts = $tag->getPostsPosition();
if (is_array($posts)) {
$insert = array_diff_key($posts, $oldPosts);
$delete = array_diff_key($oldPosts, $posts);
$update = array_intersect_key($posts, $oldPosts);
$_update = [];
foreach ($update as $key => $settings) {
if (isset($oldPosts[$key]) && $oldPosts[$key] != $settings['position']) {
$_update[$key] = $settings;
}
}
$update = $_update;
}
$adapter = $this->getConnection();
if ($posts === null && $this->request->getActionName() === 'save') {
foreach (array_keys($oldPosts) as $value) {
$condition = ['post_id =?' => (int)$value, 'tag_id=?' => (int)$id];
$adapter->delete($this->tagPostTable, $condition);
}
return $this;
}
if (!empty($delete)) {
foreach (array_keys($delete) as $value) {
$condition = ['post_id =?' => (int)$value, 'tag_id=?' => (int)$id];
$adapter->delete($this->tagPostTable, $condition);
}
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $postId => $position) {
$data[] = [
'tag_id' => (int)$id,
'post_id' => (int)$postId,
'position' => (int)$position['position']
];
}
$adapter->insertMultiple($this->tagPostTable, $data);
}
if (!empty($update)) {
foreach ($update as $postId => $position) {
$where = ['tag_id = ?' => (int)$id, 'post_id = ?' => (int)$postId];
$bind = ['position' => (int)$position['position']];
$adapter->update($this->tagPostTable, $bind, $where);
}
}
if (!empty($insert) || !empty($delete)) {
$postIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'mageplaza_blog_tag_change_posts',
['tag' => $tag, 'post_ids' => $postIds]
);
}
if (!empty($insert) || !empty($update) || !empty($delete)) {
$tag->setIsChangedPostList(true);
$postIds = array_keys($insert + $delete + $update);
$tag->setAffectedPostIds($postIds);
}
return $this;
}
/**
* Check category url key is exists
*
* @param $urlKey
*
* @return string
* @throws LocalizedException
*/
public function isDuplicateUrlKey($urlKey)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'tag_id')
->where('url_key = :url_key');
$binds = ['url_key' => $urlKey];
return $adapter->fetchOne($select, $binds);
}
/**
* Check is import tag
*
* @param $importSource
* @param $oldId
*
* @return string
* @throws LocalizedException
*/
public function isImported($importSource, $oldId)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'tag_id')
->where('import_source = :import_source');
$binds = ['import_source' => $importSource . '-' . $oldId];
return $adapter->fetchOne($select, $binds);
}
/**
* @param $importType
*
* @throws LocalizedException
*/
public function deleteImportItems($importType)
{
$adapter = $this->getConnection();
$adapter->delete($this->getMainTable(), "`import_source` LIKE '" . $importType . "%'");
}
}
@@ -0,0 +1,126 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Tag;
use Magento\Framework\DB\Select;
use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection;
use Mageplaza\Blog\Api\Data\SearchResult\TagSearchResultInterface;
use Mageplaza\Blog\Model\Tag;
use Mageplaza\Blog\Model\ResourceModel\Tag as TagResourceModel;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Tag
*/
class Collection extends AbstractCollection implements TagSearchResultInterface
{
/**
* ID Field Name
*
* @var string
*/
protected $_idFieldName = 'tag_id';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_tag_collection';
/**
* Event object
*
* @var string
*/
protected $_eventObject = 'tag_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(Tag::class, TagResourceModel::class);
}
/**
* Get SQL for get record count.
* Extra GROUP BY strip added.
*
* @return Select
*/
public function getSelectCountSql()
{
$countSelect = parent::getSelectCountSql();
$countSelect->reset(Select::GROUP);
return $countSelect;
}
/**
* @param null $valueField
* @param string $labelField
* @param array $additional
* @return array
*/
protected function _toOptionArray($valueField = null, $labelField = 'name', $additional = [])
{
$valueField = 'tag_id';
return parent::_toOptionArray($valueField, $labelField, $additional); // TODO: Change the autogenerated stub
}
/**
* Add if filter
*
* @param array|int|string $tagIds
*
* @return $this
*/
public function addIdFilter($tagIds)
{
$condition = '';
if (is_array($tagIds)) {
if (!empty($tagIds)) {
$condition = ['in' => $tagIds];
}
} elseif (is_numeric($tagIds)) {
$condition = $tagIds;
} elseif (is_string($tagIds)) {
$ids = explode(',', $tagIds);
if (empty($ids)) {
$condition = $tagIds;
} else {
$condition = ['in' => $ids];
}
}
if ($condition) {
$this->addFieldToFilter('tag_id', $condition);
}
return $this;
}
}
+279
View File
@@ -0,0 +1,279 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Mageplaza\Blog\Helper\Data;
/**
* Class Topic
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Topic extends AbstractDb
{
/**
* Date model
*
* @var DateTime
*/
public $date;
/**
* Event Manager
*
* @var ManagerInterface
*/
public $eventManager;
/**
* Post relation model
*
* @var string
*/
public $topicPostTable;
/**
* @var Data
*/
public $helperData;
/**
* @var RequestInterface
*/
private $request;
/**
* Topic constructor.
*
* @param Context $context
* @param DateTime $date
* @param ManagerInterface $eventManager
* @param RequestInterface $request
* @param Data $helperData
*/
public function __construct(
Context $context,
DateTime $date,
ManagerInterface $eventManager,
RequestInterface $request,
Data $helperData
) {
$this->helperData = $helperData;
$this->date = $date;
$this->eventManager = $eventManager;
$this->request = $request;
parent::__construct($context);
$this->topicPostTable = $this->getTable('mageplaza_blog_post_topic');
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('mageplaza_blog_topic', 'topic_id');
}
/**
* Retrieves Topic Name from DB by passed id.
*
* @param $id
*
* @return string
* @throws LocalizedException
*/
public function getTopicNameById($id)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'name')
->where('topic_id = :topic_id');
$binds = ['topic_id' => (int)$id];
return $adapter->fetchOne($select, $binds);
}
/**
* @inheritdoc
*/
protected function _beforeSave(AbstractModel $object)
{
$object->setUpdatedAt($this->date->date());
if ($object->isObjectNew()) {
$object->setCreatedAt($this->date->date());
}
if (is_array($object->getStoreIds())) {
$object->setStoreIds(implode(',', $object->getStoreIds()));
}
$object->setUrlKey(
$this->helperData->generateUrlKey($this, $object, $object->getUrlKey() ?: $object->getName())
);
return parent::_beforeSave($object);
}
/**
* @param AbstractModel $object
*
* @return AbstractDb
*/
protected function _afterSave(AbstractModel $object)
{
$this->savePostRelation($object);
return parent::_afterSave($object);
}
/**
* @param \Mageplaza\Blog\Model\Topic $topic
*
* @return array
*/
public function getPostsPosition(\Mageplaza\Blog\Model\Topic $topic)
{
$select = $this->getConnection()->select()->from(
$this->topicPostTable,
['post_id', 'position']
)
->where(
'topic_id = :topic_id'
);
$bind = ['topic_id' => (int)$topic->getId()];
return $this->getConnection()->fetchPairs($select, $bind);
}
/**
* @param \Mageplaza\Blog\Model\Topic $topic
*
* @return $this
*/
protected function savePostRelation(\Mageplaza\Blog\Model\Topic $topic)
{
$topic->setIsChangedPostList(false);
$id = $topic->getId();
$posts = $topic->getPostsData();
$oldPosts = $topic->getPostsPosition();
if (is_array($posts)) {
$insert = array_diff_key($posts, $oldPosts);
$delete = array_diff_key($oldPosts, $posts);
$update = array_intersect_key($posts, $oldPosts);
$_update = [];
foreach ($update as $key => $settings) {
if (isset($oldPosts[$key]) && $oldPosts[$key] != $settings['position']) {
$_update[$key] = $settings;
}
}
$update = $_update;
}
$adapter = $this->getConnection();
if ($posts === null && $this->request->getActionName() === 'save') {
foreach (array_keys($oldPosts) as $value) {
$condition = ['post_id =?' => (int)$value, 'topic_id=?' => (int)$id];
$adapter->delete($this->topicPostTable, $condition);
}
return $this;
}
if (!empty($delete)) {
foreach (array_keys($delete) as $value) {
$condition = ['post_id =?' => (int)$value, 'topic_id=?' => (int)$id];
$adapter->delete($this->topicPostTable, $condition);
}
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $postId => $position) {
$data[] = [
'topic_id' => (int)$id,
'post_id' => (int)$postId,
'position' => (int)$position['position']
];
}
$adapter->insertMultiple($this->topicPostTable, $data);
}
if (!empty($update)) {
foreach ($update as $postId => $position) {
$where = ['topic_id = ?' => (int)$id, 'post_id = ?' => (int)$postId];
$bind = ['position' => (int)$position['position']];
$adapter->update($this->topicPostTable, $bind, $where);
}
}
if (!empty($insert) || !empty($delete)) {
$postIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'mageplaza_blog_topic_change_posts',
['topic' => $topic, 'post_ids' => $postIds]
);
}
if (!empty($insert) || !empty($update) || !empty($delete)) {
$topic->setIsChangedPostList(true);
$postIds = array_keys($insert + $delete + $update);
$topic->setAffectedPostIds($postIds);
}
return $this;
}
/**
* Check is import topic
*
* @param $importSource
* @param $oldId
*
* @return string
* @throws LocalizedException
*/
public function isImported($importSource, $oldId)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'topic_id')
->where('import_source = :import_source');
$binds = ['import_source' => $importSource . '-' . $oldId];
return $adapter->fetchOne($select, $binds);
}
/**
* @param $importType
*
* @throws LocalizedException
*/
public function deleteImportItems($importType)
{
$adapter = $this->getConnection();
$adapter->delete($this->getMainTable(), "`import_source` LIKE '" . $importType . "%'");
}
}
@@ -0,0 +1,125 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Topic;
use Magento\Framework\DB\Select;
use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection;
use Mageplaza\Blog\Api\Data\SearchResult\TopicSearchResultInterface;
use Mageplaza\Blog\Model\Topic;
use Mageplaza\Blog\Model\ResourceModel\Topic as TopicResourceModel;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Topic
*/
class Collection extends AbstractCollection implements TopicSearchResultInterface
{
/**
* ID Field Name
*
* @var string
*/
protected $_idFieldName = 'topic_id';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_topic_collection';
/**
* Event object
*
* @var string
*/
protected $_eventObject = 'topic_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(Topic::class, TopicResourceModel::class);
}
/**
* Get SQL for get record count.
* Extra GROUP BY strip added.
*
* @return Select
*/
public function getSelectCountSql()
{
$countSelect = parent::getSelectCountSql();
$countSelect->reset(Select::GROUP);
return $countSelect;
}
/**
* @param null $valueField
* @param string $labelField
* @param array $additional
*
* @return array
*/
protected function _toOptionArray($valueField = null, $labelField = 'name', $additional = [])
{
$valueField = 'topic_id';
return parent::_toOptionArray($valueField, $labelField, $additional); // TODO: Change the autogenerated stub
}
/**
* @param mixed $topicIds
*
* @return $this
*/
public function addIdFilter($topicIds)
{
$condition = '';
if (is_array($topicIds)) {
if (!empty($topicIds)) {
$condition = ['in' => $topicIds];
}
} elseif (is_numeric($topicIds)) {
$condition = $topicIds;
} elseif (is_string($topicIds)) {
$ids = explode(',', $topicIds);
if (empty($ids)) {
$condition = $topicIds;
} else {
$condition = ['in' => $ids];
}
}
if ($condition) {
$this->addFieldToFilter('topic_id', $condition);
}
return $this;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
/**
* Class Traffic
* @package Mageplaza\Blog\Model\ResourceModel
*/
class Traffic extends AbstractDb
{
/**
* Define main table
*/
public function _construct()
{
$this->_init('mageplaza_blog_post_traffic', 'traffic_id');
}
}
@@ -0,0 +1,41 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model\ResourceModel\Traffic;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Mageplaza\Blog\Model\Traffic;
use Mageplaza\Blog\Model\ResourceModel\Traffic as TrafficResourceModel;
/**
* Class Collection
* @package Mageplaza\Blog\Model\ResourceModel\Traffic
*/
class Collection extends AbstractCollection
{
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(Traffic::class, TrafficResourceModel::class);
}
}
+175
View File
@@ -0,0 +1,175 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
use Mageplaza\Blog\Model\ResourceModel\Post\CollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Tag\CollectionFactory as TagCollectionFactory;
/**
* @method Tag setName($name)
* @method Tag setDescription($description)
* @method Tag setEnabled($enabled)
* @method mixed getName()
* @method mixed getDescription()
* @method mixed getEnabled()
* @method Tag setCreatedAt(string $createdAt)
* @method string getCreatedAt()
* @method Tag setUpdatedAt(string $updatedAt)
* @method string getUpdatedAt()
* @method Tag setPostsData(array $data)
* @method array getPostsData()
* @method Tag setIsChangedPostList(bool $flag)
* @method bool getIsChangedPostList()
* @method Tag setAffectedPostIds(array $ids)
* @method bool getAffectedPostIds()
*/
class Tag extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_tag';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_tag';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_tag';
/**
* Post Collection
*
* @var Collection
*/
public $postCollection;
/**
* Post Collection Factory
*
* @var CollectionFactory
*/
public $postCollectionFactory;
/**
* @var TagCollectionFactory
*/
public $tagCollectionFactory;
/**
* Tag constructor.
*
* @param Context $context
* @param Registry $registry
* @param CollectionFactory $postCollectionFactory
* @param TagCollectionFactory $tagCollectionFactory
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
CollectionFactory $postCollectionFactory,
TagCollectionFactory $tagCollectionFactory,
?AbstractResource $resource = null,
?AbstractDb $resourceCollection = null,
array $data = []
) {
$this->postCollectionFactory = $postCollectionFactory;
$this->tagCollectionFactory = $tagCollectionFactory;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(ResourceModel\Tag::class);
}
/**
* Get identities
*
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* @return array|mixed
*/
public function getPostsPosition()
{
if (!$this->getId()) {
return [];
}
$array = $this->getData('posts_position');
if (!$array) {
$array = $this->getResource()->getPostsPosition($this);
$this->setData('posts_position', $array);
}
return $array;
}
/**
* @return Collection
*/
public function getSelectedPostsCollection()
{
if ($this->postCollection === null) {
$collection = $this->postCollectionFactory->create();
$collection->join(
['post_tag' => $this->getResource()->getTable('mageplaza_blog_post_tag')],
'main_table.post_id=post_tag.post_id AND post_tag.tag_id=' . $this->getId(),
['position']
);
$this->postCollection = $collection;
}
return $this->postCollection;
}
}
+199
View File
@@ -0,0 +1,199 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
use Mageplaza\Blog\Model\ResourceModel\Post\CollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Topic\CollectionFactory as TopicCollectionFactory;
/**
* @method Topic setName($name)
* @method Topic setDescription($description)
* @method Topic setEnabled($enabled)
* @method Topic setUrlKey($urlKey)
* @method Topic setMetaTitle($metaTitle)
* @method Topic setMetaDescription($metaDescription)
* @method Topic setMetaKeywords($metaKeywords)
* @method Topic setMetaRobots($metaRobots)
* @method mixed getName()
* @method mixed getDescription()
* @method mixed getEnabled()
* @method mixed getUrlKey()
* @method mixed getMetaTitle()
* @method mixed getMetaDescription()
* @method mixed getMetaKeywords()
* @method mixed getMetaRobots()
* @method Topic setCreatedAt(string $createdAt)
* @method string getCreatedAt()
* @method Topic setUpdatedAt(string $updatedAt)
* @method string getUpdatedAt()
* @method Topic setPostsData(array $data)
* @method array getPostsData()
* @method Topic setIsChangedPostList(bool $flag)
* @method bool getIsChangedPostList()
* @method Topic setAffectedPostIds(array $ids)
* @method bool getAffectedPostIds()
*/
class Topic extends AbstractModel
{
/**
* Cache tag
*
* @var string
*/
const CACHE_TAG = 'mageplaza_blog_topic';
/**
* Cache tag
*
* @var string
*/
protected $_cacheTag = 'mageplaza_blog_topic';
/**
* Event prefix
*
* @var string
*/
protected $_eventPrefix = 'mageplaza_blog_topic';
/**
* Post Collection
*
* @var Collection
*/
public $postCollection;
/**
* Post Collection Factory
*
* @var CollectionFactory
*/
public $postCollectionFactory;
/**
* Topic Collection Factory
*
* @var TopicCollectionFactory
*/
public $topicCollectionFactory;
/**
* Topic constructor.
*
* @param Context $context
* @param Registry $registry
* @param CollectionFactory $postCollectionFactory
* @param TopicCollectionFactory $topicCollectionFactory
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
CollectionFactory $postCollectionFactory,
TopicCollectionFactory $topicCollectionFactory,
?AbstractResource $resource = null,
?AbstractDb $resourceCollection = null,
array $data = []
) {
$this->postCollectionFactory = $postCollectionFactory;
$this->topicCollectionFactory = $topicCollectionFactory;
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(ResourceModel\Topic::class);
}
/**
* Get identities
*
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* get entity default values
*
* @return array
*/
public function getDefaultValues()
{
$values = [];
$values['enabled'] = '1';
$values['store_ids'] = '1';
return $values;
}
/**
* @return array|mixed
*/
public function getPostsPosition()
{
if (!$this->getId()) {
return [];
}
$array = $this->getData('posts_position');
if ($array === null) {
$array = $this->getResource()->getPostsPosition($this);
$this->setData('posts_position', $array);
}
return $array;
}
/**
* @return Collection
*/
public function getSelectedPostsCollection()
{
if ($this->postCollection === null) {
$collection = $this->postCollectionFactory->create();
$collection->join(
['topic' => $this->getResource()->getTable('mageplaza_blog_post_topic')],
'main_table.post_id=topic.post_id AND topic.topic_id=' . $this->getId(),
['position']
);
$this->postCollection = $collection;
}
return $this->postCollection;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
/**
* Mageplaza
*
* NOTICE OF LICENSE
*
* This source file is subject to the Mageplaza.com license that is
* available through the world-wide-web at this URL:
* https://www.mageplaza.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this extension to newer
* version in the future.
*
* @category Mageplaza
* @package Mageplaza_Blog
* @copyright Copyright (c) Mageplaza (https://www.mageplaza.com/)
* @license https://www.mageplaza.com/LICENSE.txt
*/
namespace Mageplaza\Blog\Model;
use Magento\Framework\Model\AbstractModel;
/**
* Class Traffic
* @package Mageplaza\Blog\Model
*/
class Traffic extends AbstractModel
{
/**
* Define resource model
*/
public function _construct()
{
$this->_init(ResourceModel\Traffic::class);
}
}