Skip to content

Commit

Permalink
Fix PHP Stan
Browse files Browse the repository at this point in the history
  • Loading branch information
maximehuran committed Jun 18, 2024
1 parent cbe5253 commit 95fe933
Show file tree
Hide file tree
Showing 14 changed files with 65 additions and 32 deletions.
7 changes: 6 additions & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ parameters:
# Test dependencies
- 'tests/Application/**/*'

# Skeleton files
- 'src/Resources/skeleton/*.php'

# Maker files
- 'src/Maker/*.php'

ignoreErrors:
- identifier: missingType.generics
- identifier: missingType.iterableValue
19 changes: 14 additions & 5 deletions src/Controller/FormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ public function viewAction(Request $request, string $code): Response
$data = [];
$isEdition = $request->isMethod('post');
if ($isEdition && ($data = $request->get('data'))) {
if (!\is_string($data)) {
throw $this->createNotFoundException();
}
$data = json_decode($data, true);
if (!\is_array($data)) {
throw $this->createNotFoundException();
Expand All @@ -84,6 +87,9 @@ public function viewAction(Request $request, string $code): Response
public function renderElementsAction(Request $request, SwitchAdminLocaleInterface $switchAdminLocale): Response
{
if ($uiElements = $request->get('ui_elements')) {
if (!\is_string($uiElements)) {
throw $this->createNotFoundException();
}
$uiElements = json_decode($uiElements, true);
if (!\is_array($uiElements)) {
throw $this->createNotFoundException();
Expand All @@ -92,7 +98,7 @@ public function renderElementsAction(Request $request, SwitchAdminLocaleInterfac

// if we have a locale value in the post data, we change the current
// admin locale to make the ui elements in the correct version.
if ($locale = $request->get('locale')) {
if (($locale = $request->get('locale')) && \is_string($locale)) {
$switchAdminLocale->switchLocale($locale);
}

Expand All @@ -104,8 +110,8 @@ public function renderElementsAction(Request $request, SwitchAdminLocaleInterfac
if (!isset($uiElementData['code'])) {
if (isset($uiElementData['type'], $uiElementData['fields'])) {
$uiElementData['code'] = $uiElementData['type'];
$uiElementData['data'] = $uiElementData['fields']; // @phpstan-ignore-line
unset($uiElementData['type'], $uiElementData['fields']); // @phpstan-ignore-line
$uiElementData['data'] = $uiElementData['fields'];
unset($uiElementData['type'], $uiElementData['fields']);
} else {
continue;
}
Expand Down Expand Up @@ -188,7 +194,7 @@ public function submitAction(Request $request, FileUploaderInterface $fileUpload
/**
* Build a new form data array with the uploaded file path instead of files, or current filenames on edition.
*
* @param mixed $requestData
* @param array|string $requestData
*
* @return array|mixed|string
*/
Expand Down Expand Up @@ -217,7 +223,10 @@ private function processFormDataWithoutChild(FormInterface $form, FileUploaderIn
{
if ($form->isValid() && $form->getData() instanceof UploadedFile) {
// Upload image selected by user
return $fileUploader->upload($form->getData(), $form->getConfig()->getOption('file-type'));
/** @var ?string $fileType */
$fileType = $form->getConfig()->getOption('file-type');

return $fileUploader->upload($form->getData(), $fileType);
}
if ($form->getConfig()->getType()->getInnerType() instanceof NativeFileType && !empty($requestData)) {
// Check if we have a string value for this fields which is the file path (During edition for example)
Expand Down
10 changes: 3 additions & 7 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,8 @@ final class Configuration implements ConfigurationInterface
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('monsieurbiz_sylius_richeditor');
if (method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$rootNode = /** @scrutinizer ignore-deprecated */ $treeBuilder->root('monsieurbiz_sylius_richeditor');
}
/** @var ArrayNodeDefinition $rootNode */
$rootNode = $treeBuilder->getRootNode();

$this->addUiElements($rootNode);

Expand All @@ -40,7 +36,7 @@ public function getConfigTreeBuilder(): TreeBuilder

private function addUiElements(ArrayNodeDefinition $rootNode): void
{
/** @scrutinizer ignore-call */
/** @phpstan-ignore-next-line */
$rootNode
->children()
->scalarNode('upload_directory')->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ final class MonsieurBizSyliusRichEditorExtension extends Extension
public function load(array $config, ContainerBuilder $container): void
{
$configuration = $this->getConfiguration([], $container);
$config = $this->processConfiguration(/** @scrutinizer ignore-type */ $configuration, $config);
$config = $this->processConfiguration($configuration, $config);
$container->setParameter('monsieurbiz.richeditor.config.ui_elements', $config['ui_elements']);
$container->setParameter('monsieurbiz.richeditor.config.upload_directory', $config['upload_directory']);
$container->setParameter('monsieurbiz.richeditor.config.image_upload_directory', $config['image_upload_directory']);
Expand Down
2 changes: 1 addition & 1 deletion src/DependencyInjection/UiElementRegistryPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ private function registerUiElement(string $code, array $configuration, Container
*/
private function validateUiElementResource(string $class): void
{
$interfaces = (array) (class_implements($class) ?? []);
$interfaces = (array) class_implements($class);

if (!\in_array(UiElementInterface::class, $interfaces, true)) {
throw new InvalidArgumentException(sprintf('Class "%s" must implement "%s" to be registered as a UiElement resource.', $class, UiElementInterface::class));
Expand Down
2 changes: 1 addition & 1 deletion src/Form/Type/AlignmentType.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function configureOptions(OptionsResolver $resolver): void
public function buildForm(FormBuilderInterface $builder, array $options): void
{
// Add justify choices depending on options
if ($options['show_justify']) {
if ($options['show_justify'] && \is_array($options['choices'])) {
$options['choices']['monsieurbiz_richeditor_plugin.form.align.justify'] = 'justify';
}
parent::buildForm($builder, $options);
Expand Down
2 changes: 1 addition & 1 deletion src/Form/Type/RichEditorType.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class RichEditorType extends TextType
public function buildView(FormView $view, FormInterface $form, array $options): void
{
$view->vars['attr']['data-component'] = 'rich-editor';
$view->vars['attr']['data-tags'] = implode(',', $options['tags'] ?? []);
$view->vars['attr']['data-tags'] = implode(',', \is_array($options['tags']) ? $options['tags'] : []);
if (null !== $options['locale']) {
$view->vars['attr']['data-locale'] = $options['locale'];
}
Expand Down
2 changes: 1 addition & 1 deletion src/Form/Type/UiElement/ImageType.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public function addEvents(FormBuilderInterface $builder, array $options): void
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
// Change image field constraints depending on submitted value
$options = $event->getForm()->get('image')->getConfig()->getOptions();
$options['constraints'] = RichEditorConstraints::getImageConstraints($event->getData(), 'image');
$options['constraints'] = RichEditorConstraints::getImageConstraints(\is_array($event->getData()) ? $event->getData() : [], 'image');
$event->getForm()->add('image', $this->getImageType(), $options);
});
}
Expand Down
1 change: 1 addition & 0 deletions src/Form/Type/UiElement/SeparatorType.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
'required' => false,
])
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event): void {
/** @var array $data */
$data = $event->getData();
$data['hidden'] = (bool) ($data['hidden'] ?? false);
$event->setData($data);
Expand Down
4 changes: 2 additions & 2 deletions src/Form/Type/UiElement/VideoType.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ public function addEvents(FormBuilderInterface $builder, array $options): void
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
// Change video field constraints depending on submitted value
$options = $event->getForm()->get('video')->getConfig()->getOptions();
$options['constraints'] = RichEditorConstraints::getVideoConstraints($event->getData(), 'video');
$options['constraints'] = RichEditorConstraints::getVideoConstraints(\is_array($event->getData()) ? $event->getData() : [], 'video');
$event->getForm()->add('video', $this->getVideoType(), $options);

// Change image field constraints depending on submitted value
$options = $event->getForm()->get('image')->getConfig()->getOptions();
$options['constraints'] = RichEditorConstraints::getImageConstraints($event->getData(), 'image', false);
$options['constraints'] = RichEditorConstraints::getImageConstraints(\is_array($event->getData()) ? $event->getData() : [], 'image', false);
$event->getForm()->add('image', $this->getImageType(), $options);
});
}
Expand Down
13 changes: 9 additions & 4 deletions src/Form/Type/WysiwygType.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,14 @@ public function configureOptions(OptionsResolver $resolver): void
$resolver->setAllowedTypes('editor_custom_config', ['null', 'array']);

$resolver->setNormalizer('editor_toolbar_buttons', function (Options $options, ?array $value): string {
$editor = $this->editorCollection->getEditor($options['editor_type']);
/** @var string $editorType */
$editorType = $options['editor_type'];
$editor = $this->editorCollection->getEditor($editorType);

return match ($options['editor_toolbar_type']) {
EditorInterface::TOOLBAR_TYPE_MINIMAL => $this->encoder->encode($editor->getMinimalButtons(), 'json'),
EditorInterface::TOOLBAR_TYPE_BASIC => $this->encoder->encode($editor->getBasicButtons() ?? [], 'json'),
EditorInterface::TOOLBAR_TYPE_FULL => $this->encoder->encode($editor->getFullButtons() ?? [], 'json'),
EditorInterface::TOOLBAR_TYPE_BASIC => $this->encoder->encode($editor->getBasicButtons(), 'json'),
EditorInterface::TOOLBAR_TYPE_FULL => $this->encoder->encode($editor->getFullButtons(), 'json'),
default => $this->encoder->encode($value ?? [], 'json'),
};
});
Expand All @@ -103,9 +105,12 @@ public function configureOptions(OptionsResolver $resolver): void

private function getDataValues(array $options): array
{
/** @var string $editorType */
$editorType = $options['editor_type'];

return [
'data-component' => 'wysiwyg-editor',
'data-editor-type' => $options['editor_type'],
'data-editor-type' => $editorType,
'data-editor-height' => $options['editor_height'],
'data-editor-locale' => $options['editor_locale'],
'data-editor-buttons' => $options['editor_toolbar_buttons'],
Expand Down
1 change: 1 addition & 0 deletions src/UiElement/UiElementFormOptionsTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ trait UiElementFormOptionsTrait
public function getFormOptions(): array
{
try {
/** @phpstan-ignore-next-line */
return $this->metadata->getParameter('form_options');
} catch (InvalidArgumentException) {
return [];
Expand Down
21 changes: 17 additions & 4 deletions src/UiElement/UiElementTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace MonsieurBiz\SyliusRichEditorPlugin\UiElement;

use Exception;
use PHPUnit\Framework\Assert;
use ReturnTypeWillChange;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
Expand Down Expand Up @@ -81,31 +82,43 @@ public function isEnabled(): bool
*/
public function getTitle(): string
{
return $this->metadata->getParameter('title');
$value = $this->metadata->getParameter('title');
Assert::assertIsString($value);

return $value;
}

/**
* @inheritdoc
*/
public function getDescription(): string
{
return $this->metadata->getParameter('description');
$value = $this->metadata->getParameter('description');
Assert::assertIsString($value);

return $value;
}

/**
* @inheritdoc
*/
public function getIcon(): string
{
return $this->metadata->getParameter('icon');
$value = $this->metadata->getParameter('icon');
Assert::assertIsString($value);

return $value;
}

/**
* @inheritdoc
*/
public function getWireframe(): string
{
return $this->metadata->getParameter('wireframe');
$value = $this->metadata->getParameter('wireframe');
Assert::assertIsString($value);

return $value;
}

/**
Expand Down
11 changes: 7 additions & 4 deletions src/Validator/Constraints/YoutubeUrlValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,20 @@

class YoutubeUrlValidator extends ConstraintValidator
{
public const YOUTUBE_REGEX_VALIDATOR = '`^(?:https?://)?(?:www\.)?(?:youtu.be/|youtube\.com/(?:watch(?:/|/?\?(?:\S*&)?v=)|embed/))([\w\d-]+)$`';
public const YOUTUBE_REGEX_VALIDATOR = '`^(?:https?://)?(?:www\.)?(?:youtu.be/|youtube\.com/(?:watch(?:/|/?\?(?:\S*&)?v=)|embed|short/))([\w\d-]+)$`';

public function validate($value, Constraint $constraint): void
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof YoutubeUrl) {
throw new UnexpectedTypeException($constraint, YoutubeUrl::class);
}

if (!preg_match(self::YOUTUBE_REGEX_VALIDATOR, (string) $value)) {
/** @phpstan-ignore-next-line */
$value = (string) $value;

if (!preg_match(self::YOUTUBE_REGEX_VALIDATOR, $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ string }}', (string) $value)
->setParameter('{{ string }}', $value)
->addViolation()
;
}
Expand Down

0 comments on commit 95fe933

Please sign in to comment.