diff --git a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php index 75015d65e1a18..a3cfd8c472629 100644 --- a/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php +++ b/app/code/Magento/Review/Controller/Adminhtml/Product/Delete.php @@ -3,10 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Review\Controller\Adminhtml\Product; -use Magento\Review\Controller\Adminhtml\Product as ProductController; use Magento\Framework\Controller\ResultFactory; +use Magento\Review\Controller\Adminhtml\Product as ProductController; class Delete extends ProductController { @@ -17,9 +18,12 @@ public function execute() { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); - $reviewId = $this->getRequest()->getParam('id', false); + $reviewId = (int)$this->getRequest()->getParam('id', false); try { - $this->reviewFactory->create()->setId($reviewId)->aggregate()->delete(); + $review = $this->reviewFactory->create( + ['data' => ['review_id' => $reviewId]] + ); + $review->delete(); $this->messageManager->addSuccess(__('The review has been deleted.')); if ($this->getRequest()->getParam('ret') == 'pending') { diff --git a/app/code/Magento/Review/Model/Aggregator/Ratings.php b/app/code/Magento/Review/Model/Aggregator/Ratings.php new file mode 100644 index 0000000000000..9ab61a9e47c8d --- /dev/null +++ b/app/code/Magento/Review/Model/Aggregator/Ratings.php @@ -0,0 +1,42 @@ +reviewResource = $reviewResource; + } + + /** + * @inheritdoc + */ + public function aggregate(ReviewInterface $review): void + { + $this->reviewResource->reAggregateReview($review->getReviewId(), $review->getRelatedEntityId()); + } +} diff --git a/app/code/Magento/Review/Model/Aggregator/Review.php b/app/code/Magento/Review/Model/Aggregator/Review.php new file mode 100644 index 0000000000000..f2f3653d7c583 --- /dev/null +++ b/app/code/Magento/Review/Model/Aggregator/Review.php @@ -0,0 +1,42 @@ +reviewResource = $reviewResource; + } + + /** + * @inheritdoc + */ + public function aggregate(ReviewInterface $review): void + { + $this->reviewResource->aggregate($review); + } +} diff --git a/app/code/Magento/Review/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ReviewCustomerFilter.php b/app/code/Magento/Review/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ReviewCustomerFilter.php new file mode 100644 index 0000000000000..5ebff5bc7171e --- /dev/null +++ b/app/code/Magento/Review/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ReviewCustomerFilter.php @@ -0,0 +1,32 @@ +addCustomerFilter($filter->getValue()); + + return true; + } +} diff --git a/app/code/Magento/Review/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ReviewSkuFilter.php b/app/code/Magento/Review/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ReviewSkuFilter.php new file mode 100644 index 0000000000000..d717f28d25ea1 --- /dev/null +++ b/app/code/Magento/Review/Model/Api/SearchCriteria/CollectionProcessor/FilterProcessor/ReviewSkuFilter.php @@ -0,0 +1,53 @@ +productResource = $productResource; + } + + /** + * Apply sku Filter to Review Collection + * + * @param Filter $filter + * @param AbstractDb $collection + * @return bool Whether the filter is applied + */ + public function apply(Filter $filter, AbstractDb $collection) + { + $productId = $this->productResource->getIdBySku($filter->getValue()); + + /** @var \Magento\Review\Model\ResourceModel\Review\Collection $collection */ + $collection->addEntityFilter('product', $productId); + + return true; + } +} diff --git a/app/code/Magento/Review/Model/Command/CreateReviews.php b/app/code/Magento/Review/Model/Command/CreateReviews.php new file mode 100644 index 0000000000000..94ab8b95cb775 --- /dev/null +++ b/app/code/Magento/Review/Model/Command/CreateReviews.php @@ -0,0 +1,150 @@ +createMultiple = $createMultiple; + $this->reviewValidatorChain = $reviewValidatorChain; + $this->reviewAggregator = $reviewAggregator; + $this->reviewOperationResponse = $reviewOperationResponse; + $this->jsonSerializer = $jsonSerializer; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $reviews): ReviewOperationResponseInterface + { + if (empty($reviews)) { + throw new InputException(__('Input data is empty')); + } + + $validReviews = []; + $invalidReviews = []; + + foreach ($reviews as $key => $review) { + $validationResult = $this->reviewValidatorChain->validate($review); + if (!$validationResult->isValid()) { + $invalidReviews[] = $review; + + $this->reviewOperationResponse->addError( + $this->getErrorMessage($validationResult->getErrors(), $review) + ); + continue; + } + $validReviews[] = $review; + } + + if (!empty($validReviews)) { + try { + $this->createMultiple->execute($validReviews); + + foreach ($validReviews as $review) { + $this->reviewAggregator->aggregate($review); + } + + $this->reviewOperationResponse->addSuccessfulReviews($validReviews); + } catch (\Exception $e) { + $this->reviewOperationResponse->addFailedReviews($validReviews); + $this->reviewOperationResponse->addError( + __('There was an error while saving the reviews.') + ); + $this->logger->error($e->getMessage()); + } + } + if (!empty($invalidReviews)) { + $this->reviewOperationResponse->addFailedReviews($invalidReviews); + } + + unset($validReviews); + unset($invalidReviews); + + return $this->reviewOperationResponse; + } + + /** + * Get error message + * + * @param array $errors + * @param ReviewInterface $review + * @return string + */ + private function getErrorMessage(array $errors, ReviewInterface $review) + { + $errorMessage = sprintf( + '%s => Request Data: %s:', + implode(',', $errors), + $this->jsonSerializer->serialize($review->toArray()) + ); + + return $errorMessage; + } +} diff --git a/app/code/Magento/Review/Model/Command/DeleteReviews.php b/app/code/Magento/Review/Model/Command/DeleteReviews.php new file mode 100644 index 0000000000000..acd787b229340 --- /dev/null +++ b/app/code/Magento/Review/Model/Command/DeleteReviews.php @@ -0,0 +1,89 @@ +deleteMultiple = $deleteMultiple; + $this->reviewAggregator = $reviewAggregator; + $this->reviewOperationResponse = $reviewOperationResponse; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $reviews): ReviewOperationResponseInterface + { + if (empty($reviews)) { + throw new InputException(__('Input data is empty')); + } + + try { + $this->deleteMultiple->execute($reviews); + + foreach ($reviews as $review) { + $this->reviewAggregator->aggregate($review); + } + + $this->reviewOperationResponse->addSuccessfulReviews($reviews); + } catch (\Exception $e) { + $this->reviewOperationResponse->addFailedReviews($reviews); + $this->reviewOperationResponse->addError( + __('There was an error while deleting the reviews.') + ); + $this->logger->error($e->getMessage()); + } + + return $this->reviewOperationResponse; + } +} diff --git a/app/code/Magento/Review/Model/Command/GetReviews.php b/app/code/Magento/Review/Model/Command/GetReviews.php new file mode 100644 index 0000000000000..3ba9d63a290e7 --- /dev/null +++ b/app/code/Magento/Review/Model/Command/GetReviews.php @@ -0,0 +1,185 @@ +reviewCollectionFactory = $reviewCollectionFactory; + $this->searchResultsFactory = $searchResultsFactory; + $this->reviewFactory = $reviewFactory; + $this->ratingOptionVoteInterfaceFactory = $ratingOptionVoteInterfaceFactory; + $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor; + $this->collectionProcessor = $collectionProcessor; + $this->readExtensions = $readExtensions; + $this->dataObjectHelper = $dataObjectHelper; + } + + /** + * @inheritdoc + */ + public function execute( + SearchCriteriaInterface $searchCriteria + ): SearchResultsInterface { + /** @var Collection $collection */ + $collection = $this->reviewCollectionFactory->create(); + + $this->extensionAttributesJoinProcessor->process($collection); + $this->collectionProcessor->process($searchCriteria, $collection); + + $collection->addStoreData(); + + $this->addExtensionAttributes($collection); + + /** @var ReviewSearchResultsInterface $searchResult */ + $searchResults = $this->searchResultsFactory->create(); + $searchResults->setSearchCriteria($searchCriteria); + $searchResults->setTotalCount($collection->getSize()); + + $items = []; + /** @var \Magento\Review\Model\Review $review */ + foreach ($collection as $review) { + $itemData = $this->reviewFactory->create(); + $this->dataObjectHelper->populateWithArray( + $itemData, + $review->toArray(), + ReviewInterface::class + ); + + $items[$review->getId()] = $itemData; + } + + $collection->addRateVotes(); + + foreach ($collection as $review) { + $ratings = []; + /** @var \Magento\Review\Model\Rating\Option\Vote $rating */ + foreach ($review->getRatings() as $rating) { + $ratingData = $this->ratingOptionVoteInterfaceFactory->create(); + $this->dataObjectHelper->populateWithArray( + $ratingData, + $rating->toArray(), + RatingOptionVoteInterface::class + ); + + $ratings[$rating->getId()] = $ratingData; + } + $items[$review->getId()][ReviewInterface::RATINGS] = $ratings; + } + + $searchResults->setItems($items); + + return $searchResults; + } + + /** + * Add extension attributes to loaded items. + * + * @param Collection $collection + * @return Collection + */ + private function addExtensionAttributes(Collection $collection): Collection + { + foreach ($collection->getItems() as $item) { + $this->readExtensions->execute($item); + } + return $collection; + } +} diff --git a/app/code/Magento/Review/Model/Command/UpdateReviews.php b/app/code/Magento/Review/Model/Command/UpdateReviews.php new file mode 100644 index 0000000000000..c0507d8fa23a4 --- /dev/null +++ b/app/code/Magento/Review/Model/Command/UpdateReviews.php @@ -0,0 +1,150 @@ +updateMultiple = $updateMultiple; + $this->reviewValidatorChain = $reviewValidatorChain; + $this->reviewAggregator = $reviewAggregator; + $this->reviewOperationResponse = $reviewOperationResponse; + $this->jsonSerializer = $jsonSerializer; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $reviews): ReviewOperationResponseInterface + { + if (empty($reviews)) { + throw new InputException(__('Input data is empty')); + } + + $validReviews = []; + $invalidReviews = []; + + foreach ($reviews as $key => $review) { + $validationResult = $this->reviewValidatorChain->validate($review); + if (!$validationResult->isValid()) { + $invalidReviews[] = $review; + + $this->reviewOperationResponse->addError( + $this->getErrorMessage($validationResult->getErrors(), $review) + ); + continue; + } + $validReviews[] = $review; + } + + if (!empty($validReviews)) { + try { + $this->updateMultiple->execute($validReviews); + + foreach ($validReviews as $review) { + $this->reviewAggregator->aggregate($review); + } + + $this->reviewOperationResponse->addSuccessfulReviews($validReviews); + } catch (\Exception $e) { + $this->reviewOperationResponse->addFailedReviews($validReviews); + $this->reviewOperationResponse->addError( + __('There was an error while saving the reviews.') + ); + $this->logger->error($e->getMessage()); + } + } + if (!empty($invalidReviews)) { + $this->reviewOperationResponse->addFailedReviews($invalidReviews); + } + + unset($validReviews); + unset($invalidReviews); + + return $this->reviewOperationResponse; + } + + /** + * Get error message + * + * @param array $errors + * @param ReviewInterface $review + * @return string + */ + private function getErrorMessage(array $errors, ReviewInterface $review) + { + $errorMessage = sprintf( + '%s => Request Data: %s:', + implode(',', $errors), + $this->jsonSerializer->serialize($review->toArray()) + ); + + return $errorMessage; + } +} diff --git a/app/code/Magento/Review/Model/Rating.php b/app/code/Magento/Review/Model/Rating.php index c8506926f5160..4075cba089f4a 100644 --- a/app/code/Magento/Review/Model/Rating.php +++ b/app/code/Magento/Review/Model/Rating.php @@ -3,71 +3,90 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Model; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\Collection\AbstractDb; use Magento\Framework\DataObject\IdentityInterface; +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Review\Model\Rating\OptionFactory as RatingOptionFactory; +use Magento\Review\Model\ResourceModel\Rating\Option\CollectionFactory as RatingOptionCollectionFactory; +use Magento\ReviewApi\Api\Data\RatingInterface; /** * Rating model - * - * @api - * @method array getRatingCodes() - * @method \Magento\Review\Model\Rating setRatingCodes(array $value) - * @method array getStores() - * @method \Magento\Review\Model\Rating setStores(array $value) - * @method string getRatingCode() - * - * @author Magento Core Team - * @since 100.0.2 */ -class Rating extends \Magento\Framework\Model\AbstractModel implements IdentityInterface +class Rating extends AbstractExtensibleModel implements IdentityInterface, RatingInterface { /** * rating entity codes */ const ENTITY_PRODUCT_CODE = 'product'; - const ENTITY_PRODUCT_REVIEW_CODE = 'product_review'; - const ENTITY_REVIEW_CODE = 'review'; /** - * @var \Magento\Review\Model\Rating\OptionFactory + * @var RatingOptionFactory */ protected $_ratingOptionFactory; /** - * @var \Magento\Review\Model\ResourceModel\Rating\Option\CollectionFactory + * @var RatingOptionCollectionFactory */ protected $_ratingCollectionF; /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Review\Model\Rating\OptionFactory $ratingOptionFactory - * @param \Magento\Review\Model\ResourceModel\Rating\Option\CollectionFactory $ratingCollectionF - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * Rating constructor + * + * @param Context $context + * @param Registry $registry + * @param RatingOptionFactory $ratingOptionFactory + * @param RatingOptionCollectionFactory $ratingOptionCollectionFactory + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data + * @param ExtensionAttributesFactory|null $extensionFactory + * @param AttributeValueFactory|null $customAttributeFactory */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Review\Model\Rating\OptionFactory $ratingOptionFactory, - \Magento\Review\Model\ResourceModel\Rating\Option\CollectionFactory $ratingCollectionF, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + Context $context, + Registry $registry, + RatingOptionFactory $ratingOptionFactory, + RatingOptionCollectionFactory $ratingOptionCollectionFactory, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null ) { $this->_ratingOptionFactory = $ratingOptionFactory; - $this->_ratingCollectionF = $ratingCollectionF; - parent::__construct($context, $registry, $resource, $resourceCollection, $data); + $this->_ratingCollectionF = $ratingOptionCollectionFactory; + + $extensionFactory = $extensionFactory + ?: ObjectManager::getInstance()->get(ExtensionAttributesFactory::class); + $customAttributeFactory = $customAttributeFactory + ?: ObjectManager::getInstance()->get(AttributeValueFactory::class); + + parent::__construct( + $context, + $registry, + $extensionFactory, + $customAttributeFactory, + $resource, + $resourceCollection, + $data + ); } /** - * Define resource model - * - * @return void + * @inheritdoc */ protected function _construct() { @@ -75,6 +94,198 @@ protected function _construct() } /** + * @inheritdoc + */ + public function getRatingId(): ?int + { + return (int)$this->_getData(self::RATING_ID); + } + + /** + * @inheritdoc + */ + public function setRatingId(?int $ratingId): RatingInterface + { + $this->setData(self::RATING_ID, $ratingId); + return $this; + } + + /** + * @inheritdoc + */ + public function getRatingEntityId(): int + { + return (int)$this->_getData(self::RATING_ENTITY_ID); + } + + /** + * @inheritdoc + */ + public function setRatingEntityId(int $entityId): RatingInterface + { + $this->setData(self::RATING_ENTITY_ID, $entityId); + return $this; + } + + /** + * @inheritdoc + */ + public function getRatingName(): string + { + return $this->_getData(self::RATING_NAME); + } + + /** + * @inheritdoc + */ + public function setRatingName(string $ratingName): RatingInterface + { + $this->setData(self::RATING_NAME, $ratingName); + return $this; + } + + /** + * @inheritdoc + */ + public function getRatingNames(): ?array + { + return $this->_getData(self::RATING_NAMES); + } + + /** + * @inheritdoc + */ + public function setRatingNames(?array $ratingNames): RatingInterface + { + $this->setData(self::RATING_NAMES, $ratingNames); + return $this; + } + + /** + * @inheritdoc + */ + public function getPosition(): int + { + return (int)$this->_getData(self::POSITION); + } + + /** + * @inheritdoc + */ + public function setPosition(int $position): RatingInterface + { + $this->setData(self::POSITION, $position); + return $this; + } + + /** + * @inheritdoc + */ + public function isActive(): bool + { + return (bool)$this->_getData(self::IS_ACTIVE); + } + + /** + * @inheritdoc + */ + public function setIsActive($isActive): RatingInterface + { + $this->setData(self::IS_ACTIVE, $isActive); + return $this; + } + + /** + * @inheritdoc + */ + public function getStoreId(): ?int + { + return $this->_getData(self::STORE_ID) ? (int)$this->_getData(self::STORE_ID) : null; + } + + /** + * @inheritdoc + */ + public function setStoreId($storeId): RatingInterface + { + $this->setData(self::STORE_ID, $storeId); + return $this; + } + + /** + * @inheritdoc + */ + public function getStores(): array + { + return $this->_getData(self::STORES) ?: []; + } + + /** + * @inheritdoc + */ + public function setStores(array $stores): RatingInterface + { + $this->setData(self::STORES, $stores); + return $this; + } + + /** + * @inheritdoc + */ + public function getOptions() + { + $options = $this->getData(self::RATING_OPTIONS); + if ($options) { + return $options; + } elseif ($this->getId()) { + return $this->_ratingCollectionF->create()->addRatingFilter( + $this->getId() + )->setPositionOrder()->load()->getItems(); + } + return []; + } + + /** + * @inheritdoc + */ + public function setOptions(array $options) + { + $this->setData(self::RATING_OPTIONS, $options); + return $this; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): \Magento\ReviewApi\Api\Data\RatingExtensionInterface + { + $extensionAttributes = $this->_getExtensionAttributes(); + if (!$extensionAttributes) { + return $this->extensionAttributesFactory->create(RatingInterface::class); + } + return $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes( + \Magento\ReviewApi\Api\Data\RatingExtensionInterface $extensionAttributes + ): RatingInterface { + return $this->_setExtensionAttributes($extensionAttributes); + } + + /** + * @inheritdoc + */ + public function getIdentities() + { + return [Review::CACHE_TAG]; + } + + /** + * Add option vote + * * @param int $optionId * @param int $entityPkValue * @return $this @@ -94,6 +305,8 @@ public function addOptionVote($optionId, $entityPkValue) } /** + * Update option vote + * * @param int $optionId * @return $this */ @@ -111,30 +324,13 @@ public function updateOptionVote($optionId) return $this; } - /** - * retrieve rating options - * - * @return array - */ - public function getOptions() - { - $options = $this->getData('options'); - if ($options) { - return $options; - } elseif ($this->getId()) { - return $this->_ratingCollectionF->create()->addRatingFilter( - $this->getId() - )->setPositionOrder()->load()->getItems(); - } - return []; - } - /** * Get rating collection object * * @param int $entityPkValue * @param bool $onlyForCurrentStore - * @return \Magento\Framework\Data\Collection\AbstractDb + * @return AbstractDb + * @throws \Magento\Framework\Exception\LocalizedException */ public function getEntitySummary($entityPkValue, $onlyForCurrentStore = true) { @@ -143,9 +339,12 @@ public function getEntitySummary($entityPkValue, $onlyForCurrentStore = true) } /** + * Get review summary + * * @param int $reviewId * @param bool $onlyForCurrentStore * @return array + * @throws \Magento\Framework\Exception\LocalizedException */ public function getReviewSummary($reviewId, $onlyForCurrentStore = true) { @@ -163,15 +362,4 @@ public function getEntityIdByCode($entityCode) { return $this->getResource()->getEntityIdByCode($entityCode); } - - /** - * Return unique ID(s) for each object in system - * - * @return array - */ - public function getIdentities() - { - // clear cache for all reviews - return [Review::CACHE_TAG]; - } } diff --git a/app/code/Magento/Review/Model/Rating/Entity.php b/app/code/Magento/Review/Model/Rating/Entity.php index cc2d5ab852518..c030938068dad 100644 --- a/app/code/Magento/Review/Model/Rating/Entity.php +++ b/app/code/Magento/Review/Model/Rating/Entity.php @@ -3,21 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Review\Model\Rating; +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\ReviewApi\Api\Data\RatingEntityInterface; + /** * Ratings entity model - * - * @method string getEntityCode() - * @method \Magento\Review\Model\Rating\Entity setEntityCode(string $value) - * - * @author Magento Core Team - * @codeCoverageIgnore */ -class Entity extends \Magento\Framework\Model\AbstractModel +class Entity extends AbstractExtensibleModel implements RatingEntityInterface { /** - * @return void + * @inheritdoc */ protected function _construct() { @@ -25,8 +23,66 @@ protected function _construct() } /** + * @inheritdoc + */ + public function getEntityId() + { + return $this->_getData(self::ENTITY_ID); + } + + /** + * @inheritdoc + */ + public function setEntityId($entityId) + { + $this->setData(self::ENTITY_ID, $entityId); + return$this; + } + + /** + * @inheritdoc + */ + public function getEntityCode(): string + { + return $this->_getData(self::ENTITY_CODE); + } + + /** + * @inheritdoc + */ + public function setEntityCode(string $entityCode): RatingEntityInterface + { + $this->setData(self::ENTITY_CODE, $entityCode); + return$this; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): \Magento\ReviewApi\Api\Data\RatingEntityExtensionInterface + { + $extensionAttributes = $this->_getExtensionAttributes(); + if (!$extensionAttributes) { + return $this->extensionAttributesFactory->create(RatingEntityInterface::class); + } + return $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes( + \Magento\ReviewApi\Api\Data\RatingEntityExtensionInterface $extensionAttributes + ): RatingEntityInterface { + return $this->_setExtensionAttributes($extensionAttributes); + } + + /** + * Get entity id by code + * * @param string $entityCode * @return int + * @throws \Magento\Framework\Exception\LocalizedException */ public function getIdByCode($entityCode) { diff --git a/app/code/Magento/Review/Model/Rating/Option.php b/app/code/Magento/Review/Model/Rating/Option.php index 2f5ece53d1bb1..02e9de927d18a 100644 --- a/app/code/Magento/Review/Model/Rating/Option.php +++ b/app/code/Magento/Review/Model/Rating/Option.php @@ -3,29 +3,19 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Review\Model\Rating; +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\ReviewApi\Api\Data\RatingOptionInterface; + /** * Rating option model - * - * @api - * @method int getRatingId() - * @method \Magento\Review\Model\Rating\Option setRatingId(int $value) - * @method string getCode() - * @method \Magento\Review\Model\Rating\Option setCode(string $value) - * @method int getValue() - * @method \Magento\Review\Model\Rating\Option setValue(int $value) - * @method int getPosition() - * @method \Magento\Review\Model\Rating\Option setPosition(int $value) - * - * @author Magento Core Team - * @codeCoverageIgnore - * @since 100.0.2 */ -class Option extends \Magento\Framework\Model\AbstractModel +class Option extends AbstractExtensibleModel implements RatingOptionInterface { /** - * @return void + * @inheritdoc */ protected function _construct() { @@ -33,21 +23,119 @@ protected function _construct() } /** - * @return $this + * @inheritdoc */ - public function addVote() + public function getOptionId() { - $this->getResource()->addVote($this); - return $this; + return $this->_getData(self::OPTION_ID); + } + + /** + * @inheritdoc + */ + public function setOptionId($optionId): RatingOptionInterface + { + $this->setData(self::OPTION_ID, $optionId); + return$this; + } + + /** + * @inheritdoc + */ + public function getRatingId(): ?int + { + return $this->_getData(self::RATING_ID); + } + + /** + * @inheritdoc + */ + public function setRatingId(int $ratingId): RatingOptionInterface + { + $this->setData(self::RATING_ID, $ratingId); + return$this; + } + + /** + * @inheritdoc + */ + public function getCode(): int + { + return $this->_getData(self::CODE); + } + + /** + * @inheritdoc + */ + public function setCode(int $code): RatingOptionInterface + { + $this->setData(self::CODE, $code); + return$this; } /** - * @param mixed $id + * @inheritdoc + */ + public function getValue(): int + { + return $this->_getData(self::VALUE); + } + + /** + * @inheritdoc + */ + public function setValue(int $value): RatingOptionInterface + { + $this->setData(self::VALUE, $value); + return$this; + } + + /** + * @inheritdoc + */ + public function getPosition(): int + { + return $this->_getData(self::POSITION); + } + + /** + * @inheritdoc + */ + public function setPosition(int $position): RatingOptionInterface + { + $this->setData(self::POSITION, $position); + return$this; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): \Magento\ReviewApi\Api\Data\RatingOptionExtensionInterface + { + $extensionAttributes = $this->_getExtensionAttributes(); + if (!$extensionAttributes) { + return $this->extensionAttributesFactory->create(RatingOptionInterface::class); + } + return $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes( + \Magento\ReviewApi\Api\Data\RatingOptionExtensionInterface $extensionAttributes + ): RatingOptionInterface { + return $this->_setExtensionAttributes($extensionAttributes); + } + + /** + * Add vote + * * @return $this */ - public function setId($id) + public function addVote() { - $this->setOptionId($id); + $this->getResource()->addVote($this); return $this; } } diff --git a/app/code/Magento/Review/Model/Rating/Option/Vote.php b/app/code/Magento/Review/Model/Rating/Option/Vote.php index 1cf720092fb3e..697350778f11c 100644 --- a/app/code/Magento/Review/Model/Rating/Option/Vote.php +++ b/app/code/Magento/Review/Model/Rating/Option/Vote.php @@ -3,24 +3,397 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Review\Model\Rating\Option; +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\ReviewApi\Api\Data\RatingOptionVoteInterface; + /** * Rating vote model - * - * @api - * - * @author Magento Core Team - * @codeCoverageIgnore - * @since 100.0.2 */ -class Vote extends \Magento\Framework\Model\AbstractModel +class Vote extends AbstractExtensibleModel implements RatingOptionVoteInterface { /** - * @return void + * @inheritdoc */ protected function _construct() { $this->_init(\Magento\Review\Model\ResourceModel\Rating\Option\Vote::class); } + + /** + * @inheritdoc + */ + public function getVoteId(): ?int + { + return $this->_getData(self::VOTE_ID); + } + + /** + * @inheritdoc + */ + public function setVoteId(?int $voteId): RatingOptionVoteInterface + { + $this->setData(self::VOTE_ID, $voteId); + return $this; + } + + /** + * Get option id + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::getRatingOptionId() + * @return int + */ + public function getOptionId() + { + return $this->getRatingOptionId(); + } + + /** + * Set option id + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::setRatingOptionId() + * @param int $ratingOptionId + * @return RatingOptionVoteInterface + */ + public function setOptionId($ratingOptionId) + { + return $this->setRatingOptionId($ratingOptionId); + } + + /** + * @inheritdoc + */ + public function getRatingOptionId(): ?int + { + return $this->_getData(self::RATING_OPTION_ID); + } + + /** + * @inheritdoc + */ + public function setRatingOptionId(int $ratingOptionId): RatingOptionVoteInterface + { + $this->setData(self::RATING_OPTION_ID, $ratingOptionId); + return $this; + } + + /** + * Get remote ip + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::getRemoteIpAddress() + * @return string + */ + public function getRemoteIp() + { + return $this->getRemoteIpAddress(); + } + + /** + * Set remote ip + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::setRemoteIpAddress() + * @param string $remoteIp + * @return RatingOptionVoteInterface + */ + public function setRemoteIp($remoteIp) + { + return $this->setRemoteIpAddress($remoteIp); + } + + /** + * @inheritdoc + */ + public function getRemoteIpAddress(): ?string + { + return $this->_getData(self::REMOTE_IP_ADDRESS); + } + + /** + * @inheritdoc + */ + public function setRemoteIpAddress(string $ipAddress): RatingOptionVoteInterface + { + $this->setData(self::REMOTE_IP_ADDRESS, $ipAddress); + return $this; + } + + /** + * Get remote ip long + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::getRemoteIpAddressLong() + * @return string + */ + public function getRemoteIpLong() + { + return $this->getRemoteIpAddressLong(); + } + + /** + * Set remote ip long + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::setRemoteIpAddressLong() + * @param string $remoteIpLong + * @return RatingOptionVoteInterface + */ + public function setRemoteIpLong($remoteIpLong) + { + return $this->setRemoteIpAddressLong($remoteIpLong); + } + + /** + * @inheritdoc + */ + public function getRemoteIpAddressLong(): ?string + { + return $this->_getData(self::REMOTE_IP_ADDRESS_LONG); + } + + /** + * @inheritdoc + */ + public function setRemoteIpAddressLong(string $ipAddressLong): RatingOptionVoteInterface + { + $this->setData(self::REMOTE_IP_ADDRESS_LONG, $ipAddressLong); + return $this; + } + + /** + * @inheritdoc + */ + public function getCustomerId(): ?int + { + return $this->_getData(self::CUSTOMER_ID); + } + + /** + * @inheritdoc + */ + public function setCustomerId(?int $customerId): RatingOptionVoteInterface + { + $this->setData(self::CUSTOMER_ID, $customerId); + return $this; + } + + /** + * Get entity pk value + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::getRelatedEntityId() + * @return int + */ + public function getEntityPkValue() + { + return $this->getRelatedEntityId(); + } + + /** + * Set entity pk value + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::setRelatedEntityId() + * @param int $entityPkValue + * @return RatingOptionVoteInterface + */ + public function setEntityPkValue($entityPkValue) + { + return $this->setRelatedEntityId($entityPkValue); + } + + /** + * @inheritdoc + */ + public function getRelatedEntityId(): ?int + { + return $this->_getData(self::RELATED_ENTITY_ID); + } + + /** + * @inheritdoc + */ + public function setRelatedEntityId(int $entityId): RatingOptionVoteInterface + { + $this->setData(self::RELATED_ENTITY_ID, $entityId); + return $this; + } + + /** + * @inheritdoc + */ + public function getRatingId(): ?int + { + return $this->_getData(self::RATING_ID); + } + + /** + * @inheritdoc + */ + public function setRatingId(int $ratingId): RatingOptionVoteInterface + { + $this->setData(self::RATING_ID, $ratingId); + return $this; + } + + /** + * @inheritdoc + */ + public function getReviewId(): ?int + { + return $this->_getData(self::REVIEW_ID); + } + + /** + * @inheritdoc + */ + public function setReviewId(int $reviewId): RatingOptionVoteInterface + { + $this->setData(self::REVIEW_ID, $reviewId); + return $this; + } + + /** + * @inheritdoc + */ + public function getPercent(): ?float + { + return $this->_getData(self::PERCENT); + } + + /** + * @inheritdoc + */ + public function setPercent(float $percent): RatingOptionVoteInterface + { + $this->setData(self::PERCENT, $percent); + return $this; + } + + /** + * Get rating code + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::getRatingName() + * @return string + */ + public function getRatingCode() + { + return $this->getRatingName(); + } + + /** + * Set rating code + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::setRatingName() + * @param string $ratingCode + * @return RatingOptionVoteInterface + */ + public function setRatingCode($ratingCode) + { + return $this->setRatingName($ratingCode); + } + + /** + * @inheritdoc + */ + public function getRatingName(): ?string + { + return $this->_getData(self::RATING_NAME); + } + + /** + * @inheritdoc + */ + public function setRatingName(?string $ratingName): RatingOptionVoteInterface + { + $this->setData(self::RATING_NAME, $ratingName); + return $this; + } + + /** + * Get value + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::getRatingValue() + * @return int + */ + public function getValue() + { + return $this->getRatingValue(); + } + + /** + * Set value + * + * @deprecated + * @see \Magento\Review\Model\Rating\Option\Vote::setRatingValue() + * @param int $value + * @return RatingOptionVoteInterface + */ + public function setValue($value) + { + return $this->setRatingValue($value); + } + + /** + * @inheritdoc + */ + public function getRatingValue(): int + { + return $this->_getData(self::RATING_VALUE); + } + + /** + * @inheritdoc + */ + public function setRatingValue(int $value): RatingOptionVoteInterface + { + $this->setData(self::RATING_VALUE, $value); + return $this; + } + + /** + * @inheritdoc + */ + public function getStoreId(): ?int + { + return $this->_getData(self::STORE_ID) ? (int)$this->_getData(self::STORE_ID) : null; + } + + /** + * @inheritdoc + */ + public function setStoreId($storeId): RatingOptionVoteInterface + { + $this->setData(self::STORE_ID, $storeId); + return$this; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): \Magento\ReviewApi\Api\Data\RatingOptionVoteExtensionInterface + { + $extensionAttributes = $this->_getExtensionAttributes(); + if (!$extensionAttributes) { + return $this->extensionAttributesFactory->create(RatingOptionVoteInterface::class); + } + return $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes( + \Magento\ReviewApi\Api\Data\RatingOptionVoteExtensionInterface $extensionAttributes + ): RatingOptionVoteInterface { + return $this->_setExtensionAttributes($extensionAttributes); + } } diff --git a/app/code/Magento/Review/Model/ResourceModel/Rating.php b/app/code/Magento/Review/Model/ResourceModel/Rating.php index 37a93d40b1107..d67009d3187c7 100644 --- a/app/code/Magento/Review/Model/ResourceModel/Rating.php +++ b/app/code/Magento/Review/Model/ResourceModel/Rating.php @@ -352,7 +352,7 @@ public function getEntitySummary($object, $onlyForCurrentStore = true) $clone = clone $object; $clone->setCount(0); $clone->setSum(0); - $clone->setStoreId($store->getId()); + $clone->setStoreId((int)$store->getId()); $result[$store->getId()] = $clone; } } @@ -479,7 +479,7 @@ public function getReviewSummary($object, $onlyForCurrentStore = true) $clone = clone $object; $clone->setCount(0); $clone->setSum(0); - $clone->setStoreId($store->getId()); + $clone->setStoreId((int)$store->getId()); $result[$store->getId()] = $clone; } } @@ -525,4 +525,28 @@ public function deleteAggregatedRatingsByProductId($productId) return $this; } + + /** + * Get rating id by name + * + * @param string $ratingName + * @param int $storeId + * @return int + */ + public function getRatingIdByName($ratingName, $storeId) + { + $select = $this->getConnection()->select()->from( + ['rating' => $this->getMainTable()], + ['rating_id'] + )->joinInner( + ['rating_store' => $this->getTable('rating_store')], + 'rating_store.rating_id = rating.rating_id AND store_id = :store_id', + [] + )->where( + 'rating_code = :rating_code' + )->where( + 'is_active = 1' + )->limit(1); + return (int)$this->getConnection()->fetchOne($select, [':rating_code' => $ratingName, ':store_id' => $storeId]); + } } diff --git a/app/code/Magento/Review/Model/ResourceModel/Rating/Collection.php b/app/code/Magento/Review/Model/ResourceModel/Rating/Collection.php index 0dcb9da6a8c75..e074099f7f84c 100644 --- a/app/code/Magento/Review/Model/ResourceModel/Rating/Collection.php +++ b/app/code/Magento/Review/Model/ResourceModel/Rating/Collection.php @@ -15,6 +15,11 @@ */ class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { + /** + * @var string + */ + protected $_idFieldName = 'rating_id'; + /** * @var \Magento\Store\Model\StoreManagerInterface */ @@ -331,4 +336,12 @@ public function setActiveFilter($isActive = true) $this->getSelect()->where('main_table.is_active=?', $isActive); return $this; } + + /** + * @inheritdoc + */ + protected function _toOptionHash($valueField = null, $labelField = 'rating_code') + { + return parent::_toOptionHash($valueField, $labelField); + } } diff --git a/app/code/Magento/Review/Model/ResourceModel/Rating/Option.php b/app/code/Magento/Review/Model/ResourceModel/Rating/Option.php index ef4acb6c90cb8..dde6e6fbfcc82 100644 --- a/app/code/Magento/Review/Model/ResourceModel/Rating/Option.php +++ b/app/code/Magento/Review/Model/ResourceModel/Rating/Option.php @@ -283,4 +283,28 @@ public function loadDataById($optionId) return $this->_optionData; } + + /** + * Get option id by rating id and value + * + * @param int $ratingId + * @param int $value + * @return int + */ + public function getOptionIdByRatingIdAndValue($ratingId, $value) + { + $select = $this->getConnection()->select()->from( + $this->getMainTable(), + ['option_id'] + )->where( + 'rating_id = :rating_id' + )->where( + 'value = :value' + ); + $binds = [ + ':rating_id' => $ratingId, + ':value' => $value + ]; + return (int)$this->getConnection()->fetchOne($select, $binds); + } } diff --git a/app/code/Magento/Review/Model/ResourceModel/Rating/Option/Collection.php b/app/code/Magento/Review/Model/ResourceModel/Rating/Option/Collection.php index 394eb5c3e077a..232521d16ec44 100644 --- a/app/code/Magento/Review/Model/ResourceModel/Rating/Option/Collection.php +++ b/app/code/Magento/Review/Model/ResourceModel/Rating/Option/Collection.php @@ -12,6 +12,11 @@ */ class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { + /** + * @var string + */ + protected $_idFieldName = 'option_id'; + /** * Rating votes table * @@ -60,4 +65,12 @@ public function setPositionOrder($dir = 'ASC') $this->setOrder('main_table.position', $dir); return $this; } + + /** + * @inheritdoc + */ + protected function _toOptionHash($valueField = null, $labelField = 'value') + { + return parent::_toOptionHash($valueField, $labelField); + } } diff --git a/app/code/Magento/Review/Model/ResourceModel/Review.php b/app/code/Magento/Review/Model/ResourceModel/Review.php index 2e08838e4c885..2944a1aea2e43 100644 --- a/app/code/Magento/Review/Model/ResourceModel/Review.php +++ b/app/code/Magento/Review/Model/ResourceModel/Review.php @@ -15,6 +15,13 @@ */ class Review extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { + /**#@+ + * Constants related to specific db layer + */ + const TABLE_NAME_REVIEW = 'review'; + const TABLE_NAME_REVIEW_DETAIL = 'review_detail'; + const TABLE_NAME_REVIEW_STORE = 'review_store'; + /** * Review table * @@ -375,7 +382,7 @@ protected function aggregateReviewSummary($object, $ratingSummaryObject) ->setEntityPkValue($object->getEntityPkValue()) ->setEntityType($object->getEntityId()) ->setRatingSummary($ratingSummary > 0 ? $ratingSummary : 0) - ->setStoreId($ratingSummaryObject->getStoreId()); + ->setStoreId((int)$ratingSummaryObject->getStoreId()); $this->writeReviewSummary($oldData, $data); } diff --git a/app/code/Magento/Review/Model/ResourceModel/Review/CreateMultiple.php b/app/code/Magento/Review/Model/ResourceModel/Review/CreateMultiple.php new file mode 100644 index 0000000000000..bf753fa6d39af --- /dev/null +++ b/app/code/Magento/Review/Model/ResourceModel/Review/CreateMultiple.php @@ -0,0 +1,191 @@ +resourceConnection = $resourceConnection; + $this->ratingsProcessor = $ratingsProcessor; + + $this->reviewTableName = $resourceConnection->getConnection()->getTableName( + ReviewResource::TABLE_NAME_REVIEW + ); + $this->reviewDetailTableName = $resourceConnection->getConnection()->getTableName( + ReviewResource::TABLE_NAME_REVIEW_DETAIL + ); + $this->reviewStoreTable = $resourceConnection->getConnection()->getTableName( + ReviewResource::TABLE_NAME_REVIEW_STORE + ); + + // TODO: remove when implementing review rating save using SQL QUERIES + $this->ratingFactory = ObjectManager::getInstance()->get(RatingFactory::class); + } + + /** + * Create reviews + * + * @param ReviewInterface[] $reviews + * @throws \Exception + */ + public function execute(array $reviews) + { + if (!count($reviews)) { + return; + } + + foreach ($reviews as $review) { + $this->insertReview($review); + + $stores = array_unique(array_merge($review->getStores(), [$review->getStoreId(), Store::DEFAULT_STORE_ID])); + $review->setStores($stores); + + $this->insertReviewDetail($review); + $this->insertReviewStores($review); + + if (!empty($review->getRatings())) { + $this->insertRatings($review); + } + } + } + + /** + * Insert review + * + * @param ReviewInterface $review + */ + private function insertReview(ReviewInterface $review) + { + $connection = $this->resourceConnection->getConnection(); + + $reviewBindData = [ + ReviewInterFace::REVIEW_ENTITY_ID => $review->getReviewEntityId(), + ReviewInterFace::RELATED_ENTITY_ID => $review->getRelatedEntityId(), + ReviewInterFace::STATUS => $review->getStatus() ?: Review::STATUS_PENDING, + ]; + + $connection->insert($this->reviewTableName, $reviewBindData); + + $reviewId = $connection->lastInsertId($this->reviewTableName); + $review->setReviewId($reviewId); + } + + /** + * Insert review detail + * + * @param ReviewInterface $review + */ + private function insertReviewDetail(ReviewInterface $review) + { + $connection = $this->resourceConnection->getConnection(); + + $reviewDetailBindData = [ + ReviewInterFace::REVIEW_ID => $review->getReviewId(), + ReviewInterFace::STORE_ID => $review->getStoreId(), + ReviewInterFace::TITLE => $review->getTitle(), + ReviewInterFace::REVIEW_TEXT => $review->getReviewText(), + ReviewInterFace::CUSTOMER_NICKNAME => $review->getCustomerNickname(), + ReviewInterFace::CUSTOMER_ID => $review->getCustomerId(), + ]; + + $connection->insert($this->reviewDetailTableName, $reviewDetailBindData); + } + + /** + * Insert review stores + * + * @param ReviewInterface $review + */ + private function insertReviewStores(ReviewInterface $review) + { + $connection = $this->resourceConnection->getConnection(); + + $reviewStoreBindData = []; + foreach ($review->getStores() as $storeId) { + $reviewStoreBindData[] = [ + ReviewInterFace::REVIEW_ID => $review->getReviewId(), + ReviewInterFace::STORE_ID => $storeId, + ]; + } + + $connection->insertMultiple($this->reviewStoreTable, $reviewStoreBindData); + } + + /** + * Insert ratings + * + * @param ReviewInterface $review + */ + private function insertRatings(ReviewInterface $review) + { + foreach ($review->getRatings() as $rating) { + $ratingId = $this->ratingsProcessor->getRatingIdByName($rating->getRatingName(), $review->getStoreId()); + $optionId = $this->ratingsProcessor->getOptionIdByRatingIdAndValue($ratingId, $rating->getRatingValue()); + + $rating->setRatingId($ratingId); + $rating->setRatingOptionId($optionId); + + $this->ratingFactory->create() + ->setRatingId($ratingId) + ->setReviewId($review->getReviewId()) + ->addOptionVote($optionId, $review->getRelatedEntityId()); + } + } +} diff --git a/app/code/Magento/Review/Model/ResourceModel/Review/DeleteMultiple.php b/app/code/Magento/Review/Model/ResourceModel/Review/DeleteMultiple.php new file mode 100644 index 0000000000000..ed10ec114df04 --- /dev/null +++ b/app/code/Magento/Review/Model/ResourceModel/Review/DeleteMultiple.php @@ -0,0 +1,70 @@ +resourceConnection = $resourceConnection; + } + + /** + * Multiple delete source items + * + * @param ReviewInterface[] $reviews + * @return void + */ + public function execute(array $reviews) + { + if (!count($reviews)) { + return; + } + + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(ReviewResource::TABLE_NAME_REVIEW); + $whereSql = $this->buildWhereSqlPart($reviews); + $connection->delete($tableName, $whereSql); + } + + /** + * Build where sql condition + * + * @param ReviewInterface[] $reviews + * @return array + */ + private function buildWhereSqlPart(array $reviews): array + { + $reviewIds = []; + foreach ($reviews as $review) { + $reviewIds[] = $review->getReviewId(); + } + + $conditionSql = sprintf('%s IN(?)', ReviewInterface::REVIEW_ID); + + return [$conditionSql => $reviewIds]; + } +} diff --git a/app/code/Magento/Review/Model/ResourceModel/Review/UpdateMultiple.php b/app/code/Magento/Review/Model/ResourceModel/Review/UpdateMultiple.php new file mode 100644 index 0000000000000..58ff5fd4fc53d --- /dev/null +++ b/app/code/Magento/Review/Model/ResourceModel/Review/UpdateMultiple.php @@ -0,0 +1,238 @@ +resourceConnection = $resourceConnection; + $this->ratingsProcessor = $ratingsProcessor; + + $this->reviewTableName = $resourceConnection->getConnection()->getTableName( + ReviewResource::TABLE_NAME_REVIEW + ); + $this->reviewDetailTableName = $resourceConnection->getConnection()->getTableName( + ReviewResource::TABLE_NAME_REVIEW_DETAIL + ); + $this->reviewStoreTable = $resourceConnection->getConnection()->getTableName( + ReviewResource::TABLE_NAME_REVIEW_STORE + ); + + // TODO: remove when implementing review rating save using SQL QUERIES + $this->ratingFactory = ObjectManager::getInstance()->get(RatingFactory::class); + $this->voteCollectionFactory = ObjectManager::getInstance()->get(VoteCollectionFactory::class); + } + + /** + * Create reviews + * + * @param ReviewInterface[] $reviews + * @throws \Exception + */ + public function execute(array $reviews) + { + if (!count($reviews)) { + return; + } + + foreach ($reviews as $review) { + $this->updateReview($review); + + $stores = array_unique(array_merge($review->getStores(), [$review->getStoreId(), Store::DEFAULT_STORE_ID])); + $review->setStores($stores); + + $this->updateReviewDetail($review); + $this->updateReviewStores($review); + + if (!empty($review->getRatings())) { + $this->updateRatings($review); + } + } + } + + /** + * Update review + * + * @param ReviewInterface $review + */ + private function updateReview(ReviewInterface $review) + { + $connection = $this->resourceConnection->getConnection(); + + $reviewBindData = [ + ReviewInterFace::STATUS => $review->getStatus() ?: Review::STATUS_PENDING, + ]; + $where = sprintf( + '%s=%d', + $connection->quoteIdentifier(ReviewInterFace::REVIEW_ID), + $review->getReviewId() + ); + + $connection->update($this->reviewTableName, $reviewBindData, $where); + } + + /** + * Update review detail + * + * @param ReviewInterface $review + */ + private function updateReviewDetail(ReviewInterface $review) + { + $connection = $this->resourceConnection->getConnection(); + + $reviewDetailBindData = [ + ReviewInterFace::TITLE => $review->getTitle(), + ReviewInterFace::REVIEW_TEXT => $review->getReviewText(), + ReviewInterFace::CUSTOMER_NICKNAME => $review->getCustomerNickname(), + ]; + $where = sprintf( + '%s=%d', + $connection->quoteIdentifier(ReviewInterFace::REVIEW_ID), + $review->getReviewId() + ); + + $connection->update($this->reviewDetailTableName, $reviewDetailBindData, $where); + } + + /** + * Update review stores + * + * @param ReviewInterface $review + */ + private function updateReviewStores(ReviewInterface $review) + { + $this->deleteReviewStores($review); + $this->insertReviewStores($review); + } + + /** + * Delete review store data + * + * @param ReviewInterface $review + */ + private function deleteReviewStores(ReviewInterface $review) + { + $connection = $this->resourceConnection->getConnection(); + + $where = sprintf('%s=%d', ReviewInterface::REVIEW_ID, $review->getReviewId()); + $connection->delete($this->reviewStoreTable, $where); + } + + /** + * Insert review stores + * + * @param ReviewInterface $review + */ + private function insertReviewStores(ReviewInterface $review) + { + $connection = $this->resourceConnection->getConnection(); + + $reviewStoreBindData = []; + foreach ($review->getStores() as $storeId) { + $reviewStoreBindData[] = [ + ReviewInterFace::REVIEW_ID => $review->getReviewId(), + ReviewInterFace::STORE_ID => $storeId, + ]; + } + + $connection->insertMultiple($this->reviewStoreTable, $reviewStoreBindData); + } + + /** + * Update ratings + * + * @param ReviewInterface $review + */ + private function updateRatings(ReviewInterface $review) + { + $votes = $this->voteCollectionFactory->create() + ->setReviewFilter($review->getReviewId()) + ->addOptionInfo() + ->load() + ->addRatingOptions(); + + foreach ($review->getRatings() as $rating) { + $ratingId = $this->ratingsProcessor->getRatingIdByName($rating->getRatingName(), $review->getStoreId()); + $optionId = $this->ratingsProcessor->getOptionIdByRatingIdAndValue($ratingId, $rating->getRatingValue()); + + $rating->setRatingId($ratingId); + $rating->setRatingOptionId($optionId); + + if ($vote = $votes->getItemByColumnValue('rating_id', $ratingId)) { + $this->ratingFactory->create() + ->setVoteId($vote->getId()) + ->setReviewId($review->getReviewId()) + ->updateOptionVote($optionId); + } else { + $this->ratingFactory->create() + ->setRatingId($ratingId) + ->setReviewId($review->getReviewId()) + ->addOptionVote($optionId, $review->getRelatedEntityId()); + } + } + } +} diff --git a/app/code/Magento/Review/Model/Review.php b/app/code/Magento/Review/Model/Review.php index e689d4ed460ac..125573f8c683c 100644 --- a/app/code/Magento/Review/Model/Review.php +++ b/app/code/Magento/Review/Model/Review.php @@ -3,37 +3,38 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Model; use Magento\Framework\DataObject; -use Magento\Catalog\Model\Product; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Data\Collection\AbstractDb; use Magento\Framework\DataObject\IdentityInterface; -use Magento\Review\Model\ResourceModel\Review\Product\Collection as ProductCollection; +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\Framework\Model\Context; +use Magento\Framework\Model\ResourceModel\AbstractResource; +use Magento\Framework\Registry; +use Magento\Framework\UrlInterface; +use Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory as ProductCollectionFactory; use Magento\Review\Model\ResourceModel\Review\Status\Collection as StatusCollection; +use Magento\Review\Model\ResourceModel\Review\Status\CollectionFactory as StatusCollectionFactory; +use Magento\Review\Model\ResourceModel\Review\Summary\CollectionFactory as SummaryCollectionFactory; +use Magento\Review\Model\Review\Summary; +use Magento\Review\Model\Review\SummaryFactory; +use Magento\ReviewApi\Api\Data\ReviewExtensionInterface; +use Magento\ReviewApi\Api\Data\ReviewInterface; +use Magento\ReviewApi\Model\AggregatorInterface; +use Magento\ReviewApi\Model\ReviewValidatorInterface; +use Magento\Store\Model\StoreManagerInterface; /** * Review model - * - * @api - * @method string getCreatedAt() - * @method \Magento\Review\Model\Review setCreatedAt(string $value) - * @method \Magento\Review\Model\Review setEntityId(int $value) - * @method int getEntityPkValue() - * @method \Magento\Review\Model\Review setEntityPkValue(int $value) - * @method int getStatusId() - * @method \Magento\Review\Model\Review setStatusId(int $value) - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @since 100.0.2 */ -class Review extends \Magento\Framework\Model\AbstractModel implements IdentityInterface +class Review extends AbstractExtensibleModel implements IdentityInterface, ReviewInterface { - /** - * Event prefix for observer - * - * @var string - */ - protected $_eventPrefix = 'review'; - /** * Cache tag */ @@ -69,83 +70,114 @@ class Review extends \Magento\Framework\Model\AbstractModel implements IdentityI */ const STATUS_NOT_APPROVED = 3; + /** + * Event prefix for observer + * + * @var string + */ + protected $_eventPrefix = 'review'; + + /** + * @var + */ + protected $ratings; + /** * Review product collection factory * - * @var \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory + * @var ProductCollectionFactory */ protected $productCollectionFactory; /** * Review status collection factory * - * @var \Magento\Review\Model\ResourceModel\Review\Status\CollectionFactory + * @var StatusCollectionFactory */ protected $_statusFactory; /** - * Review model summary factory + * Review summary collection factory * - * @var \Magento\Review\Model\Review\SummaryFactory + * @var SummaryCollectionFactory */ protected $_summaryFactory; /** * Review model summary factory * - * @var \Magento\Review\Model\Review\SummaryFactory + * @var SummaryFactory */ protected $_summaryModFactory; /** * Review model summary * - * @var \Magento\Review\Model\Review\Summary + * @var Summary */ protected $_reviewSummary; /** * Core model store manager interface * - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ protected $_storeManager; /** * Url interface * - * @var \Magento\Framework\UrlInterface + * @var UrlInterface */ protected $_urlModel; /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory $productFactory - * @param \Magento\Review\Model\ResourceModel\Review\Status\CollectionFactory $statusFactory - * @param \Magento\Review\Model\ResourceModel\Review\Summary\CollectionFactory $summaryFactory - * @param \Magento\Review\Model\Review\SummaryFactory $summaryModFactory - * @param \Magento\Review\Model\Review\Summary $reviewSummary - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\UrlInterface $urlModel - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @var AggregatorInterface + */ + private $reviewAggregator; + + /** + * @var ReviewValidatorInterface + */ + private $reviewValidator; + + /** + * Review constructor + * + * @param Context $context + * @param Registry $registry + * @param ProductCollectionFactory $productFactory + * @param StatusCollectionFactory $statusFactory + * @param SummaryCollectionFactory $summaryFactory + * @param SummaryFactory $summaryModFactory + * @param Summary $reviewSummary + * @param StoreManagerInterface $storeManager + * @param UrlInterface $urlModel + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data - * @SuppressWarnings(PHPMD.ExcessiveParameterList) + * @param ExtensionAttributesFactory $extensionFactory + * @param AttributeValueFactory $customAttributeFactory + * @param AggregatorInterface|null $reviewAggregator + * @param ReviewValidatorInterface|null $reviewValidator */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory $productFactory, - \Magento\Review\Model\ResourceModel\Review\Status\CollectionFactory $statusFactory, - \Magento\Review\Model\ResourceModel\Review\Summary\CollectionFactory $summaryFactory, - \Magento\Review\Model\Review\SummaryFactory $summaryModFactory, - \Magento\Review\Model\Review\Summary $reviewSummary, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\UrlInterface $urlModel, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + Context $context, + Registry $registry, + ProductCollectionFactory $productFactory, + StatusCollectionFactory $statusFactory, + SummaryCollectionFactory $summaryFactory, + SummaryFactory $summaryModFactory, + Summary $reviewSummary, + StoreManagerInterface $storeManager, + UrlInterface $urlModel, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null, + AggregatorInterface $reviewAggregator = null, + ReviewValidatorInterface $reviewValidator = null ) { $this->productCollectionFactory = $productFactory; $this->_statusFactory = $statusFactory; @@ -154,13 +186,29 @@ public function __construct( $this->_reviewSummary = $reviewSummary; $this->_storeManager = $storeManager; $this->_urlModel = $urlModel; - parent::__construct($context, $registry, $resource, $resourceCollection, $data); + $this->reviewAggregator = $reviewAggregator + ?: ObjectManager::getInstance()->get(AggregatorInterface::class); + $this->reviewValidator = $reviewValidator + ?: ObjectManager::getInstance()->get(ReviewValidatorInterface::class); + + $extensionFactory = $extensionFactory + ?: ObjectManager::getInstance()->get(ExtensionAttributesFactory::class); + $customAttributeFactory = $customAttributeFactory + ?: ObjectManager::getInstance()->get(AttributeValueFactory::class); + + parent::__construct( + $context, + $registry, + $extensionFactory, + $customAttributeFactory, + $resource, + $resourceCollection, + $data + ); } /** - * Initialization - * - * @return void + * @inheritdoc */ protected function _construct() { @@ -168,174 +216,400 @@ protected function _construct() } /** - * Get product collection - * - * @return ProductCollection + * @inheritdoc */ - public function getProductCollection() + public function afterDeleteCommit() { - return $this->productCollectionFactory->create(); + $this->getResource()->afterDeleteCommit($this); + return parent::afterDeleteCommit(); } /** - * Get status collection - * - * @return StatusCollection + * @inheritdoc */ - public function getStatusCollection() + public function getReviewId() { - return $this->_statusFactory->create(); + return $this->_getData(self::REVIEW_ID); } /** - * Get total reviews - * - * @param int $entityPkValue - * @param bool $approvedOnly - * @param int $storeId - * @return int + * @inheritdoc */ - public function getTotalReviews($entityPkValue, $approvedOnly = false, $storeId = 0) + public function setReviewId($reviewId): ReviewInterface { - return $this->getResource()->getTotalReviews($entityPkValue, $approvedOnly, $storeId); + $this->setData(self::REVIEW_ID, $reviewId); + return$this; } /** - * Aggregate reviews + * @inheritdoc + */ + public function getStoreId(): ?int + { + return $this->_getData(self::STORE_ID) ? (int)$this->_getData(self::STORE_ID) : null; + } + + /** + * @inheritdoc + */ + public function setStoreId($storeId): ReviewInterface + { + $this->setData(self::STORE_ID, $storeId); + return$this; + } + + /** + * @inheritdoc + */ + public function getStores(): array + { + return $this->_getData(self::STORES) ?: []; + } + + /** + * @inheritdoc + */ + public function setStores(array $stores): ReviewInterface + { + $this->setData(self::STORES, $stores); + return $this; + } + + /** + * @inheritdoc + */ + public function getTitle(): string + { + return $this->_getData(self::TITLE); + } + + /** + * @inheritdoc + */ + public function setTitle(string $title): ReviewInterface + { + $this->setData(self::TITLE, $title); + return$this; + } + + /** + * @inheritdoc + */ + public function getReviewText(): string + { + return $this->_getData(self::REVIEW_TEXT); + } + + /** + * @inheritdoc + */ + public function setReviewText(string $text): ReviewInterface + { + $this->setData(self::REVIEW_TEXT, $text); + return$this; + } + + /** + * Set review detail * + * @param string $text + * @deprecated + * @see \Magento\Review\Model\Review::setReviewText * @return $this */ - public function aggregate() + public function setDetail($text) { - $this->getResource()->aggregate($this); + $this->setReviewText($text); return $this; } /** - * Get entity summary - * - * @param Product $product - * @param int $storeId - * @return void + * @inheritdoc */ - public function getEntitySummary($product, $storeId = 0) + public function getCustomerNickname(): string { - $summaryData = $this->_summaryModFactory->create()->setStoreId($storeId)->load($product->getId()); - $summary = new \Magento\Framework\DataObject(); - $summary->setData($summaryData->getData()); - $product->setRatingSummary($summary); + return $this->_getData(self::CUSTOMER_NICKNAME); } /** - * Get pending status + * @inheritdoc + */ + public function setCustomerNickname(string $nickname): ReviewInterface + { + $this->setData(self::CUSTOMER_NICKNAME, $nickname); + return$this; + } + + /** + * Set customer nickname * - * @return int + * @param string $nickname + * @deprecated + * @see \Magento\Review\Model\Review::setCustomerNickname + * @return $this */ - public function getPendingStatus() + public function setNickname($nickname) { - return self::STATUS_PENDING; + $this->setCustomerNickname($nickname); + return $this; } /** - * Get review product view url + * @inheritdoc + */ + public function getCustomerId(): ?int + { + return $this->_getData(self::CUSTOMER_ID); + } + + /** + * @inheritdoc + */ + public function setCustomerId(?int $customerId): ReviewInterface + { + $this->setData(self::CUSTOMER_ID, $customerId); + return$this; + } + + /** + * @inheritdoc + */ + public function getReviewEntityId(): int + { + return (int)$this->_getData(self::REVIEW_ENTITY_ID); + } + + /** + * @inheritdoc + */ + public function setReviewEntityId(int $entityId): ReviewInterface + { + $this->setData(self::REVIEW_ENTITY_ID, $entityId); + return$this; + } + + /** + * Set entity pk value * - * @return string + * @deprecated + * @see \Magento\Review\Model\Review::setReviewEntityId + * @param int $entityType + * @return $this */ - public function getReviewUrl() + public function setEntityType($entityType) { - return $this->_urlModel->getUrl('review/product/view', ['id' => $this->getReviewId()]); + $this->setReviewEntityId((int)$entityType); + return $this; } /** - * Get product view url + * @inheritdoc + */ + public function getRelatedEntityId(): int + { + return (int)$this->_getData(self::RELATED_ENTITY_ID); + } + + /** + * @inheritdoc + */ + public function setRelatedEntityId(int $entityId): ReviewInterface + { + $this->setData(self::RELATED_ENTITY_ID, $entityId); + return$this; + } + + /** + * Set entity pk value * - * @param string|int $productId - * @param string|int $storeId - * @return string + * @deprecated + * @see \Magento\Review\Model\Review::setRelatedEntityId + * @param int $entityPkValue + * @return $this */ - public function getProductUrl($productId, $storeId) + public function setEntityPkValue($entityPkValue) { - if ($storeId) { - $this->_urlModel->setScope($storeId); - } + $this->setRelatedEntityId((int)$entityPkValue); + return $this; + } - return $this->_urlModel->getUrl('catalog/product/view', ['id' => $productId]); + /** + * @inheritdoc + */ + public function getStatus(): int + { + return (int)$this->_getData(self::STATUS); + } + + /** + * @inheritdoc + */ + public function setStatus(int $status): ReviewInterface + { + $this->setData(self::STATUS, $status); + return$this; } /** - * Validate review summary fields + * Set status id * - * @return bool|string[] + * @deprecated + * @see \Magento\Review\Model\Review::setStatus + * @param int $statusId + * @return $this */ - public function validate() + public function setStatusId($statusId) + { + $this->setStatus((int)$statusId); + return $this; + } + + /** + * @inheritdoc + */ + public function getCreatedAt(): ?string { - $errors = []; + return $this->_getData(self::CREATED_AT); + } - if (!\Zend_Validate::is($this->getTitle(), 'NotEmpty')) { - $errors[] = __('Please enter a review summary.'); - } + /** + * @inheritdoc + */ + public function setCreatedAt(?string $createdAt): ReviewInterface + { + $this->setData(self::CREATED_AT, $createdAt); + return$this; + } - if (!\Zend_Validate::is($this->getNickname(), 'NotEmpty')) { - $errors[] = __('Please enter a nickname.'); - } + /** + * @inheritdoc + */ + public function getUpdatedAt(): ?string + { + return $this->_getData(self::UPDATED_AT); + } - if (!\Zend_Validate::is($this->getDetail(), 'NotEmpty')) { - $errors[] = __('Please enter a review.'); - } + /** + * @inheritdoc + */ + public function setUpdatedAt(?string $updatedAt): ReviewInterface + { + $this->setData(self::UPDATED_AT, $updatedAt); + return$this; + } - if (empty($errors)) { - return true; - } - return $errors; + /** + * @inheritdoc + */ + public function getRatings(): array + { + return $this->_getData(self::RATINGS) ?: []; } /** - * Perform actions after object delete + * Set rating votes * - * @return \Magento\Framework\Model\AbstractModel + * @deprecated + * @see \Magento\Review\Model\Review::getRatings + * @return array */ - public function afterDeleteCommit() + public function getRatingVotes() { - $this->getResource()->afterDeleteCommit($this); - return parent::afterDeleteCommit(); + return $this->getRatings(); } /** - * Append review summary to product collection + * @inheritdoc + */ + public function setRatings(array $ratings): ReviewInterface + { + $this->setData(self::RATINGS, $ratings); + return$this; + } + + /** + * Set rating votes * - * @param ProductCollection $collection - * @return $this + * @param \Magento\Review\Model\ResourceModel\Rating\Option\Vote\Collection|array $ratingVotes + * @deprecated + * @see \Magento\Review\Model\Review::setRatings + * @return ReviewInterface */ - public function appendSummary($collection) + public function setRatingVotes($ratingVotes) { - $entityIds = []; - foreach ($collection->getItems() as $item) { - $entityIds[] = $item->getEntityId(); - } + return $this->setRatings($ratingVotes->getItems()); + } - if (sizeof($entityIds) == 0) { - return $this; + /** + * @inheritdoc + */ + public function getExtensionAttributes(): ReviewExtensionInterface + { + $extensionAttributes = $this->_getExtensionAttributes(); + if (!$extensionAttributes) { + return $this->extensionAttributesFactory->create(ReviewInterface::class); } + return $extensionAttributes; + } - $summaryData = $this->_summaryFactory->create() - ->addEntityFilter($entityIds) - ->addStoreFilter($this->_storeManager->getStore()->getId()) - ->load(); + /** + * @inheritdoc + */ + public function setExtensionAttributes( + ReviewExtensionInterface $extensionAttributes + ): ReviewInterface { + return $this->_setExtensionAttributes($extensionAttributes); + } - foreach ($collection->getItems() as $item) { - foreach ($summaryData as $summary) { - if ($summary->getEntityPkValue() == $item->getEntityId()) { - $item->setRatingSummary($summary); - } - } - if (!$item->getRatingSummary()) { - $item->setRatingSummary(new DataObject()); - } + /** + * Return unique ID(s) for each object in system + * + * @return array + */ + public function getIdentities() + { + $tags = []; + if ($this->getRelatedEntityId()) { + $tags[] = \Magento\Catalog\Model\Product::CACHE_TAG . '_' . $this->getRelatedEntityId(); } + return $tags; + } + + /** + * Validate review data + * + * @return bool|string[] + */ + public function validate() + { + $validationResult = $this->reviewValidator->validate($this); + if ($validationResult->isValid()) { + return true; + } + return $validationResult->getErrors(); + } + /** + * Aggregate reviews + * + * @return $this + */ + public function aggregate() + { + $this->reviewAggregator->aggregate($this); return $this; } + /** + * Get pending status + * + * @return int + */ + public function getPendingStatus() + { + return self::STATUS_PENDING; + } + /** * Check if current review approved or not * @@ -343,7 +617,27 @@ public function appendSummary($collection) */ public function isApproved() { - return $this->getStatusId() == self::STATUS_APPROVED; + return $this->getStatus() == self::STATUS_APPROVED; + } + + /** + * Check if current review is pending approval + * + * @return bool + */ + public function isPending() + { + return $this->getStatus() == self::STATUS_PENDING; + } + + /** + * Check if current review is rejected + * + * @return bool + */ + public function isRejected() + { + return $this->getStatus() == self::STATUS_NOT_APPROVED; } /** @@ -351,6 +645,7 @@ public function isApproved() * * @param int|\Magento\Store\Model\Store $store * @return bool + * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function isAvailableOnStore($store = null) { @@ -373,16 +668,113 @@ public function getEntityIdByCode($entityCode) } /** - * Return unique ID(s) for each object in system + * Get total reviews * - * @return array + * @param int $relatedEntityId + * @param bool $approvedOnly + * @param int $storeId + * @return int */ - public function getIdentities() + public function getTotalReviews($relatedEntityId, $approvedOnly = false, $storeId = 0) { - $tags = []; - if ($this->getEntityPkValue()) { - $tags[] = Product::CACHE_TAG . '_' . $this->getEntityPkValue(); + return $this->getResource()->getTotalReviews($relatedEntityId, $approvedOnly, $storeId); + } + + /** + * Get status collection + * + * @return StatusCollection + */ + public function getStatusCollection() + { + return $this->_statusFactory->create(); + } + + /** + * Get product collection + * + * @return \Magento\Review\Model\ResourceModel\Review\Product\Collection + */ + public function getProductCollection() + { + return $this->productCollectionFactory->create(); + } + + /** + * Get product view url + * + * @param string|int $productId + * @param string|int $storeId + * @return string + */ + public function getProductUrl($productId, $storeId) + { + if ($storeId) { + $this->_urlModel->setScope($storeId); } - return $tags; + + return $this->_urlModel->getUrl('catalog/product/view', ['id' => $productId]); + } + + /** + * Get review product view url + * + * @return string + */ + public function getReviewUrl() + { + return $this->_urlModel->getUrl('review/product/view', ['id' => $this->getReviewId()]); + } + + /** + * Get entity summary + * + * @param \Magento\Catalog\Model\Product $product + * @param int $storeId + * @return void + */ + public function getEntitySummary($product, $storeId = 0) + { + $summaryData = $this->_summaryModFactory->create()->setStoreId((int)$storeId)->load($product->getId()); + $summary = new \Magento\Framework\DataObject(); + $summary->setData($summaryData->getData()); + $product->setRatingSummary($summary); + } + + /** + * Append review summary to product collection + * + * @param \Magento\Review\Model\ResourceModel\Review\Product\Collection $collection + * @return $this + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ + public function appendSummary($collection) + { + $entityIds = []; + foreach ($collection->getItems() as $item) { + $entityIds[] = $item->getEntityId(); + } + + if (sizeof($entityIds) == 0) { + return $this; + } + + $summaryData = $this->_summaryFactory->create() + ->addEntityFilter($entityIds) + ->addStoreFilter($this->_storeManager->getStore()->getId()) + ->load(); + + foreach ($collection->getItems() as $item) { + foreach ($summaryData as $summary) { + if ($summary->getEntityPkValue() == $item->getEntityId()) { + $item->setRatingSummary($summary); + } + } + if (!$item->getRatingSummary()) { + $item->setRatingSummary(new DataObject()); + } + } + + return $this; } } diff --git a/app/code/Magento/Review/Model/Review/RatingsProcessor.php b/app/code/Magento/Review/Model/Review/RatingsProcessor.php new file mode 100644 index 0000000000000..5d634ea4fdb2b --- /dev/null +++ b/app/code/Magento/Review/Model/Review/RatingsProcessor.php @@ -0,0 +1,87 @@ +ratingCollectionFactory = $ratingCollectionFactory; + $this->ratingOptionCollectionFactory = $ratingOptionCollectionFactory; + } + + /** + * @inheritdoc + */ + public function getRatingIdByName(string $ratingName, int $storeId): ?int + { + if (!isset($this->ratingsByStore[$storeId])) { + $collection = $this->ratingCollectionFactory->create(); + $collection->setStoreFilter($storeId); + + $this->ratingsByStore[$storeId] = $collection->toOptionHash(); + } + + $ratingId = array_search($ratingName, $this->ratingsByStore[$storeId]); + + return $ratingId !== false ? (int)$ratingId : null; + } + + /** + * @inheritdoc + */ + public function getOptionIdByRatingIdAndValue(int $ratingId, int $value): ?int + { + if (!isset($this->ratingOptionsByRating[$ratingId])) { + $collection = $this->ratingOptionCollectionFactory->create(); + $collection->addRatingFilter($ratingId); + + $this->ratingOptionsByRating[$ratingId] = $collection->toOptionHash(); + } + + $optionId = array_search($value, $this->ratingOptionsByRating[$ratingId]); + + return $optionId !== false ? (int)$optionId : null; + } +} diff --git a/app/code/Magento/Review/Model/Review/RatingsProcessorInterface.php b/app/code/Magento/Review/Model/Review/RatingsProcessorInterface.php new file mode 100644 index 0000000000000..26075c6192fb4 --- /dev/null +++ b/app/code/Magento/Review/Model/Review/RatingsProcessorInterface.php @@ -0,0 +1,34 @@ + - * @codeCoverageIgnore */ -namespace Magento\Review\Model\Review; - -class Status extends \Magento\Framework\Model\AbstractModel +class Status extends AbstractExtensibleModel implements ReviewStatusInterface { /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * Status constructor + * + * @param Context $context + * @param Registry $registry + * @param AbstractResource $resource + * @param AbstractDb $resourceCollection * @param array $data + * @param ExtensionAttributesFactory|null $extensionFactory + * @param AttributeValueFactory|null $customAttributeFactory */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, - \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + Context $context, + Registry $registry, + AbstractResource $resource = null, + AbstractDb $resourceCollection = null, + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null ) { - parent::__construct($context, $registry, $resource, $resourceCollection, $data); + $extensionFactory = $extensionFactory + ?: ObjectManager::getInstance()->get(ExtensionAttributesFactory::class); + $customAttributeFactory = $customAttributeFactory + ?: ObjectManager::getInstance()->get(AttributeValueFactory::class); + + parent::__construct( + $context, + $registry, + $extensionFactory, + $customAttributeFactory, + $resource, + $resourceCollection, + $data + ); + } + + /** + * @inheritdoc + */ + protected function _construct() + { $this->_init(\Magento\Review\Model\ResourceModel\Review\Status::class); } + + /** + * @inheritdoc + */ + public function getStatusId(): ?int + { + return $this->_getData(self::STATUS_ID); + } + + /** + * @inheritdoc + */ + public function setStatusId(?int $statusId): ReviewStatusInterface + { + $this->setData(self::STATUS_ID, $statusId); + return $this; + } + + /** + * @inheritdoc + */ + public function getStatusCode(): string + { + return $this->_getData(self::STATUS_CODE); + } + + /** + * @inheritdoc + */ + public function setStatusCode(string $statusCode): ReviewStatusInterface + { + $this->setData(self::STATUS_CODE, $statusCode); + return $this; + } + + /** + * @inheritdoc + */ + public function getExtensionAttributes(): \Magento\ReviewApi\Api\Data\ReviewStatusExtensionInterface + { + $extensionAttributes = $this->_getExtensionAttributes(); + if (!$extensionAttributes) { + return $this->extensionAttributesFactory->create(ReviewStatusInterface::class); + } + return $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes( + \Magento\ReviewApi\Api\Data\ReviewStatusExtensionInterface $extensionAttributes + ): ReviewStatusInterface { + return $this->_setExtensionAttributes($extensionAttributes); + } } diff --git a/app/code/Magento/Review/Model/Review/Summary.php b/app/code/Magento/Review/Model/Review/Summary.php index 792dc531d9d97..7e8426e1c00ce 100644 --- a/app/code/Magento/Review/Model/Review/Summary.php +++ b/app/code/Magento/Review/Model/Review/Summary.php @@ -3,62 +3,200 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Review\Model\Review; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Model\AbstractExtensibleModel; +use Magento\Framework\Model\Context; +use Magento\Framework\Registry; +use Magento\Review\Model\ResourceModel\Review\Summary as ReviewSummaryResource; +use Magento\Review\Model\ResourceModel\Review\Summary\Collection as ReviewSummaryCollection; +use Magento\ReviewApi\Api\Data\ReviewSummaryInterface; + /** * Review summary - * - * @api - * - * @codeCoverageIgnore - * @since 100.0.2 */ -class Summary extends \Magento\Framework\Model\AbstractModel +class Summary extends AbstractExtensibleModel implements ReviewSummaryInterface { /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Review\Model\ResourceModel\Review\Summary $resource - * @param \Magento\Review\Model\ResourceModel\Review\Summary\Collection $resourceCollection + * Summary constructor + * + * @param Context $context + * @param Registry $registry + * @param ReviewSummaryResource $resource + * @param ReviewSummaryCollection $resourceCollection * @param array $data + * @param ExtensionAttributesFactory|null $extensionFactory + * @param AttributeValueFactory|null $customAttributeFactory */ public function __construct( - \Magento\Framework\Model\Context $context, - \Magento\Framework\Registry $registry, - \Magento\Review\Model\ResourceModel\Review\Summary $resource, - \Magento\Review\Model\ResourceModel\Review\Summary\Collection $resourceCollection, - array $data = [] + Context $context, + Registry $registry, + ReviewSummaryResource $resource, + ReviewSummaryCollection $resourceCollection, + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null ) { - parent::__construct($context, $registry, $resource, $resourceCollection, $data); + $extensionFactory = $extensionFactory + ?: ObjectManager::getInstance()->get(ExtensionAttributesFactory::class); + $customAttributeFactory = $customAttributeFactory + ?: ObjectManager::getInstance()->get(AttributeValueFactory::class); + + parent::__construct( + $context, + $registry, + $extensionFactory, + $customAttributeFactory, + $resource, + $resourceCollection, + $data + ); } /** - * Get entity primary key value - * - * @return int + * @inheritdoc */ - public function getEntityPkValue() + protected function _construct() { - return $this->_getData('entity_pk_value'); + $this->_init(\Magento\Review\Model\ResourceModel\Review\Summary::class); } /** - * Get rating summary data - * - * @return string + * @inheritdoc + */ + public function getPrimaryId(): ?int + { + return $this->_getData(self::PRIMARY_ID); + } + + /** + * @inheritdoc + */ + public function setPrimaryId(?int $primaryId): ReviewSummaryInterface + { + $this->setData(self::PRIMARY_ID, $primaryId); + return$this; + } + + /** + * @inheritdoc + */ + public function getRelatedEntityId(): int + { + return (int)$this->_getData(self::RELATED_ENTITY_ID); + } + + /** + * @inheritdoc + */ + public function setRelatedEntityId(int $entityId): ReviewSummaryInterface + { + $this->setData(self::RELATED_ENTITY_ID, $entityId); + return$this; + } + + /** + * @inheritdoc + */ + public function getRelatedEntityTypeId(): int + { + return (int)$this->_getData(self::RELATED_ENTITY_TYPE_ID); + } + + /** + * @inheritdoc + */ + public function setRelatedEntityTypeId(int $entityTypeId): ReviewSummaryInterface + { + $this->setData(self::RELATED_ENTITY_TYPE_ID, $entityTypeId); + return$this; + } + + /** + * @inheritdoc + */ + public function getReviewsCount() + { + return (int)$this->_getData(self::REVIEWS_COUNT); + } + + /** + * @inheritdoc + */ + public function setReviewsCount($count) + { + $this->setData(self::REVIEWS_COUNT, $count); + return$this; + } + + /** + * @inheritdoc */ public function getRatingSummary() { - return $this->_getData('rating_summary'); + return (int)$this->_getData(self::RATING_SUMMARY); + } + + /** + * @inheritdoc + */ + public function setRatingSummary($summary) + { + $this->setData(self::RATING_SUMMARY, $summary); + return$this; + } + + /** + * @inheritdoc + */ + public function getStoreId(): ?int + { + return $this->_getData(self::STORE_ID) ? (int)$this->_getData(self::STORE_ID) : null; + } + + /** + * @inheritdoc + */ + public function setStoreId($storeId): ReviewSummaryInterface + { + $this->setData(self::STORE_ID, $storeId); + return$this; } /** - * Get count of reviews + * @inheritdoc + */ + public function getExtensionAttributes(): \Magento\ReviewApi\Api\Data\ReviewSummaryExtensionInterface + { + $extensionAttributes = $this->_getExtensionAttributes(); + if (!$extensionAttributes) { + return $this->extensionAttributesFactory->create(ReviewSummaryInterface::class); + } + return $extensionAttributes; + } + + /** + * @inheritdoc + */ + public function setExtensionAttributes( + \Magento\ReviewApi\Api\Data\ReviewSummaryExtensionInterface $extensionAttributes + ): ReviewSummaryInterface { + return $this->_setExtensionAttributes($extensionAttributes); + } + + /** + * Get entity primary key value * + * @deprecated * @return int */ - public function getReviewsCount() + public function getEntityPkValue() { - return $this->_getData('reviews_count'); + return $this->getRelatedEntityId(); } } diff --git a/app/code/Magento/Review/Model/Validator/CustomerNickname.php b/app/code/Magento/Review/Model/Validator/CustomerNickname.php new file mode 100644 index 0000000000000..0d51ce2d27137 --- /dev/null +++ b/app/code/Magento/Review/Model/Validator/CustomerNickname.php @@ -0,0 +1,48 @@ +validationResultFactory = $validationResultFactory; + } + + /** + * @inheritdoc + */ + public function validate(ReviewInterface $review): ValidationResult + { + $errors = []; + if (!\Zend_Validate::is($review->getCustomerNickname(), 'NotEmpty')) { + $errors[] = __('Nickname can not be empty.'); + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/Review/Model/Validator/Ratings.php b/app/code/Magento/Review/Model/Validator/Ratings.php new file mode 100644 index 0000000000000..7e2a1aa68a224 --- /dev/null +++ b/app/code/Magento/Review/Model/Validator/Ratings.php @@ -0,0 +1,75 @@ +validationResultFactory = $validationResultFactory; + $this->reviewRatingsProcessor = $ratingsProcessor; + } + + /** + * @inheritdoc + */ + public function validate(ReviewInterface $review): ValidationResult + { + $errors = []; + foreach ($review->getRatings() as $rating) { + $ratingId = $this->reviewRatingsProcessor->getRatingIdByName( + $rating->getRatingName(), + $review->getStoreId() + ); + if (!$ratingId) { + $errors[] = __( + 'Invalid rating name "%1" for store %2', + $rating->getRatingName(), + $review->getStoreId() + ); + } + + $optionId = $this->reviewRatingsProcessor->getOptionIdByRatingIdAndValue( + $ratingId, + $rating->getRatingValue() + ); + if (!$optionId) { + $errors[] = __('Invalid value for rating "%1"', $rating->getRatingName()); + } + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/Review/Model/Validator/ReviewText.php b/app/code/Magento/Review/Model/Validator/ReviewText.php new file mode 100644 index 0000000000000..d92b65505fa92 --- /dev/null +++ b/app/code/Magento/Review/Model/Validator/ReviewText.php @@ -0,0 +1,48 @@ +validationResultFactory = $validationResultFactory; + } + + /** + * @inheritdoc + */ + public function validate(ReviewInterface $review): ValidationResult + { + $errors = []; + if (!\Zend_Validate::is($review->getReviewText(), 'NotEmpty')) { + $errors[] = __('Review Text can not be empty.'); + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/Review/Model/Validator/ReviewsValidator.php b/app/code/Magento/Review/Model/Validator/ReviewsValidator.php new file mode 100644 index 0000000000000..75b0431a02cec --- /dev/null +++ b/app/code/Magento/Review/Model/Validator/ReviewsValidator.php @@ -0,0 +1,65 @@ +validationResultFactory = $validationResultFactory; + $this->reviewValidatorChain = $reviewValidatorChain; + } + + /** + * Validate reviews + * + * @param ReviewInterface[] $reviews + * @return ValidationResult + */ + public function validate(array $reviews): ValidationResult + { + $errors = [[]]; + foreach ($reviews as $review) { + $validationResult = $this->reviewValidatorChain->validate($review); + if (!$validationResult->isValid()) { + $errors[] = $validationResult->getErrors(); + } + } + $errors = array_merge(...$errors); + + $validationResult = $this->validationResultFactory->create(['errors' => $errors]); + return $validationResult; + } +} diff --git a/app/code/Magento/Review/Model/Validator/Store.php b/app/code/Magento/Review/Model/Validator/Store.php new file mode 100644 index 0000000000000..ec034430d686e --- /dev/null +++ b/app/code/Magento/Review/Model/Validator/Store.php @@ -0,0 +1,48 @@ +validationResultFactory = $validationResultFactory; + } + + /** + * @inheritdoc + */ + public function validate(ReviewInterface $review): ValidationResult + { + $errors = []; + if (!is_numeric($review->getStoreId())) { + $errors[] = __('Store ID can not be empty.'); + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/Review/Model/Validator/Title.php b/app/code/Magento/Review/Model/Validator/Title.php new file mode 100644 index 0000000000000..ab30074ceab9b --- /dev/null +++ b/app/code/Magento/Review/Model/Validator/Title.php @@ -0,0 +1,48 @@ +validationResultFactory = $validationResultFactory; + } + + /** + * @inheritdoc + */ + public function validate(ReviewInterface $review): ValidationResult + { + $errors = []; + if (!\Zend_Validate::is($review->getTitle(), 'NotEmpty')) { + $errors[] = __('Review Title can not be empty.'); + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php b/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php index 9f57b289fa749..04aaf1d099b7a 100644 --- a/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/ReviewTest.php @@ -51,6 +51,18 @@ class ReviewTest extends \PHPUnit\Framework\TestCase /** @var \Magento\Review\Model\ResourceModel\Review|\PHPUnit_Framework_MockObject_MockObject */ protected $resource; + /** @var \Magento\Framework\Api\AttributeValueFactory|\PHPUnit_Framework_MockObject_MockObject */ + protected $extensionFactoryMock; + + /** @var \Magento\Framework\Api\ExtensionAttributesFactory|\PHPUnit_Framework_MockObject_MockObject */ + private $customAttributeFactoryMock; + + /** @var \Magento\ReviewApi\Model\AggregatorInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $reviewAggregatorMock; + + /** @var \Magento\ReviewApi\Model\ReviewValidatorInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $reviewValidatorMock; + /** @var int */ protected $reviewId = 8; @@ -77,6 +89,14 @@ protected function setUp() $this->storeManagerMock = $this->createMock(\Magento\Store\Model\StoreManagerInterface::class); $this->urlInterfaceMock = $this->createMock(\Magento\Framework\UrlInterface::class); $this->resource = $this->createMock(\Magento\Review\Model\ResourceModel\Review::class); + $this->extensionFactoryMock = $this->createMock( + \Magento\Framework\Api\ExtensionAttributesFactory::class + ); + $this->customAttributeFactoryMock = $this->createMock( + \Magento\Framework\Api\AttributeValueFactory::class + ); + $this->reviewAggregatorMock = $this->createMock(\Magento\ReviewApi\Model\AggregatorInterface::class); + $this->reviewValidatorMock = $this->createMock(\Magento\ReviewApi\Model\ReviewValidatorInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->review = $this->objectManagerHelper->getObject( @@ -92,7 +112,11 @@ protected function setUp() 'storeManager' => $this->storeManagerMock, 'urlModel' => $this->urlInterfaceMock, 'resource' => $this->resource, - 'data' => ['review_id' => $this->reviewId, 'status_id' => 1, 'stores' => [2, 3, 4]] + 'data' => ['review_id' => $this->reviewId, 'status_id' => 1, 'stores' => [2, 3, 4]], + 'extensionFactory' => $this->extensionFactoryMock, + 'customAttributeFactory' => $this->customAttributeFactoryMock, + 'reviewAggregator' => $this->reviewAggregatorMock, + 'reviewValidator' => $this->reviewValidatorMock ] ); } @@ -129,7 +153,7 @@ public function testGetTotalReviews() public function testAggregate() { - $this->resource->expects($this->once())->method('aggregate') + $this->reviewAggregatorMock->expects($this->once())->method('aggregate') ->with($this->equalTo($this->review)) ->will($this->returnValue($this->review)); $this->assertSame($this->review, $this->review->aggregate()); diff --git a/app/code/Magento/Review/composer.json b/app/code/Magento/Review/composer.json index 17e0d9bebcf50..a58141e7b0dd9 100644 --- a/app/code/Magento/Review/composer.json +++ b/app/code/Magento/Review/composer.json @@ -14,7 +14,8 @@ "magento/module-newsletter": "*", "magento/module-store": "*", "magento/module-theme": "*", - "magento/module-ui": "*" + "magento/module-ui": "*", + "magento/module-review-api": "*" }, "suggest": { "magento/module-cookie": "*", diff --git a/app/code/Magento/Review/etc/db_schema.xml b/app/code/Magento/Review/etc/db_schema.xml index d1090d413384b..dafe29a8cb96f 100644 --- a/app/code/Magento/Review/etc/db_schema.xml +++ b/app/code/Magento/Review/etc/db_schema.xml @@ -28,6 +28,8 @@ comment="Review id"/> + + + + + + + + + + + + + + + + + + + + @@ -38,4 +57,47 @@ + + + + + Magento\Review\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ReviewSkuFilter + Magento\Review\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ReviewCustomerFilter + + + + + + + Magento\Review\Model\Api\SearchCriteria\CollectionProcessor\ProductFilterProcessor + Magento\Framework\Api\SearchCriteria\CollectionProcessor\SortingProcessor + Magento\Framework\Api\SearchCriteria\CollectionProcessor\PaginationProcessor + + + + + + Magento\Review\Model\Api\SearchCriteria\ReviewCollectionProcessor + + + + + + + Magento\Review\Model\Validator\Title + Magento\Review\Model\Validator\CustomerNickname + Magento\Review\Model\Validator\ReviewText + Magento\Review\Model\Validator\Store + Magento\Review\Model\Validator\Ratings + + + + + + + Magento\Review\Model\Aggregator\Review + Magento\Review\Model\Aggregator\Ratings + + + diff --git a/app/code/Magento/ReviewApi/Api/CreateReviewsInterface.php b/app/code/Magento/ReviewApi/Api/CreateReviewsInterface.php new file mode 100644 index 0000000000000..72323da5b9bbe --- /dev/null +++ b/app/code/Magento/ReviewApi/Api/CreateReviewsInterface.php @@ -0,0 +1,24 @@ +" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/ReviewApi/LICENSE_AFL.txt b/app/code/Magento/ReviewApi/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/ReviewApi/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/ReviewApi/Model/Aggregator.php b/app/code/Magento/ReviewApi/Model/Aggregator.php new file mode 100644 index 0000000000000..e8b12b1fa6fde --- /dev/null +++ b/app/code/Magento/ReviewApi/Model/Aggregator.php @@ -0,0 +1,51 @@ +aggregators = $aggregators; + } + + /** + * @inheritdoc + */ + public function aggregate(ReviewInterface $review): void + { + foreach ($this->aggregators as $aggregator) { + $aggregator->aggregate($review); + } + } +} diff --git a/app/code/Magento/ReviewApi/Model/AggregatorInterface.php b/app/code/Magento/ReviewApi/Model/AggregatorInterface.php new file mode 100644 index 0000000000000..417f039412b85 --- /dev/null +++ b/app/code/Magento/ReviewApi/Model/AggregatorInterface.php @@ -0,0 +1,26 @@ +successful += $reviews; + return $this; + } + + /** + * @inheritdoc + */ + public function addRetryableReviews(array $reviews): ReviewOperationResponseInterface + { + $this->retryable += $reviews; + return $this; + } + + /** + * @inheritdoc + */ + public function addFailedReviews(array $reviews): ReviewOperationResponseInterface + { + $this->failed += $reviews; + return $this; + } + + /** + * @inheritdoc + */ + public function addError($error): ReviewOperationResponseInterface + { + $this->errors[] = $error; + return $this; + } + + /** + * @inheritdoc + */ + public function getSuccessfulReviews(): array + { + return $this->successful; + } + + /** + * @inheritdoc + */ + public function getRetryableReviews(): array + { + return $this->retryable; + } + + /** + * @inheritdoc + */ + public function getFailedReviews(): array + { + return $this->failed; + } + + /** + * @inheritdoc + */ + public function getErrors(): array + { + return $this->errors; + } +} diff --git a/app/code/Magento/ReviewApi/Model/ReviewValidatorChain.php b/app/code/Magento/ReviewApi/Model/ReviewValidatorChain.php new file mode 100644 index 0000000000000..29fad79bb8649 --- /dev/null +++ b/app/code/Magento/ReviewApi/Model/ReviewValidatorChain.php @@ -0,0 +1,68 @@ +validationResultFactory = $validationResultFactory; + + foreach ($validators as $validator) { + if (!$validator instanceof ReviewValidatorInterface) { + throw new LocalizedException( + __('Review Validator must implement ReviewValidatorInterface.') + ); + } + } + $this->validators = $validators; + } + + /** + * @inheritdoc + */ + public function validate(ReviewInterface $review): ValidationResult + { + $errors = []; + foreach ($this->validators as $validator) { + $validationResult = $validator->validate($review); + + if (!$validationResult->isValid()) { + $errors = array_merge($errors, $validationResult->getErrors()); + } + } + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/ReviewApi/Model/ReviewValidatorInterface.php b/app/code/Magento/ReviewApi/Model/ReviewValidatorInterface.php new file mode 100644 index 0000000000000..3a78d6c9b3cd2 --- /dev/null +++ b/app/code/Magento/ReviewApi/Model/ReviewValidatorInterface.php @@ -0,0 +1,29 @@ +ratingCollectionFactory = $objectManager->get(RatingCollectionFactory::class); + $this->ratingOptionCollectionFactory = $objectManager->get(RatingOptionCollectionFactory::class); + } + + /**#@-*/ + /** + * @magentoApiDataFixture Magento/Review/_files/active_ratings.php + */ + public function testCreateProductReviews() + { + /** @var \Magento\Review\Model\Rating $firstRating */ + $firstRating = $this->ratingCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(1) + ->getFirstItem(); + + /** @var \Magento\Review\Model\Rating\Option $firstRatingOption */ + $firstRatingOption = $this->ratingOptionCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(2) + ->addRatingFilter($firstRating->getId()) + ->getFirstItem(); + + /** @var \Magento\Review\Model\Rating $secondRating */ + $secondRating = $this->ratingCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(3) + ->getFirstItem(); + + /** @var \Magento\Review\Model\Rating\Option $secondRatingOption */ + $secondRatingOption = $this->ratingOptionCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(3) + ->addRatingFilter($secondRating->getId()) + ->getFirstItem(); + + $reviewsForCreate = [ + [ + 'related_entity_id' => 1, + 'review_entity_id' => 1, //product + 'customer_nickname' => 'Nickname', + 'title' => 'Review Summary', + 'review_text' => 'Review Text', + 'ratings' => [ + [ + 'rating_name' => $firstRating->getRatingName(), + 'rating_value' => $firstRatingOption->getValue(), + ], + [ + 'rating_name' => $secondRating->getRatingName(), + 'rating_value' => $secondRatingOption->getValue(), + ], + ], + 'store_id' => 1, + 'stores' => [1, 2], + ], + [ + 'related_entity_id' => 1, + 'review_entity_id' => 1, //product + 'customer_nickname' => 'Customer Nickname', + 'title' => 'Review Title', + 'review_text' => 'Review Comment', + 'ratings' => [ + [ + 'rating_name' => $secondRating->getRatingName(), + 'rating_value' => $secondRatingOption->getValue(), + ], + ], + 'store_id' => 1, + 'stores' => [1], + ], + ]; + + $expectedReviewsAfterCreate = [ + [ + 'title' => 'Review Summary', + 'review_text' => 'Review Text', + 'customer_nickname' => 'Nickname', + 'review_entity_id' => 1, + 'related_entity_id' => 1, + 'status' => Review::STATUS_PENDING, + ], + [ + 'title' => 'Review Title', + 'review_text' => 'Review Comment', + 'customer_nickname' => 'Customer Nickname', + 'review_entity_id' => 1, + 'related_entity_id' => 1, + 'status' => Review::STATUS_PENDING, + ] + ]; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::CREATE_RESOURCE_PATH . '?' . http_build_query(['reviews' => $reviewsForCreate]), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::CREATE_SERVICE_NAME, + 'operation' => self::CREATE_SERVICE_NAME . 'Execute', + ], + ]; + + (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, ['reviews' => $reviewsForCreate]); + + $actualData = $this->getReviews(); + + self::assertEquals(2, $actualData['total_count']); + AssertArrayContains::assert($expectedReviewsAfterCreate, $actualData['items']); + } + + /** + * @return array + */ + private function getReviews() + { + $requestData = [ + 'searchCriteria' => [ + SearchCriteria::FILTER_GROUPS => [ + [ + 'filters' => [ + [ + 'field' => ProductInterface::SKU, + 'value' => 'simple', + 'condition_type' => 'eq', + ], + ], + ], + ], + SearchCriteria::SORT_ORDERS => [ + [ + 'field' => ReviewInterface::CREATED_AT, + 'direction' => SortOrder::SORT_DESC, + ], + ], + SearchCriteria::CURRENT_PAGE => 1, + SearchCriteria::PAGE_SIZE => 10, + ], + ]; + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::GET_RESOURCE_PATH . '?' . http_build_query($requestData), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::GET_SERVICE_NAME, + 'operation' => self::GET_SERVICE_NAME . 'Execute', + ], + ]; + + return (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, $requestData); + } +} diff --git a/app/code/Magento/ReviewApi/Test/Api/DeleteReviewsTest.php b/app/code/Magento/ReviewApi/Test/Api/DeleteReviewsTest.php new file mode 100644 index 0000000000000..2fce4fd5feaa8 --- /dev/null +++ b/app/code/Magento/ReviewApi/Test/Api/DeleteReviewsTest.php @@ -0,0 +1,133 @@ + 1, + 'related_entity_id' => 1, + 'review_entity_id' => 1, //product + 'customer_nickname' => 'Nickname', + 'title' => 'Review Summary', + 'review_text' => 'Review text', + 'created_at' => '0000-00-00 00:00:00', + 'updated_at' => '0000-00-00 00:00:00', + ], + [ + 'review_id' => 2, + 'related_entity_id' => 1, + 'review_entity_id' => 1, //product + 'customer_nickname' => 'Nickname', + 'title' => '2 filter first review', + 'review_text' => 'Review text', + 'created_at' => '0000-00-00 00:00:00', + 'updated_at' => '0000-00-00 00:00:00', + ], + ]; + $expectedReviewsAfterDelete = [ + [ + 'review_id' => 3, + 'related_entity_id' => 1, + 'review_entity_id' => 1, //product + 'customer_nickname' => 'Nickname', + 'title' => '1 filter second review', + 'review_text' => 'Review text', + ], + ]; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::DELETE_RESOURCE_PATH . '?' . http_build_query(['reviews' => $reviewsForDelete]), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::DELETE_SERVICE_NAME, + 'operation' => self::DELETE_SERVICE_NAME . 'Execute', + ], + ]; + (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, ['reviews' => $reviewsForDelete]); + + $actualData = $this->getReviews(); + + self::assertEquals(1, $actualData['total_count']); + AssertArrayContains::assert($expectedReviewsAfterDelete, $actualData['items']); + } + + /** + * @return array + */ + private function getReviews() + { + $requestData = [ + 'searchCriteria' => [ + SearchCriteria::FILTER_GROUPS => [ + [ + 'filters' => [ + [ + 'field' => ProductInterface::SKU, + 'value' => 'simple', + 'condition_type' => 'eq', + ], + ], + ], + ], + SearchCriteria::SORT_ORDERS => [ + [ + 'field' => ReviewInterface::CREATED_AT, + 'direction' => SortOrder::SORT_DESC, + ], + ], + SearchCriteria::CURRENT_PAGE => 1, + SearchCriteria::PAGE_SIZE => 10, + ], + ]; + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::GET_RESOURCE_PATH . '?' . http_build_query($requestData), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::GET_SERVICE_NAME, + 'operation' => self::GET_SERVICE_NAME . 'Execute', + ], + ]; + + return (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, $requestData); + } +} diff --git a/app/code/Magento/ReviewApi/Test/Api/GetReviewsTest.php b/app/code/Magento/ReviewApi/Test/Api/GetReviewsTest.php new file mode 100644 index 0000000000000..ccf2f5333cfd5 --- /dev/null +++ b/app/code/Magento/ReviewApi/Test/Api/GetReviewsTest.php @@ -0,0 +1,142 @@ + [ + SearchCriteria::FILTER_GROUPS => [ + [ + 'filters' => [ + [ + 'field' => ProductInterface::SKU, + 'value' => 'simple3', + 'condition_type' => 'eq', + ], + ], + ], + ], + SearchCriteria::SORT_ORDERS => [ + [ + 'field' => ReviewInterface::CREATED_AT, + 'direction' => SortOrder::SORT_DESC, + ], + ], + SearchCriteria::CURRENT_PAGE => 1, + SearchCriteria::PAGE_SIZE => 10, + ], + ]; + $expectedTotalCount = 1; + $expectedItemsData = [ + [ + 'related_entity_id' => 12, + 'customer_nickname' => 'Nickname', + 'title' => 'Review Summary', + 'review_text' => 'Review text', + ], + ]; + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($requestData), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::SERVICE_NAME, + 'operation' => self::SERVICE_NAME . 'Execute', + ], + ]; + $response = (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, $requestData); + AssertArrayContains::assert($requestData['searchCriteria'], $response['search_criteria']); + self::assertEquals($expectedTotalCount, $response['total_count']); + AssertArrayContains::assert($expectedItemsData, $response['items']); + } + + /**#@-*/ + /** + * @magentoApiDataFixture Magento/Review/_files/different_reviews.php + * @magentoApiDataFixture Magento/Review/_files/customer_review.php + */ + public function testGetCustomerReviews() + { + $requestData = [ + 'searchCriteria' => [ + SearchCriteria::FILTER_GROUPS => [ + [ + 'filters' => [ + [ + 'field' => ReviewInterface::CUSTOMER_ID, + 'value' => 1, + 'condition_type' => 'eq', + ], + ], + ], + ], + SearchCriteria::SORT_ORDERS => [ + [ + 'field' => ReviewInterface::CREATED_AT, + 'direction' => SortOrder::SORT_DESC, + ], + ], + SearchCriteria::CURRENT_PAGE => 1, + SearchCriteria::PAGE_SIZE => 10, + ], + ]; + $expectedTotalCount = 1; + $expectedItemsData = [ + [ + 'customer_id' => 1, + 'customer_nickname' => 'Nickname', + 'title' => 'Review Summary', + 'review_text' => 'Review text', + ], + ]; + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($requestData), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::SERVICE_NAME, + 'operation' => self::SERVICE_NAME . 'Execute', + ], + ]; + $response = (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, $requestData); + AssertArrayContains::assert($requestData['searchCriteria'], $response['search_criteria']); + self::assertEquals($expectedTotalCount, $response['total_count']); + AssertArrayContains::assert($expectedItemsData, $response['items']); + } +} diff --git a/app/code/Magento/ReviewApi/Test/Api/UpdateReviewsTest.php b/app/code/Magento/ReviewApi/Test/Api/UpdateReviewsTest.php new file mode 100644 index 0000000000000..e3cec8880baf1 --- /dev/null +++ b/app/code/Magento/ReviewApi/Test/Api/UpdateReviewsTest.php @@ -0,0 +1,227 @@ +ratingCollectionFactory = $objectManager->get(RatingCollectionFactory::class); + $this->ratingOptionCollectionFactory = $objectManager->get(RatingOptionCollectionFactory::class); + } + + /**#@-*/ + /** + * @magentoApiDataFixture Magento/Review/_files/different_reviews.php + * @magentoApiDataFixture Magento/Review/_files/active_ratings.php + */ + public function testUpdateProductReviews() + { + /** @var \Magento\Review\Model\Rating $firstRating */ + $firstRating = $this->ratingCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(1) + ->getFirstItem(); + + /** @var \Magento\Review\Model\Rating\Option $firstRatingOption */ + $firstRatingOption = $this->ratingOptionCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(2) + ->addRatingFilter($firstRating->getId()) + ->getFirstItem(); + + /** @var \Magento\Review\Model\Rating $secondRating */ + $secondRating = $this->ratingCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(3) + ->getFirstItem(); + + /** @var \Magento\Review\Model\Rating\Option $secondRatingOption */ + $secondRatingOption = $this->ratingOptionCollectionFactory + ->create() + ->setPageSize(1) + ->setCurPage(3) + ->addRatingFilter($secondRating->getId()) + ->getFirstItem(); + + $reviewsForUpdate = [ + [ + 'review_id' => 1, + 'related_entity_id' => 1, + 'review_entity_id' => 1, //product + 'customer_nickname' => 'Updated Nickname', + 'title' => 'Updated Review Summary', + 'review_text' => 'Updated Review Text', + 'status' => Review::STATUS_APPROVED, + 'ratings' => [ + [ + 'rating_name' => $firstRating->getRatingName(), + 'rating_value' => $firstRatingOption->getValue(), + ], + [ + 'rating_name' => $secondRating->getRatingName(), + 'rating_value' => $secondRatingOption->getValue(), + ], + ], + 'store_id' => 1, + 'stores' => [1, 2], + ], + [ + 'review_id' => 2, + 'related_entity_id' => 1, + 'review_entity_id' => 1, //product + 'customer_nickname' => 'Updated Customer Nickname', + 'title' => 'Updated Review Title', + 'review_text' => 'Updated Review Comment', + 'status' => Review::STATUS_PENDING, + 'ratings' => [ + [ + 'rating_name' => $secondRating->getRatingName(), + 'rating_value' => $secondRatingOption->getValue(), + ], + ], + 'store_id' => 1, + 'stores' => [1], + ], + ]; + + $expectedReviewsAfterUpdate = [ + [ + 'review_id' => 1, + 'title' => 'Updated Review Summary', + 'review_text' => 'Updated Review Text', + 'customer_nickname' => 'Updated Nickname', + 'review_entity_id' => 1, + 'related_entity_id' => 1, + 'status' => Review::STATUS_APPROVED, + ], + [ + 'review_id' => 2, + 'title' => 'Updated Review Title', + 'review_text' => 'Updated Review Comment', + 'customer_nickname' => 'Updated Customer Nickname', + 'review_entity_id' => 1, + 'related_entity_id' => 1, + 'status' => Review::STATUS_PENDING, + ], + [ + 'review_id' => 3, + 'title' => '1 filter second review', + 'review_text' => 'Review text', + 'customer_nickname' => 'Nickname', + 'review_entity_id' => 1, + 'related_entity_id' => 1, + 'status' => Review::STATUS_APPROVED, + ] + ]; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::UPDATE_RESOURCE_PATH . '?' . http_build_query(['reviews' => $reviewsForUpdate]), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::UPDATE_SERVICE_NAME, + 'operation' => self::UPDATE_SERVICE_NAME . 'Execute', + ], + ]; + (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, ['reviews' => $reviewsForUpdate]); + + $actualData = $this->getReviews(); + + self::assertEquals(3, $actualData['total_count']); + AssertArrayContains::assert($expectedReviewsAfterUpdate, $actualData['items']); + } + + /** + * @return array + */ + private function getReviews() + { + $requestData = [ + 'searchCriteria' => [ + SearchCriteria::FILTER_GROUPS => [ + [ + 'filters' => [ + [ + 'field' => ProductInterface::SKU, + 'value' => 'simple', + 'condition_type' => 'eq', + ], + ], + ], + ], + SearchCriteria::SORT_ORDERS => [ + [ + 'field' => ReviewInterface::CREATED_AT, + 'direction' => SortOrder::SORT_DESC, + ], + ], + SearchCriteria::CURRENT_PAGE => 1, + SearchCriteria::PAGE_SIZE => 10, + ], + ]; + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::GET_RESOURCE_PATH . '?' . http_build_query($requestData), + 'httpMethod' => Request::HTTP_METHOD_POST, + ], + 'soap' => [ + 'service' => self::GET_SERVICE_NAME, + 'operation' => self::GET_SERVICE_NAME . 'Execute', + ], + ]; + + return (TESTS_WEB_API_ADAPTER === self::ADAPTER_REST) + ? $this->_webApiCall($serviceInfo) + : $this->_webApiCall($serviceInfo, $requestData); + } +} diff --git a/app/code/Magento/ReviewApi/composer.json b/app/code/Magento/ReviewApi/composer.json new file mode 100644 index 0000000000000..14f87f38a0459 --- /dev/null +++ b/app/code/Magento/ReviewApi/composer.json @@ -0,0 +1,21 @@ +{ + "name": "magento/module-review-api", + "description": "N/A", + "require": { + "php": "~7.1.3||~7.2.0", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\ReviewApi\\": "" + } + } +} diff --git a/app/code/Magento/ReviewApi/etc/di.xml b/app/code/Magento/ReviewApi/etc/di.xml new file mode 100644 index 0000000000000..b97d251cf5f18 --- /dev/null +++ b/app/code/Magento/ReviewApi/etc/di.xml @@ -0,0 +1,17 @@ + + + + + + + + diff --git a/app/code/Magento/ReviewApi/etc/module.xml b/app/code/Magento/ReviewApi/etc/module.xml new file mode 100644 index 0000000000000..a424a298c83b0 --- /dev/null +++ b/app/code/Magento/ReviewApi/etc/module.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/code/Magento/ReviewApi/etc/webapi.xml b/app/code/Magento/ReviewApi/etc/webapi.xml new file mode 100644 index 0000000000000..08200f0518cef --- /dev/null +++ b/app/code/Magento/ReviewApi/etc/webapi.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/Magento/ReviewApi/registration.php b/app/code/Magento/ReviewApi/registration.php new file mode 100644 index 0000000000000..be06d3c9f499e --- /dev/null +++ b/app/code/Magento/ReviewApi/registration.php @@ -0,0 +1,12 @@ +get( + \Magento\Store\Model\StoreManagerInterface::class +)->getStore()->getId(); + +$secondStoreId = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->create(\Magento\Store\Model\Store::class)->load('test')->getId(); + +/** @var \Magento\Review\Model\ResourceModel\Review\Collection $ratingCollection */ +$ratingCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( + \Magento\Review\Model\Rating::class +)->getCollection(); + +foreach ($ratingCollection as $rating) { + $rating->setStores([$firstStoreId, $secondStoreId])->setIsActive(1)->save(); +}