Skip to content

Commit

Permalink
feat: Added Example PageController and more phpstan fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ambroisemaupate committed Jun 26, 2023
1 parent c08593d commit db8cec8
Show file tree
Hide file tree
Showing 39 changed files with 325 additions and 193 deletions.
14 changes: 11 additions & 3 deletions lib/Documents/src/DocumentArchiver.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ public function __construct(FilesystemOperator $documentsStorage)
}

/**
* @param array $documents
* @param iterable<DocumentInterface> $documents
* @param string $name
* @param bool $keepFolders
* @return string Zip file path
* @throws FilesystemException
*/
public function archive(array $documents, string $name, bool $keepFolders = true): string
public function archive(iterable $documents, string $name, bool $keepFolders = true): string
{
$filename = (new AsciiSlugger())->slug($name . ' ' . date('YmdHis'), '_') . '.zip';
$tmpFileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
Expand Down Expand Up @@ -60,8 +60,16 @@ public function archive(array $documents, string $name, bool $keepFolders = true
return $tmpFileName;
}

/**
* @param iterable<DocumentInterface> $documents
* @param string $name
* @param bool $keepFolders
* @param bool $unlink
* @return BinaryFileResponse
* @throws FilesystemException
*/
public function archiveAndServe(
array $documents,
iterable $documents,
string $name,
bool $keepFolders = true,
bool $unlink = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
use RZ\Roadiz\CoreBundle\Api\Dto\TranslationOutput;
use RZ\Roadiz\Core\AbstractEntities\TranslationInterface;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;

/**
* @deprecated Just use `translation_base` serialization group
Expand All @@ -18,6 +19,9 @@ class TranslationOutputDataTransformer implements DataTransformerInterface
*/
public function transform($data, string $to, array $context = []): object
{
if (!$data instanceof TranslationInterface) {
throw new \InvalidArgumentException('Data to transform must be instance of ' . TranslationInterface::class);
}
$output = new TranslationOutput();
$output->locale = $data->getPreferredLocale();
$output->defaultTranslation = $data->isDefaultTranslation();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,10 @@ protected function filterByCriteria(
if ($key == "tags" || $key == "tagExclusive") {
continue;
}
/*
/**
* Main QueryBuilder dispatch loop for
* custom properties criteria.
* @var QueryBuilderNodesSourcesBuildEvent $event
*/
$event = $this->dispatchQueryBuilderBuildEvent($qb, $key, $value);

Expand Down
8 changes: 5 additions & 3 deletions lib/RoadizCoreBundle/src/Repository/PrefixAwareRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,9 +321,11 @@ protected function classicLikeComparison(
}

foreach ($criteriaFields as $key => $value) {
$realKey = $this->getRealKey($qb, $key);
$fullKey = sprintf('LOWER(%s)', $realKey['prefix'] . $realKey['key']);
$qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value)));
if (\is_string($key)) {
$realKey = $this->getRealKey($qb, $key);
$fullKey = sprintf('LOWER(%s)', $realKey['prefix'] . $realKey['key']);
$qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value)));
}
}
return $qb;
}
Expand Down
19 changes: 13 additions & 6 deletions lib/RoadizCoreBundle/src/Repository/UrlAliasRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace RZ\Roadiz\CoreBundle\Repository;

use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Doctrine\Persistence\ManagerRegistry;
use RZ\Roadiz\CoreBundle\Entity\UrlAlias;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
Expand All @@ -28,18 +30,21 @@ public function __construct(
/**
* Get all url aliases linked to given node.
*
* @param integer $nodeId
* @param int|string|null $nodeId
*
* @return array
* @return iterable<UrlAlias>
*/
public function findAllFromNode($nodeId)
public function findAllFromNode(int|string|null $nodeId): iterable
{
if (null === $nodeId) {
return [];
}
$query = $this->_em->createQuery('
SELECT ua FROM RZ\Roadiz\CoreBundle\Entity\UrlAlias ua
INNER JOIN ua.nodeSource ns
INNER JOIN ns.node n
WHERE n.id = :nodeId')
->setParameter('nodeId', (int) $nodeId);
->setParameter('nodeId', $nodeId);

return $query->getResult();
}
Expand All @@ -48,14 +53,16 @@ public function findAllFromNode($nodeId)
* @param string $alias
*
* @return boolean
* @throws NoResultException
* @throws NonUniqueResultException
*/
public function exists($alias)
public function exists(string $alias): bool
{
$query = $this->_em->createQuery('
SELECT COUNT(ua.alias) FROM RZ\Roadiz\CoreBundle\Entity\UrlAlias ua
WHERE ua.alias = :alias')
->setParameter('alias', $alias);

return (bool) $query->getSingleScalarResult();
return $query->getSingleScalarResult() > 0;
}
}
6 changes: 5 additions & 1 deletion lib/RoadizCoreBundle/src/Routing/NodePathInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,16 @@ public function setContainsScheme(bool $containsScheme): NodePathInfo
*/
public function serialize(): string
{
return \json_encode([
$json = \json_encode([
'path' => $this->getPath(),
'parameters' => $this->getParameters(),
'is_complete' => $this->isComplete(),
'contains_scheme' => $this->containsScheme()
]);
if (false === $json) {
throw new \RuntimeException('Unable to serialize NodePathInfo');
}
return $json;
}

public function __serialize(): array
Expand Down
37 changes: 24 additions & 13 deletions lib/RoadizCoreBundle/src/Routing/NodeRouteHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ final class NodeRouteHelper
private LoggerInterface $logger;
private string $defaultControllerNamespace;
/**
* @var class-string
* @var class-string<AbstractController>
*/
private string $defaultControllerClass;
/**
* @var class-string|null
* @var class-string<AbstractController>|null
*/
private ?string $controller = null;

Expand Down Expand Up @@ -54,33 +54,44 @@ public function __construct(
/**
* Get controller class path for a given node.
*
* @return string
* @return class-string<AbstractController>|null
*/
public function getController(): string
public function getController(): ?string
{
if (null === $this->controller) {
$namespace = $this->getControllerNamespace();
$this->controller = $namespace . '\\' .
if (!$this->node->getNodeType()->isReachable()) {
return null;
}
$controllerClassName = $this->getControllerNamespace() . '\\' .
StringHandler::classify($this->node->getNodeType()->getName()) .
'Controller';

/*
* Use a default controller if no controller was found in Theme.
*/
if (!class_exists($this->controller) && $this->node->getNodeType()->isReachable()) {
if (\class_exists($controllerClassName)) {
$reflection = new \ReflectionClass($controllerClassName);
if (!$reflection->isSubclassOf(AbstractController::class)) {
throw new \InvalidArgumentException(
'Controller class ' . $controllerClassName . ' must extends ' . AbstractController::class
);
}
// @phpstan-ignore-next-line
$this->controller = $controllerClassName;
} else {
/*
* Use a default controller if no controller was found in Theme.
*/
$this->controller = $this->defaultControllerClass;
}
}

// @phpstan-ignore-next-line
return $this->controller;
}

protected function getControllerNamespace(): string
{
$namespace = $this->defaultControllerNamespace;
if (null !== $this->theme) {
$refl = new \ReflectionClass($this->theme->getClassName());
$namespace = $refl->getNamespaceName() . '\\Controllers';
$reflection = new \ReflectionClass($this->theme->getClassName());
$namespace = $reflection->getNamespaceName() . '\\Controllers';
}
return $namespace;
}
Expand Down
5 changes: 3 additions & 2 deletions lib/RoadizCoreBundle/src/Routing/NodeUrlMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
use RZ\Roadiz\CoreBundle\Entity\Theme;
use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;
Expand All @@ -21,7 +22,7 @@ final class NodeUrlMatcher extends DynamicUrlMatcher implements NodeUrlMatcherIn
{
protected PathResolverInterface $pathResolver;
/**
* @var class-string
* @var class-string<AbstractController>
*/
private string $defaultControllerClass;

Expand All @@ -47,7 +48,7 @@ public function getDefaultSupportedFormatExtension(): string
* @param PreviewResolverInterface $previewResolver
* @param Stopwatch $stopwatch
* @param LoggerInterface $logger
* @param class-string $defaultControllerClass
* @param class-string<AbstractController> $defaultControllerClass
*/
public function __construct(
PathResolverInterface $pathResolver,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function aggregatePath(NodesSources $nodesSources, array $parameters = []
/**
* @param Node $parent
*
* @return array
* @return array<int, int|string>
*/
protected function getParentsIds(Node $parent): array
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ protected function getFormattedQuery(string $q, int $proximity = 1): array
* @see https://lucene.apache.org/solr/guide/6_6/the-standard-query-parser.html#TheStandardQueryParser-FuzzySearches
*/
$words = preg_split('#[\s,]+#', $q, -1, PREG_SPLIT_NO_EMPTY);
if (false === $words) {
throw new \RuntimeException('Cannot split query string.');
}
$fuzzyiedQuery = implode(' ', array_map(function (string $word) use ($proximity) {
/*
* Do not fuzz short words: Solr crashes
Expand Down
9 changes: 8 additions & 1 deletion lib/RoadizCoreBundle/src/SearchEngine/ClientRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,17 @@ public function __construct(ContainerInterface $container)

public function getClient(): ?Client
{
return $this->container->get(
$client = $this->container->get(
'roadiz_core.solr.client',
ContainerInterface::NULL_ON_INVALID_REFERENCE
);
if (null === $client) {
return null;
}
if (!($client instanceof Client)) {
throw new \RuntimeException('Solr client must be an instance of ' . Client::class);
}
return $client;
}

public function isClientReady(?Client $client): bool
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,11 @@ protected function nativeSearch(
'params' => $query->getParams(),
]);

$query = $this->eventDispatcher->dispatch(
/** @var DocumentSearchQueryEvent $event */
$event = $this->eventDispatcher->dispatch(
new DocumentSearchQueryEvent($query, $args)
)->getQuery();
);
$query = $event->getQuery();

$solrRequest = $this->getSolr()->execute($query);
return $solrRequest->getData();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function __construct(string $classname, mixed $identifier)
}

/**
* @return string
* @return class-string
*/
public function getClassname(): string
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,11 @@ protected function nativeSearch(
'params' => $query->getParams(),
]);

$query = $this->eventDispatcher->dispatch(
/** @var NodeSourceSearchQueryEvent $event */
$event = $this->eventDispatcher->dispatch(
new NodeSourceSearchQueryEvent($query, $args)
)->getQuery();
);
$query = $event->getQuery();

$solrRequest = $this->getSolr()->execute($query);
return $solrRequest->getData();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ public function getDocumentId(): int|string
public function getFieldsAssoc(bool $subResource = false): array
{
$event = new DocumentTranslationIndexingEvent($this->documentTranslation, [], $this);

return $this->dispatcher->dispatch($event)->getAssociations();
/** @var DocumentTranslationIndexingEvent $event */
$event = $this->dispatcher->dispatch($event);
return $event->getAssociations();
}

/**
Expand Down
5 changes: 3 additions & 2 deletions lib/RoadizCoreBundle/src/SearchEngine/SolariumNodeSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@ public function getDocumentId(): int|string
public function getFieldsAssoc(bool $subResource = false): array
{
$event = new NodesSourcesIndexingEvent($this->nodeSource, [], $this);

return $this->dispatcher->dispatch($event)->getAssociations();
/** @var NodesSourcesIndexingEvent $event */
$event = $this->dispatcher->dispatch($event);
return $event->getAssociations();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,15 @@ private function getTranslationFromLocale(string $locale): ?TranslationInterface
private function getTranslationFromRequest(): ?TranslationInterface
{
$request = $this->requestStack->getMainRequest();
if (
null !== $request &&
null !== $translation = $this->getTranslationFromLocale(
$request->query->get('_locale', $request->getLocale())
)
) {
return $translation;

if (null !== $request) {
$locale = $request->query->get('_locale', $request->getLocale());
if (
\is_string($locale) &&
null !== $translation = $this->getTranslationFromLocale($locale)
) {
return $translation;
}
}

return $this->managerRegistry
Expand Down
Loading

0 comments on commit db8cec8

Please sign in to comment.