First pass of the search bundle
This commit is contained in:
94
src/Service/SearchService.php
Normal file
94
src/Service/SearchService.php
Normal file
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pcm\SearchBundle\Service;
|
||||
|
||||
use Pcm\SearchBundle\Entity\SearchIndex;
|
||||
use Pcm\SearchBundle\Entity\Interface\SearchableInterface;
|
||||
use Doctrine\Common\Util\ClassUtils;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Doctrine\ORM\Proxy\Proxy;
|
||||
|
||||
class SearchService
|
||||
{
|
||||
public function __construct(private EntityManagerInterface $em) {}
|
||||
|
||||
public function index($entity)
|
||||
{
|
||||
$searchIndex = $this->createSearchResult($entity);
|
||||
|
||||
$this->em->persist($searchIndex);
|
||||
$this->em->flush();
|
||||
}
|
||||
|
||||
public function unIndex($entity)
|
||||
{
|
||||
$class = get_class($entity);
|
||||
|
||||
$search_result = $this
|
||||
->em
|
||||
->getRepository(SearchIndex::class)
|
||||
->findOneBy(['entityClass' => $class, 'entityId' => $entity->getId()]);
|
||||
|
||||
if ($search_result) {
|
||||
$this->em->remove($search_result);
|
||||
$this->em->flush();
|
||||
}
|
||||
}
|
||||
|
||||
public function createSearchResult(SearchableInterface $entity): SearchIndex
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach ($entity->getSearchValues() as $value) {
|
||||
$values[] = $value;
|
||||
}
|
||||
|
||||
$data = implode(' ', $values);
|
||||
|
||||
$class = get_class($entity);
|
||||
|
||||
if ($entity instanceof Proxy) {
|
||||
$class = ClassUtils::getRealClass($class);
|
||||
}
|
||||
|
||||
$searchResult = $this
|
||||
->em
|
||||
->getRepository(SearchIndex::class)
|
||||
->findOneBy(
|
||||
[
|
||||
'entityClass' => $class,
|
||||
'entityId' => $entity->getId()
|
||||
]
|
||||
);
|
||||
|
||||
if (!$searchResult) {
|
||||
$searchResult = new SearchIndex();
|
||||
$searchResult->setEntityClass($class);
|
||||
$searchResult->setEntityId($entity->getId());
|
||||
}
|
||||
|
||||
$searchResult->setTitle($entity->getSearchTitle());
|
||||
$searchResult->setData($data);
|
||||
|
||||
return $searchResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all searchable Doctrine entities.
|
||||
*/
|
||||
public function getSearchableClasses(): array
|
||||
{
|
||||
$metadata = $this->em->getMetadataFactory()->getAllMetadata();
|
||||
$searchables = [];
|
||||
|
||||
foreach ($metadata as $meta) {
|
||||
if ($meta->reflClass->implementsInterface(SearchableInterface::class)) {
|
||||
$searchables[] = $meta->name;
|
||||
}
|
||||
}
|
||||
|
||||
return $searchables;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user