Skip to content

Commit 50f2c96

Browse files
Benjamin Schultzbschultz
authored andcommitted
Cleanup and optimize code
Add strict types and return types where it was missing.
1 parent c08343a commit 50f2c96

30 files changed

+147
-84
lines changed

src/Cache/ComponentsWarmer.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Qossmic\TwigDocBundle\Cache;
46

7+
use Psr\Cache\InvalidArgumentException;
8+
use Psr\Container\ContainerExceptionInterface;
59
use Psr\Container\ContainerInterface;
10+
use Psr\Container\NotFoundExceptionInterface;
611
use Qossmic\TwigDocBundle\Service\ComponentService;
712
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
813

9-
class ComponentsWarmer implements CacheWarmerInterface
14+
readonly class ComponentsWarmer implements CacheWarmerInterface
1015
{
11-
public function __construct(private readonly ContainerInterface $container)
16+
public function __construct(private ContainerInterface $container)
1217
{
1318
}
1419

@@ -17,6 +22,11 @@ public function isOptional(): bool
1722
return true;
1823
}
1924

25+
/**
26+
* @throws ContainerExceptionInterface
27+
* @throws NotFoundExceptionInterface
28+
* @throws InvalidArgumentException
29+
*/
2030
public function warmUp(string $cacheDir, ?string $buildDir = null): array
2131
{
2232
$componentService ??= $this->container->get('twig_doc.service.component');

src/Component/ComponentInvalid.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@
99
/**
1010
* @codeCoverageIgnore
1111
*/
12-
class ComponentInvalid
12+
readonly class ComponentInvalid
1313
{
1414
public function __construct(
15-
public readonly ConstraintViolationList $violationList,
16-
public readonly array $originalConfig
15+
public ConstraintViolationList $violationList,
16+
public array $originalConfig
1717
) {
1818
}
1919
}

src/Component/ComponentItem.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,21 +13,29 @@ class ComponentItem
1313
{
1414
#[Assert\NotBlank]
1515
private string $name;
16+
1617
#[Assert\NotBlank]
1718
private string $title;
19+
1820
#[Assert\NotBlank]
1921
private string $description;
22+
2023
#[Assert\Type('array')]
2124
private array $tags;
25+
2226
#[Assert\Type('array')]
2327
private array $parameters;
28+
2429
#[Assert\Type('array')]
2530
private array $variations;
31+
2632
#[Assert\Valid]
2733
private ComponentCategory $category;
34+
2835
#[Assert\Length(max: 4096)]
2936
#[Assert\NotBlank]
3037
private string $projectPath;
38+
3139
#[Assert\Length(max: 4096)]
3240
#[Assert\NotBlank]
3341
private string $renderPath;

src/Component/ComponentItemFactory.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,15 @@
99
use Symfony\Component\Validator\ConstraintViolationList;
1010
use Symfony\Component\Validator\Validator\ValidatorInterface;
1111

12-
class ComponentItemFactory
12+
readonly class ComponentItemFactory
1313
{
14-
public function __construct(private readonly ValidatorInterface $validator, private readonly CategoryService $categoryService)
14+
public function __construct(private ValidatorInterface $validator, private CategoryService $categoryService)
1515
{
1616
}
1717

18+
/**
19+
* @throws InvalidComponentConfigurationException
20+
*/
1821
public function create(array $data): ComponentItem
1922
{
2023
$item = $this->createItem($data);
@@ -28,7 +31,7 @@ public function create(array $data): ComponentItem
2831
isset($data['sub_category']) ? 'sub_category' : 'category',
2932
$data['sub_category'] ?? $data['category'],
3033
implode(', ', array_keys($this->categoryService->getCategories())),
31-
implode(', ', array_map(fn (ComponentCategory $category) => $category->getName(), $this->categoryService->getSubCategories()))
34+
implode(', ', array_map(static fn (ComponentCategory $category) => $category->getName(), $this->categoryService->getSubCategories()))
3235
)
3336
);
3437
throw new InvalidComponentConfigurationException($violations);
@@ -68,12 +71,14 @@ public function getParamsFromVariables(array $variables): array
6871
foreach ($variables as $dotted) {
6972
$keys = explode('.', $dotted);
7073
$c = &$r[array_shift($keys)];
74+
7175
foreach ($keys as $key) {
7276
if (isset($c[$key]) && $c[$key] === true) {
7377
$c[$key] = [];
7478
}
7579
$c = &$c[$key];
7680
}
81+
7782
if ($c === null) {
7883
$c = 'Scalar';
7984
}

src/Component/ComponentItemList.php

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Qossmic\TwigDocBundle\Component;
46

57
/**
@@ -34,7 +36,7 @@ public function paginate(int $start = 0, int $limit = 15): array
3436

3537
public function sort(string $field, string $direction = self::SORT_ASC): void
3638
{
37-
if (!\in_array($field, $this->sortableFields)) {
39+
if (!\in_array($field, $this->sortableFields, true)) {
3840
throw new \InvalidArgumentException(sprintf('field "%s" is not sortable', $field));
3941
}
4042

@@ -52,13 +54,15 @@ public function sort(string $field, string $direction = self::SORT_ASC): void
5254
public function filter(string $query, ?string $type): self
5355
{
5456
$components = [];
57+
5558
switch ($type) {
5659
case 'category':
5760
$components = array_filter(
5861
$this->getArrayCopy(),
59-
function (ComponentItem $item) use ($query) {
62+
static function (ComponentItem $item) use ($query) {
6063
$category = $item->getCategory()->getName();
6164
$parent = $item->getCategory()->getParent();
65+
6266
while ($parent !== null) {
6367
$category = $parent->getName();
6468
$parent = $parent->getParent();
@@ -72,28 +76,28 @@ function (ComponentItem $item) use ($query) {
7276
case 'sub_category':
7377
$components = array_filter(
7478
$this->getArrayCopy(),
75-
fn (ComponentItem $item) => $item->getCategory()->getParent() !== null
79+
static fn (ComponentItem $item) => $item->getCategory()->getParent() !== null
7680
&& strtolower($item->getCategory()->getName()) === strtolower($query)
7781
);
7882

7983
break;
8084
case 'tags':
8185
$tags = array_map('trim', explode(',', strtolower($query)));
82-
$components = array_filter($this->getArrayCopy(), function (ComponentItem $item) use ($tags) {
86+
$components = array_filter($this->getArrayCopy(), static function (ComponentItem $item) use ($tags) {
8387
return array_intersect($tags, array_map('strtolower', $item->getTags())) !== [];
8488
});
8589

8690
break;
8791
case 'name':
8892
$components = array_filter(
8993
$this->getArrayCopy(),
90-
fn (ComponentItem $item) => str_contains(strtolower($item->getName()), strtolower($query))
94+
static fn (ComponentItem $item) => str_contains(strtolower($item->getName()), strtolower($query))
9195
);
9296

9397
break;
9498
default:
95-
foreach (['category', 'sub_category', 'tags', 'name'] as $type) {
96-
$components = array_merge($components, (array) $this->filter($query, $type));
99+
foreach (['category', 'sub_category', 'tags', 'name'] as $componentType) {
100+
$components = array_merge($components, (array) $this->filter($query, $componentType));
97101
}
98102

99103
break;

src/Configuration/ParserInterface.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Qossmic\TwigDocBundle\Configuration;
46

57
interface ParserInterface

src/Configuration/YamlParser.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Qossmic\TwigDocBundle\Configuration;
46

57
use Symfony\Component\Yaml\Yaml;
@@ -21,15 +23,16 @@ private function fixIndentation(string $content): string
2123

2224
$firstLineDetected = false;
2325
$indentationWhitespace = null;
24-
2526
$lines = [];
2627

2728
while ($fileObject->valid()) {
2829
$line = $fileObject->current();
30+
2931
if (empty(trim($line))) {
3032
$fileObject->next();
3133
continue;
3234
}
35+
3336
if ($firstLineDetected === false) {
3437
$firstLineDetected = true;
3538
// check for whitespaces at the beginning
@@ -39,6 +42,7 @@ private function fixIndentation(string $content): string
3942
}
4043
$indentationWhitespace = $matches[1];
4144
}
45+
4246
$line = substr($line, \strlen($indentationWhitespace));
4347
$lines[] = $line;
4448
$fileObject->next();

src/Controller/TwigDocController.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@
1111
use Symfony\Component\HttpKernel\Profiler\Profiler;
1212
use Twig\Environment;
1313

14-
class TwigDocController
14+
readonly class TwigDocController
1515
{
1616
public function __construct(
17-
private readonly Environment $twig,
18-
private readonly ComponentService $componentService,
19-
private readonly ?Profiler $profiler = null
17+
private Environment $twig,
18+
private ComponentService $componentService,
19+
private ?Profiler $profiler = null
2020
) {
2121
}
2222

src/DependencyInjection/Compiler/TwigDocCollectDocsPass.php

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Qossmic\TwigDocBundle\DependencyInjection\Compiler;
46

57
use Qossmic\TwigDocBundle\Component\ComponentCategory;
@@ -11,9 +13,9 @@
1113
use Symfony\Component\Finder\Finder;
1214
use Symfony\Component\Finder\SplFileInfo;
1315

14-
class TwigDocCollectDocsPass implements CompilerPassInterface
16+
readonly class TwigDocCollectDocsPass implements CompilerPassInterface
1517
{
16-
public function __construct(private readonly ParserInterface $parser)
18+
public function __construct(private ParserInterface $parser)
1719
{
1820
}
1921

@@ -22,6 +24,7 @@ public function process(ContainerBuilder $container): void
2224
if (!$container->hasExtension('twig_doc')) {
2325
return;
2426
}
27+
2528
$config = $container->getParameter('twig_doc.config');
2629
$directories = $this->resolveDirectories($container, $config['directories']);
2730
$container->getParameterBag()->remove('twig_doc.config');
@@ -51,9 +54,10 @@ public function process(ContainerBuilder $container): void
5154
$filename = $file->getFilename();
5255
$componentName = substr($filename, 0, strpos($filename, '.'));
5356

54-
if (array_filter($componentConfig, fn (array $data) => $data['name'] === $componentName)) {
55-
throw new InvalidConfigException(sprintf('component "%s" is configured twice, please configure either directly in the template or the general bundle configuration', $componentName));
57+
if (array_filter($componentConfig, static fn (array $data) => $data['name'] === $componentName)) {
58+
throw new InvalidConfigException(sprintf('Component "%s" is configured twice, please configure either directly in the template or the general bundle configuration', $componentName));
5659
}
60+
5761
$itemConfig = [
5862
'name' => $componentName,
5963
'path' => str_replace($projectDir.'/', '', $file->getRealPath()),
@@ -69,7 +73,6 @@ public function process(ContainerBuilder $container): void
6973
private function parseDoc(SplFileInfo $file, string $docIdentifier): ?array
7074
{
7175
$content = $file->getContents();
72-
7376
$pattern = sprintf("/\{#%s\s(.*)%s#}/s", $docIdentifier, $docIdentifier);
7477

7578
preg_match($pattern, $content, $matches);
@@ -84,10 +87,10 @@ private function parseDoc(SplFileInfo $file, string $docIdentifier): ?array
8487
private function enrichComponentsConfig(ContainerBuilder $container, array $directories, array $components): array
8588
{
8689
foreach ($components as &$component) {
87-
if (!isset($component['path'])) {
88-
$component['path'] = str_replace($container->getParameter('kernel.project_dir').'/', '', $this->getTemplatePath($component['name'], $directories));
90+
if (!isset($component['path']) && $templatePath = $this->getTemplatePath($component['name'], $directories)) {
91+
$component['path'] = str_replace($container->getParameter('kernel.project_dir').'/', '', $templatePath);
8992
}
90-
if (!isset($component['renderPath'])) {
93+
if (!isset($component['renderPath']) && isset($component['path'])) {
9194
$component['renderPath'] = str_replace($container->getParameter('twig.default_path').'/', '', $component['path']);
9295
}
9396
}
@@ -98,8 +101,7 @@ private function enrichComponentsConfig(ContainerBuilder $container, array $dire
98101
private function resolveDirectories(ContainerBuilder $container, array $directories): array
99102
{
100103
$directories[] = $container->getParameter('twig.default_path').'/components';
101-
102-
$directories = array_map(fn (string $dir) => $container->getParameterBag()->resolveValue($dir), $directories);
104+
$directories = array_map(static fn (string $dir) => $container->getParameterBag()->resolveValue($dir), $directories);
103105

104106
foreach ($directories as $idx => $dir) {
105107
if (!is_dir($dir)) {
@@ -113,9 +115,7 @@ private function resolveDirectories(ContainerBuilder $container, array $director
113115
private function getTemplatePath(string $name, array $directories): ?string
114116
{
115117
$template = sprintf('%s.html.twig', $name);
116-
117118
$finder = new Finder();
118-
119119
$files = $finder->in($directories)->files()->filter(fn (SplFileInfo $file) => $file->getFilename() === $template);
120120

121121
if ($files->count() > 1) {
@@ -128,6 +128,6 @@ private function getTemplatePath(string $name, array $directories): ?string
128128

129129
$files->getIterator()->rewind();
130130

131-
return $files->getIterator()->current();
131+
return $files->getIterator()->current()?->__toString();
132132
}
133133
}

src/DependencyInjection/Configuration.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
namespace Qossmic\TwigDocBundle\DependencyInjection;
46

57
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

0 commit comments

Comments
 (0)