Skip to content

Commit

Permalink
Merge pull request #155 from delyriand/fix/153-add-prefix-option
Browse files Browse the repository at this point in the history
Add prefix option for names of indexes and aliases
  • Loading branch information
maximehuran authored Dec 23, 2022
2 parents d735fd2 + 13efed5 commit 0fc4c25
Show file tree
Hide file tree
Showing 10 changed files with 98 additions and 12 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ server.stop: ## Stop the local webserver
es.reindex: ## Reindex elasticsearch
${CONSOLE} monsieurbiz:search:populate

consume.reindex: ## Consume reindex messages during 10min
${CONSOLE} messenger:consume async_search --time-limit=600 -vv

doctrine.diff: ## Doctrine diff
${CONSOLE} doctrine:migration:diff

Expand Down
5 changes: 5 additions & 0 deletions dist/config/packages/monsieurbiz_sylius_search_plugin.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
imports:
- { resource: "@MonsieurBizSyliusSearchPlugin/Resources/config/config.yaml" }

monsieurbiz_sylius_search:
documents:
monsieurbiz_product:
prefix: 'myprefix' # define a custom index prefix
17 changes: 17 additions & 0 deletions doc/Tips.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Tips

## Add prefix for index names and aliases

In the `config/packages/monsieurbiz_sylius_search_plugin.yaml` file, add the `prefix` node for documents that need a prefix in the names of indexes and aliases.

Example, for the products index:

```diff
imports:
- { resource: "@MonsieurBizSyliusSearchPlugin/Resources/config/config.yaml" }

+monsieurbiz_sylius_search:
+ documents:
+ monsieurbiz_product:
+ prefix: 'myproject' # define a custom index prefix
```
1 change: 1 addition & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->defaultValue([])
->arrayPrototype()
->children()
->scalarNode('prefix')->defaultValue(null)->end()
->scalarNode('document_class')->defaultValue(Documentable::class)->end()
->scalarNode('instant_search_enabled')->defaultValue(false)->end()
->scalarNode('source')->isRequired()->cannotBeEmpty()->end()
Expand Down
11 changes: 11 additions & 0 deletions src/DependencyInjection/DocumentableRegistryPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use InvalidArgumentException;
use MonsieurBiz\SyliusSearchPlugin\Model\Documentable\DocumentableInterface;
use MonsieurBiz\SyliusSearchPlugin\Model\Documentable\PrefixedDocumentableInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
Expand Down Expand Up @@ -56,6 +57,9 @@ public function process(ContainerBuilder $container): void
$documentableDefinition->addTag('monsieurbiz.search.documentable');
$documentableDefinition->addMethodCall('setMappingProvider', [new Reference($documentableConfiguration['mapping_provider'])]);
$documentableDefinition->addMethodCall('setDatasource', [new Reference($documentableConfiguration['datasource'])]);
if ($this->isPrefixedDocumentableClass($documentableClass) && isset($documentableConfiguration['prefix'])) {
$documentableDefinition->addMethodCall('setPrefix', [$documentableConfiguration['prefix']]);
}

// Add documentable into registry
$registry->addMethodCall('register', [$documentableServiceId, new Reference($documentableServiceId)]);
Expand All @@ -81,4 +85,11 @@ private function validateDocumentableResource(string $class): void
throw new InvalidArgumentException(sprintf('Class "%s" must implement "%s" to be registered as a Documentable.', $class, DocumentableInterface::class));
}
}

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

return \in_array(PrefixedDocumentableInterface::class, $interfaces, true);
}
}
13 changes: 4 additions & 9 deletions src/Index/Indexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ public function indexByDocuments(DocumentableInterface $documentable, array $doc

return;
}
$indexName = $this->getIndexName($documentable, $locale);
$index = $this->clientFactory->getIndex($documentable, $locale);
foreach ($documents as $document) {
if (null !== $locale && $document instanceof TranslatableInterface) {
$document->setCurrentLocale($locale);
}
$dto = $this->autoMapper->map($document, $documentable->getTargetClass());
// @phpstan-ignore-next-line
$indexer->scheduleIndex($indexName, new Document((string) $document->getId(), $dto));
$indexer->scheduleIndex($index, new Document((string) $document->getId(), $dto));
}
}

Expand All @@ -107,12 +107,12 @@ public function deleteByDocuments(DocumentableInterface $documentable, array $do
return;
}

$indexName = $this->getIndexName($documentable, $locale);
$index = $this->clientFactory->getIndex($documentable, $locale);
foreach ($documents as $document) {
if (null !== $locale && $document instanceof TranslatableInterface) {
$document->setCurrentLocale($locale);
}
$indexer->scheduleDelete($indexName, (string) $document->getId());
$indexer->scheduleDelete($index, (string) $document->getId());
}
}

Expand Down Expand Up @@ -169,11 +169,6 @@ private function indexDocumentable(DocumentableInterface $documentable, ?string
$indexBuilder->purgeOldIndices($indexName);
}

private function getIndexName(DocumentableInterface $documentable, ?string $locale = null): string
{
return $documentable->getIndexCode() . strtolower(null !== $locale ? '_' . $locale : '');
}

/**
* Convert proxies classes to the entity one.
*
Expand Down
14 changes: 13 additions & 1 deletion src/Model/Documentable/Documentable.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

use Sylius\Component\Resource\Model\TranslatableInterface;

class Documentable implements DocumentableInterface
class Documentable implements PrefixedDocumentableInterface
{
use DocumentableDatasourceTrait;

Expand All @@ -34,6 +34,8 @@ class Documentable implements DocumentableInterface

private array $limits;

private ?string $prefix = null;

public function __construct(
string $indexCode,
string $sourceClass,
Expand Down Expand Up @@ -83,4 +85,14 @@ public function getLimits(?string $queryType = null): array

return $this->limits[$queryType] ?? [];
}

public function getPrefix(): string
{
return $this->prefix ?? '';
}

public function setPrefix(string $prefix): void
{
$this->prefix = $prefix;
}
}
21 changes: 21 additions & 0 deletions src/Model/Documentable/PrefixedDocumentableInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* This file is part of Monsieur Biz' Search plugin for Sylius.
*
* (c) Monsieur Biz <[email protected]>
*
* 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\Model\Documentable;

interface PrefixedDocumentableInterface extends DocumentableInterface
{
public function getPrefix(): string;

public function setPrefix(string $prefix): void;
}
1 change: 1 addition & 0 deletions src/Resources/config/monsieurbiz_search.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
monsieurbiz_sylius_search:
documents:
monsieurbiz_product:
#prefix: '…' # define a custom index prefix on index names and aliases
#document_class: '…' # by default MonsieurBiz\SyliusSearchPlugin\Model\Documentable\Documentable
instant_search_enabled: true # by default false
limits:
Expand Down
24 changes: 22 additions & 2 deletions src/Search/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@

namespace MonsieurBiz\SyliusSearchPlugin\Search;

use Elastica\Index;
use JoliCode\Elastically\Client;
use JoliCode\Elastically\Factory;
use JoliCode\Elastically\IndexBuilder;
use JoliCode\Elastically\Indexer;
use MonsieurBiz\SyliusSearchPlugin\Model\Documentable\DocumentableInterface;
use MonsieurBiz\SyliusSearchPlugin\Model\Documentable\PrefixedDocumentableInterface;
use Symfony\Component\Serializer\SerializerInterface;

class ClientFactory
Expand Down Expand Up @@ -58,16 +60,34 @@ public function getIndexName(DocumentableInterface $documentable, ?string $local
return $documentable->getIndexCode() . strtolower(null !== $locale ? '_' . $locale : '');
}

private function getConfig(DocumentableInterface $documentable, ?string $localeCode): array
/**
* This method allows to find the name of the index with the prefix,
* because the methods of the JoliCode\ElasticallyIndexer class do not add
* it automatically.
*/
public function getIndex(DocumentableInterface $documentable, ?string $locale): Index
{
$indexName = $this->getIndexName($documentable, $localeCode);
$indexName = $this->getIndexName($documentable, $locale);
$factory = new Factory($this->getConfig($documentable, $locale, $indexName));
$client = $factory->buildClient();

return $client->getIndex($indexName);
}

private function getConfig(DocumentableInterface $documentable, ?string $localeCode, ?string $indexName = null): array
{
$indexName = $indexName ?? $this->getIndexName($documentable, $localeCode);
$additionalConfig = [
Factory::CONFIG_INDEX_CLASS_MAPPING => [
$indexName => $documentable->getTargetClass(),
],
Factory::CONFIG_MAPPINGS_PROVIDER => $documentable->getMappingProvider(),
Factory::CONFIG_SERIALIZER => $this->serializer,
];
$prefix = $documentable instanceof PrefixedDocumentableInterface ? trim($documentable->getPrefix()) : '';
if ('' !== $prefix) {
$additionalConfig[Factory::CONFIG_INDEX_PREFIX] = $prefix;
}

return array_merge($this->config, $additionalConfig);
}
Expand Down

0 comments on commit 0fc4c25

Please sign in to comment.