Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Graphql products query returns only ids for select or multiselect fields #31622

Open
wants to merge 5 commits into
base: 2.4-develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?php

/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

declare(strict_types=1);

namespace Magento\CatalogGraphQl\Model\Product\Attributes;

use Magento\CatalogGraphQl\Model\Resolver\Products\Attributes\Collection as AttributesCollection;
use Magento\CatalogGraphQl\Model\Resolver\Products\DataProvider\Product as ProductDataProvider;
use Magento\Eav\Model\Entity\Attribute\Frontend\DefaultFrontend;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Phrase;

/**
* Collection for fetching custom attributes for products in filter.
*/
class Collection
{
/**
* @var int[]
*/
private $productIds = [];

/**
* @var array
*/
private $attributeValueMap = [];

/**
* @var AttributesCollection
*/
private $attributesCollection;

/**
* @var ProductDataProvider
*/
private $productDataProvider;

/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;

/**
* @var DefaultFrontend
*/
private $frontend;

/**
* @param AttributesCollection $attributesCollection
* @param ProductDataProvider $productDataProvider
* @param SearchCriteriaBuilder $searchCriteriaBuilder
* @param DefaultFrontend $frontend
*/
public function __construct(
AttributesCollection $attributesCollection,
ProductDataProvider $productDataProvider,
SearchCriteriaBuilder $searchCriteriaBuilder,
DefaultFrontend $frontend
) {
$this->attributesCollection = $attributesCollection;
$this->productDataProvider = $productDataProvider;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->frontend = $frontend;
}

/**
* Add product id to attribute collection filter.
*
* @param int $productId
*/
public function addProductId(int $productId): void
{
if (!in_array($productId, $this->productIds)) {
$this->productIds[] = $productId;
}
}

/**
* Retrieve attributes values for given product id or empty array
*
* @param int $productId
* @return array
*/
public function getAttributesValueByProductId(int $productId): array
{
$attributes = $this->fetch();
if (!isset($attributes[$productId])) {
return [];
}

return $attributes[$productId];
}

/**
* Fetch attribute data
*
* @return array
*/
private function fetch(): array
{
if (empty($this->productIds) || !empty($this->attributeValueMap)) {
return $this->attributeValueMap;
}

$attributes = $this->attributesCollection->getAttributes();

$this->searchCriteriaBuilder->addFilter('entity_id', $this->productIds, 'in');
$products = $this->productDataProvider->getList(
$this->searchCriteriaBuilder->create(),
['*'],
false,
true
)->getItems();

foreach ($products as $productId => $product) {
$data = [];
foreach ($attributes as $attribute) {
$value = $this->frontend->setAttribute($attribute)->getValue($product);
if ($value instanceof Phrase) {
$value = (string) $value;
}
$value = $value ? $value : null;
$data[] = [
'value' => $value,
'code' => $attribute->getAttributeCode(),
];
}
$this->attributeValueMap[$productId] = $data;
}
return $this->attributeValueMap;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

declare(strict_types=1);

namespace Magento\CatalogGraphQl\Model\Resolver\Product;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\CatalogGraphQl\Model\Product\Attributes\Collection as AttributesCollection;
use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;

/**
* Retrieves CustomAttributes
*/
class CustomAttributes implements ResolverInterface
{
/**
* @var AttributesCollection
*/
private $attributesCollection;

/**
* @var ValueFactory
*/
private $valueFactory;

/**
* @param AttributesCollection $attributesCollection
* @param ValueFactory $valueFactory
*/
public function __construct(
AttributesCollection $attributesCollection,
ValueFactory $valueFactory
) {
$this->attributesCollection = $attributesCollection;
$this->valueFactory = $valueFactory;
}

/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
if (!isset($value['model'])) {
throw new LocalizedException(__('"model" value should be specified'));
}
$product = $value['model'];

$this->attributesCollection->addProductId((int)$product->getId());
$productId = $product->getId();
$result = function () use ($productId) {
return $this->attributesCollection->getAttributesValueByProductId((int)$productId);
};
return $this->valueFactory->create($result);
}
}
6 changes: 6 additions & 0 deletions app/code/Magento/CatalogGraphQl/etc/schema.graphqls
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@ interface ProductInterface @typeResolver(class: "Magento\\CatalogGraphQl\\Model\
categories: [CategoryInterface] @doc(description: "The categories assigned to a product.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Categories") @cache(cacheIdentity: "Magento\\CatalogGraphQl\\Model\\Resolver\\Category\\CategoriesIdentity")
canonical_url: String @doc(description: "The relative canonical URL. This value is returned only if the system setting 'Use Canonical Link Meta Tag For Products' is enabled.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\CanonicalUrl")
media_gallery: [MediaGalleryInterface] @doc(description: "An array of media gallery objects.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\MediaGallery")
custom_attributes: [CustomAttribute] @doc(description: "An array of custom product attributes.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\CustomAttributes")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

type CustomAttribute {
code: String!
value: String
}

interface PhysicalProductInterface @typeResolver(class: "Magento\\CatalogGraphQl\\Model\\ProductInterfaceTypeResolverComposite") @doc(description: "Contains attributes specific to tangible products.") {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare (strict_types = 1);

namespace Magento\GraphQl\Catalog;

use Magento\TestFramework\TestCase\GraphQlAbstract;

/**
* Test class for product with custom attributes
*/
class ProductsWithCustomAttributesTest extends GraphQlAbstract
{
/**
* @magentoApiDataFixture Magento/Catalog/_files/products_with_multiselect_attribute.php
*/
public function testQueryProductWithMultiSelectCustomAttribute()
{
if (!$this->cleanCache()) {
$this->fail('Cache could not be cleaned properly.');
}

$multiSelectAttribute = "multiselect_attribute";
$value = 'Option 2, Option 3, Option 4 "!@#$%^&*';
$query = <<<QUERY
{
products(filter: {sku: {eq: "simple_ms_2" }}) {
items {
name
custom_attributes{
code
value
}
}
}
}
QUERY;
$response = $this->graphQlQuery($query);
$this->assertArrayHasKey('products', $response);
$this->assertArrayHasKey('items', $response['products']);
$this->assertCount(1, $response['products']['items']);
$this->assertArrayHasKey(0, $response['products']['items']);
$this->assertArrayHasKey('custom_attributes', $response['products']['items'][0]);
$customAttributes = $response['products']['items'][0]['custom_attributes'];
$this->assertCustomAttribute($customAttributes, $multiSelectAttribute, $value);
}

/**
* @magentoApiDataFixture Magento/Catalog/_files/product_simple_with_custom_attribute.php
*/
public function testQueryProductWithTextCustomAttribute()
{
if (!$this->cleanCache()) {
$this->fail('Cache could not be cleaned properly.');
}
$prductSku = 'simple';
$textAttribute = "attribute_code_custom";
$value = 'customAttributeValue';
$query = <<<QUERY
{
products(filter: {sku: {eq: "{$prductSku}"}})
{
items
{
custom_attributes{
code
value
}
}
}
}
QUERY;

$response = $this->graphQlQuery($query);
$this->assertArrayHasKey('products', $response);
$this->assertArrayHasKey('items', $response['products']);
$this->assertCount(1, $response['products']['items']);
$this->assertArrayHasKey(0, $response['products']['items']);
$this->assertArrayHasKey('custom_attributes', $response['products']['items'][0]);
$customAttributes = $response['products']['items'][0]['custom_attributes'];
$this->assertCustomAttribute($customAttributes, $textAttribute, $value);
}

/**
* @param array $customAttributes
* @param string $searchAttribute
* @param string $actualValue
*/
private function assertCustomAttribute($customAttributes, $searchAttribute, $actualValue)
{
$flag = false;
$customAttributeValue = "";
foreach ($customAttributes as $attributes) {
if ($attributes['code'] == $searchAttribute) {
$flag = true;
$customAttributeValue = $attributes['value'];
break;
}
}
$this->assertStringContainsString($actualValue, $customAttributeValue);
$this->assertEquals(true, $flag);
}
}