Skip to content

Commit

Permalink
Fix PHP Stan
Browse files Browse the repository at this point in the history
  • Loading branch information
maximehuran committed Jul 13, 2024
1 parent eeb1ed9 commit 36b82f8
Show file tree
Hide file tree
Showing 23 changed files with 63 additions and 37 deletions.
1 change: 1 addition & 0 deletions src/AutoMapper/ProductMapperConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ public function process(MapperGeneratorMetadataInterface $metadata): void
});

$metadata->forMember('channels', function (ProductInterface $product): array {
/** @phpstan-ignore-next-line */
return array_map(function (ChannelInterface $channel) {
return $this->autoMapper->map($channel, $this->configuration->getTargetClass('channel'));
}, $product->getChannels()->toArray());
Expand Down
9 changes: 1 addition & 8 deletions src/Command/SearchCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace MonsieurBiz\SyliusSearchPlugin\Command;

use Elastica\Exception\Connection\HttpException;
use MonsieurBiz\SyliusSearchPlugin\Model\Documentable\DocumentableInterface;
use MonsieurBiz\SyliusSearchPlugin\Model\Product\ProductDTO;
use MonsieurBiz\SyliusSearchPlugin\Search\Request\RequestConfiguration;
Expand Down Expand Up @@ -85,13 +84,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$this->channelContext
);

try {
$result = $this->search->search($requestConfiguration);
} catch (HttpException $exception) {
$io->error('Error with the HTTP request: ' . $exception->getMessage());

return Command::FAILURE;
}
$result = $this->search->search($requestConfiguration);

$io->title('Search result for: ' . $query);
$io->section('Nb results: ' . $result->count());
Expand Down
6 changes: 4 additions & 2 deletions src/Controller/SearchController.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public function searchAction(
*/
public function postAction(Request $request): RedirectResponse
{
$query = (array) $request->request->all()['monsieurbiz_searchplugin_search'] ?? [];
$query = (array) ($request->request->all()['monsieurbiz_searchplugin_search'] ?? []);
$query = $query['query'] ?? '';

// With Apache a URL with a encoded slash (%2F) is provoking a 404 error on the server level
Expand Down Expand Up @@ -143,13 +143,15 @@ public function taxonAction(
string $documentType = 'monsieurbiz_product'
): Response {
$documentable = $this->getDocumentable($documentType);
/** @var array $syliusAttribute */
$syliusAttribute = $request->attributes->get('_sylius', []);
$requestConfiguration = new RequestConfiguration(
$request,
RequestInterface::TAXON_TYPE,
$documentable,
$this->searchSettings,
$this->channelContext,
new Parameters($this->parametersParser->parseRequestValues($request->attributes->get('_sylius', []), $request))
new Parameters($this->parametersParser->parseRequestValues($syliusAttribute, $request))
);
$result = $this->search->search($requestConfiguration);

Expand Down
5 changes: 3 additions & 2 deletions src/DependencyInjection/DocumentableRegistryPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function process(ContainerBuilder $container): void
*/
private function validateDocumentableResource(string $class): void
{
$interfaces = (array) (class_implements($class) ?? []);
$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));
Expand All @@ -55,7 +55,7 @@ private function validateDocumentableResource(string $class): void

private function isPrefixedDocumentableClass(string $class): bool
{
$interfaces = (array) (class_implements($class) ?? []);
$interfaces = (array) class_implements($class);

return \in_array(PrefixedDocumentableInterface::class, $interfaces, true);
}
Expand All @@ -66,6 +66,7 @@ private function addDocumentableServices(ContainerBuilder $container, array $doc

$searchSettings = [];
if ($container->hasParameter('monsieurbiz.settings.config.plugins')) {
/** @var array $searchSettings */
$searchSettings = $container->getParameter('monsieurbiz.settings.config.plugins');
}

Expand Down
6 changes: 3 additions & 3 deletions src/Fixture/Factory/SearchableFixtureFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ public function create(array $options = []): SearchableInterface
{
$options = $this->optionsResolver->resolve($options);
$object = $this->getSearchableObject($options);
$object->setFilterable(((bool) $options['filterable']) ?? false);
$object->setSearchable(((bool) $options['searchable']) ?? false);
$object->setSearchWeight(((int) $options['search_weight']) ?? 1);
$object->setFilterable((bool) ($options['filterable'] ?? false));
$object->setSearchable((bool) ($options['searchable'] ?? false));
$object->setSearchWeight((int) ($options['search_weight'] ?? 1));

return $object;
}
Expand Down
4 changes: 3 additions & 1 deletion src/Form/Type/Settings/SettingsSearchType.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
'label' => 'monsieurbiz_searchplugin.admin.setting_form.instant_search_enabled_' . $documentable->getIndexCode(),
]
);
/** @var array $optionsData */
$optionsData = $options['data'] ?? [];
$subOptions = [];
$subOptions['data'] = $options['data']['limits__' . $documentable->getIndexCode()] ?? [];
$subOptions['data'] = $optionsData['limits__' . $documentable->getIndexCode()] ?? [];
$subOptions['documentable'] = $documentable;
$this->addWithDefaultCheckbox(
$builder,
Expand Down
1 change: 1 addition & 0 deletions src/Index/Indexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ private function indexDocumentable(OutputInterface $output, DocumentableInterfac

$indexer = $this->clientFactory->getIndexer($documentable, $locale);
foreach ($documentable->getDatasource()->getItems($documentable->getSourceClass()) as $item) {
/** @var object $item */
$item = $this->getRealEntity($item);
if (null !== $locale && $item instanceof TranslatableInterface) {
$item->setCurrentLocale($locale);
Expand Down
5 changes: 4 additions & 1 deletion src/Mapping/YamlWithLocaleProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ private function appendMapping(string $configurationDirectory, array $mapping, s
$fileName = $context['filename'] ?? ($indexName . '_mapping.yaml');
$mappingFilePath = $configurationDirectory . \DIRECTORY_SEPARATOR . $fileName;

$mapping = array_merge_recursive($mapping, $this->parser->parseFile($mappingFilePath));
/** @var array $parsedMapping */
$parsedMapping = $this->parser->parseFile($mappingFilePath) ?? [];
$mapping = array_merge_recursive($mapping, $parsedMapping);
} catch (ParseException $exception) {
// the mapping yaml file does not exist.
}
Expand All @@ -107,6 +109,7 @@ private function appendLocaleAnalyzers(string $configurationDirectory, array $ma
private function appendAnalyzers(string $analyzerFilePath, array $mapping): array
{
try {
/** @var array $analyzer */
$analyzer = $this->parser->parseFile($analyzerFilePath) ?? [];
$mapping['settings']['analysis'] = array_merge_recursive($mapping['settings']['analysis'] ?? [], $analyzer);
} catch (ParseException $exception) {
Expand Down
2 changes: 2 additions & 0 deletions src/MessageHandler/ProductReindexFromTaxonHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public function __invoke(ProductReindexFromTaxon $message): void
if (!$this->productRepository instanceof EntityRepository) {
return;
}

/** @var array $products */
$products = $this->productRepository->createQueryBuilder('o')
->innerJoin('o.productTaxons', 'productTaxon')
->andWhere('productTaxon.taxon = :taxonId')
Expand Down
5 changes: 0 additions & 5 deletions src/MessageHandler/ProductToDeleteFromIdsHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,19 @@
use MonsieurBiz\SyliusSearchPlugin\Index\IndexerInterface;
use MonsieurBiz\SyliusSearchPlugin\Message\ProductToDeleteFromIds;
use MonsieurBiz\SyliusSearchPlugin\Model\Documentable\DocumentableInterface;
use Sylius\Component\Core\Repository\ProductRepositoryInterface;
use Sylius\Component\Registry\ServiceRegistryInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class ProductToDeleteFromIdsHandler implements MessageHandlerInterface
{
private ProductRepositoryInterface $productRepository;

private IndexerInterface $indexer;

private ServiceRegistryInterface $documentableRegistry;

public function __construct(
ProductRepositoryInterface $productRepository,
IndexerInterface $indexer,
ServiceRegistryInterface $documentableRegistry
) {
$this->productRepository = $productRepository;
$this->indexer = $indexer;
$this->documentableRegistry = $documentableRegistry;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Model/Documentable/Documentable.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function getTargetClass(): string

public function isTranslatable(): bool
{
$interface = (array) (class_implements($this->getSourceClass()) ?? []);
$interface = (array) class_implements($this->getSourceClass());

return \in_array(TranslatableInterface::class, $interface, true);
}
Expand Down
1 change: 1 addition & 0 deletions src/Model/Product/VariantDTO.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ final class VariantDTO extends Eater
{
public function getCode(): ?string
{
/** @phpstan-ignore-next-line */
return $this->getData('code');
}

Expand Down
14 changes: 8 additions & 6 deletions src/Normalizer/Product/ProductDTONormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

/** @TODO remove ObjectNormalizer extends before Symfony 7.0 */
/** @phpstan-ignore-next-line */
final class ProductDTONormalizer extends ObjectNormalizer implements DenormalizerInterface, NormalizerInterface, DenormalizerAwareInterface, NormalizerAwareInterface
{
use DenormalizerAwareTrait;
Expand Down Expand Up @@ -68,13 +70,13 @@ public function denormalize($data, string $type, string $format = null, array $c
/** @var ProductDTO $object */
$object = parent::denormalize($data, $type, $format, $context);

if (\array_key_exists('main_taxon', $data) && null !== $data['main_taxon']) {
if (\is_array($data) && \array_key_exists('main_taxon', $data) && null !== $data['main_taxon']) {
$taxonDTOClass = $this->automapperConfiguration->getTargetClass('taxon');
$object->setData('main_taxon', $this->denormalizer->denormalize($data['main_taxon'], $taxonDTOClass, 'json', $context));
unset($data['main_taxon']);
}

if (\array_key_exists('product_taxons', $data) && null !== $data['product_taxons']) {
if (\is_array($data) && \array_key_exists('product_taxons', $data) && null !== $data['product_taxons']) {
$values = [];
$productTaxonDTOClass = $this->automapperConfiguration->getTargetClass('product_taxon');
foreach ($data['product_taxons'] as $value) {
Expand All @@ -84,7 +86,7 @@ public function denormalize($data, string $type, string $format = null, array $c
unset($data['product_taxons']);
}

if (\array_key_exists('images', $data) && null !== $data['images']) {
if (\is_array($data) && \array_key_exists('images', $data) && null !== $data['images']) {
$values = [];
$imageDTOClass = $this->automapperConfiguration->getTargetClass('image');
foreach ($data['images'] as $value) {
Expand All @@ -94,7 +96,7 @@ public function denormalize($data, string $type, string $format = null, array $c
unset($data['product_taxons']);
}

if (\array_key_exists('channels', $data) && null !== $data['channels']) {
if (\is_array($data) && \array_key_exists('channels', $data) && null !== $data['channels']) {
$values = [];
$channelDTOClass = $this->automapperConfiguration->getTargetClass('channel');
foreach ($data['channels'] as $value) {
Expand All @@ -104,7 +106,7 @@ public function denormalize($data, string $type, string $format = null, array $c
unset($data['channels']);
}

if (\array_key_exists('attributes', $data) && null !== $data['attributes']) {
if (\is_array($data) && \array_key_exists('attributes', $data) && null !== $data['attributes']) {
$values = [];
$productAttributeDTOClass = $this->automapperConfiguration->getTargetClass('product_attribute');
foreach ($data['attributes'] as $key => $value) {
Expand All @@ -114,7 +116,7 @@ public function denormalize($data, string $type, string $format = null, array $c
unset($data['channels']);
}

if (\array_key_exists('prices', $data) && null !== $data['prices']) {
if (\is_array($data) && \array_key_exists('prices', $data) && null !== $data['prices']) {
$values = [];
$pricingDTOClass = $this->automapperConfiguration->getTargetClass('pricing');
foreach ($data['prices'] as $key => $value) {
Expand Down
1 change: 1 addition & 0 deletions src/Repository/ProductAttributeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public function __construct(EntityRepository $attributeRepository)

public function findIsSearchableOrFilterable(): array
{
/** @phpstan-ignore-next-line */
return $this->attributeRepository->createQueryBuilder('o')
->innerJoin('o.translations', 'translation')
->andWhere('o.searchable = true')
Expand Down
1 change: 1 addition & 0 deletions src/Repository/ProductOptionRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public function __construct(EntityRepository $productOptionRepository)

public function findIsSearchableOrFilterable(): array
{
/** @phpstan-ignore-next-line */
return $this->productOptionRepository->createQueryBuilder('o')
->innerJoin('o.translations', 'translation')
->andWhere('o.searchable = true')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct()
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
* @param mixed $aggregation
* @param array $aggregation
*/
public function build($aggregation, array $filters)
{
Expand All @@ -40,7 +40,10 @@ public function build($aggregation, array $filters)
$qb = new QueryBuilder();

$currentFilters = array_filter($filters, function (AbstractQuery $filter): bool {
return !$filter->hasParam('path') || false === strpos($filter->getParam('path'), 'attributes.');
/** @var string $path */
$path = $filter->hasParam('path') ? $filter->getParam('path') : '';

return !$filter->hasParam('path') || false === strpos($path, 'attributes.');
});

$filterQuery = $qb->query()->bool();
Expand Down
7 changes: 5 additions & 2 deletions src/Search/Request/Aggregation/ProductOptionAggregation.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,12 @@ public function build($aggregation, array $filters)
$qb = new QueryBuilder();

$filters = array_filter($filters, function (AbstractQuery $filter) use ($aggregation): bool {
/** @var string $path */
$path = $filter->hasParam('path') ? $filter->getParam('path') : '';

return !$filter->hasParam('path') || (
false !== strpos($filter->getParam('path'), 'options.')
&& 'options.' . $aggregation->getCode() . '.values' !== $filter->getParam('path')
false !== strpos($path, 'options.')
&& 'options.' . $aggregation->getCode() . '.values' !== $path
);
});

Expand Down
7 changes: 5 additions & 2 deletions src/Search/Request/Aggregation/ProductOptionsAggregation.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct(ProductOptionAggregation $productOptionAggregationBu
/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
* @param mixed $aggregation
* @param array $aggregation
*/
public function build($aggregation, array $filters)
{
Expand All @@ -39,7 +39,10 @@ public function build($aggregation, array $filters)

$qb = new QueryBuilder();
$currentFilters = array_filter($filters, function (AbstractQuery $filter): bool {
return !$filter->hasParam('path') || false === strpos($filter->getParam('path'), 'options.');
/** @var string $path */
$path = $filter->hasParam('path') ? $filter->getParam('path') : '';

return !$filter->hasParam('path') || false === strpos($path, 'options.');
});
$filterQuery = $qb->query()->bool();
foreach ($currentFilters as $filter) {
Expand Down
4 changes: 3 additions & 1 deletion src/Search/Request/ProductRequest/Search.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,16 @@ public function __construct(

protected function addAggregations(Query $query, BoolQuery $postFilter): void
{
/** @var array $mustParam */
$mustParam = $postFilter->hasParam('must') ? $postFilter->getParam('must') : [];
$aggregations = $this->aggregationBuilder->buildAggregations(
[
'main_taxon',
'price',
$this->productAttributeRepository->findIsSearchableOrFilterable(),
$this->productOptionRepository->findIsSearchableOrFilterable(),
],
$postFilter->hasParam('must') ? $postFilter->getParam('must') : []
$mustParam
);

foreach ($aggregations as $aggregation) {
Expand Down
4 changes: 3 additions & 1 deletion src/Search/Request/ProductRequest/Taxon.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,16 @@ protected function addAggregations(Query $query, Query\BoolQuery $postFilter): v
if (null === $this->configuration) {
throw new RuntimeException('Missing request configuration');
}
/** @var array $mustParam */
$mustParam = $postFilter->hasParam('must') ? $postFilter->getParam('must') : [];
$aggregations = $this->aggregationBuilder->buildAggregations(
[
['taxons' => $this->configuration->getTaxon()],
'price',
$this->productAttributeRepository->findIsSearchableOrFilterable(),
$this->productOptionRepository->findIsSearchableOrFilterable(),
],
$postFilter->hasParam('must') ? $postFilter->getParam('must') : []
$mustParam
);

foreach ($aggregations as $aggregation) {
Expand Down
6 changes: 6 additions & 0 deletions src/Search/Request/RequestConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public function __construct(

public function getQueryText(): string
{
/** @phpstan-ignore-next-line */
return trim(urldecode($this->request->get('query', '')));
}

Expand All @@ -71,16 +72,19 @@ public function getAppliedFilters(string $type = null): array

public function getSorting(): array
{
/** @phpstan-ignore-next-line */
return $this->request->get('sorting', []);
}

public function getPage(): int
{
/** @phpstan-ignore-next-line */
return (int) $this->request->get('page', 1);
}

public function getLimit(): int
{
/** @phpstan-ignore-next-line */
$limit = (int) $this->request->get('limit', self::FALLBACK_LIMIT);
$availableLimits = $this->getAvailableLimits();

Expand All @@ -93,6 +97,7 @@ public function getLimit(): int

public function getAvailableLimits(): array
{
/** @var array $configLimits */
$configLimits = $this->searchSettings->getCurrentValue(
$this->channelContext->getChannel(),
null,
Expand Down Expand Up @@ -122,6 +127,7 @@ public function getTaxon(): TaxonInterface
throw ObjectNotInstanceOfClassException::fromClassName(TaxonInterface::class);
}

/** @phpstan-ignore-next-line */
return $this->parameters->get('taxon');
}

Expand Down
Loading

0 comments on commit 36b82f8

Please sign in to comment.