Skip to content

Commit

Permalink
Merge pull request #167 from tgrochowski/master
Browse files Browse the repository at this point in the history
Add proper attributes data casting for elasticsearch boolean type
  • Loading branch information
KrisFlorq committed Jun 8, 2021
2 parents 39c5fb8 + e1e34b7 commit 7e60cbb
Show file tree
Hide file tree
Showing 14 changed files with 90 additions and 32 deletions.
Expand Up @@ -15,6 +15,7 @@
use BitBag\SyliusElasticsearchPlugin\Controller\RequestDataHandler\DataHandlerInterface;
use BitBag\SyliusElasticsearchPlugin\Controller\RequestDataHandler\ShopProductListDataHandler;
use BitBag\SyliusElasticsearchPlugin\Exception\TaxonNotFoundException;
use BitBag\SyliusElasticsearchPlugin\Finder\ProductAttributesFinderInterface;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
Expand All @@ -24,11 +25,13 @@ final class ShopProductListDataHandlerSpec extends ObjectBehavior
{
function let(
TaxonRepositoryInterface $taxonRepository,
LocaleContextInterface $localeContext
LocaleContextInterface $localeContext,
ProductAttributesFinderInterface $attributesFinder
): void {
$this->beConstructedWith(
$taxonRepository,
$localeContext,
$attributesFinder,
'name',
'taxons',
'option',
Expand Down
3 changes: 2 additions & 1 deletion src/Block/SearchFormEventListener.php
Expand Up @@ -42,7 +42,7 @@ public function onBlockEvent(BlockEvent $event): void
$event->getSettings(),
[
'template' => $this->template,
'form' => $this->getForm()->createView()
'form' => $this->getForm()->createView(),
]
)
);
Expand All @@ -60,6 +60,7 @@ public function getForm(Search $search = null): FormInterface
$this->form = $this->formFactory
->create(SearchType::class, $search, ['action' => $this->router->generate('bitbag_sylius_elasticsearch_plugin_shop_search')]);
}

return $this->form;
}
}
4 changes: 2 additions & 2 deletions src/Controller/Action/Shop/ListProductsAction.php
Expand Up @@ -17,12 +17,12 @@
use BitBag\SyliusElasticsearchPlugin\Controller\RequestDataHandler\SortDataHandlerInterface;
use BitBag\SyliusElasticsearchPlugin\Finder\ShopProductsFinderInterface;
use BitBag\SyliusElasticsearchPlugin\Form\Type\ShopProductsFilterType;
use Twig\Environment;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Twig\Environment;

final class ListProductsAction
{
Expand Down Expand Up @@ -62,7 +62,7 @@ public function __construct(

public function __invoke(Request $request): Response
{
$form = $this->formFactory->create( ShopProductsFilterType::class);
$form = $this->formFactory->create(ShopProductsFilterType::class);
$form->handleRequest($request);
$requestData = array_merge(
$form->getData(),
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/Action/Shop/SearchAction.php
Expand Up @@ -11,9 +11,9 @@
use BitBag\SyliusElasticsearchPlugin\QueryBuilder\QueryBuilderInterface;
use Elastica\Query;
use FOS\ElasticaBundle\Finder\PaginatedFinderInterface;
use Twig\Environment;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;

final class SearchAction
{
Expand Down
79 changes: 70 additions & 9 deletions src/Controller/RequestDataHandler/ShopProductListDataHandler.php
Expand Up @@ -13,7 +13,11 @@
namespace BitBag\SyliusElasticsearchPlugin\Controller\RequestDataHandler;

use BitBag\SyliusElasticsearchPlugin\Exception\TaxonNotFoundException;
use BitBag\SyliusElasticsearchPlugin\Finder\ProductAttributesFinderInterface;
use Sylius\Component\Attribute\AttributeType\CheckboxAttributeType;
use Sylius\Component\Attribute\AttributeType\IntegerAttributeType;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Product\Model\ProductAttribute;
use Sylius\Component\Taxonomy\Repository\TaxonRepositoryInterface;

final class ShopProductListDataHandler implements DataHandlerInterface
Expand All @@ -24,6 +28,9 @@ final class ShopProductListDataHandler implements DataHandlerInterface
/** @var LocaleContextInterface */
private $localeContext;

/** @var ProductAttributesFinderInterface */
private $attributesFinder;

/** @var string */
private $namePropertyPrefix;

Expand All @@ -39,13 +46,15 @@ final class ShopProductListDataHandler implements DataHandlerInterface
public function __construct(
TaxonRepositoryInterface $taxonRepository,
LocaleContextInterface $localeContext,
ProductAttributesFinderInterface $attributesFinder,
string $namePropertyPrefix,
string $taxonsProperty,
string $optionPropertyPrefix,
string $attributePropertyPrefix
) {
$this->taxonRepository = $taxonRepository;
$this->localeContext = $localeContext;
$this->attributesFinder = $attributesFinder;
$this->namePropertyPrefix = $namePropertyPrefix;
$this->taxonsProperty = $taxonsProperty;
$this->optionPropertyPrefix = $optionPropertyPrefix;
Expand All @@ -66,28 +75,80 @@ public function retrieveData(array $requestData): array
$data['taxon'] = $taxon;
$data = array_merge($data, $requestData['price']);

$this->handlePrefixedProperty($requestData, $data, 'options', $this->optionPropertyPrefix);
$this->handlePrefixedProperty($requestData, $data, 'attributes', $this->attributePropertyPrefix);
$attributesDefinitions = $this->attributesFinder->findByTaxon($taxon);

$this->handleOptionsPrefixedProperty($requestData, $data);
$this->handleAttributesPrefixedProperty($requestData, $data, $attributesDefinitions);

return $data;
}

private function handlePrefixedProperty(
private function handleOptionsPrefixedProperty(
array $requestData,
array &$data,
string $formName,
string $propertyPrefix
array &$data
): void {
if (!isset($requestData[$formName])) {
if (!isset($requestData['options'])) {
return;
}

foreach ($requestData[$formName] as $key => $value) {
if (is_array($value) && 0 === strpos($key, $propertyPrefix)) {
foreach ($requestData['options'] as $key => $value) {
if (is_array($value) && 0 === strpos($key, $this->optionPropertyPrefix)) {
$data[$key] = array_map(function (string $property): string {
return strtolower($property);
}, $value);
}
}
}

private function handleAttributesPrefixedProperty(
array $requestData,
array &$data,
?array $attributesDefinitions = []
): void {
if (!isset($requestData['attributes'])) {
return;
}

$attributeTypes = $this->getAttributeTypes($attributesDefinitions);

foreach ($requestData['attributes'] as $key => $value) {
if (!is_array($value) || 0 !== strpos($key, $this->attributePropertyPrefix)) {
continue;
}
$data[$key] = $this->reformatAttributeArrayValues($value, $key, $attributeTypes);
}
}

private function getAttributeTypes(array $attributesDefinitions): array
{
$data = [];
/** @var ProductAttribute $attributesDefinition */
foreach ($attributesDefinitions as $attributesDefinition) {
$data['attribute_' . $attributesDefinition->getCode()] = $attributesDefinition->getType();
}

return $data;
}

private function reformatAttributeArrayValues(array $attributeValues, string $property, array $attributesDefinitions): array
{
$reformattedValues = [];
foreach ($attributeValues as $attributeValue) {
switch ($attributesDefinitions[$property]) {
case CheckboxAttributeType::TYPE:
$value = (bool) ($attributeValue);

break;
case IntegerAttributeType::TYPE:
$value = (float) ($attributeValue);

break;
default:
$value = strtolower($attributeValue);
}
$reformattedValues[] = $value;
}

return $reformattedValues;
}
}
Expand Up @@ -62,8 +62,8 @@ public function retrieveData(array $requestData): array
$data = [];
$positionSortingProperty = $this->getPositionSortingProperty();

$orderBy = isset($requestData[self::ORDER_BY_INDEX]) ? $requestData[self::ORDER_BY_INDEX] : $positionSortingProperty;
$sort = isset($requestData[self::SORT_INDEX]) ? $requestData[self::SORT_INDEX] : self::SORT_ASC_INDEX;
$orderBy = $requestData[self::ORDER_BY_INDEX] ?? $positionSortingProperty;
$sort = $requestData[self::SORT_INDEX] ?? self::SORT_ASC_INDEX;

$availableSorters = [$positionSortingProperty, $this->soldUnitsProperty, $this->createdAtProperty, $this->pricePropertyPrefix];
$availableSorting = [self::SORT_ASC_INDEX, self::SORT_DESC_INDEX];
Expand Down
1 change: 0 additions & 1 deletion src/EventListener/OrderProductsListener.php
Expand Up @@ -14,7 +14,6 @@

use BitBag\SyliusElasticsearchPlugin\Refresher\ResourceRefresherInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\OrderItem;
use Sylius\Component\Core\Model\OrderItemInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Webmozart\Assert\Assert;
Expand Down
2 changes: 1 addition & 1 deletion src/Facet/AttributeFacet.php
Expand Up @@ -25,7 +25,7 @@ final class AttributeFacet implements FacetInterface
private $attributeCode;

/** @var LocaleContextInterface */
protected $localeContext;
private $localeContext;

public function __construct(
ConcatedNameResolverInterface $attributeNameResolver,
Expand Down
2 changes: 1 addition & 1 deletion src/Form/Type/AbstractFilterType.php
Expand Up @@ -28,6 +28,6 @@ public function configureOptions(OptionsResolver $resolver): void

public function getBlockPrefix(): ?string
{
return "";
return '';
}
}
5 changes: 2 additions & 3 deletions src/Form/Type/ChoiceMapper/ProductAttributesMapper.php
Expand Up @@ -33,8 +33,7 @@ public function __construct(
ProductAttributeValueRepositoryInterface $productAttributeValueRepository,
LocaleContextInterface $localeContext,
StringFormatterInterface $stringFormatter
)
{
) {
$this->productAttributeValueRepository = $productAttributeValueRepository;
$this->localeContext = $localeContext;
$this->stringFormatter = $stringFormatter;
Expand Down Expand Up @@ -73,7 +72,7 @@ public function mapToChoices(ProductAttributeInterface $productAttribute): array
$label = $configuration['choices'][$singleValue][$this->localeContext->getLocaleCode()];
$choices[$label] = $choice;
}
} else if ($productAttributeValue->getLocaleCode() === $this->localeContext->getLocaleCode()) {
} else {
$choice = is_string($value) ? $this->stringFormatter->formatToLowercaseWithoutSpaces($value) : $value;
$choices[$value] = $choice;
}
Expand Down
2 changes: 0 additions & 2 deletions src/PropertyBuilder/AttributeBuilder.php
Expand Up @@ -83,7 +83,6 @@ private function resolveProductAttribute(array $attributeConfiguration, $attribu
return $attributes;
}


private function processAttribute(AttributeInterface $attribute, $productAttribute, Document $document): void
{
$attributeCode = $attribute->getCode();
Expand All @@ -100,5 +99,4 @@ private function processAttribute(AttributeInterface $attribute, $productAttribu
$document->set($code, $values);
}
}

}
8 changes: 2 additions & 6 deletions src/QueryBuilder/HasAttributesQueryBuilder.php
Expand Up @@ -19,7 +19,7 @@

final class HasAttributesQueryBuilder implements QueryBuilderInterface
{
protected $localeContext;
private $localeContext;

public function __construct(LocaleContextInterface $localeContext)
{
Expand All @@ -33,11 +33,7 @@ public function buildQuery(array $data): ?AbstractQuery
foreach ((array) $data['attribute_values'] as $attributeValue) {
$termQuery = new Term();
$attribute = \sprintf('%s_%s', $data['attribute'], $this->localeContext->getLocaleCode());
$termQuery->setTerm(
strtolower($attribute),
$attributeValue
);

$termQuery->setTerm($attribute, $attributeValue);
$attributeQuery->addShould($termQuery);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Repository/ProductAttributeValueRepository.php
Expand Up @@ -29,12 +29,12 @@ public function getUniqueAttributeValues(AttributeInterface $productAttribute):
{
$queryBuilder = $this->baseAttributeValueRepository->createQueryBuilder('o');

/** @var null|string $storageType */
/** @var string|null $storageType */
$storageType = $productAttribute->getStorageType();

return $queryBuilder
->join('o.subject', 'p', 'WITH', 'p.enabled = 1')
->select('o.localeCode, o.'.$storageType.' as value')
->select('o.localeCode, o.' . $storageType . ' as value')
->where('o.attribute = :attribute')
->groupBy('o.' . $storageType)
->addGroupBy('o.localeCode')
Expand Down
1 change: 1 addition & 0 deletions src/Resources/config/services/controller.xml
Expand Up @@ -15,6 +15,7 @@
<service id="bitbag_sylius_elasticsearch_plugin.controller.request_data_handler.shop_product_list" class="BitBag\SyliusElasticsearchPlugin\Controller\RequestDataHandler\ShopProductListDataHandler">
<argument type="service" id="sylius.repository.taxon" />
<argument type="service" id="sylius.context.locale" />
<argument type="service" id="bitbag_sylius_elasticsearch_plugin.finder.product_attributes" />
<argument>%bitbag_es_shop_name_property_prefix%</argument>
<argument>%bitbag_es_shop_product_taxons_property%</argument>
<argument>%bitbag_es_shop_option_property_prefix%</argument>
Expand Down

0 comments on commit 7e60cbb

Please sign in to comment.