Skip to content

Commit

Permalink
Bump phpstan to level 8 (#1027)
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet authored Mar 7, 2022
1 parent c185190 commit f2eecc2
Show file tree
Hide file tree
Showing 24 changed files with 157 additions and 112 deletions.
2 changes: 1 addition & 1 deletion phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ includes:
- phpstan-baseline.neon

parameters:
level: 6
level: 8
paths:
- src
- tests
Expand Down
2 changes: 1 addition & 1 deletion src/Block/BlockContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public function getSettings(): array
public function getSetting(string $name)
{
if (!\array_key_exists($name, $this->settings)) {
throw new \RuntimeException(sprintf('Unable to find the option `%s` (%s) - define the option in the related BlockServiceInterface', $name, $this->block->getType()));
throw new \RuntimeException(sprintf('Unable to find the option `%s` (%s) - define the option in the related BlockServiceInterface', $name, $this->block->getType() ?? ''));
}

return $this->settings[$name];
Expand Down
22 changes: 11 additions & 11 deletions src/Block/BlockContextManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ final class BlockContextManager implements BlockContextManagerInterface
/**
* @var array<string, array<string, mixed>>
*/
private $settingsByType;
private $settingsByType = [];

/**
* @var array<string, array<string, mixed>>
* @phpstan-var array<class-string, array<string, mixed>>
*/
private $settingsByClass;
private $settingsByClass = [];

/**
* @var array{by_class?: array<class-string, string>, by_type?: array<string, string>}
* @var array{by_class: array<class-string, string>, by_type: array<string, string>}
*/
private $cacheBlocks;

Expand All @@ -55,12 +55,12 @@ final class BlockContextManager implements BlockContextManagerInterface
private $logger;

/**
* @param array{by_class?: array<class-string, string>, by_type?: array<string, string>} $cacheBlocks
* @param array{by_class: array<class-string, string>, by_type: array<string, string>} $cacheBlocks
*/
public function __construct(
BlockLoaderInterface $blockLoader,
BlockServiceManagerInterface $blockService,
array $cacheBlocks = [],
array $cacheBlocks = ['by_class' => [], 'by_type' => []],
?LoggerInterface $logger = null
) {
$this->blockLoader = $blockLoader;
Expand Down Expand Up @@ -114,7 +114,7 @@ public function get($meta, array $settings = []): BlockContextInterface
} catch (ExceptionInterface $e) {
$this->logger->error(sprintf(
'[cms::blockContext] block.id=%s - error while resolving options - %s',
$block->getId(),
$block->getId() ?? '',
$e->getMessage()
));

Expand Down Expand Up @@ -163,7 +163,7 @@ static function (Options $options, $value): string {

// add type and class settings for block
$class = ClassUtils::getClass($block);
$settingsByType = $this->settingsByType[$block->getType()] ?? [];
$settingsByType = $this->settingsByType[$block->getType() ?? ''] ?? [];
$settingsByClass = $this->settingsByClass[$class] ?? [];
$optionsResolver->setDefaults(array_merge($settingsByType, $settingsByClass));
}
Expand All @@ -184,14 +184,14 @@ private function setDefaultExtraCacheKeys(BlockContextInterface $blockContext, a

// type by block class
$class = ClassUtils::getClass($block);
$cacheServiceId = $this->cacheBlocks['by_class'][$class] ?? false;
$cacheServiceId = $this->cacheBlocks['by_class'][$class] ?? null;

// type by block service
if (!$cacheServiceId) {
$cacheServiceId = $this->cacheBlocks['by_type'][$block->getType()] ?? false;
if (null === $cacheServiceId) {
$cacheServiceId = $this->cacheBlocks['by_type'][$block->getType() ?? ''] ?? null;
}

if (!$cacheServiceId) {
if (null === $cacheServiceId) {
// no context cache needed
return;
}
Expand Down
11 changes: 7 additions & 4 deletions src/Block/BlockRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ public function render(BlockContextInterface $blockContext, ?Response $response
$block = $blockContext->getBlock();

if (null !== $this->logger) {
$this->logger->info(sprintf('[cms::renderBlock] block.id=%d, block.type=%s ', $block->getId(), $block->getType()));
$this->logger->info(
sprintf('[cms::renderBlock] block.id=%d, block.type=%s', $block->getId() ?? '', $block->getType() ?? '')
);
}

try {
Expand All @@ -83,7 +85,7 @@ public function render(BlockContextInterface $blockContext, ?Response $response
if (null !== $this->logger) {
$this->logger->error(sprintf(
'[cms::renderBlock] block.id=%d - error while rendering block - %s',
$block->getId(),
$block->getId() ?? '',
$exception->getMessage()
), compact('exception'));
}
Expand Down Expand Up @@ -118,8 +120,9 @@ private function addMetaInformation(Response $response, BlockContextInterface $b
{
// a response exists, use it
if (null !== $this->lastResponse && $this->lastResponse->isCacheable()) {
if (null !== $this->lastResponse->getTtl()) {
$response->setTtl($this->lastResponse->getTtl());
$lastResponseTtl = $this->lastResponse->getTtl();
if (null !== $lastResponseTtl) {
$response->setTtl($lastResponseTtl);
}
$response->setPublic();
} elseif (null !== $this->lastResponse) { // not cacheable
Expand Down
21 changes: 12 additions & 9 deletions src/Block/BlockServiceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ final class BlockServiceManager implements BlockServiceManagerInterface
/**
* @var bool
*/
private $inValidate;
private $inValidate = false;

/**
* @var array<string, string[]>
Expand All @@ -53,13 +53,14 @@ public function __construct(ContainerInterface $container)

public function get(BlockInterface $block): BlockServiceInterface
{
if (null === $block->getType()) {
$blockType = $block->getType();
if (null === $blockType) {
throw new \RuntimeException('The block service `` does not exist');
}

$this->load($block->getType());
$this->load($blockType);

$service = $this->services[$block->getType()];
$service = $this->services[$blockType];
\assert($service instanceof BlockServiceInterface);

return $service;
Expand Down Expand Up @@ -121,6 +122,7 @@ public function getServicesByContext(string $context, bool $includeContainers =

$services = [];

/** @var string[] $containers */
$containers = $this->container->getParameter('sonata.block.container.types');

foreach ($this->contexts[$context] as $name) {
Expand All @@ -147,7 +149,7 @@ public function validate(ErrorElement $errorElement, BlockInterface $block): voi
return;
}

// As block can be nested, we only need to validate the main block, no the children
// As block can be nested, we only need to validate the main block, not the children
try {
$this->inValidate = true;

Expand All @@ -173,11 +175,12 @@ private function load(string $type): BlockServiceInterface
}

if (!$this->services[$type] instanceof BlockServiceInterface) {
$this->services[$type] = $this->container->get($type);
}
$blockService = $this->container->get($type);
if (!$blockService instanceof BlockServiceInterface) {
throw new \RuntimeException(sprintf('The service %s does not implement BlockServiceInterface', $type));
}

if (!$this->services[$type] instanceof BlockServiceInterface) {
throw new \RuntimeException(sprintf('The service %s does not implement BlockServiceInterface', $type));
$this->services[$type] = $blockService;
}

return $this->services[$type];
Expand Down
9 changes: 7 additions & 2 deletions src/Block/Service/AbstractBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,11 @@ public function configureSettings(OptionsResolver $resolver): void

public function getCacheKeys(BlockInterface $block): array
{
$updatedAt = $block->getUpdatedAt();

return [
'block_id' => $block->getId(),
'updated_at' => null !== $block->getUpdatedAt() ? $block->getUpdatedAt()->format('U') : null,
'updated_at' => null !== $updatedAt ? $updatedAt->format('U') : null,
];
}

Expand All @@ -82,7 +84,10 @@ public function load(BlockInterface $block): void

public function execute(BlockContextInterface $blockContext, ?Response $response = null): Response
{
return $this->renderResponse($blockContext->getTemplate(), [
$template = $blockContext->getTemplate();
\assert(null !== $template);

return $this->renderResponse($template, [
'block_context' => $blockContext,
'block' => $blockContext->getBlock(),
], $response);
Expand Down
5 changes: 4 additions & 1 deletion src/Block/Service/ContainerBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ public function configureEditForm(FormMapper $form, BlockInterface $block): void

public function execute(BlockContextInterface $blockContext, ?Response $response = null): Response
{
return $this->renderResponse($blockContext->getTemplate(), [
$template = $blockContext->getTemplate();
\assert(null !== $template);

return $this->renderResponse($template, [
'block' => $blockContext->getBlock(),
'decorator' => $this->getDecorator($blockContext->getSetting('layout')),
'settings' => $blockContext->getSettings(),
Expand Down
7 changes: 5 additions & 2 deletions src/Block/Service/MenuBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public function __construct(

public function execute(BlockContextInterface $blockContext, ?Response $response = null): Response
{
$template = $blockContext->getTemplate();
\assert(null !== $template);

$responseSettings = [
'menu' => $this->getMenu($blockContext),
'menu_options' => $this->getMenuOptions($blockContext->getSettings()),
Expand All @@ -67,10 +70,10 @@ public function execute(BlockContextInterface $blockContext, ?Response $response
];

if ('private' === $blockContext->getSetting('cache_policy')) {
return $this->renderPrivateResponse($blockContext->getTemplate(), $responseSettings, $response);
return $this->renderPrivateResponse($template, $responseSettings, $response);
}

return $this->renderResponse($blockContext->getTemplate(), $responseSettings, $response);
return $this->renderResponse($template, $responseSettings, $response);
}

public function configureCreateForm(FormMapper $form, BlockInterface $block): void
Expand Down
20 changes: 13 additions & 7 deletions src/Block/Service/RssBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;

/**
* @author Thomas Rabaix <[email protected]>
Expand Down Expand Up @@ -80,13 +83,13 @@ public function validate(ErrorElement $errorElement, BlockInterface $block): voi
{
$errorElement
->with('settings[url]')
->assertNotNull([])
->assertNotBlank()
->addConstraint(new NotNull())
->addConstraint(new NotBlank())
->end()
->with('settings[title]')
->assertNotNull([])
->assertNotBlank()
->assertLength(['max' => 50])
->addConstraint(new NotNull())
->addConstraint(new NotBlank())
->addConstraint(new Length(['max' => 50]))
->end();
}

Expand All @@ -107,7 +110,7 @@ public function execute(BlockContextInterface $blockContext, ?Response $response
// retrieve contents with a specific stream context to avoid php errors
$content = @file_get_contents($settings['url'], false, stream_context_create($options));

if ($content) {
if (false !== $content && '' !== $content) {
// generate a simple xml element
try {
$feeds = new \SimpleXMLElement($content);
Expand All @@ -118,7 +121,10 @@ public function execute(BlockContextInterface $blockContext, ?Response $response
}
}

return $this->renderResponse($blockContext->getTemplate(), [
$template = $blockContext->getTemplate();
\assert(null !== $template);

return $this->renderResponse($template, [
'feeds' => $feeds,
'block' => $blockContext->getBlock(),
'settings' => $settings,
Expand Down
5 changes: 4 additions & 1 deletion src/Block/Service/TemplateBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ final class TemplateBlockService extends AbstractBlockService implements Editabl
{
public function execute(BlockContextInterface $blockContext, ?Response $response = null): Response
{
return $this->renderResponse($blockContext->getTemplate(), [
$template = $blockContext->getTemplate();
\assert(null !== $template);

return $this->renderResponse($template, [
'block' => $blockContext->getBlock(),
'settings' => $blockContext->getSettings(),
], $response);
Expand Down
5 changes: 4 additions & 1 deletion src/Block/Service/TextBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ final class TextBlockService extends AbstractBlockService implements EditableBlo
{
public function execute(BlockContextInterface $blockContext, ?Response $response = null): Response
{
return $this->renderResponse($blockContext->getTemplate(), [
$template = $blockContext->getTemplate();
\assert(null !== $template);

return $this->renderResponse($template, [
'block' => $blockContext->getBlock(),
'settings' => $blockContext->getSettings(),
], $response);
Expand Down
5 changes: 3 additions & 2 deletions src/Command/DebugBlocksCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ public function configure(): void

public function execute(InputInterface $input, OutputInterface $output): int
{
if (null !== $input->getOption('context')) {
$services = $this->blockManager->getServicesByContext((string) $input->getOption('context'));
$context = $input->getOption('context');
if (\is_string($context)) {
$services = $this->blockManager->getServicesByContext($context);
} else {
$services = $this->blockManager->getServices();
}
Expand Down
19 changes: 13 additions & 6 deletions src/DependencyInjection/Compiler/TweakCompilerPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@ public function process(ContainerBuilder $container): void
$blockTypes = $container->getParameter('sonata_blocks.block_types');
/** @var array<string, mixed> $cacheBlocks */
$cacheBlocks = $container->getParameter('sonata_block.cache_blocks');
/** @var string[] $defaultContexs */
$defaultContexs = $container->getParameter('sonata_blocks.default_contexts');
/** @var string[] $defaultContexts */
$defaultContexts = $container->getParameter('sonata_blocks.default_contexts');

foreach ($container->findTaggedServiceIds('sonata.block') as $id => $tags) {
$container->getDefinition($id)
->setPublic(true);

$settings = $this->createBlockSettings($tags, $defaultContexs);
$settings = $this->createBlockSettings($tags, $defaultContexts);

// Register blocks dynamicaly
// Register blocks dynamically
if (!\array_key_exists($id, $blocks)) {
$blocks[$id] = $settings;
}
Expand Down Expand Up @@ -83,18 +83,25 @@ public function process(ContainerBuilder $container): void
}

/**
* NEXT_MAJOR: Change visibility to private.
*
* Apply configurations to the context manager.
*/
public function applyContext(ContainerBuilder $container): void
{
$definition = $container->findDefinition('sonata.block.context_manager');

foreach ($container->getParameter('sonata_block.blocks') as $service => $settings) {
/** @var array<string, array<string, mixed>> $blocks */
$blocks = $container->getParameter('sonata_block.blocks');
foreach ($blocks as $service => $settings) {
if (\count($settings['settings']) > 0) {
$definition->addMethodCall('addSettingsByType', [$service, $settings['settings'], true]);
}
}
foreach ($container->getParameter('sonata_block.blocks_by_class') as $class => $settings) {

/** @var array<class-string, array<string, mixed>> $blocksByClass */
$blocksByClass = $container->getParameter('sonata_block.blocks_by_class');
foreach ($blocksByClass as $class => $settings) {
if (\count($settings['settings']) > 0) {
$definition->addMethodCall('addSettingsByClass', [$class, $settings['settings'], true]);
}
Expand Down
3 changes: 2 additions & 1 deletion src/DependencyInjection/SonataBlockExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public function load(array $configs, ContainerBuilder $container): void

$processor = new Processor();
$configuration = $this->getConfiguration($configs, $container);
\assert(null !== $configuration);
$config = $processor->processConfiguration($configuration, $configs);

$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
Expand Down Expand Up @@ -131,7 +132,7 @@ public function configureCache(ContainerBuilder $container, array $config): void
->addTag('kernel.event_listener', ['event' => 'kernel.response', 'method' => 'onKernelResponse']);
}

$cacheBlocks = [];
$cacheBlocks = ['by_class' => [], 'by_type' => []];
foreach ($config['blocks'] as $service => $settings) {
$cacheBlocks['by_type'][$service] = $settings['cache'];
}
Expand Down
Loading

0 comments on commit f2eecc2

Please sign in to comment.