Skip to content

Commit

Permalink
Merge pull request #220 from etienne-monsieurbiz/feature/twig-check-i…
Browse files Browse the repository at this point in the history
…f-available

Twig: Add method to check if ElasticSearch is available
  • Loading branch information
etienne-monsieurbiz committed Jul 30, 2024
2 parents 613f08f + e033f24 commit dcf4096
Show file tree
Hide file tree
Showing 16 changed files with 78 additions and 48 deletions.
2 changes: 1 addition & 1 deletion src/AutoMapper/ProductAttributeValueConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public function getProductAttributeValue(ProductAttributeValueInterface $product
}
if (!\array_key_exists($productAttributeValue->getType(), $this->productAttributeValueReaders)) {
// @phpstan-ignore-next-line The logger can't be null here
$this->logger->alert(sprintf('Missing product attribute value reader for "%s" type', $productAttributeValue->getType()));
$this->logger->alert(\sprintf('Missing product attribute value reader for "%s" type', $productAttributeValue->getType()));

return null;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/SearchController.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ private function getDocumentable(?string $documentType): DocumentableInterface
/** @phpstan-ignore-next-line */
return $this->documentableRegistry->get('search.documentable.' . $documentType);
} catch (NonExistingServiceException $exception) {
throw new NotFoundHttpException(sprintf('Documentable "%s" not found', $documentType));
throw new NotFoundHttpException(\sprintf('Documentable "%s" not found', $documentType));
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/DependencyInjection/DocumentableRegistryPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ private function validateDocumentableResource(string $class): void
$interfaces = (array) class_implements($class);

if (!\in_array(DocumentableInterface::class, $interfaces, true)) {
throw new InvalidArgumentException(sprintf('Class "%s" must implement "%s" to be registered as a Documentable.', $class, DocumentableInterface::class));
throw new InvalidArgumentException(\sprintf('Class "%s" must implement "%s" to be registered as a Documentable.', $class, DocumentableInterface::class));
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Exception/ObjectNotInstanceOfClassException.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ class ObjectNotInstanceOfClassException extends InvalidArgumentException
{
public static function fromClassName(string $className): self
{
return new self(sprintf('Object is not instance of class "%s"', $className));
return new self(\sprintf('Object is not instance of class "%s"', $className));
}
}
12 changes: 6 additions & 6 deletions src/Index/Indexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ public function indexAll(?OutputInterface $output = null): void
/** @var DocumentableInterface $documentable */
foreach ($this->documentableRegistry->all() as $documentable) {
$documentable instanceof PrefixedDocumentableInterface && !empty($documentable->getPrefix()) ?
$output->writeln(sprintf('Indexing <info>%s</info> (Prefix: <info>%s</info>)', $documentable->getIndexCode(), $documentable->getPrefix()))
: $output->writeln(sprintf('Indexing <info>%s</info>', $documentable->getIndexCode()));
$output->writeln(\sprintf('Indexing <info>%s</info> (Prefix: <info>%s</info>)', $documentable->getIndexCode(), $documentable->getPrefix()))
: $output->writeln(\sprintf('Indexing <info>%s</info>', $documentable->getIndexCode()));
$this->indexDocumentable($output, $documentable);
}
}
Expand Down Expand Up @@ -165,11 +165,11 @@ private function indexDocumentable(OutputInterface $output, DocumentableInterfac
foreach ($this->getLocales() as $localeCode) {
$documentable instanceof PrefixedDocumentableInterface && !empty($documentable->getPrefix()) ?
$output->writeln(
sprintf('Indexing <info>%s</info> for locale <info>%s</info> (Prefix: <info>%s</info>)', $documentable->getIndexCode(), $localeCode, $documentable->getPrefix()),
\sprintf('Indexing <info>%s</info> for locale <info>%s</info> (Prefix: <info>%s</info>)', $documentable->getIndexCode(), $localeCode, $documentable->getPrefix()),
OutputInterface::VERBOSITY_VERBOSE
)
: $output->writeln(
sprintf('Indexing <info>%s</info> for locale <info>%s</info>', $documentable->getIndexCode(), $localeCode),
\sprintf('Indexing <info>%s</info> for locale <info>%s</info>', $documentable->getIndexCode(), $localeCode),
OutputInterface::VERBOSITY_VERBOSE
);

Expand Down Expand Up @@ -199,10 +199,10 @@ private function indexDocumentable(OutputInterface $output, DocumentableInterfac
$indexer->flush();

$indexBuilder->markAsLive($newIndex, $indexName);
$output->writeln(sprintf('Index <info>%s</info> is now live', $indexName), OutputInterface::VERBOSITY_VERBOSE);
$output->writeln(\sprintf('Index <info>%s</info> is now live', $indexName), OutputInterface::VERBOSITY_VERBOSE);
$indexBuilder->speedUpRefresh($newIndex);
$indexBuilder->purgeOldIndices($indexName);
$output->writeln(sprintf('Old indices for <info>%s</info> are now purged', $indexName), OutputInterface::VERBOSITY_VERBOSE);
$output->writeln(\sprintf('Old indices for <info>%s</info> are now purged', $indexName), OutputInterface::VERBOSITY_VERBOSE);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Mapping/YamlWithLocaleProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function provideMapping(string $indexName, array $context = []): ?array

$mapping = (array) $mappingProviderEvent->getMapping();
if (empty($mapping['mappings'] ?? [])) {
throw new InvalidException(sprintf('Mapping no found for "%s" not found. Please check your configuration.', $indexName));
throw new InvalidException(\sprintf('Mapping no found for "%s" not found. Please check your configuration.', $indexName));
}

return $mapping;
Expand Down
4 changes: 4 additions & 0 deletions src/Resources/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,10 @@ services:
arguments:
$elasticsearchChecker: '@monsieurbiz.search.checker.elasticsearch_checker'

MonsieurBiz\SyliusSearchPlugin\Twig\Extension\SearchExtension:
arguments:
$elasticsearchChecker: '@monsieurbiz.search.checker.elasticsearch_checker'

# Routing Context
MonsieurBiz\SyliusSearchPlugin\Routing\RequestContext:
decorates: router.request_context
Expand Down
2 changes: 1 addition & 1 deletion src/Routing/RequestContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@ public function __call(string $name, array $arguments)
return \call_user_func($callback, ...$arguments);
}

throw new Exception(sprintf('Method %s not found for class "%s"', $name, \get_class($this->decorated)));
throw new Exception(\sprintf('Method %s not found for class "%s"', $name, \get_class($this->decorated)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ public function build($aggregation, array $filters)
->setFilter($filterQuery)
->addAggregation(
/** @phpstan-ignore-next-line */
$qb->aggregation()->nested($aggregation->getCode(), sprintf('attributes.%s', $aggregation->getCode()))
$qb->aggregation()->nested($aggregation->getCode(), \sprintf('attributes.%s', $aggregation->getCode()))
->addAggregation(
$qb->aggregation()->terms('names')
->setField(sprintf('attributes.%s.name', $aggregation->getCode()))
->setField(\sprintf('attributes.%s.name', $aggregation->getCode()))
->addAggregation(
$qb->aggregation()->terms('values')
->setField(sprintf('attributes.%s.value.keyword', $aggregation->getCode()))
->setField(\sprintf('attributes.%s.value.keyword', $aggregation->getCode()))
)
)
)
Expand Down
12 changes: 6 additions & 6 deletions src/Search/Request/Aggregation/ProductOptionAggregation.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,15 @@ public function build($aggregation, array $filters)

$qb = new QueryBuilder();
$optionBoolConditions = $qb->query()->bool()
->addMust($qb->query()->term([sprintf('options.%s.values.enabled', $aggregation->getCode()) => ['value' => true]]))
->addMust($qb->query()->term([\sprintf('options.%s.values.enabled', $aggregation->getCode()) => ['value' => true]]))
;
if ($this->enableStockFilter) {
$optionBoolConditions->addMust($qb->query()->term([sprintf('options.%s.values.is_in_stock', $aggregation->getCode()) => ['value' => true]]));
$optionBoolConditions->addMust($qb->query()->term([\sprintf('options.%s.values.is_in_stock', $aggregation->getCode()) => ['value' => true]]));
}
$valuesAggregation = $qb->aggregation()->filter('values', $optionBoolConditions)
->addAggregation(
$qb->aggregation()->terms('values')
->setField(sprintf('options.%s.values.value.keyword', $aggregation->getCode()))
->setField(\sprintf('options.%s.values.value.keyword', $aggregation->getCode()))
)
;

Expand All @@ -75,12 +75,12 @@ public function build($aggregation, array $filters)
->setFilter($filterQuery)
->addAggregation(
/** @phpstan-ignore-next-line */
$qb->aggregation()->nested($aggregation->getCode(), sprintf('options.%s', $aggregation->getCode()))
$qb->aggregation()->nested($aggregation->getCode(), \sprintf('options.%s', $aggregation->getCode()))
->addAggregation(
$qb->aggregation()->terms('names')
->setField(sprintf('options.%s.name', $aggregation->getCode()))
->setField(\sprintf('options.%s.name', $aggregation->getCode()))
->addAggregation(
$qb->aggregation()->nested('values', sprintf('options.%s.values', $aggregation->getCode()))
$qb->aggregation()->nested('values', \sprintf('options.%s.values', $aggregation->getCode()))
->addAggregation(
$valuesAggregation
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ public function apply(BoolQuery $boolQuery, RequestConfiguration $requestConfigu
$attributeValueQuery = $qb->query()->bool();

foreach ($values as $value) {
$termQuery = $qb->query()->term([sprintf('attributes.%s.value.keyword', $field) => SlugHelper::toLabel($value)]);
$termQuery = $qb->query()->term([\sprintf('attributes.%s.value.keyword', $field) => SlugHelper::toLabel($value)]);
$attributeValueQuery->addShould($termQuery); // todo configure the "and" or "or"
}

$attributeQuery = $qb->query()->nested();
$attributeQuery->setPath(sprintf('attributes.%s', $field))->setQuery($attributeValueQuery);
$attributeQuery->setPath(\sprintf('attributes.%s', $field))->setQuery($attributeValueQuery);

$boolQuery->addMust($attributeQuery);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function apply(BoolQuery $boolQuery, RequestConfiguration $requestConfigu
$mainTaxonQuery->addShould(
$qb->query()
->term()
->setTerm(sprintf('%s.code', $field), SlugHelper::toLabel($value))
->setTerm(\sprintf('%s.code', $field), SlugHelper::toLabel($value))
);
}
$boolQuery->addMust(
Expand Down
8 changes: 4 additions & 4 deletions src/Search/Request/PostFilter/Product/OptionsPostFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,19 @@ public function apply(BoolQuery $boolQuery, RequestConfiguration $requestConfigu
foreach ($requestConfiguration->getAppliedFilters('options') as $field => $values) {
$optionValueQuery = $qb->query()->bool();
foreach ($values as $value) {
$termQuery = $qb->query()->term([sprintf('options.%s.values.value.keyword', $field) => SlugHelper::toLabel($value)]);
$termQuery = $qb->query()->term([\sprintf('options.%s.values.value.keyword', $field) => SlugHelper::toLabel($value)]);
$optionValueQuery->addShould($termQuery); // todo configure the "and" or "or"
}

$optionQuery = $qb->query()->nested();
$condition = $qb->query()->bool()
->addMust($qb->query()->term([sprintf('options.%s.values.enabled', $field) => true]))
->addMust($qb->query()->term([\sprintf('options.%s.values.enabled', $field) => true]))
;
if ($this->enableStockFilter) {
$condition->addMust($qb->query()->term([sprintf('options.%s.values.is_in_stock', $field) => true]));
$condition->addMust($qb->query()->term([\sprintf('options.%s.values.is_in_stock', $field) => true]));
}
$condition->addMust($optionValueQuery);
$optionQuery->setPath(sprintf('options.%s.values', $field))->setQuery($condition);
$optionQuery->setPath(\sprintf('options.%s.values', $field))->setQuery($condition);

$boolQuery->addMust($optionQuery);
}
Expand Down
8 changes: 4 additions & 4 deletions src/Search/Request/QueryFilter/Product/SearchTermFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ private function addAttributesQueries(BoolQuery $searchQuery, RequestConfigurati

$attributeValueQuery = $qb->query()->multi_match();
$attributeValueQuery->setFields([
sprintf('attributes.%s.value^%d', $productAttribute->getCode(), $productAttribute->getSearchWeight()),
\sprintf('attributes.%s.value^%d', $productAttribute->getCode(), $productAttribute->getSearchWeight()),
]);
$attributeValueQuery->setQuery($requestConfiguration->getQueryText());
$attributeValueQuery->setFuzziness(MultiMatch::FUZZINESS_AUTO);

$attributeQuery = $qb->query()->nested();
$attributeQuery->setPath(sprintf('attributes.%s', $productAttribute->getCode()))->setQuery($attributeValueQuery);
$attributeQuery->setPath(\sprintf('attributes.%s', $productAttribute->getCode()))->setQuery($attributeValueQuery);

$searchQuery->addShould($attributeQuery);
}
Expand All @@ -76,13 +76,13 @@ private function addOptionsQueries(BoolQuery $searchQuery, RequestConfiguration

$attributeValueQuery = $qb->query()->multi_match();
$attributeValueQuery->setFields([
sprintf('options.%s.values.value^%d', $productOption->getCode(), $productOption->getSearchWeight()),
\sprintf('options.%s.values.value^%d', $productOption->getCode(), $productOption->getSearchWeight()),
]);
$attributeValueQuery->setQuery($requestConfiguration->getQueryText());
$attributeValueQuery->setFuzziness(MultiMatch::FUZZINESS_AUTO);

$attributeQuery = $qb->query()->nested();
$attributeQuery->setPath(sprintf('options.%s.values', $productOption->getCode()))->setQuery($attributeValueQuery);
$attributeQuery->setPath(\sprintf('options.%s.values', $productOption->getCode()))->setQuery($attributeValueQuery);

$searchQuery->addShould($attributeQuery);
}
Expand Down
20 changes: 4 additions & 16 deletions src/Twig/Extension/RenderSearchForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,12 @@

class RenderSearchForm extends AbstractExtension
{
private FormFactoryInterface $formFactory;

private Environment $templatingEngine;

private RequestStack $requestStack;

private ElasticsearchCheckerInterface $elasticsearchChecker;

public function __construct(
FormFactoryInterface $formFactory,
Environment $templatingEngine,
RequestStack $requestStack,
ElasticsearchCheckerInterface $elasticsearchChecker
private FormFactoryInterface $formFactory,
private Environment $templatingEngine,
private RequestStack $requestStack,
private ElasticsearchCheckerInterface $elasticsearchChecker
) {
$this->formFactory = $formFactory;
$this->templatingEngine = $templatingEngine;
$this->requestStack = $requestStack;
$this->elasticsearchChecker = $elasticsearchChecker;
}

public function getFunctions()
Expand Down
38 changes: 38 additions & 0 deletions src/Twig/Extension/SearchExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* This file is part of Monsieur Biz' Search plugin for Sylius.
*
* (c) Monsieur Biz <sylius@monsieurbiz.com>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace MonsieurBiz\SyliusSearchPlugin\Twig\Extension;

use MonsieurBiz\SyliusSearchPlugin\Checker\ElasticsearchCheckerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class SearchExtension extends AbstractExtension
{
public function __construct(
private ElasticsearchCheckerInterface $elasticsearchChecker,
) {
}

public function getFunctions()
{
return [
new TwigFunction('is_elasticsearch_available', [$this, 'isElasticsearchAvailable']),
];
}

public function isElasticsearchAvailable(): bool
{
return $this->elasticsearchChecker->check();
}
}

0 comments on commit dcf4096

Please sign in to comment.