|
| 1 | +<?php |
| 2 | +namespace Ecomteck\OrderComment\Model; |
| 3 | + |
| 4 | +use Ecomteck\OrderComment\Model\Data\OrderComment; |
| 5 | +use Magento\Framework\App\Config\ScopeConfigInterface; |
| 6 | +use Magento\Framework\Exception\NoSuchEntityException; |
| 7 | +use Magento\Framework\Exception\CouldNotSaveException; |
| 8 | +use Magento\Framework\Exception\ValidatorException; |
| 9 | + |
| 10 | +class OrderCommentManagement implements \Ecomteck\OrderComment\Api\OrderCommentManagementInterface |
| 11 | +{ |
| 12 | + /** |
| 13 | + * Quote repository. |
| 14 | + * |
| 15 | + * @var \Magento\Quote\Api\CartRepositoryInterface |
| 16 | + */ |
| 17 | + protected $quoteRepository; |
| 18 | + |
| 19 | + /** |
| 20 | + * @var ScopeConfigInterface |
| 21 | + */ |
| 22 | + protected $scopeConfig; |
| 23 | + |
| 24 | + /** |
| 25 | + * |
| 26 | + * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository Quote repository. |
| 27 | + */ |
| 28 | + public function __construct( |
| 29 | + \Magento\Quote\Api\CartRepositoryInterface $quoteRepository, |
| 30 | + ScopeConfigInterface $scopeConfig |
| 31 | + ) { |
| 32 | + $this->quoteRepository = $quoteRepository; |
| 33 | + $this->scopeConfig = $scopeConfig; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param int $cartId |
| 38 | + * @param \Ecomteck\OrderComment\Api\Data\OrderCommentInterface $orderComment |
| 39 | + * @return null|string |
| 40 | + * @throws CouldNotSaveException |
| 41 | + * @throws NoSuchEntityException |
| 42 | + */ |
| 43 | + public function saveOrderComment( |
| 44 | + $cartId, |
| 45 | + \Ecomteck\OrderComment\Api\Data\OrderCommentInterface $orderComment |
| 46 | + ) { |
| 47 | + $quote = $this->quoteRepository->getActive($cartId); |
| 48 | + if (!$quote->getItemsCount()) { |
| 49 | + throw new NoSuchEntityException(__('Cart %1 doesn\'t contain products', $cartId)); |
| 50 | + } |
| 51 | + $comment = $orderComment->getComment(); |
| 52 | + |
| 53 | + $this->validateComment($comment); |
| 54 | + |
| 55 | + try { |
| 56 | + $quote->setData(OrderComment::COMMENT_FIELD_NAME, strip_tags($comment)); |
| 57 | + $this->quoteRepository->save($quote); |
| 58 | + } catch (\Exception $e) { |
| 59 | + throw new CouldNotSaveException(__('The order comment could not be saved')); |
| 60 | + } |
| 61 | + |
| 62 | + return $comment; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * @param string $comment |
| 67 | + * @throws ValidatorException |
| 68 | + */ |
| 69 | + protected function validateComment($comment) |
| 70 | + { |
| 71 | + $maxLength = $this->scopeConfig->getValue(OrderCommentConfigProvider::CONFIG_MAX_LENGTH); |
| 72 | + if ($maxLength && (mb_strlen($comment) > $maxLength)) { |
| 73 | + throw new ValidatorException(__('Comment is too long')); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments