Skip to content

Commit

Permalink
Merge pull request #3470 from magento-engcom/graphql-develop-prs
Browse files Browse the repository at this point in the history
[EngCom] Public Pull Requests - GraphQL
  • Loading branch information
Valeriy Naida authored Nov 20, 2018
2 parents 5e17b04 + 1022233 commit 1a805d0
Show file tree
Hide file tree
Showing 13 changed files with 495 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ public function hydrateCategory(Category $category, $basicFieldsOnly = false) :
$categoryData = $category->getData();
} else {
$categoryData = $this->dataObjectProcessor->buildOutputDataArray($category, CategoryInterface::class);
$categoryData['product_count'] = $category->getProductCount();
}
$categoryData['id'] = $category->getId();
$categoryData['children'] = [];
$categoryData['available_sort_by'] = $category->getAvailableSortBy();
$categoryData['model'] = $category;
return $this->flattener->flatten($categoryData);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ public function resolve(
'items' => $searchResult->getProductsSearchResult(),
'page_info' => [
'page_size' => $searchCriteria->getPageSize(),
'current_page' => $currentPage
'current_page' => $currentPage,
'total_pages' => $maxPages
]
];
return $data;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\CatalogGraphQl\Model\Resolver\Category;

use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product\Visibility;
use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product\CollectionProcessor\StockProcessor;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;

/**
* Retrieves products count for a category
*/
class ProductsCount implements ResolverInterface
{
/**
* @var Visibility
*/
private $catalogProductVisibility;

/**
* @var StockProcessor
*/
private $stockProcessor;

/**
* @var SearchCriteriaInterface
*/
private $searchCriteria;

/**
* @param Visibility $catalogProductVisibility
* @param SearchCriteriaInterface $searchCriteria
* @param StockProcessor $stockProcessor
*/
public function __construct(
Visibility $catalogProductVisibility,
SearchCriteriaInterface $searchCriteria,
StockProcessor $stockProcessor
) {
$this->catalogProductVisibility = $catalogProductVisibility;
$this->searchCriteria = $searchCriteria;
$this->stockProcessor = $stockProcessor;
}

/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
if (!isset($value['model'])) {
throw new GraphQlInputException(__('"model" value should be specified'));
}
/** @var Category $category */
$category = $value['model'];
$productsCollection = $category->getProductCollection();
$productsCollection->setVisibility($this->catalogProductVisibility->getVisibleInSiteIds());
$productsCollection = $this->stockProcessor->process($productsCollection, $this->searchCriteria, []);

return $productsCollection->getSize();
}
}
2 changes: 1 addition & 1 deletion app/code/Magento/CatalogGraphQl/etc/schema.graphqls
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ interface CategoryInterface @typeResolver(class: "Magento\\CatalogGraphQl\\Model
level: Int @doc(description: "Indicates the depth of the category within the tree")
created_at: String @doc(description: "Timestamp indicating when the category was created")
updated_at: String @doc(description: "Timestamp indicating when the category was updated")
product_count: Int @doc(description: "The number of products in the category")
product_count: Int @doc(description: "The number of products in the category") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Category\\ProductsCount")
default_sort_by: String @doc(description: "The attribute to use for sorting")
products(
pageSize: Int = 20 @doc(description: "Specifies the maximum number of results to return at once. This attribute is optional."),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\SendFriendGraphQl\Model\Resolver;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\SendFriend\Model\SendFriend;
use Magento\SendFriend\Model\SendFriendFactory;

/**
* @inheritdoc
*/
class SendEmailToFriend implements ResolverInterface
{
/**
* @var SendFriendFactory
*/
private $sendFriendFactory;

/**
* @var ProductRepositoryInterface
*/
private $productRepository;

/**
* @var DataObjectFactory
*/
private $dataObjectFactory;

/**
* @var ManagerInterface
*/
private $eventManager;

/**
* @param SendFriendFactory $sendFriendFactory
* @param ProductRepositoryInterface $productRepository
* @param DataObjectFactory $dataObjectFactory
* @param ManagerInterface $eventManager
*/
public function __construct(
SendFriendFactory $sendFriendFactory,
ProductRepositoryInterface $productRepository,
DataObjectFactory $dataObjectFactory,
ManagerInterface $eventManager
) {
$this->sendFriendFactory = $sendFriendFactory;
$this->productRepository = $productRepository;
$this->dataObjectFactory = $dataObjectFactory;
$this->eventManager = $eventManager;
}

/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
/** @var SendFriend $sendFriend */
$sendFriend = $this->sendFriendFactory->create();

if ($sendFriend->getMaxSendsToFriend() && $sendFriend->isExceedLimit()) {
throw new GraphQlInputException(
__('You can\'t send messages more than %1 times an hour.', $sendFriend->getMaxSendsToFriend())
);
}

$product = $this->getProduct($args['input']['product_id']);
$this->eventManager->dispatch('sendfriend_product', ['product' => $product]);
$sendFriend->setProduct($product);

$senderData = $this->extractSenderData($args);
$sendFriend->setSender($senderData);

$recipientsData = $this->extractRecipientsData($args);
$sendFriend->setRecipients($recipientsData);

$this->validateSendFriendModel($sendFriend, $senderData, $recipientsData);
$sendFriend->send();

return array_merge($senderData, $recipientsData);
}

/**
* Validate send friend model
*
* @param SendFriend $sendFriend
* @param array $senderData
* @param array $recipientsData
* @return void
* @throws GraphQlInputException
*/
private function validateSendFriendModel(SendFriend $sendFriend, array $senderData, array $recipientsData): void
{
$sender = $this->dataObjectFactory->create()->setData($senderData['sender']);
$sendFriend->setData('_sender', $sender);

$emails = array_column($recipientsData['recipients'], 'email');
$recipients = $this->dataObjectFactory->create()->setData('emails', $emails);
$sendFriend->setData('_recipients', $recipients);

$validationResult = $sendFriend->validate();
if ($validationResult !== true) {
throw new GraphQlInputException(__(implode($validationResult)));
}
}

/**
* Get product
*
* @param int $productId
* @return ProductInterface
* @throws GraphQlNoSuchEntityException
*/
private function getProduct(int $productId): ProductInterface
{
try {
$product = $this->productRepository->getById($productId);
if (!$product->isVisibleInCatalog()) {
throw new GraphQlNoSuchEntityException(
__("The product that was requested doesn't exist. Verify the product and try again.")
);
}
} catch (NoSuchEntityException $e) {
throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
}
return $product;
}

/**
* Extract recipients data
*
* @param array $args
* @return array
* @throws GraphQlInputException
*/
private function extractRecipientsData(array $args): array
{
$recipients = [];
foreach ($args['input']['recipients'] as $recipient) {
if (empty($recipient['name'])) {
throw new GraphQlInputException(__('Please provide Name for all of recipients.'));
}

if (empty($recipient['email'])) {
throw new GraphQlInputException(__('Please provide Email for all of recipients.'));
}

$recipients[] = [
'name' => $recipient['name'],
'email' => $recipient['email'],
];
}
return ['recipients' => $recipients];
}

/**
* Extract sender data
*
* @param array $args
* @return array
* @throws GraphQlInputException
*/
private function extractSenderData(array $args): array
{
if (empty($args['input']['sender']['name'])) {
throw new GraphQlInputException(__('Please provide Name of sender.'));
}

if (empty($args['input']['sender']['email'])) {
throw new GraphQlInputException(__('Please provide Email of sender.'));
}

if (empty($args['input']['sender']['message'])) {
throw new GraphQlInputException(__('Please provide Message.'));
}

return [
'sender' => [
'name' => $args['input']['sender']['name'],
'email' => $args['input']['sender']['email'],
'message' => $args['input']['sender']['message'],
],
];
}
}
3 changes: 3 additions & 0 deletions app/code/Magento/SendFriendGraphQl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# SendFriendGraphQl

**SendFriendGraphQl** provides support of GraphQL for SendFriend functionality.
26 changes: 26 additions & 0 deletions app/code/Magento/SendFriendGraphQl/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "magento/module-send-friend-graph-ql",
"description": "N/A",
"type": "magento2-module",
"require": {
"php": "~7.1.3||~7.2.0",
"magento/framework": "*",
"magento/module-catalog": "*",
"magento/module-send-friend": "*"
},
"suggest": {
"magento/module-graph-ql": "*"
},
"license": [
"OSL-3.0",
"AFL-3.0"
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Magento\\SendFriendGraphQl\\": ""
}
}
}
11 changes: 11 additions & 0 deletions app/code/Magento/SendFriendGraphQl/etc/module.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magento_SendFriendGraphQl"/>
</config>
28 changes: 28 additions & 0 deletions app/code/Magento/SendFriendGraphQl/etc/schema.graphqls
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Copyright © Magento, Inc. All rights reserved.
# See COPYING.txt for license details.

type Mutation {
sendEmailToFriend (input: SendEmailToFriendSenderInput): SendEmailToFriendOutput @resolver(class: "\\Magento\\SendFriendGraphQl\\Model\\Resolver\\SendEmailToFriend") @doc(description:"Recommends Product by Sending Single/Multiple Email")
}

input SendEmailToFriendSenderInput {
product_id: Int!
sender: Sender!
recipients: [Recipient!]!
}

type Sender {
name: String!
email: String!
message: String!
}

type Recipient {
name: String!
email: String!
}

type SendEmailToFriendOutput {
sender: Sender
recipients: [Recipient]
}
10 changes: 10 additions & 0 deletions app/code/Magento/SendFriendGraphQl/registration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_SendFriendGraphQl', __DIR__);
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@
"magento/module-search": "*",
"magento/module-security": "*",
"magento/module-send-friend": "*",
"magento/module-send-friend-graph-ql": "*",
"magento/module-shipping": "*",
"magento/module-signifyd": "*",
"magento/module-sitemap": "*",
Expand Down
Loading

0 comments on commit 1a805d0

Please sign in to comment.