Skip to content

Commit

Permalink
Fix some psalm issues
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed Apr 5, 2021
1 parent c764727 commit 5131c90
Show file tree
Hide file tree
Showing 31 changed files with 117 additions and 117 deletions.
17 changes: 16 additions & 1 deletion psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<code>array&lt;string, array&lt;string, array&lt;string, array&lt;string, array&lt;string, string&gt;&gt;&gt;&gt;&gt;</code>
</InvalidReturnType>
</file>
<!--The next error is due to not installed Doctrine ORM\ODM-->
<!-- The next error is due to not installed Doctrine ORM\ODM -->
<file src="src/Admin/AdminHelper.php">
<UndefinedClass occurrences="1">
<code>DoctrinePersistentCollection</code>
Expand All @@ -25,4 +25,19 @@
<code>array_merge(array_flip($keys), $this-&gt;elements)</code>
</InvalidPropertyAssignmentValue>
</file>
<!-- This error is made on purpose for php version < 8 -->
<file src="tests/Fixtures/Entity/FooToStringNull.php">
<InvalidToString occurrences="1">
<code>__toString</code>
</InvalidToString>
<NullableReturnStatement occurrences="1">
<code>null</code>
</NullableReturnStatement>
</file>
<!-- Will be fixed in Symfony 5.3 https://github.com/symfony/symfony/pull/40604 -->
<file src="src/Translator/Extractor/AdminExtractor.php">
<MoreSpecificImplementedParamType occurrences="1">
<code>$resource</code>
</MoreSpecificImplementedParamType>
</file>
</files>
5 changes: 4 additions & 1 deletion psalm.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<psalm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" errorLevel="5" resolveFromConfigFile="true" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" autoloader="vendor/bin/.phpunit/phpunit/vendor/autoload.php" errorBaseline="psalm-baseline.xml">
<psalm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" errorLevel="4" resolveFromConfigFile="true" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" autoloader="vendor/bin/.phpunit/phpunit/vendor/autoload.php" errorBaseline="psalm-baseline.xml">
<projectFiles>
<directory name="src"/>
<directory name="tests"/>
Expand All @@ -14,5 +14,8 @@
</plugins>
<issueHandlers>
<PluginIssue name="ContainerDependency" errorLevel="suppress"/>
<InternalClass errorLevel="suppress"/>
<InternalMethod errorLevel="suppress"/>
<InternalProperty errorLevel="suppress"/>
</issueHandlers>
</psalm>
9 changes: 2 additions & 7 deletions src/Action/SearchAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace Sonata\AdminBundle\Action;

use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Admin\BreadcrumbsBuilderInterface;
use Sonata\AdminBundle\Admin\Pool;
use Sonata\AdminBundle\Search\SearchHandler;
Expand Down Expand Up @@ -87,11 +86,7 @@ public function __invoke(Request $request): Response
try {
$admin = $this->pool->getAdminByAdminCode($request->get('admin'));
} catch (ServiceNotFoundException $e) {
throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
}

if (!$admin instanceof AdminInterface) {
throw new \RuntimeException('The requested service is not an Admin instance');
throw new \RuntimeException('Unable to find the Admin instance', (int) $e->getCode(), $e);
}

$results = [];
Expand All @@ -113,7 +108,7 @@ public function __invoke(Request $request): Response
'id' => $admin->id($result),
];
}
$page = (int) $pager->getPage();
$page = $pager->getPage();
$total = $pager->countResults();
}

Expand Down
8 changes: 5 additions & 3 deletions src/Action/SetObjectFieldValueAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ public function __invoke(Request $request): JsonResponse
), Response::HTTP_METHOD_NOT_ALLOWED);
}

$rootObject = $object = $admin->getObject($objectId);

$object = $admin->getObject($objectId);
if (!$object) {
return new JsonResponse('Object does not exist', Response::HTTP_NOT_FOUND);
}
Expand All @@ -121,10 +120,13 @@ public function __invoke(Request $request): JsonResponse
}

$propertyPath = new PropertyPath($field);
$rootObject = $object;

// If property path has more than 1 element, take the last object in order to validate it
if ($propertyPath->getLength() > 1) {
$object = $this->propertyAccessor->getValue($object, $propertyPath->getParent());
$parent = $propertyPath->getParent();
\assert(null !== $parent);
$object = $this->propertyAccessor->getValue($object, $parent);

$elements = $propertyPath->getElements();
$field = end($elements);
Expand Down
28 changes: 16 additions & 12 deletions src/Admin/AbstractAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ final public function getBaseRoutePattern(): string

if ($this->isChild()) { // the admin class is a child, prefix it with the parent route pattern
$baseRoutePattern = $this->baseRoutePattern;
if (!$this->baseRoutePattern) {
if (!$baseRoutePattern) {
preg_match(self::CLASS_REGEX, $this->class, $matches);

if (!$matches) {
Expand Down Expand Up @@ -625,7 +625,7 @@ final public function getBaseRouteName(): string

if ($this->isChild()) { // the admin class is a child, prefix it with the parent route name
$baseRouteName = $this->baseRouteName;
if (!$this->baseRouteName) {
if (!$baseRouteName) {
preg_match(self::CLASS_REGEX, $this->class, $matches);

if (!$matches) {
Expand Down Expand Up @@ -675,6 +675,7 @@ final public function getClass(): string
}

$subClass = $this->getRequest()->query->get('subclass');
\assert(\is_string($subClass));

if (!$this->hasSubClass($subClass)) {
throw new \LogicException(sprintf('Subclass "%s" is not defined.', $subClass));
Expand Down Expand Up @@ -713,7 +714,7 @@ final public function hasSubClass(string $name): bool
final public function hasActiveSubClass(): bool
{
if (\count($this->subClasses) > 0 && $this->hasRequest()) {
return null !== $this->getRequest()->query->get('subclass');
return \is_string($this->getRequest()->query->get('subclass'));
}

return false;
Expand Down Expand Up @@ -741,6 +742,7 @@ final public function getActiveSubclassCode(): string
}

$subClass = $this->getRequest()->query->get('subclass');
\assert(\is_string($subClass));

if (!$this->hasSubClass($subClass)) {
throw new \LogicException(sprintf(
Expand Down Expand Up @@ -786,7 +788,7 @@ final public function getBatchActions(): array
final public function getRoutes(): RouteCollectionInterface
{
$this->buildRoutes();
\assert($this->routes !== null);
\assert(null !== $this->routes);

return $this->routes;
}
Expand Down Expand Up @@ -1003,7 +1005,7 @@ final public function getSideMenu(string $action, ?AdminInterface $childAdmin =
}

$this->buildTabMenu($action, $childAdmin);
\assert($this->menu !== null);
\assert(null !== $this->menu);

return $this->menu;
}
Expand Down Expand Up @@ -1127,7 +1129,7 @@ final public function getParentFieldDescription(): FieldDescriptionInterface
static::class
));
}
\assert($this->parentFieldDescription !== null);
\assert(null !== $this->parentFieldDescription);

return $this->parentFieldDescription;
}
Expand Down Expand Up @@ -1159,7 +1161,7 @@ final public function getSubject(): object
static::class
));
}
\assert($this->subject !== null);
\assert(null !== $this->subject);

return $this->subject;
}
Expand Down Expand Up @@ -1598,7 +1600,7 @@ final public function createObjectSecurity(object $object): void

final public function isGranted($name, ?object $object = null): bool
{
$objectRef = $object ? sprintf('/%s#%s', spl_object_hash($object), $this->id($object)) : '';
$objectRef = $object ? sprintf('/%s#%s', spl_object_hash($object), $this->id($object) ?? '') : '';
$key = md5(json_encode($name).$objectRef);

if (!\array_key_exists($key, $this->cacheIsGranted)) {
Expand Down Expand Up @@ -1626,7 +1628,7 @@ public function id(object $model): ?string
final public function getShow(): FieldDescriptionCollection
{
$this->buildShow();
\assert($this->show !== null);
\assert(null !== $this->show);

return $this->show;
}
Expand Down Expand Up @@ -1693,10 +1695,12 @@ public function getPerPageOptions(): array

/**
* Returns true if the per page value is allowed, false otherwise.
*
* @param mixed $perPage
*/
final public function determinedPerPageValue(int $perPage): bool
final public function determinedPerPageValue($perPage): bool
{
return \in_array($perPage, $this->getPerPageOptions(), true);
return \is_int($perPage) && \in_array($perPage, $this->getPerPageOptions(), true);
}

final public function isAclEnabled(): bool
Expand Down Expand Up @@ -1917,7 +1921,7 @@ final public function getTemplateRegistry(): MutableTemplateRegistryInterface
if (false === $this->hasTemplateRegistry()) {
throw new \LogicException(sprintf('Unable to find the template registry for admin `%s`.', static::class));
}
\assert($this->templateRegistry !== null);
\assert(null !== $this->templateRegistry);

return $this->templateRegistry;
}
Expand Down
7 changes: 1 addition & 6 deletions src/Block/AdminSearchBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace Sonata\AdminBundle\Block;

use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Admin\Pool;
use Sonata\AdminBundle\Search\SearchHandler;
use Sonata\AdminBundle\Templating\TemplateRegistryInterface;
Expand Down Expand Up @@ -72,11 +71,7 @@ public function execute(BlockContextInterface $blockContext, ?Response $response
try {
$admin = $this->pool->getAdminByAdminCode($blockContext->getSetting('admin_code'));
} catch (ServiceNotFoundException $e) {
throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
}

if (!$admin instanceof AdminInterface) {
throw new \RuntimeException('The requested service is not an Admin instance');
throw new \RuntimeException('Unable to find the Admin instance', (int) $e->getCode(), $e);
}

$admin->checkAccess('list');
Expand Down
6 changes: 2 additions & 4 deletions src/Controller/CRUDController.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Exception\LockException;
use Sonata\AdminBundle\Exception\ModelManagerException;
use Sonata\AdminBundle\FieldDescription\FieldDescriptionCollection;
use Sonata\AdminBundle\Model\AuditManagerInterface;
use Sonata\AdminBundle\Templating\TemplateRegistryInterface;
use Sonata\AdminBundle\Util\AdminAclUserManagerInterface;
Expand Down Expand Up @@ -390,7 +389,7 @@ public function batchAction(Request $request): Response
$allElements = $forwardedRequest->request->getBoolean('all_elements');

$forwardedRequest->request->set('idx', $idx);
$forwardedRequest->request->set('all_elements', $allElements);
$forwardedRequest->request->set('all_elements', (string) $allElements);

$data = $forwardedRequest->request->all();
$data['all_elements'] = $allElements;
Expand Down Expand Up @@ -618,7 +617,6 @@ public function showAction(Request $request): Response
$this->admin->setSubject($object);

$fields = $this->admin->getShow();
\assert($fields instanceof FieldDescriptionCollection);

$template = $this->templateRegistry->getTemplate('show');

Expand Down Expand Up @@ -1201,7 +1199,7 @@ protected function validateCsrfToken(string $intention): void
*/
protected function escapeHtml(string $s): string
{
return htmlspecialchars((string) $s, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
return htmlspecialchars($s, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/DependencyInjection/Admin/AbstractTaggedAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ final public function getFilterPersister(): FilterPersisterInterface
if (!$this->hasFilterPersister()) {
throw new \LogicException(sprintf('Admin "%s" has no filter persister.', static::class));
}
\assert($this->filterPersister !== null);
\assert(null !== $this->filterPersister);

return $this->filterPersister;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,11 @@ public function process(ContainerBuilder $container): void
$groups[$resolvedGroupName]['roles'] = $groupDefaults[$resolvedGroupName]['roles'];
}

if (isset($groups[$resolvedGroupName]['on_top']) && !empty($group['on_top']) && $group['on_top']
&& (\count($groups[$resolvedGroupName]['items']) > 1)) {
if (
isset($groups[$resolvedGroupName]['on_top'])
&& !empty($group['on_top'])
&& (\count($groups[$resolvedGroupName]['items']) > 1)
) {
throw new \RuntimeException('You can\'t use "on_top" option with multiple same name groups.');
}
if (empty($group['on_top'])) {
Expand Down
17 changes: 3 additions & 14 deletions src/EventListener/AssetsInstallCommandListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,9 @@
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\KernelInterface;

/**
* This listener extends `assets:install` command when SonataCoreBundle will be not register. Files from `Resources/private/SonataCoreBundleAssets`
Expand Down Expand Up @@ -74,15 +72,12 @@ public function copySonataCoreBundleAssets(ConsoleTerminateEvent $event): void

private function execute(InputInterface $input, OutputInterface $output, FrameworkApplication $application): int
{
/**
* @var KernelInterface
*/
$kernel = $application->getKernel();

$targetArg = rtrim($input->getArgument('target') ?? '', '/');

if (!$targetArg) {
$targetArg = $this->getPublicDirectory($kernel->getContainer());
$targetArg = $this->getPublicDirectory();
}

if (!is_dir($targetArg)) {
Expand Down Expand Up @@ -168,7 +163,6 @@ private function execute(InputInterface $input, OutputInterface $output, Framewo
case 'warning':
$io->$ioMethod('All deprecated SonataCoreBundle assets from SonataAdminBundle were successfully installed.');
break;
case 'error':
default:
$io->$ioMethod('No deprecated SonataCoreBundle assets from SonataAdminBundle were provided by any bundle.');
break;
Expand Down Expand Up @@ -245,15 +239,10 @@ private function hardCopy(string $originDir, string $targetDir): string
return self::METHOD_COPY;
}

private function getPublicDirectory(ContainerInterface $container): string
private function getPublicDirectory(): string
{
$defaultPublicDir = 'public';

if (null === $this->projectDir && !$container->hasParameter('kernel.project_dir')) {
return $defaultPublicDir;
}

$composerFilePath = ($this->projectDir ?? $container->getParameter('kernel.project_dir')).'/composer.json';
$composerFilePath = $this->projectDir.'/composer.json';

if (!file_exists($composerFilePath)) {
return $defaultPublicDir;
Expand Down
2 changes: 1 addition & 1 deletion src/FieldDescription/BaseFieldDescription.php
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ protected function getFieldValue(?object $object, ?string $fieldName)
} catch (ExceptionInterface $exception) {
throw new NoValueException(
sprintf('Cannot access property "%s" in class "%s".', $this->getName(), \get_class($object)),
$exception->getCode(),
(int) $exception->getCode(),
$exception
);
}
Expand Down
3 changes: 2 additions & 1 deletion src/Mapper/BaseGroupedMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ public function with(string $name, array $options = []): self
'translation_domain' => $options['translation_domain'] ?? null,
]); // add new tab automatically
}
\assert(null !== $this->currentTab);

// if no tab is selected, we go the the main one named '_' ..
if ('default' !== $this->currentTab) {
Expand Down Expand Up @@ -372,7 +373,7 @@ protected function getCurrentGroupName(): string
]);
}
}
\assert($this->currentGroup !== null);
\assert(null !== $this->currentGroup);

return $this->currentGroup;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Route/RouteGeneratorInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function generateUrl(AdminInterface $admin, string $name, array $paramete
*
* @return array<string, mixed>
*
* @phpstan-return array{route: string, routeParameters: array, routeAbsolute: bool}
* @phpstan-return array{route: string, routeParameters: array<string, string>, routeAbsolute: bool}
*/
public function generateMenuUrl(AdminInterface $admin, string $name, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): array;

Expand Down
Loading

0 comments on commit 5131c90

Please sign in to comment.