From 756d7338e7efd122a1df47be8bc73068fcde8a1e Mon Sep 17 00:00:00 2001 From: Ambroise Maupate Date: Wed, 6 Nov 2024 00:59:28 +0100 Subject: [PATCH 1/5] refactor: Use friendsofphp/php-cs-fixer instead of squizlabs/php_codesniffer --- .github/workflows/run-test.yml | 2 +- .gitignore | 11 +- .php-cs-fixer.dist.php | 17 + Makefile | 7 +- composer.json | 2 +- config/bundles.php | 2 + config/preload.php | 2 + .../src/Generators/AbstractFieldGenerator.php | 25 +- .../Generators/ChildrenNodeFieldGenerator.php | 11 +- .../src/Generators/CommonFieldGenerator.php | 2 +- .../DefaultValuedFieldGenerator.php | 6 +- .../src/Generators/DocumentationGenerator.php | 14 +- .../Generators/MarkdownGeneratorFactory.php | 12 +- .../NodeReferencesFieldGenerator.php | 4 +- .../src/Generators/NodeTypeGenerator.php | 26 +- lib/Documents/src/AbstractDocumentFactory.php | 58 +- lib/Documents/src/AbstractDocumentFinder.php | 35 +- lib/Documents/src/ArrayDocumentFinder.php | 4 +- lib/Documents/src/AverageColorResolver.php | 8 +- .../src/Console/AbstractDocumentCommand.php | 13 +- .../Console/DocumentAverageColorCommand.php | 2 +- .../Console/DocumentClearFolderCommand.php | 4 +- .../src/Console/DocumentDownscaleCommand.php | 15 +- .../src/Console/DocumentDuplicatesCommand.php | 7 +- .../src/Console/DocumentFileHashCommand.php | 9 +- .../src/Console/DocumentPruneCommand.php | 2 + .../Console/DocumentPruneOrphansCommand.php | 9 +- .../src/Console/DocumentSizeCommand.php | 2 +- lib/Documents/src/DocumentArchiver.php | 18 +- lib/Documents/src/DocumentFinderInterface.php | 13 - lib/Documents/src/DownloadedFile.php | 28 +- lib/Documents/src/DownscaleImageManager.php | 48 +- .../src/Events/DocumentCreatedEvent.php | 2 +- .../src/Events/DocumentDeletedEvent.php | 2 +- .../src/Events/DocumentFileUpdatedEvent.php | 2 +- .../Events/DocumentLifeCycleSubscriber.php | 61 +- .../src/Events/DocumentUpdatedEvent.php | 2 +- .../EmbedDocumentAlreadyExistsException.php | 6 +- .../src/Exceptions/InvalidEmbedId.php | 6 - .../AbstractDailymotionEmbedFinder.php | 67 +- .../AbstractDeezerEmbedFinder.php | 55 +- .../src/MediaFinders/AbstractEmbedFinder.php | 126 +- .../AbstractMixcloudEmbedFinder.php | 57 +- .../MediaFinders/AbstractPodcastFinder.php | 75 +- .../AbstractSoundcloudEmbedFinder.php | 50 +- .../AbstractSpotifyEmbedFinder.php | 69 +- .../MediaFinders/AbstractTedEmbedFinder.php | 26 +- .../AbstractTwitchEmbedFinder.php | 38 +- .../AbstractUnsplashPictureFinder.php | 91 +- .../MediaFinders/AbstractVimeoEmbedFinder.php | 30 +- .../AbstractYoutubeEmbedFinder.php | 76 +- .../src/MediaFinders/EmbedFinderFactory.php | 23 +- .../src/MediaFinders/EmbedFinderInterface.php | 10 - .../MediaFinders/FacebookPictureFinder.php | 22 +- .../src/MediaFinders/RandomImageFinder.php | 7 +- .../src/Models/AdvancedDocumentInterface.php | 4 - .../src/Models/DisplayableInterface.php | 4 - .../src/Models/DocumentInterface.php | 45 +- lib/Documents/src/Models/DocumentTrait.php | 73 +- .../src/Models/FileAwareInterface.php | 12 +- .../src/Models/FileHashInterface.php | 3 + lib/Documents/src/Models/FolderInterface.php | 15 +- .../src/Models/HasThumbnailInterface.php | 14 +- lib/Documents/src/Models/SimpleDocument.php | 29 +- lib/Documents/src/Models/SimpleFileAware.php | 9 +- .../src/Models/SizeableInterface.php | 11 - .../src/Models/TimeableInterface.php | 4 - .../OptionsResolver/UrlOptionsResolver.php | 27 +- .../src/Renderer/AbstractImageRenderer.php | 92 +- .../src/Renderer/AbstractRenderer.php | 19 +- lib/Documents/src/Renderer/AudioRenderer.php | 10 +- lib/Documents/src/Renderer/ChainRenderer.php | 6 +- lib/Documents/src/Renderer/EmbedRenderer.php | 8 +- lib/Documents/src/Renderer/ImageRenderer.php | 12 +- .../src/Renderer/InlineSvgRenderer.php | 8 +- lib/Documents/src/Renderer/PdfRenderer.php | 6 +- .../src/Renderer/PictureRenderer.php | 15 +- .../src/Renderer/RendererInterface.php | 12 - lib/Documents/src/Renderer/SvgRenderer.php | 16 +- .../src/Renderer/ThumbnailRenderer.php | 32 +- lib/Documents/src/Renderer/VideoRenderer.php | 24 +- .../DocumentRepositoryInterface.php | 2 + lib/Documents/src/SvgSizeResolver.php | 21 +- .../src/TwigExtension/DocumentExtension.php | 65 +- .../AbstractDocumentUrlGenerator.php | 16 +- .../DocumentUrlGeneratorInterface.php | 9 - .../DummyDocumentUrlGenerator.php | 13 +- .../src/UrlGenerators/OptionsCompiler.php | 27 +- .../src/Viewers/SvgDocumentViewer.php | 29 +- .../MediaFinders/SimpleVimeoEmbedFinder.php | 6 - .../MediaFinders/SimpleYoutubeEmbedFinder.php | 6 - .../Renderer/AbstractRendererTestCase.php | 29 +- .../tests/Renderer/AudioRendererTest.php | 35 +- .../tests/Renderer/ChainRendererTest.php | 32 +- .../tests/Renderer/EmbedRendererTest.php | 41 +- .../tests/Renderer/ImageRendererTest.php | 78 +- .../tests/Renderer/PdfRendererTest.php | 5 +- .../tests/Renderer/PictureRendererTest.php | 132 +-- .../tests/Renderer/VideoRendererTest.php | 5 +- .../src/DeclarationGeneratorFactory.php | 13 - .../src/Generators/AbstractFieldGenerator.php | 25 +- .../Generators/ChildrenNodeFieldGenerator.php | 6 +- .../src/Generators/DeclarationGenerator.php | 5 +- .../src/Generators/EnumFieldGenerator.php | 9 +- .../NodeReferencesFieldGenerator.php | 7 +- .../src/Generators/NodeTypeGenerator.php | 18 +- lib/EntityGenerator/src/EntityGenerator.php | 47 +- .../src/EntityGeneratorFactory.php | 12 +- .../AbstractConfigurableFieldGenerator.php | 10 +- .../src/Field/AbstractFieldGenerator.php | 86 +- .../src/Field/CustomFormsFieldGenerator.php | 8 +- .../Field/DefaultValuesResolverInterface.php | 6 +- .../src/Field/DocumentsFieldGenerator.php | 14 +- .../src/Field/ManyToManyFieldGenerator.php | 42 +- .../src/Field/ManyToOneFieldGenerator.php | 16 +- .../src/Field/NodesFieldGenerator.php | 45 +- .../src/Field/NonVirtualFieldGenerator.php | 34 +- .../Field/ProxiedManyToManyFieldGenerator.php | 80 +- .../src/Field/YamlFieldGenerator.php | 14 +- .../src/RepositoryGenerator.php | 17 +- .../tests/EntityGeneratorFactoryTest.php | 22 +- .../tests/EntityGeneratorTest.php | 14 +- .../tests/NodeTypeAwareTestTrait.php | 331 +++--- .../tests/SimpleNodeTypeField.php | 232 +--- .../Validation/Constraint/HostedDomain.php | 8 +- .../Constraint/UserInfoEndpoint.php | 6 +- lib/Markdown/src/CommonMark.php | 23 +- lib/Markdown/src/MarkdownInterface.php | 18 +- lib/Markdown/src/Twig/MarkdownExtension.php | 18 +- lib/Models/src/Bag/LazyParameterBag.php | 30 +- .../AbstractEntities/AbstractDateTimed.php | 76 +- .../Core/AbstractEntities/AbstractEntity.php | 19 +- .../Core/AbstractEntities/AbstractField.php | 258 ++-- .../Core/AbstractEntities/AbstractHuman.php | 105 +- .../AbstractEntities/AbstractPositioned.php | 10 +- .../Core/AbstractEntities/LeafInterface.php | 5 +- .../src/Core/AbstractEntities/LeafTrait.php | 17 +- .../Core/AbstractEntities/NodeInterface.php | 5 + .../AbstractEntities/PersistableInterface.php | 2 - .../AbstractEntities/PositionedInterface.php | 4 - .../Core/AbstractEntities/PositionedTrait.php | 12 +- .../AbstractEntities/TranslationInterface.php | 34 - .../Events/LeafEntityLifeCycleSubscriber.php | 4 +- .../src/Core/Handlers/AbstractHandler.php | 6 +- lib/Models/src/Utils/StringHandler.php | 51 +- lib/Models/tests/StringHandlerTest.php | 214 ++-- .../Authentication/OpenIdAuthenticator.php | 62 +- .../Provider/ChainJwtRoleStrategy.php | 4 +- .../Provider/JwtRoleStrategy.php | 1 + .../Provider/OpenIdAccountProvider.php | 8 +- .../Provider/SettingsRoleStrategy.php | 3 +- lib/OpenId/src/Discovery.php | 18 +- .../DiscoveryNotAvailableException.php | 4 +- .../OpenIdAuthenticationException.php | 2 - .../OpenIdConfigurationException.php | 4 +- lib/OpenId/src/OAuth2LinkGenerator.php | 22 +- .../src/OpenIdJwtConfigurationFactory.php | 13 +- lib/OpenId/src/User/OpenIdAccount.php | 75 +- lib/Random/src/PasswordGenerator.php | 3 +- lib/Random/src/PasswordGeneratorInterface.php | 1 - lib/Random/src/RandomGenerator.php | 9 +- lib/RoadizCompatBundle/deprecated.php | 1 + lib/RoadizCompatBundle/src/Aliases.php | 6 +- .../src/Console/ThemeAssetsCommand.php | 9 +- .../src/Console/ThemeInfoCommand.php | 9 +- .../src/Console/ThemesListCommand.php | 19 +- .../src/Controller/AppController.php | 129 +- .../src/Controller/Controller.php | 109 +- .../ThemesTranslatorPathsCompilerPass.php | 9 +- .../src/DependencyInjection/Configuration.php | 3 +- .../RoadizCompatExtension.php | 19 +- .../ControllerEventSubscriber.php | 3 - .../EventSubscriber/ExceptionSubscriber.php | 74 +- .../MaintenanceModeSubscriber.php | 29 +- .../src/Routing/ThemeAwareNodeRouter.php | 7 +- .../src/Routing/ThemeAwareNodeUrlMatcher.php | 6 +- .../src/Theme/StaticThemeResolver.php | 38 +- .../src/Theme/ThemeGenerator.php | 89 +- .../src/Theme/ThemeInfo.php | 67 +- .../src/Theme/ThemeResolverInterface.php | 17 +- lib/RoadizCoreBundle/config/services.yaml | 1 + .../migrations/Version20201203004857.php | 16 +- .../migrations/Version20201214232628.php | 14 +- .../migrations/Version20201225181256.php | 13 +- .../migrations/Version20210423072744.php | 9 +- .../migrations/Version20210423161606.php | 8 +- .../migrations/Version20210423164248.php | 14 +- .../migrations/Version20210506085247.php | 6 +- .../migrations/Version20210520092543.php | 8 +- .../migrations/Version20210527131435.php | 4 +- .../migrations/Version20210701151713.php | 2 +- .../migrations/Version20210715120118.php | 4 +- .../src/Api/Breadcrumbs/Breadcrumbs.php | 4 +- .../NodesSourcesBreadcrumbsFactory.php | 8 +- .../GetWebResponseByPathController.php | 18 +- .../NodesSourcesSearchController.php | 9 +- .../TranslationAwareControllerTrait.php | 3 +- ...eWebResponseOutputDataTransformerTrait.php | 3 + ...eWebResponseOutputDataTransformerTrait.php | 7 +- .../WebResponseDataTransformerInterface.php | 4 +- .../WebResponseOutputDataTransformer.php | 12 +- lib/RoadizCoreBundle/src/Api/Dto/Archive.php | 4 +- .../src/Api/Extension/ArchiveExtension.php | 14 +- .../AttributeValueQueryExtension.php | 18 +- .../AttributeValueRealmExtension.php | 9 +- .../Api/Extension/DocumentQueryExtension.php | 12 +- .../src/Api/Extension/NodeQueryExtension.php | 18 +- .../Extension/NodesSourcesQueryExtension.php | 18 +- .../Api/Extension/NodesTagsQueryExtension.php | 16 +- .../src/Api/Filter/ArchiveFilter.php | 41 +- .../src/Api/Filter/CopyrightValidFilter.php | 26 +- .../src/Api/Filter/GeneratedEntityFilter.php | 19 +- .../src/Api/Filter/IntersectionFilter.php | 29 +- .../src/Api/Filter/LocaleFilter.php | 47 +- .../src/Api/Filter/NotFilter.php | 21 +- .../src/Api/ListManager/SolrPaginator.php | 6 + .../Api/ListManager/SolrSearchListManager.php | 26 +- .../Model/BlocksAwareWebResponseInterface.php | 1 + .../src/Api/Model/NodesSourcesHead.php | 110 +- .../src/Api/Model/NodesSourcesHeadFactory.php | 2 +- .../NodesSourcesHeadFactoryInterface.php | 1 + .../Api/Model/NodesSourcesHeadInterface.php | 8 + .../Model/RealmsAwareWebResponseInterface.php | 5 +- .../src/Api/Model/WebResponseInterface.php | 6 +- .../src/Api/Model/WebResponseTrait.php | 33 +- .../src/Api/OpenApi/JwtDecorator.php | 4 +- .../src/Api/OpenApi/PreviewDecorator.php | 6 +- .../src/Api/OpenApi/WebResponseDecorator.php | 4 +- .../AutoChildrenNodeSourceWalker.php | 7 +- .../DefinitionFactoryConfiguration.php | 4 +- .../MultiTypeChildrenDefinition.php | 9 +- .../NonReachableNodeSourceBlockDefinition.php | 7 +- .../ReachableNodeSourceDefinition.php | 7 +- .../TreeWalker/NodeSourceWalkerContext.php | 31 +- .../NodeSourceWalkerContextFactory.php | 2 +- .../Api/TreeWalker/TreeWalkerGenerator.php | 23 +- lib/RoadizCoreBundle/src/Bag/NodeTypes.php | 1 + lib/RoadizCoreBundle/src/Bag/Roles.php | 6 +- lib/RoadizCoreBundle/src/Bag/Settings.php | 12 +- .../src/Cache/Clearer/ClearerInterface.php | 10 +- .../src/Cache/Clearer/FileClearer.php | 2 - .../Clearer/NodesSourcesUrlsCacheClearer.php | 2 + .../src/Cache/Clearer/OPCacheClearer.php | 5 +- .../src/Cache/CloudflareProxyCache.php | 23 +- .../src/Cache/ReverseProxyCache.php | 11 +- .../src/Cache/ReverseProxyCacheLocator.php | 6 +- .../CollectionFieldConfiguration.php | 3 - .../JoinNodeTypeFieldConfiguration.php | 3 - .../ProviderFieldConfiguration.php | 3 - .../src/Console/AppInstallCommand.php | 68 +- .../src/Console/AppMigrateCommand.php | 14 +- .../Console/CustomFormAnswerPurgeCommand.php | 6 +- .../src/Console/FilesCommandTrait.php | 9 - .../src/Console/FilesExportCommand.php | 35 +- .../src/Console/FilesImportCommand.php | 26 +- .../Console/GenerateApiResourceCommand.php | 8 +- .../GenerateNodeSourceEntitiesCommand.php | 10 +- .../Console/GetCronLastExecDateCommand.php | 5 +- .../src/Console/InstallCommand.php | 57 +- .../src/Console/LogsCleanupCommand.php | 12 +- .../src/Console/MailerTestCommand.php | 7 +- .../NodeApplyUniversalFieldsCommand.php | 7 +- .../src/Console/NodeClearTagCommand.php | 6 +- .../src/Console/NodeTypesAddFieldCommand.php | 8 +- .../src/Console/NodeTypesCommand.php | 16 +- .../src/Console/NodeTypesCreationCommand.php | 22 +- .../Console/NodeTypesDefaultValuesCommand.php | 7 +- .../src/Console/NodeTypesDeleteCommand.php | 18 +- .../src/Console/NodesCleanNamesCommand.php | 33 +- .../src/Console/NodesCommand.php | 7 +- .../src/Console/NodesDetailsCommand.php | 5 +- .../src/Console/NodesEmptyTrashCommand.php | 5 +- .../src/Console/NodesOrphansCommand.php | 14 +- .../RegisterCronLastExecDateCommand.php | 4 +- .../src/Console/RunningCommandsTrait.php | 17 +- .../src/Console/SolrCommand.php | 5 +- .../src/Console/SolrOptimizeCommand.php | 3 +- .../src/Console/SolrReindexCommand.php | 5 +- .../src/Console/SolrResetCommand.php | 5 +- .../src/Console/TranslationsCommand.php | 10 +- .../Console/TranslationsCreationCommand.php | 13 +- .../src/Console/TranslationsDeleteCommand.php | 17 +- .../Console/TranslationsDisableCommand.php | 8 +- .../src/Console/TranslationsEnableCommand.php | 8 +- .../src/Console/UsersCommand.php | 14 +- .../src/Console/UsersCreationCommand.php | 24 +- .../src/Console/UsersDeleteCommand.php | 8 +- .../src/Console/UsersDisableCommand.php | 8 +- .../src/Console/UsersEnableCommand.php | 8 +- .../src/Console/UsersExpireCommand.php | 6 +- .../src/Console/UsersInactiveCommand.php | 8 +- .../src/Console/UsersLockCommand.php | 8 +- .../src/Console/UsersPasswordCommand.php | 8 +- .../src/Console/UsersRolesCommand.php | 12 +- .../src/Console/UsersUnexpireCommand.php | 8 +- .../src/Console/UsersUnlockCommand.php | 8 +- .../src/Console/VersionsPurgeCommand.php | 5 +- .../src/Controller/CustomFormController.php | 38 +- .../DefaultNodeSourceController.php | 2 +- .../src/Controller/HealthCheckController.php | 10 +- .../src/Controller/RedirectionController.php | 7 +- .../CustomForm/CustomFormAnswerSerializer.php | 5 +- .../src/CustomForm/CustomFormHelper.php | 40 +- .../CustomForm/CustomFormHelperFactory.php | 2 +- .../Message/CustomFormAnswerNotifyMessage.php | 2 +- .../CustomFormAnswerNotifyMessageHandler.php | 11 +- .../DataCollector/RequestDataCollector.php | 14 +- .../src/DataCollector/SolariumLogger.php | 22 +- .../Compiler/CommonMarkCompilerPass.php | 7 +- .../DoctrineMigrationCompilerPass.php | 19 +- .../Compiler/DocumentRendererCompilerPass.php | 3 - .../Compiler/FlysystemStorageCompilerPass.php | 8 +- .../Compiler/ImporterCompilerPass.php | 3 - .../Compiler/MediaFinderCompilerPass.php | 3 - .../NodesSourcesEntitiesPathCompilerPass.php | 9 +- .../Compiler/PathResolverCompilerPass.php | 5 +- .../Compiler/RateLimitersCompilerPass.php | 8 +- ...reeWalkerDefinitionFactoryCompilerPass.php | 5 +- .../Compiler/TwigLoaderCompilerPass.php | 5 +- .../src/DependencyInjection/Configuration.php | 4 +- .../RoadizCoreExtension.php | 37 +- ...rNodesSourcesQueryBuilderCriteriaEvent.php | 20 +- .../Event/FilterQueryBuilderCriteriaEvent.php | 69 +- .../Event/FilterQueryBuilderEvent.php | 24 +- .../Event/FilterQueryCriteriaEvent.php | 56 +- .../src/Doctrine/Event/QueryEvent.php | 15 +- .../Doctrine/Event/QueryNodesSourcesEvent.php | 4 +- .../AttributeValueLifeCycleSubscriber.php | 20 +- .../CustomFormFieldLifeCycleSubscriber.php | 5 +- .../NodesSourcesInheritanceSubscriber.php | 16 +- .../UserLifeCycleSubscriber.php | 51 +- .../src/Doctrine/ORM/Filter/ANodesFilter.php | 41 +- .../src/Doctrine/ORM/Filter/BNodesFilter.php | 11 +- .../ORM/Filter/NodeTranslationFilter.php | 37 +- .../Doctrine/ORM/Filter/NodeTypeFilter.php | 22 +- .../ORM/Filter/NodesSourcesNodeFilter.php | 16 +- .../ORM/Filter/NodesSourcesNodeTypeFilter.php | 27 +- .../Filter/NodesSourcesReachableFilter.php | 19 +- .../src/Doctrine/ORM/SimpleQueryBuilder.php | 118 +- .../src/Doctrine/SchemaUpdater.php | 27 +- .../src/Document/DocumentFactory.php | 5 +- .../src/Document/DocumentFinder.php | 24 +- .../DocumentMessageDispatchSubscriber.php | 15 +- .../Document/MediaFinder/EmbedFinderTrait.php | 10 +- .../Document/MediaFinder/PodcastFinder.php | 2 +- .../Message/AbstractDocumentMessage.php | 6 - .../AbstractDocumentMessageHandler.php | 2 +- .../AbstractLockingDocumentMessageHandler.php | 9 +- .../DocumentAudioVideoMessageHandler.php | 20 +- .../DocumentAverageColorMessageHandler.php | 9 +- .../DocumentExifMessageHandler.php | 33 +- .../DocumentFilesizeMessageHandler.php | 4 - .../DocumentPdfMessageHandler.php | 18 +- .../DocumentRawMessageHandler.php | 6 +- .../DocumentSizeMessageHandler.php | 6 +- .../DocumentSvgMessageHandler.php | 4 - .../src/Document/PrivateDocumentFactory.php | 6 +- .../Entity/AbstractDateTimedPositioned.php | 14 +- lib/RoadizCoreBundle/src/Entity/Attribute.php | 47 +- .../src/Entity/AttributeDocuments.php | 38 +- .../src/Entity/AttributeGroup.php | 8 +- .../src/Entity/AttributeGroupTranslation.php | 14 +- .../src/Entity/AttributeTranslation.php | 10 +- .../src/Entity/AttributeValue.php | 36 +- .../src/Entity/AttributeValueTranslation.php | 8 +- .../src/Entity/CustomForm.php | 164 +-- .../src/Entity/CustomFormAnswer.php | 66 +- .../src/Entity/CustomFormField.php | 52 +- .../src/Entity/CustomFormFieldAttribute.php | 36 +- lib/RoadizCoreBundle/src/Entity/Document.php | 205 +--- .../src/Entity/DocumentTranslation.php | 33 +- .../src/Entity/FieldAwareEntityTrait.php | 2 + lib/RoadizCoreBundle/src/Entity/Folder.php | 82 +- .../src/Entity/FolderTranslation.php | 26 +- lib/RoadizCoreBundle/src/Entity/Group.php | 33 +- lib/RoadizCoreBundle/src/Entity/Node.php | 215 ++-- lib/RoadizCoreBundle/src/Entity/NodeType.php | 255 ++-- .../src/Entity/NodeTypeField.php | 190 ++- .../src/Entity/NodesCustomForms.php | 20 +- .../src/Entity/NodesSources.php | 199 ++-- .../src/Entity/NodesSourcesDocuments.php | 28 +- lib/RoadizCoreBundle/src/Entity/NodesTags.php | 34 +- .../src/Entity/NodesToNodes.php | 21 +- lib/RoadizCoreBundle/src/Entity/Realm.php | 76 +- lib/RoadizCoreBundle/src/Entity/RealmNode.php | 40 +- .../src/Entity/Redirection.php | 61 +- lib/RoadizCoreBundle/src/Entity/Role.php | 53 +- lib/RoadizCoreBundle/src/Entity/Setting.php | 64 +- .../src/Entity/SettingGroup.php | 18 +- lib/RoadizCoreBundle/src/Entity/Tag.php | 130 +-- .../src/Entity/TagTranslation.php | 25 +- .../src/Entity/TagTranslationDocuments.php | 13 +- lib/RoadizCoreBundle/src/Entity/Theme.php | 34 +- .../src/Entity/Translation.php | 1035 ++++++++--------- lib/RoadizCoreBundle/src/Entity/UrlAlias.php | 13 +- lib/RoadizCoreBundle/src/Entity/User.php | 230 ++-- .../src/Entity/UserLogEntry.php | 12 +- lib/RoadizCoreBundle/src/Entity/Webhook.php | 114 +- .../src/EntityApi/AbstractApi.php | 32 +- .../src/EntityApi/NodeApi.php | 28 +- .../src/EntityApi/NodeSourceApi.php | 50 +- .../src/EntityApi/NodeTypeApi.php | 24 +- lib/RoadizCoreBundle/src/EntityApi/TagApi.php | 30 +- .../EntityHandler/CustomFormFieldHandler.php | 10 +- .../src/EntityHandler/CustomFormHandler.php | 4 +- .../src/EntityHandler/DocumentHandler.php | 16 +- .../src/EntityHandler/FolderHandler.php | 16 +- .../src/EntityHandler/GroupHandler.php | 9 +- .../src/EntityHandler/HandlerFactory.php | 26 +- .../src/EntityHandler/NodeHandler.php | 92 +- .../EntityHandler/NodeTypeFieldHandler.php | 8 +- .../src/EntityHandler/NodeTypeHandler.php | 39 +- .../src/EntityHandler/NodesSourcesHandler.php | 106 +- .../src/EntityHandler/TagHandler.php | 16 +- .../src/EntityHandler/TranslationHandler.php | 3 +- .../DocumentTranslationIndexingEvent.php | 19 +- .../DocumentTranslationUpdatedEvent.php | 5 +- .../src/Event/FilterCacheEvent.php | 31 +- .../src/Event/FilterFolderEvent.php | 3 - .../src/Event/FilterNodeEvent.php | 3 - .../src/Event/FilterNodePathEvent.php | 16 +- .../src/Event/FilterNodesSourcesEvent.php | 3 - .../src/Event/FilterTagEvent.php | 6 - .../src/Event/FilterTranslationEvent.php | 3 - .../src/Event/FilterUrlAliasEvent.php | 3 - .../src/Event/FilterUserEvent.php | 3 - .../NodesSourcesIndexingEvent.php | 8 +- .../NodesSourcesPathGeneratingEvent.php | 69 +- .../Event/Realm/AbstractRealmNodeEvent.php | 5 - .../Event/Redirection/RedirectionEvent.php | 11 +- .../src/Event/Role/RoleEvent.php | 11 +- .../src/Event/User/UserJoinedGroupEvent.php | 3 - .../src/Event/User/UserLeavedGroupEvent.php | 3 - .../AssetsCacheEventSubscriber.php | 4 +- .../AutomaticWebhookSubscriber.php | 22 +- .../CloudflareCacheEventSubscriber.php | 23 +- .../DocumentTimestampSubscriber.php | 5 +- ...wtAuthenticationSuccessEventSubscriber.php | 3 - .../src/EventSubscriber/LocaleSubscriber.php | 18 +- .../EventSubscriber/LoggableSubscriber.php | 4 +- .../NodeDuplicationSubscriber.php | 4 +- .../EventSubscriber/NodeNameSubscriber.php | 19 +- .../NodeRedirectionSubscriber.php | 22 +- .../NodeSourcePathSubscriber.php | 8 +- .../NodesSourcesAddHeadersSubscriber.php | 4 +- .../NodesSourcesLinkHeaderEventSubscriber.php | 9 +- .../NodesSourcesUniversalSubscriber.php | 9 - .../NodesSourcesUrlsCacheEventSubscriber.php | 3 - .../OPCacheEventSubscriber.php | 6 - .../RealmNodeInheritanceSubscriber.php | 3 - .../RedirectionCacheSubscriber.php | 3 - .../ReverseProxyCacheEventSubscriber.php | 34 +- .../src/EventSubscriber/RoleSubscriber.php | 11 +- .../EventSubscriber/SignatureSubscriber.php | 3 +- .../TagTimestampSubscriber.php | 6 +- .../EventSubscriber/TranslationSubscriber.php | 6 +- .../EventSubscriber/UserLocaleSubscriber.php | 21 +- .../src/Exception/BadFormRequestException.php | 6 - .../src/Exception/ForceResponseException.php | 2 - .../Exception/MaintenanceModeException.php | 3 +- .../NoConfigurationFoundException.php | 2 +- .../NoYamlConfigurationFoundException.php | 2 +- .../AbstractDoctrineExplorerProvider.php | 23 +- .../src/Explorer/AbstractExplorerItem.php | 3 - .../src/Explorer/AbstractExplorerProvider.php | 10 +- .../src/Explorer/ExplorerItemInterface.php | 13 - .../Explorer/ExplorerProviderInterface.php | 10 +- .../src/Filesystem/RoadizFileDirectories.php | 8 +- .../src/Form/AttributeChoiceType.php | 15 +- .../src/Form/AttributeDocumentType.php | 22 +- .../Form/AttributeGroupTranslationType.php | 24 +- .../src/Form/AttributeGroupType.php | 14 +- .../src/Form/AttributeGroupsType.php | 15 +- .../src/Form/AttributeImportType.php | 9 +- .../src/Form/AttributeTranslationType.php | 30 +- .../src/Form/AttributeType.php | 33 +- .../Form/AttributeValueTranslationType.php | 36 +- .../src/Form/AttributeValueType.php | 10 - lib/RoadizCoreBundle/src/Form/ColorType.php | 3 - .../src/Form/CompareDateType.php | 7 +- .../src/Form/CompareDatetimeType.php | 10 +- .../Constraint/HexadecimalColorValidator.php | 2 +- .../src/Form/Constraint/NodeTypeField.php | 3 - .../Constraint/NodeTypeFieldValidator.php | 18 +- .../Form/Constraint/NonSqlReservedWord.php | 1 + .../NonSqlReservedWordValidator.php | 6 +- .../Constraint/RecaptchaServiceInterface.php | 4 +- .../Form/Constraint/RecaptchaValidator.php | 14 +- .../Constraint/SimpleLatinStringValidator.php | 2 +- .../src/Form/Constraint/UniqueFilename.php | 3 - .../Constraint/UniqueFilenameValidator.php | 8 +- .../Constraint/UniqueNodeNameValidator.php | 16 +- .../Constraint/UniqueTagNameValidator.php | 17 +- .../ValidAccountConfirmationToken.php | 4 +- ...ValidAccountConfirmationTokenValidator.php | 5 - .../Constraint/ValidAccountEmailValidator.php | 5 - .../Constraint/ValidFacebookNameValidator.php | 14 +- .../Form/Constraint/ValidJsonValidator.php | 9 +- .../Form/Constraint/ValidYamlValidator.php | 6 +- .../src/Form/CreatePasswordType.php | 10 +- lib/RoadizCoreBundle/src/Form/CssType.php | 10 +- .../src/Form/CustomFormsType.php | 84 +- .../src/Form/DataListTextType.php | 1 - .../AttributeDocumentsTransformer.php | 11 +- .../AttributeGroupTransformer.php | 17 +- .../DocumentCollectionTransformer.php | 7 - .../EntityCollectionTransformer.php | 16 +- .../ExplorerProviderItemTransformer.php | 17 +- .../FolderCollectionTransformer.php | 7 - .../DataTransformer/JoinDataTransformer.php | 19 +- .../DataTransformer/NodeTypeTransformer.php | 11 +- .../PersistableTransformer.php | 5 +- .../ProviderDataTransformer.php | 20 +- .../ReversePersistableTransformer.php | 8 +- .../TagTranslationDocumentsTransformer.php | 16 +- .../TranslationTransformer.php | 11 +- .../src/Form/DocumentCollectionType.php | 17 +- .../src/Form/EnumerationType.php | 13 +- .../src/Form/Error/FormErrorSerializer.php | 5 +- .../src/Form/ExplorerProviderItemType.php | 24 +- .../src/Form/ExtendedBooleanType.php | 11 +- lib/RoadizCoreBundle/src/Form/GroupsType.php | 29 +- .../src/Form/HoneypotType.php | 18 +- lib/RoadizCoreBundle/src/Form/JsonType.php | 14 +- .../src/Form/LoginRequestForm.php | 3 - .../src/Form/LoginResetForm.php | 9 - .../src/Form/MarkdownType.php | 10 +- .../src/Form/MultipleEnumerationType.php | 13 +- .../src/Form/NodeStatesType.php | 11 +- .../src/Form/NodeTypesType.php | 16 +- lib/RoadizCoreBundle/src/Form/NodesType.php | 30 +- .../src/Form/RealmChoiceType.php | 9 - .../src/Form/RealmNodeType.php | 8 +- lib/RoadizCoreBundle/src/Form/RealmType.php | 18 +- .../src/Form/RecaptchaType.php | 12 +- .../src/Form/RoleEntityType.php | 14 +- lib/RoadizCoreBundle/src/Form/RolesType.php | 22 +- .../src/Form/SeparatorType.php | 9 +- .../src/Form/SettingDocumentType.php | 15 +- .../src/Form/SettingGroupType.php | 23 +- lib/RoadizCoreBundle/src/Form/SettingType.php | 18 +- .../src/Form/SettingTypeResolver.php | 1 - .../src/Form/TagTranslationDocumentType.php | 23 +- lib/RoadizCoreBundle/src/Form/TagsType.php | 20 +- lib/RoadizCoreBundle/src/Form/ThemesType.php | 10 +- .../src/Form/TranslationsType.php | 13 +- .../src/Form/UrlAliasType.php | 9 - .../src/Form/UserCollectionType.php | 9 - lib/RoadizCoreBundle/src/Form/UsersType.php | 15 +- lib/RoadizCoreBundle/src/Form/WebhookType.php | 7 +- .../src/Form/WebhooksChoiceType.php | 11 +- lib/RoadizCoreBundle/src/Form/YamlType.php | 13 +- .../src/Importer/AttributeImporter.php | 10 +- .../src/Importer/ChainImporter.php | 17 +- .../src/Importer/EntityImporterInterface.php | 10 - .../src/Importer/GroupsImporter.php | 14 +- .../src/Importer/NodeTypesImporter.php | 7 +- .../src/Importer/RolesImporter.php | 13 +- .../src/Importer/SettingsImporter.php | 14 +- .../src/Importer/TagsImporter.php | 11 +- .../ListManager/AbstractEntityListManager.php | 53 +- .../src/ListManager/EntityListManager.php | 73 +- .../EntityListManagerInterface.php | 37 - .../src/ListManager/NodePaginator.php | 4 +- .../ListManager/NodeTreeDtoListManager.php | 4 +- .../src/ListManager/NodeTreeDtoPaginator.php | 7 +- .../src/ListManager/NodesSourcesPaginator.php | 4 +- .../src/ListManager/Paginator.php | 59 +- .../ListManager/QueryBuilderListManager.php | 45 +- .../src/ListManager/SessionListFilters.php | 19 +- .../src/ListManager/TagListManager.php | 12 +- .../src/Logger/DoctrineHandler.php | 20 +- .../src/Logger/Entity/Log.php | 100 +- .../src/Mailer/ContactFormManager.php | 149 +-- .../src/Mailer/ContactFormManagerFactory.php | 2 +- .../src/Mailer/EmailManager.php | 97 +- .../src/Mailer/EmailManagerFactory.php | 2 +- .../ApplyRealmNodeInheritanceMessage.php | 8 +- .../CleanRealmNodeInheritanceMessage.php | 8 +- .../src/Message/DeleteNodeTypeMessage.php | 3 - .../src/Message/GuzzleRequestMessage.php | 14 +- ...pplyRealmNodeInheritanceMessageHandler.php | 8 +- ...leanRealmNodeInheritanceMessageHandler.php | 6 +- .../Handler/DeleteNodeTypeMessageHandler.php | 4 +- .../Handler/HttpRequestMessageHandler.php | 2 +- .../PurgeReverseProxyCacheMessageHandler.php | 17 +- ...archRealmNodeInheritanceMessageHandler.php | 6 +- .../UpdateNodeTypeSchemaMessageHandler.php | 4 +- .../src/Message/HttpRequestMessage.php | 1 + .../Message/PurgeReverseProxyCacheMessage.php | 3 - .../SearchRealmNodeInheritanceMessage.php | 3 - .../Message/UpdateNodeTypeSchemaMessage.php | 3 - .../src/Model/AttributableInterface.php | 13 - .../src/Model/AttributableTrait.php | 17 +- .../src/Model/AttributeGroupInterface.php | 5 + .../src/Model/AttributeGroupTrait.php | 43 +- .../AttributeGroupTranslationInterface.php | 27 +- .../Model/AttributeGroupTranslationTrait.php | 40 +- .../src/Model/AttributeInterface.php | 81 +- .../src/Model/AttributeTrait.php | 167 ++- .../Model/AttributeTranslationInterface.php | 37 +- .../src/Model/AttributeTranslationTrait.php | 45 +- .../src/Model/AttributeValueInterface.php | 32 +- .../src/Model/AttributeValueTrait.php | 73 +- .../AttributeValueTranslationInterface.php | 32 +- .../Model/AttributeValueTranslationTrait.php | 42 +- .../src/Model/NodeTreeDto.php | 20 +- .../src/Model/RealmInterface.php | 8 +- .../src/Node/CachedNodeOffspringResolver.php | 14 +- .../CachedNodeOffspringResolverInterface.php | 1 + .../src/Node/NodeDuplicator.php | 11 +- lib/RoadizCoreBundle/src/Node/NodeFactory.php | 12 +- lib/RoadizCoreBundle/src/Node/NodeMover.php | 54 +- .../src/Node/NodeNameChecker.php | 32 +- .../src/Node/NodeNamePolicyFactory.php | 2 +- .../src/Node/NodeNamePolicyInterface.php | 9 +- .../Node/NodeOffspringResolverInterface.php | 1 - .../src/Node/NodeTranslator.php | 6 +- .../src/Node/NodeTranstyper.php | 49 +- .../src/Node/UniqueNodeGenerator.php | 34 +- .../src/Node/UniversalDataDuplicator.php | 14 +- .../src/NodeType/ApiResourceGenerator.php | 100 +- .../src/NodeType/DefaultValuesResolver.php | 5 +- .../src/NodeType/NodeTypeResolver.php | 6 +- .../EventSubscriber/PreviewBarSubscriber.php | 31 +- .../EventSubscriber/PreviewModeSubscriber.php | 20 +- .../Exception/PreviewNotAllowedException.php | 2 +- .../src/Preview/PreviewResolverInterface.php | 1 + .../src/Preview/RequestPreviewRevolver.php | 8 +- .../src/Preview/User/PreviewUser.php | 19 - .../src/Preview/User/PreviewUserProvider.php | 11 +- .../User/PreviewUserProviderInterface.php | 1 - .../src/Realm/RealmResolver.php | 23 +- .../src/Realm/RealmResolverInterface.php | 12 +- .../AttributeDocumentsRepository.php | 5 +- .../Repository/AttributeGroupRepository.php | 2 +- .../AttributeGroupTranslationRepository.php | 3 +- .../src/Repository/AttributeRepository.php | 2 +- .../AttributeTranslationRepository.php | 2 +- .../Repository/AttributeValueRepository.php | 17 +- .../AttributeValueTranslationRepository.php | 2 +- .../Repository/CustomFormAnswerRepository.php | 10 +- .../CustomFormFieldAttributeRepository.php | 2 +- .../Repository/CustomFormFieldRepository.php | 3 +- .../src/Repository/CustomFormRepository.php | 8 +- .../src/Repository/DocumentRepository.php | 174 +-- .../DocumentTranslationRepository.php | 4 +- .../src/Repository/EntityRepository.php | 165 +-- .../src/Repository/FolderRepository.php | 69 +- .../FolderTranslationRepository.php | 2 +- .../src/Repository/GroupRepository.php | 3 +- .../src/Repository/LogRepository.php | 7 +- .../src/Repository/NodeRepository.php | 290 ++--- .../Repository/NodeTypeFieldRepository.php | 18 +- .../src/Repository/NodeTypeRepository.php | 7 +- .../Repository/NodesCustomFormsRepository.php | 7 +- .../NodesSourcesDocumentsRepository.php | 6 +- .../src/Repository/NodesSourcesRepository.php | 284 ++--- .../src/Repository/NodesTagsRepository.php | 2 +- .../src/Repository/NodesToNodesRepository.php | 7 +- .../src/Repository/PrefixAwareRepository.php | 91 +- .../src/Repository/RealmNodeRepository.php | 1 + .../src/Repository/RealmRepository.php | 1 + .../src/Repository/RedirectionRepository.php | 3 +- .../src/Repository/RoleRepository.php | 15 +- .../src/Repository/SettingGroupRepository.php | 10 +- .../src/Repository/SettingRepository.php | 17 +- .../src/Repository/StatusAwareRepository.php | 29 +- .../src/Repository/TagRepository.php | 167 +-- .../TagTranslationDocumentsRepository.php | 7 +- .../Repository/TagTranslationRepository.php | 3 +- .../src/Repository/TranslationRepository.php | 101 +- .../src/Repository/UrlAliasRepository.php | 8 +- .../src/Repository/UserLogEntryRepository.php | 13 +- .../src/Repository/UserRepository.php | 10 +- .../src/Repository/WebhookRepository.php | 3 +- .../src/Routing/ChainResourcePathResolver.php | 8 +- .../src/Routing/DocumentUrlGenerator.php | 5 +- .../src/Routing/DynamicUrlMatcher.php | 2 +- .../src/Routing/NodePathInfo.php | 37 +- .../src/Routing/NodeRouteHelper.php | 29 +- .../src/Routing/NodeRouter.php | 87 +- .../src/Routing/NodeUrlMatcher.php | 24 +- .../src/Routing/NodesSourcesPathResolver.php | 58 +- .../src/Routing/NodesSourcesUrlGenerator.php | 53 +- .../src/Routing/NullLoader.php | 16 +- ...timizedNodesSourcesGraphPathAggregator.php | 26 +- .../src/Routing/PathResolverInterface.php | 8 +- .../src/Routing/RedirectableUrlMatcher.php | 6 +- .../src/Routing/RedirectionMatcher.php | 13 +- .../src/Routing/RedirectionPathResolver.php | 2 +- .../src/Routing/RedirectionRouter.php | 14 +- .../src/Routing/ResourceInfo.php | 32 +- .../src/Routing/RouteHandler.php | 3 +- .../SearchEngine/AbstractSearchHandler.php | 153 +-- .../src/SearchEngine/AbstractSolarium.php | 54 +- .../src/SearchEngine/ClientRegistry.php | 4 +- .../SearchEngine/DocumentSearchHandler.php | 46 +- .../Event/AbstractSearchQueryEvent.php | 6 - .../GlobalNodeSourceSearchHandler.php | 15 +- .../SearchEngine/Indexer/AbstractIndexer.php | 13 +- .../src/SearchEngine/Indexer/Indexer.php | 4 + .../SearchEngine/Indexer/IndexerFactory.php | 5 +- .../Indexer/IndexerFactoryInterface.php | 1 - .../Indexer/NodesSourcesIndexer.php | 9 +- .../Message/AbstractSolrMessage.php | 16 +- .../Handler/SolrDeleteMessageHandler.php | 2 +- .../Handler/SolrReindexMessageHandler.php | 2 +- .../SearchEngine/NodeSourceSearchHandler.php | 125 +- .../NodeSourceSearchHandlerInterface.php | 2 + .../SearchEngine/SearchHandlerInterface.php | 22 +- .../SearchEngine/SearchResultsInterface.php | 2 + .../src/SearchEngine/SolariumDocument.php | 41 +- .../SolariumDocumentTranslation.php | 17 +- .../src/SearchEngine/SolariumFactory.php | 2 +- .../SearchEngine/SolariumFactoryInterface.php | 2 + .../src/SearchEngine/SolariumNodeSource.php | 16 +- .../src/SearchEngine/SolrSearchResultItem.php | 4 +- .../src/SearchEngine/SolrSearchResults.php | 55 +- .../Subscriber/AbstractIndexingSubscriber.php | 18 +- .../AttributeValueIndexingSubscriber.php | 11 +- ...tDocumentTranslationIndexingSubscriber.php | 19 +- .../DefaultNodesSourcesIndexingSubscriber.php | 24 +- .../Subscriber/SolariumSubscriber.php | 22 +- .../TreeWalkerIndexingEventSubscriber.php | 10 +- ...BackofficeAuthenticationSuccessHandler.php | 6 +- .../Authentication/RoadizAuthenticator.php | 6 +- .../Authorization/AccessDeniedHandler.php | 24 +- .../Chroot/NodeChrootChainResolver.php | 10 +- .../Chroot/NodeChrootResolver.php | 12 - .../Chroot/RoadizUserNodeChrootResolver.php | 4 - .../Authorization/Voter/GroupVoter.php | 12 +- .../Voter/NodeTypeFieldVoter.php | 5 +- .../Authorization/Voter/NodeVoter.php | 40 +- .../Authorization/Voter/RealmVoter.php | 34 +- .../Authorization/Voter/RoleArrayVoter.php | 3 - .../Voter/SuperAdminRoleHierarchyVoter.php | 10 +- .../src/Security/Blacklist/Top500Provider.php | 3 - .../LoginLink/EmailLoginLinkSender.php | 4 +- .../Security/User/AdvancedUserInterface.php | 3 + .../src/Security/User/UserProvider.php | 21 +- .../src/Security/User/UserViewer.php | 24 +- .../Serializer/CircularReferenceHandler.php | 1 + .../Normalizer/AbstractPathNormalizer.php | 17 +- .../Normalizer/AttributeValueNormalizer.php | 9 +- .../Normalizer/CustomFormNormalizer.php | 15 +- .../Normalizer/DocumentNormalizer.php | 23 +- .../Normalizer/DocumentSourcesNormalizer.php | 5 +- .../Normalizer/FolderNormalizer.php | 7 +- .../Normalizer/NodesSourcesPathNormalizer.php | 21 +- .../RealmSerializationGroupNormalizer.php | 8 +- .../Serializer/Normalizer/TagNormalizer.php | 15 +- .../Normalizer/TranslationAwareNormalizer.php | 14 +- .../AbstractTypedObjectConstructor.php | 35 +- .../AttributeObjectConstructor.php | 16 +- .../ChainDoctrineObjectConstructor.php | 9 +- .../GroupObjectConstructor.php | 14 +- .../NodeObjectConstructor.php | 9 +- .../NodeTypeObjectConstructor.php | 13 +- .../ObjectConstructor/ObjectConstructor.php | 3 +- .../RoleObjectConstructor.php | 11 +- .../SettingGroupObjectConstructor.php | 11 +- .../SettingObjectConstructor.php | 11 +- .../TagObjectConstructor.php | 18 +- .../TranslationObjectConstructor.php | 14 +- .../TypedObjectConstructorInterface.php | 6 - .../TranslationAwareContextBuilder.php | 9 +- lib/RoadizCoreBundle/src/Tag/TagFactory.php | 7 +- .../src/Traits/LoginRequestTrait.php | 10 +- .../src/Traits/LoginResetTrait.php | 9 - .../src/Translation/TranslationViewer.php | 37 +- .../src/TwigExtension/AttributesExtension.php | 46 +- .../TwigExtension/BlockRenderExtension.php | 28 +- .../CentralTruncateExtension.php | 16 +- .../TwigExtension/DocumentUrlExtension.php | 19 +- .../src/TwigExtension/HandlerExtension.php | 2 - .../src/TwigExtension/JwtExtension.php | 4 +- .../src/TwigExtension/LogExtension.php | 10 +- .../TwigExtension/NodesSourcesExtension.php | 63 +- .../src/TwigExtension/RoadizExtension.php | 7 +- .../src/TwigExtension/RoutingExtension.php | 13 +- .../TokenParser/TransChoiceTokenParser.php | 10 - .../TwigExtension/TransChoiceExtension.php | 2 +- .../TwigExtension/TranslationExtension.php | 18 +- .../TranslationMenuExtension.php | 9 +- .../TooManyWebhookTriggeredException.php | 9 +- .../Message/GenericJsonPostMessage.php | 12 +- .../Message/GitlabPipelineTriggerMessage.php | 11 +- .../Message/NetlifyBuildHookMessage.php | 11 +- .../src/Webhook/Message/WebhookMessage.php | 1 - .../Webhook/Message/WebhookMessageFactory.php | 2 +- .../Webhook/ThrottledWebhookDispatcher.php | 7 +- .../src/Webhook/WebhookInterface.php | 9 + .../Event/NodeStatusGuardListener.php | 5 +- .../src/Workflow/NodeWorkflow.php | 2 +- .../src/Xlsx/AbstractXlsxSerializer.php | 8 +- .../src/Xlsx/NodeSourceXlsxSerializer.php | 24 +- .../src/Xlsx/SerializerInterface.php | 19 +- .../src/Xlsx/XlsxExporter.php | 37 +- .../NodeType/ApiResourceGeneratorTest.php | 29 +- lib/RoadizCoreBundle/tests/bootstrap.php | 2 + lib/RoadizCoreBundle/tests/object-manager.php | 7 +- .../src/Controller/Admin/FontsController.php | 63 +- .../src/Controller/FontFaceController.php | 25 +- .../DoctrineMigrationCompilerPass.php | 20 +- .../RoadizFontExtension.php | 5 +- .../FontLifeCycleSubscriber.php | 22 +- lib/RoadizFontBundle/src/Entity/Font.php | 116 +- .../src/Event/Font/FontEvent.php | 14 +- .../EventSubscriber/UpdateFontSubscriber.php | 5 - lib/RoadizFontBundle/src/Form/FontType.php | 12 +- .../src/Form/FontVariantsType.php | 9 +- .../src/Repository/FontRepository.php | 2 +- .../Document/DocumentArchiveController.php | 10 +- .../Document/DocumentDuplicatesController.php | 4 - .../DocumentLimitationsController.php | 3 +- .../Document/DocumentPreviewController.php | 13 +- .../Document/DocumentPublicListController.php | 31 +- .../Document/DocumentUnusedController.php | 2 - .../Login/LoginRequestController.php | 7 +- .../Controller/Node/NodesTagsController.php | 4 - .../Controller/Node/RealmNodeController.php | 10 +- .../src/Controller/Node/SeoController.php | 75 +- .../Controller/Node/TranslateController.php | 1 + .../src/Controller/Realm/RealmController.php | 30 - .../src/Controller/SecurityController.php | 12 +- .../Compiler/JwtRoleStrategyCompilerPass.php | 3 - .../Compiler/RozierPathsCompilerPass.php | 21 +- .../src/DependencyInjection/Configuration.php | 1 + .../RoadizRozierExtension.php | 13 +- .../DataTransformer/NodesTagsTransformer.php | 2 + .../src/Form/DocumentLimitationsType.php | 5 +- .../src/Form/NodesTagsType.php | 14 - .../src/Form/TranslateNodeType.php | 13 - .../src/Security/RozierAuthenticator.php | 2 + .../src/Backup/BackupCodeManager.php | 2 +- .../Console/DisableTwoFactorUserCommand.php | 5 +- .../src/Console/UsersCommand.php | 3 +- .../Controller/BackupCodesAdminController.php | 2 +- .../src/Controller/QrCodeController.php | 2 +- .../Controller/TwoFactorAdminController.php | 3 + .../DoctrineMigrationCompilerPass.php | 20 +- .../RoadizTwoFactorExtension.php | 3 +- .../src/Entity/TwoFactorUser.php | 75 +- .../UserActionsMenuEventSubscriber.php | 4 +- .../src/Form/TwoFactorCodeActivationType.php | 6 +- .../Repository/TwoFactorUserRepository.php | 2 +- .../AuthenticatorTwoFactorProvider.php | 8 +- .../Provider/TwoFactorUserProvider.php | 6 +- .../TwoFactorUserProviderInterface.php | 1 - .../PurgeUserValidationTokenCommand.php | 3 +- .../DoctrineMigrationCompilerPass.php | 20 +- .../src/DependencyInjection/Configuration.php | 1 + .../RoadizUserExtension.php | 5 +- .../src/Entity/UserMetadata.php | 24 +- .../src/Entity/UserValidationToken.php | 33 +- ...ssAuthenticationSuccessEventSubscriber.php | 3 - .../PasswordlessUserSignedUpSubscriber.php | 7 +- .../UserSignedUpSubscriber.php | 7 +- .../src/Manager/UserMetadataManager.php | 1 + .../Manager/UserMetadataManagerInterface.php | 1 + .../Manager/UserValidationTokenManager.php | 13 +- .../UserValidationTokenManagerInterface.php | 1 + .../UserValidationTokenRepository.php | 1 + .../src/Security/FrontendLoginLinkHandler.php | 16 +- .../src/State/RecaptchaProtectedTrait.php | 7 +- .../src/State/SignupProcessorTrait.php | 1 + .../State/UserPasswordRequestProcessor.php | 11 +- .../src/State/UserPasswordResetProcessor.php | 2 +- .../src/State/UserTokenProvider.php | 1 + .../State/UserValidationRequestProcessor.php | 4 +- .../State/UserValidationTokenProcessor.php | 4 +- .../AbstractAjaxController.php | 24 +- .../AjaxAbstractFieldsController.php | 23 +- .../AjaxAttributeValuesController.php | 14 +- .../AjaxCustomFormFieldsController.php | 10 +- .../AjaxCustomFormsExplorerController.php | 11 +- .../AjaxDocumentsExplorerController.php | 18 +- .../AjaxEntitiesExplorerController.php | 16 +- .../AjaxExplorerProviderController.php | 16 +- .../AjaxFolderTreeController.php | 10 +- .../AjaxControllers/AjaxFoldersController.php | 36 +- .../AjaxFoldersExplorerController.php | 2 +- .../AjaxNodeTreeController.php | 16 +- .../AjaxNodeTypeFieldsController.php | 10 +- .../AjaxNodeTypesController.php | 15 +- .../AjaxControllers/AjaxNodesController.php | 74 +- .../AjaxNodesExplorerController.php | 39 +- .../AjaxSearchNodesSourcesController.php | 24 +- .../AjaxControllers/AjaxSessionMessages.php | 3 +- .../AjaxControllers/AjaxTagTreeController.php | 10 +- .../AjaxControllers/AjaxTagsController.php | 84 +- .../Controllers/AbstractAdminController.php | 115 +- .../AbstractAdminWithBulkController.php | 37 +- .../Attributes/AttributeController.php | 47 +- .../Attributes/AttributeGroupController.php | 35 +- .../src/Controllers/CacheController.php | 5 +- .../CustomFormAnswersController.php | 24 +- .../CustomFormFieldAttributesController.php | 10 +- .../CustomFormFieldsController.php | 38 +- .../CustomForms/CustomFormsController.php | 2 +- .../CustomFormsUtilsController.php | 26 +- .../src/Controllers/DashboardController.php | 4 +- .../DocumentTranslationsController.php | 42 +- .../Documents/DocumentsController.php | 162 +-- .../src/Controllers/FoldersController.php | 41 +- .../src/Controllers/GroupsController.php | 68 +- .../src/Controllers/GroupsUtilsController.php | 27 +- .../src/Controllers/HistoryController.php | 23 +- .../src/Controllers/LoginController.php | 14 +- .../src/Controllers/LoginResetController.php | 4 - .../Controllers/NodeTypeFieldsController.php | 31 +- .../NodeTypes/NodeTypesController.php | 18 +- .../NodeTypes/NodeTypesUtilsController.php | 51 +- .../Controllers/Nodes/ExportController.php | 13 +- .../Controllers/Nodes/HistoryController.php | 5 +- .../Nodes/NodesAttributesController.php | 41 +- .../src/Controllers/Nodes/NodesController.php | 96 +- .../Nodes/NodesSourcesController.php | 35 +- .../Nodes/NodesTreesController.php | 56 +- .../Nodes/NodesUtilsController.php | 15 +- .../Controllers/Nodes/TranstypeController.php | 4 - .../Controllers/RedirectionsController.php | 44 +- .../src/Controllers/RolesController.php | 50 +- .../src/Controllers/RolesUtilsController.php | 25 +- .../src/Controllers/SearchController.php | 296 ++--- .../Controllers/SettingGroupsController.php | 35 +- .../src/Controllers/SettingsController.php | 43 +- .../Controllers/SettingsUtilsController.php | 23 +- .../Tags/TagMultiCreationController.php | 3 - .../src/Controllers/Tags/TagsController.php | 108 +- .../Controllers/Tags/TagsUtilsController.php | 19 +- .../Controllers/TranslationsController.php | 21 +- .../src/Controllers/Users/UsersController.php | 27 +- .../Users/UsersGroupsController.php | 15 +- .../Users/UsersRolesController.php | 20 +- .../Users/UsersSecurityController.php | 8 +- .../src/Controllers/WebhookController.php | 8 +- .../src/Explorer/ConfigurableExplorerItem.php | 14 +- .../src/Explorer/CustomFormExplorerItem.php | 6 +- .../src/Explorer/DocumentExplorerItem.php | 43 +- .../src/Explorer/ExplorerItemFactory.php | 14 +- .../src/Explorer/FolderExplorerItem.php | 17 +- lib/Rozier/src/Explorer/FoldersProvider.php | 5 +- lib/Rozier/src/Explorer/NodeExplorerItem.php | 6 +- .../src/Explorer/NodeSourceExplorerItem.php | 4 +- .../src/Explorer/NodeTypeExplorerItem.php | 4 +- .../src/Explorer/SettingExplorerItem.php | 17 +- lib/Rozier/src/Explorer/SettingsProvider.php | 5 +- lib/Rozier/src/Explorer/TagExplorerItem.php | 11 +- lib/Rozier/src/Explorer/UserExplorerItem.php | 23 +- lib/Rozier/src/Explorer/UsersProvider.php | 5 +- lib/Rozier/src/Forms/AddUserType.php | 10 +- lib/Rozier/src/Forms/CustomFormFieldType.php | 11 +- lib/Rozier/src/Forms/CustomFormType.php | 13 +- .../Forms/DataTransformer/TagTransformer.php | 11 +- lib/Rozier/src/Forms/DocumentEditType.php | 44 +- lib/Rozier/src/Forms/DocumentEmbedType.php | 14 +- .../src/Forms/DocumentTranslationType.php | 11 +- lib/Rozier/src/Forms/DynamicType.php | 14 +- lib/Rozier/src/Forms/FolderCollectionType.php | 22 +- lib/Rozier/src/Forms/GeoJsonType.php | 3 - lib/Rozier/src/Forms/GroupType.php | 6 - .../src/Forms/ImageCropAlignmentType.php | 3 +- lib/Rozier/src/Forms/LoginType.php | 21 +- lib/Rozier/src/Forms/Node/AddNodeType.php | 19 +- ...bstractConfigurableNodeSourceFieldType.php | 10 +- .../AbstractNodeSourceFieldType.php | 14 - .../Forms/NodeSource/NodeSourceBaseType.php | 20 +- .../NodeSource/NodeSourceCollectionType.php | 3 - .../NodeSource/NodeSourceCustomFormType.php | 27 +- .../NodeSource/NodeSourceDocumentType.php | 26 +- .../Forms/NodeSource/NodeSourceJoinType.php | 14 - .../Forms/NodeSource/NodeSourceNodeType.php | 25 +- .../NodeSource/NodeSourceProviderType.php | 15 +- .../Forms/NodeSource/NodeSourceSeoType.php | 34 +- .../src/Forms/NodeSource/NodeSourceType.php | 84 +- lib/Rozier/src/Forms/NodeTreeType.php | 32 +- lib/Rozier/src/Forms/NodeType.php | 14 +- .../Forms/NodeTypeFieldSerializationType.php | 19 +- lib/Rozier/src/Forms/NodeTypeFieldType.php | 2 +- lib/Rozier/src/Forms/RedirectionType.php | 8 +- lib/Rozier/src/Forms/RoleType.php | 9 - lib/Rozier/src/Forms/SettingGroupType.php | 6 - lib/Rozier/src/Forms/TagTranslationType.php | 22 +- lib/Rozier/src/Forms/TagType.php | 4 +- lib/Rozier/src/Forms/TranslationType.php | 2 +- lib/Rozier/src/Forms/TranstypeType.php | 17 - lib/Rozier/src/Forms/UserDetailsType.php | 16 +- lib/Rozier/src/Forms/UserSecurityType.php | 12 +- lib/Rozier/src/Forms/UserType.php | 8 +- lib/Rozier/src/Models/ModelInterface.php | 4 +- lib/Rozier/src/RozierApp.php | 23 +- lib/Rozier/src/RozierServiceRegistry.php | 6 +- .../DocumentThumbnailSerializeSubscriber.php | 12 +- lib/Rozier/src/Traits/NodesTrait.php | 35 +- .../src/Traits/VersionedControllerTrait.php | 8 +- lib/Rozier/src/Widgets/AbstractWidget.php | 9 +- lib/Rozier/src/Widgets/FolderTreeWidget.php | 12 +- lib/Rozier/src/Widgets/NodeTreeWidget.php | 68 +- lib/Rozier/src/Widgets/TagTreeWidget.php | 31 +- lib/Rozier/src/Widgets/TreeWidgetFactory.php | 2 +- monorepo-builder.php | 2 +- public/index.php | 2 + rector.php | 34 +- src/Api/Model/CommonContent.php | 6 +- src/Controller/ContactFormController.php | 3 +- src/Controller/GetCommonContentController.php | 12 +- src/Controller/PageController.php | 2 +- src/DataFixtures/AppFixtures.php | 2 + src/DataFixtures/ArticleFixtures.php | 4 +- src/DataFixtures/NodeTypeFixtures.php | 10 +- src/DataFixtures/OfferFixtures.php | 4 +- src/Doctrine/ProjectVersionComparator.php | 2 + src/Entity/PositionedPageUser.php | 29 +- src/Form/ContactFormType.php | 16 +- src/GeneratedEntity/NSArticle.php | 28 +- src/GeneratedEntity/NSArticleContainer.php | 8 +- src/GeneratedEntity/NSArticleFeedBlock.php | 11 +- src/GeneratedEntity/NSBasicBlock.php | 19 +- src/GeneratedEntity/NSGroupBlock.php | 8 +- src/GeneratedEntity/NSMenu.php | 8 +- src/GeneratedEntity/NSMenuLink.php | 27 +- src/GeneratedEntity/NSNeutral.php | 12 +- src/GeneratedEntity/NSOffer.php | 30 +- src/GeneratedEntity/NSPage.php | 109 +- .../NSArticleContainerRepository.php | 1 + .../NSArticleFeedBlockRepository.php | 1 + .../Repository/NSArticleRepository.php | 1 + .../Repository/NSBasicBlockRepository.php | 1 + .../Repository/NSGroupBlockRepository.php | 1 + .../Repository/NSMenuLinkRepository.php | 1 + .../Repository/NSMenuRepository.php | 1 + .../Repository/NSNeutralRepository.php | 1 + .../Repository/NSOfferRepository.php | 1 + .../Repository/NSPageRepository.php | 1 + src/Kernel.php | 12 +- .../Normalizer/MenuLinkPathNormalizer.php | 7 +- .../Definition/ArticleFeedBlockDefinition.php | 11 +- .../ArticleFeedBlockDefinitionFactory.php | 2 +- src/TreeWalker/MenuNodeSourceWalker.php | 10 +- tests/ArticleTest.php | 6 +- tests/OfferTest.php | 2 + tests/bootstrap.php | 2 + tests/object-manager.php | 7 +- 1045 files changed, 8154 insertions(+), 16044 deletions(-) create mode 100644 .php-cs-fixer.dist.php diff --git a/.github/workflows/run-test.yml b/.github/workflows/run-test.yml index 61e9c82f..7c5e12f2 100644 --- a/.github/workflows/run-test.yml +++ b/.github/workflows/run-test.yml @@ -43,7 +43,7 @@ jobs: XDEBUG_MODE=coverage vendor/bin/phpunit -v - name: Run PHP Code Sniffer run: | - php -d "memory_limit=-1" vendor/bin/phpcs --report=full -p + php -d "memory_limit=-1" vendor/bin/php-cs-fixer check --ansi -vvv - name: Run PHP Stan run: | php -d "memory_limit=-1" vendor/bin/phpstan analyse -c phpstan.neon diff --git a/.gitignore b/.gitignore index f54cca66..d9641099 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ - # Created by https://www.toptal.com/developers/gitignore/api/phpstorm # Edit at https://www.toptal.com/developers/gitignore?templates=phpstorm @@ -155,11 +154,6 @@ fabric.properties !/.data/db_test/.gitkeep !/.data/pgsql_test/.gitkeep !/.data/solr/.gitkeep - -###> squizlabs/php_codesniffer ### -/.phpcs-cache -/phpcs.xml -###< squizlabs/php_codesniffer ### /report.txt /composer.lock /symfony.lock @@ -167,3 +161,8 @@ fabric.properties ###> lexik/jwt-authentication-bundle ### /config/jwt/*.pem ###< lexik/jwt-authentication-bundle ### + +###> friendsofphp/php-cs-fixer ### +/.php-cs-fixer.php +/.php-cs-fixer.cache +###< friendsofphp/php-cs-fixer ### diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..3d2bdab8 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,17 @@ +in(__DIR__) + ->exclude(['var', 'vendor', 'docker', 'lib/EntityGenerator/tests/Mocks']) +; + +return (new PhpCsFixer\Config()) + ->setRules([ + '@Symfony' => true, + 'blank_line_after_opening_tag' => true, + 'declare_strict_types' => true, + ]) + ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) + ->setRiskyAllowed(true) + ->setFinder($finder) +; diff --git a/Makefile b/Makefile index 606b639f..9358a0ff 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ test: vendor/bin/monorepo-builder validate make phpstan XDEBUG_MODE=coverage vendor/bin/phpunit -v - php -d "memory_limit=-1" vendor/bin/phpcs -p + php -d "memory_limit=-1" vendor/bin/php-cs-fixer check --ansi -vvv php -d "memory_limit=-1" bin/console lint:twig ./lib/Documents/src/Resources/views php -d "memory_limit=-1" bin/console lint:twig ./lib/RoadizCoreBundle/templates php -d "memory_limit=-1" bin/console lint:twig ./lib/RoadizFontBundle/templates @@ -19,7 +19,10 @@ phpunit: APP_ENV=test docker compose exec -u www-data app php vendor/bin/phpunit -v fix: - php -d "memory_limit=-1" vendor/bin/phpcbf -p + php -d "memory_limit=-1" vendor/bin/php-cs-fixer fix --ansi -vvv + +check: + php -d "memory_limit=-1" vendor/bin/php-cs-fixer check --ansi -vvv requirements: vendor/bin/requirements-checker diff --git a/composer.json b/composer.json index 425422c1..8b6a6dda 100644 --- a/composer.json +++ b/composer.json @@ -141,6 +141,7 @@ "ambroisemaupate/intervention-request": "^4.0", "async-aws/simple-s3": "^1.1", "doctrine/doctrine-fixtures-bundle": "^3.6", + "friendsofphp/php-cs-fixer": "^3.64", "league/flysystem-async-aws-s3": "^3.10", "league/flysystem-aws-s3-v3": "^3.10", "php-coveralls/php-coveralls": "^2.4", @@ -149,7 +150,6 @@ "phpstan/phpstan-symfony": "^1.1.8", "phpunit/phpunit": "^9.5", "rector/rector": "^0.14.5", - "squizlabs/php_codesniffer": "^3.5", "symfony/browser-kit": "6.4.*", "symfony/css-selector": "6.4.*", "symfony/debug-bundle": "6.4.*", diff --git a/config/bundles.php b/config/bundles.php index ee819bd6..45f11a68 100644 --- a/config/bundles.php +++ b/config/bundles.php @@ -1,5 +1,7 @@ ['all' => true], Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true], diff --git a/config/preload.php b/config/preload.php index 5ebcdb21..7cbe578d 100644 --- a/config/preload.php +++ b/config/preload.php @@ -1,5 +1,7 @@ field = $field; $this->nodeTypesBag = $nodeTypesBag; @@ -35,13 +29,10 @@ public function __construct( abstract public function getContents(): string; - /** - * @return string - */ public function getIntroduction(): string { $lines = [ - '### ' . $this->field->getLabel(), + '### '.$this->field->getLabel(), ]; if (!empty($this->field->getDescription())) { $lines[] = $this->field->getDescription(); @@ -50,19 +41,19 @@ public function getIntroduction(): string '', '| | |', '| --- | --- |', - '| **' . trim($this->translator->trans('docs.type')) . '** | ' . $this->translator->trans($this->field->getTypeName()) . ' |', - '| **' . trim($this->translator->trans('docs.technical_name')) . '** | `' . $this->field->getVarName() . '` |', - '| **' . trim($this->translator->trans('docs.universal')) . '** | *' . $this->markdownGeneratorFactory->getHumanBool($this->field->isUniversal()) . '* |', + '| **'.trim($this->translator->trans('docs.type')).'** | '.$this->translator->trans($this->field->getTypeName()).' |', + '| **'.trim($this->translator->trans('docs.technical_name')).'** | `'.$this->field->getVarName().'` |', + '| **'.trim($this->translator->trans('docs.universal')).'** | *'.$this->markdownGeneratorFactory->getHumanBool($this->field->isUniversal()).'* |', ]); if (!empty($this->field->getGroupName())) { - $lines[] = '| **' . trim($this->translator->trans('docs.group')) . '** | ' . $this->field->getGroupName() . ' |'; + $lines[] = '| **'.trim($this->translator->trans('docs.group')).'** | '.$this->field->getGroupName().' |'; } if (!$this->field->isVisible()) { - $lines[] = '| **' . trim($this->translator->trans('docs.visible')) . '** | *' . $this->markdownGeneratorFactory->getHumanBool($this->field->isVisible()) . '* |'; + $lines[] = '| **'.trim($this->translator->trans('docs.visible')).'** | *'.$this->markdownGeneratorFactory->getHumanBool($this->field->isVisible()).'* |'; } - return implode("\n", $lines) . "\n"; + return implode("\n", $lines)."\n"; } } diff --git a/lib/DocGenerator/src/Generators/ChildrenNodeFieldGenerator.php b/lib/DocGenerator/src/Generators/ChildrenNodeFieldGenerator.php index ba5fe902..0a933887 100644 --- a/lib/DocGenerator/src/Generators/ChildrenNodeFieldGenerator.php +++ b/lib/DocGenerator/src/Generators/ChildrenNodeFieldGenerator.php @@ -12,8 +12,8 @@ public function getContents(): string { return implode("\n\n", [ $this->getIntroduction(), - '#### ' . $this->translator->trans('docs.available_children_blocks'), - $this->getAvailableChildren() + '#### '.$this->translator->trans('docs.available_children_blocks'), + $this->getAvailableChildren(), ]); } @@ -25,9 +25,11 @@ protected function getChildrenNodeTypes(): array if (null !== $this->field->getDefaultValues()) { return array_filter(array_map(function (string $nodeTypeName) { $nodeType = $this->nodeTypesBag->get(trim($nodeTypeName)); + return $nodeType instanceof NodeTypeInterface ? $nodeType : null; }, explode(',', $this->field->getDefaultValues()))); } + return []; } @@ -35,10 +37,11 @@ protected function getAvailableChildren(): string { return implode("\n", array_map(function (NodeTypeInterface $nodeType) { $nodeTypeGenerator = $this->markdownGeneratorFactory->createForNodeType($nodeType); + return implode("\n", [ - '* **' . trim($nodeTypeGenerator->getMenuEntry()) . '** ', + '* **'.trim($nodeTypeGenerator->getMenuEntry()).'** ', $nodeType->getDescription(), ]); - }, $this->getChildrenNodeTypes())) . "\n"; + }, $this->getChildrenNodeTypes()))."\n"; } } diff --git a/lib/DocGenerator/src/Generators/CommonFieldGenerator.php b/lib/DocGenerator/src/Generators/CommonFieldGenerator.php index e6c96b09..6beec48b 100644 --- a/lib/DocGenerator/src/Generators/CommonFieldGenerator.php +++ b/lib/DocGenerator/src/Generators/CommonFieldGenerator.php @@ -9,7 +9,7 @@ final class CommonFieldGenerator extends AbstractFieldGenerator public function getContents(): string { return implode("\n\n", [ - $this->getIntroduction() + $this->getIntroduction(), ]); } } diff --git a/lib/DocGenerator/src/Generators/DefaultValuedFieldGenerator.php b/lib/DocGenerator/src/Generators/DefaultValuedFieldGenerator.php index 32e14c58..fbdf63d2 100644 --- a/lib/DocGenerator/src/Generators/DefaultValuedFieldGenerator.php +++ b/lib/DocGenerator/src/Generators/DefaultValuedFieldGenerator.php @@ -10,7 +10,7 @@ public function getContents(): string { return implode("\n\n", [ $this->getIntroduction(), - $this->getDefaultValues() + $this->getDefaultValues(), ]); } @@ -18,8 +18,8 @@ private function getDefaultValues(): string { return implode("\n", array_map(function (string $value) { return implode("\n", [ - '* **' . trim($this->translator->trans(trim($value))) . '** `' . $value . '`', + '* **'.trim($this->translator->trans(trim($value))).'** `'.$value.'`', ]); - }, explode(',', $this->field->getDefaultValues() ?? ''))) . "\n"; + }, explode(',', $this->field->getDefaultValues() ?? '')))."\n"; } } diff --git a/lib/DocGenerator/src/Generators/DocumentationGenerator.php b/lib/DocGenerator/src/Generators/DocumentationGenerator.php index 06616ac3..6dcd46b9 100644 --- a/lib/DocGenerator/src/Generators/DocumentationGenerator.php +++ b/lib/DocGenerator/src/Generators/DocumentationGenerator.php @@ -16,10 +16,6 @@ class DocumentationGenerator private ?array $reachableTypeGenerators = null; private ?array $nonReachableTypeGenerators = null; - /** - * @param ParameterBag $nodeTypesBag - * @param TranslatorInterface $translator - */ public function __construct(ParameterBag $nodeTypesBag, TranslatorInterface $translator) { $this->nodeTypesBag = $nodeTypesBag; @@ -65,6 +61,7 @@ public function getReachableTypeGenerators(): array return $this->markdownGeneratorFactory->createForNodeType($nodeType); }, $this->getReachableTypes()); } + return $this->reachableTypeGenerators; } @@ -78,6 +75,7 @@ public function getNonReachableTypeGenerators(): array return $this->markdownGeneratorFactory->createForNodeType($nodeType); }, $this->getNonReachableTypes()); } + return $this->nonReachableTypeGenerators; } @@ -103,10 +101,10 @@ public function getNavBar(): string } return implode("\n", [ - '* ' . $this->translator->trans('docs.pages'), - " * " . implode("\n * ", $pages), - '* ' . $this->translator->trans('docs.blocks'), - " * " . implode("\n * ", $blocks) + '* '.$this->translator->trans('docs.pages'), + ' * '.implode("\n * ", $pages), + '* '.$this->translator->trans('docs.blocks'), + ' * '.implode("\n * ", $blocks), ]); } } diff --git a/lib/DocGenerator/src/Generators/MarkdownGeneratorFactory.php b/lib/DocGenerator/src/Generators/MarkdownGeneratorFactory.php index c38925e3..0dd41ef9 100644 --- a/lib/DocGenerator/src/Generators/MarkdownGeneratorFactory.php +++ b/lib/DocGenerator/src/Generators/MarkdownGeneratorFactory.php @@ -13,7 +13,7 @@ final class MarkdownGeneratorFactory { public function __construct( private readonly ParameterBag $nodeTypesBag, - private readonly TranslatorInterface $translator + private readonly TranslatorInterface $translator, ) { } @@ -22,11 +22,6 @@ public function getHumanBool(bool $bool): string return $bool ? $this->translator->trans('docs.yes') : $this->translator->trans('docs.no'); } - /** - * @param NodeTypeInterface $nodeType - * - * @return NodeTypeGenerator - */ public function createForNodeType(NodeTypeInterface $nodeType): NodeTypeGenerator { return new NodeTypeGenerator( @@ -36,11 +31,6 @@ public function createForNodeType(NodeTypeInterface $nodeType): NodeTypeGenerato ); } - /** - * @param NodeTypeFieldInterface $field - * - * @return AbstractFieldGenerator - */ public function createForNodeTypeField(NodeTypeFieldInterface $field): AbstractFieldGenerator { return match (true) { diff --git a/lib/DocGenerator/src/Generators/NodeReferencesFieldGenerator.php b/lib/DocGenerator/src/Generators/NodeReferencesFieldGenerator.php index 8bfe44d5..9f6ac0e7 100644 --- a/lib/DocGenerator/src/Generators/NodeReferencesFieldGenerator.php +++ b/lib/DocGenerator/src/Generators/NodeReferencesFieldGenerator.php @@ -10,8 +10,8 @@ public function getContents(): string { return implode("\n\n", [ $this->getIntroduction(), - '#### ' . $this->translator->trans('docs.available_referenced_nodes'), - $this->getAvailableChildren() + '#### '.$this->translator->trans('docs.available_referenced_nodes'), + $this->getAvailableChildren(), ]); } } diff --git a/lib/DocGenerator/src/Generators/NodeTypeGenerator.php b/lib/DocGenerator/src/Generators/NodeTypeGenerator.php index 4a98426d..cb3d0dbf 100644 --- a/lib/DocGenerator/src/Generators/NodeTypeGenerator.php +++ b/lib/DocGenerator/src/Generators/NodeTypeGenerator.php @@ -8,9 +8,6 @@ use RZ\Roadiz\Contracts\NodeType\NodeTypeInterface; use Symfony\Contracts\Translation\TranslatorInterface; -/** - * @package RZ\Roadiz\Documentation\Generators - */ class NodeTypeGenerator { protected TranslatorInterface $translator; @@ -18,15 +15,10 @@ class NodeTypeGenerator protected NodeTypeInterface $nodeType; protected array $fieldGenerators; - /** - * @param NodeTypeInterface $nodeType - * @param TranslatorInterface $translator - * @param MarkdownGeneratorFactory $markdownGeneratorFactory - */ public function __construct( NodeTypeInterface $nodeType, TranslatorInterface $translator, - MarkdownGeneratorFactory $markdownGeneratorFactory + MarkdownGeneratorFactory $markdownGeneratorFactory, ) { $this->nodeType = $nodeType; $this->fieldGenerators = []; @@ -41,7 +33,7 @@ public function __construct( public function getMenuEntry(): string { - return '[' . $this->nodeType->getLabel() . '](' . $this->getPath() . ')'; + return '['.$this->nodeType->getLabel().']('.$this->getPath().')'; } public function getType(): string @@ -51,22 +43,22 @@ public function getType(): string public function getPath(): string { - return $this->getType() . '/' . $this->nodeType->getName() . '.md'; + return $this->getType().'/'.$this->nodeType->getName().'.md'; } public function getContents(): string { return implode("\n\n", [ $this->getIntroduction(), - '## ' . $this->translator->trans('docs.fields'), - $this->getFieldsContents() + '## '.$this->translator->trans('docs.fields'), + $this->getFieldsContents(), ]); } protected function getIntroduction(): string { $lines = [ - '# ' . $this->nodeType->getLabel(), + '# '.$this->nodeType->getLabel(), ]; if (!empty($this->nodeType->getDescription())) { $lines[] = $this->nodeType->getDescription(); @@ -75,14 +67,14 @@ protected function getIntroduction(): string '', '| | |', '| --- | --- |', - '| **' . trim($this->translator->trans('docs.technical_name')) . '** | `' . $this->nodeType->getName() . '` |', + '| **'.trim($this->translator->trans('docs.technical_name')).'** | `'.$this->nodeType->getName().'` |', ]); if ($this->nodeType->isPublishable()) { - $lines[] = '| **' . trim($this->translator->trans('docs.publishable')) . '** | *' . $this->markdownGeneratorFactory->getHumanBool($this->nodeType->isPublishable()) . '* |'; + $lines[] = '| **'.trim($this->translator->trans('docs.publishable')).'** | *'.$this->markdownGeneratorFactory->getHumanBool($this->nodeType->isPublishable()).'* |'; } if (!$this->nodeType->isVisible()) { - $lines[] = '| **' . trim($this->translator->trans('docs.visible')) . '** | *' . $this->markdownGeneratorFactory->getHumanBool($this->nodeType->isVisible()) . '* |'; + $lines[] = '| **'.trim($this->translator->trans('docs.visible')).'** | *'.$this->markdownGeneratorFactory->getHumanBool($this->nodeType->isVisible()).'* |'; } return implode("\n", $lines); diff --git a/lib/Documents/src/AbstractDocumentFactory.php b/lib/Documents/src/AbstractDocumentFactory.php index 1e3a0dd9..472f78c3 100644 --- a/lib/Documents/src/AbstractDocumentFactory.php +++ b/lib/Documents/src/AbstractDocumentFactory.php @@ -32,7 +32,7 @@ abstract class AbstractDocumentFactory public function __construct( FilesystemOperator $documentsStorage, DocumentFinderInterface $documentFinder, - ?LoggerInterface $logger = null + ?LoggerInterface $logger = null, ) { if (!$documentsStorage instanceof MountManager) { trigger_error('Document Storage must be a MountManager to address public and private files.', E_USER_WARNING); @@ -42,69 +42,56 @@ public function __construct( $this->logger = $logger ?? new NullLogger(); } - /** - * @return File - */ public function getFile(): File { if (null === $this->file) { throw new \BadMethodCallException('File should be defined before using it.'); } + return $this->file; } /** - * @param File $file * @return $this */ public function setFile(File $file): static { $this->file = $file; + return $this; } - /** - * @return FolderInterface|null - */ public function getFolder(): ?FolderInterface { return $this->folder; } /** - * @param FolderInterface|null $folder * @return $this */ public function setFolder(?FolderInterface $folder = null): static { $this->folder = $folder; + return $this; } /** * Special case for SVG without XML statement. - * - * @param DocumentInterface $document */ protected function parseSvgMimeType(DocumentInterface $document): void { if ( - ($document->getMimeType() === 'text/plain' || $document->getMimeType() === 'text/html') && - preg_match('#\.svg$#', $document->getFilename()) + ('text/plain' === $document->getMimeType() || 'text/html' === $document->getMimeType()) + && preg_match('#\.svg$#', $document->getFilename()) ) { $this->logger->debug('Uploaded a SVG without xml declaration. Presuming it’s a valid SVG file.'); $document->setMimeType('image/svg+xml'); } } - /** - * @return DocumentInterface - */ abstract protected function createDocument(): DocumentInterface; - /** - * @param DocumentInterface $document - */ abstract protected function persistDocument(DocumentInterface $document): void; protected function getHashAlgorithm(): string @@ -116,14 +103,14 @@ protected function getHashAlgorithm(): string * Create a document from UploadedFile, Be careful, this method does not flush, only * persists current Document. * - * @param bool $allowEmpty Default false, requires a local file to create new document entity + * @param bool $allowEmpty Default false, requires a local file to create new document entity * @param bool $allowDuplicates Default false, always import new document even if file already exists - * @return null|DocumentInterface + * * @throws FilesystemException */ public function getDocument(bool $allowEmpty = false, bool $allowDuplicates = false): ?DocumentInterface { - if ($allowEmpty === false) { + if (false === $allowEmpty) { // Getter throw exception on null file $file = $this->getFile(); } else { @@ -147,8 +134,8 @@ public function getDocument(bool $allowEmpty = false, bool $allowDuplicates = fa $existingDocument = $this->documentFinder->findOneByHashAndAlgorithm($fileHash, $this->getHashAlgorithm()); if (null !== $existingDocument) { if ( - $existingDocument->isRaw() && - null !== $existingDownscaledDocument = $existingDocument->getDownscaledDocument() + $existingDocument->isRaw() + && null !== $existingDownscaledDocument = $existingDocument->getDownscaledDocument() ) { $existingDocument = $existingDownscaledDocument; } @@ -160,6 +147,7 @@ public function getDocument(bool $allowEmpty = false, bool $allowDuplicates = fa 'File %s already exists with same checksum, do not upload it twice.', $existingDocument->getFilename() )); + return $existingDocument; } } @@ -175,8 +163,8 @@ public function getDocument(bool $allowEmpty = false, bool $allowDuplicates = fa $this->parseSvgMimeType($document); if ( - $document instanceof FileHashInterface && - false !== $fileHash + $document instanceof FileHashInterface + && false !== $fileHash ) { $document->setFileHash($fileHash); $document->setFileHashAlgorithm($this->getHashAlgorithm()); @@ -196,8 +184,6 @@ public function getDocument(bool $allowEmpty = false, bool $allowDuplicates = fa /** * Updates a document from UploadedFile, Be careful, this method does not flush. * - * @param DocumentInterface $document - * @return DocumentInterface * @throws FilesystemException */ public function updateDocument(DocumentInterface $document): DocumentInterface @@ -231,7 +217,7 @@ public function updateDocument(DocumentInterface $document): DocumentInterface } } - $document->setFolder(\mb_substr(hash("crc32b", date('YmdHi')), 0, 12)); + $document->setFolder(\mb_substr(hash('crc32b', date('YmdHi')), 0, 12)); } $document->setFilename($this->getFileName()); @@ -247,9 +233,6 @@ public function updateDocument(DocumentInterface $document): DocumentInterface } /** - * @param File $localFile - * @param DocumentInterface $document - * @return void * @throws FilesystemException */ public function moveFile(File $localFile, DocumentInterface $document): void @@ -267,9 +250,6 @@ public function moveFile(File $localFile, DocumentInterface $document): void } } - /** - * @return string - */ protected function getFileName(): string { $file = $this->getFile(); @@ -278,8 +258,8 @@ protected function getFileName(): string $fileName = $file->getClientOriginalName(); } elseif ( $file instanceof DownloadedFile - && $file->getOriginalFilename() !== null - && $file->getOriginalFilename() !== '' + && null !== $file->getOriginalFilename() + && '' !== $file->getOriginalFilename() ) { $fileName = $file->getOriginalFilename(); } else { @@ -292,9 +272,6 @@ protected function getFileName(): string /** * Create a Document from an external URL. * - * @param string $downloadUrl - * - * @return DocumentInterface|null * @throws FilesystemException */ public function getDocumentFromUrl(string $downloadUrl): ?DocumentInterface @@ -303,6 +280,7 @@ public function getDocumentFromUrl(string $downloadUrl): ?DocumentInterface if (null !== $downloadedFile) { return $this->setFile($downloadedFile)->getDocument(); } + return null; } } diff --git a/lib/Documents/src/AbstractDocumentFinder.php b/lib/Documents/src/AbstractDocumentFinder.php index ff42399c..e400617f 100644 --- a/lib/Documents/src/AbstractDocumentFinder.php +++ b/lib/Documents/src/AbstractDocumentFinder.php @@ -6,49 +6,40 @@ abstract class AbstractDocumentFinder implements DocumentFinderInterface { - /** - * @inheritDoc - */ public function findVideosWithFilename(string $fileName): iterable { $basename = pathinfo($fileName); $basename = $basename['filename']; $sourcesDocsName = [ - $basename . '.ogg', - $basename . '.ogv', - $basename . '.mp4', - $basename . '.mov', - $basename . '.avi', - $basename . '.webm', - $basename . '.mkv', + $basename.'.ogg', + $basename.'.ogv', + $basename.'.mp4', + $basename.'.mov', + $basename.'.avi', + $basename.'.webm', + $basename.'.mkv', ]; return $this->findAllByFilenames($sourcesDocsName); } - /** - * @inheritDoc - */ public function findAudiosWithFilename(string $fileName): iterable { $basename = pathinfo($fileName); $basename = $basename['filename']; $sourcesDocsName = [ - $basename . '.mp3', - $basename . '.ogg', - $basename . '.wav', - $basename . '.m4a', - $basename . '.aac', + $basename.'.mp3', + $basename.'.ogg', + $basename.'.wav', + $basename.'.m4a', + $basename.'.aac', ]; return $this->findAllByFilenames($sourcesDocsName); } - /** - * @inheritDoc - */ public function findPicturesWithFilename(string $fileName): iterable { $pathInfo = pathinfo($fileName); @@ -70,7 +61,7 @@ public function findPicturesWithFilename(string $fileName): iterable $extensionsList = array_diff($extensionsList, [$currentExtension]); // list sources paths for extensions $sourcesDocsName = array_values(array_map(function ($extension) use ($basename) { - return $basename . '.' . $extension; + return $basename.'.'.$extension; }, $extensionsList)); return $this->findAllByFilenames($sourcesDocsName); diff --git a/lib/Documents/src/ArrayDocumentFinder.php b/lib/Documents/src/ArrayDocumentFinder.php index 14a4f019..56c9ead0 100644 --- a/lib/Documents/src/ArrayDocumentFinder.php +++ b/lib/Documents/src/ArrayDocumentFinder.php @@ -24,6 +24,7 @@ public function __construct() /** * @param array $fileNames + * * @return ArrayCollection */ public function findAllByFilenames(array $fileNames): ArrayCollection @@ -49,9 +50,7 @@ public function findOneByHashAndAlgorithm(string $hash, string $algorithm): ?Doc return null; } - /** - * @param DocumentInterface $document * @return $this */ public function addDocument(DocumentInterface $document): self @@ -59,6 +58,7 @@ public function addDocument(DocumentInterface $document): self if (!$this->documents->contains($document)) { $this->documents->add($document); } + return $this; } } diff --git a/lib/Documents/src/AverageColorResolver.php b/lib/Documents/src/AverageColorResolver.php index 39ce6100..b7989054 100644 --- a/lib/Documents/src/AverageColorResolver.php +++ b/lib/Documents/src/AverageColorResolver.php @@ -11,6 +11,7 @@ class AverageColorResolver public function getAverageColor(Image $image): string { $colorArray = $this->getAverageColorAsArray($image); + return sprintf( '#%02x%02x%02x', $colorArray[0], @@ -18,16 +19,13 @@ public function getAverageColor(Image $image): string $colorArray[2] ); } - /** - * @param Image $image - * - * @return array - */ + public function getAverageColorAsArray(Image $image): array { $image->resize(1, 1); /** @var array $array */ $array = $image->pickColor(0, 0); + return $array; } } diff --git a/lib/Documents/src/Console/AbstractDocumentCommand.php b/lib/Documents/src/Console/AbstractDocumentCommand.php index ca11e684..5536b40b 100644 --- a/lib/Documents/src/Console/AbstractDocumentCommand.php +++ b/lib/Documents/src/Console/AbstractDocumentCommand.php @@ -20,7 +20,7 @@ public function __construct( protected ManagerRegistry $managerRegistry, protected ImageManager $imageManager, protected FilesystemOperator $documentsStorage, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -31,22 +31,19 @@ protected function getManager(): ObjectManager } /** - * @return DocumentRepositoryInterface & EntityRepository + * @return DocumentRepositoryInterface&EntityRepository */ protected function getDocumentRepository(): DocumentRepositoryInterface { $repository = $this->managerRegistry->getRepository(DocumentInterface::class); if (!$repository instanceof DocumentRepositoryInterface) { - throw new \InvalidArgumentException('Document repository must implement ' . DocumentRepositoryInterface::class); + throw new \InvalidArgumentException('Document repository must implement '.DocumentRepositoryInterface::class); } + return $repository; } /** - * @param callable $method - * @param SymfonyStyle $io - * @param int $batchSize - * @return int * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ @@ -62,6 +59,7 @@ protected function onEachDocument(callable $method, SymfonyStyle $io, int $batch if ($count < 1) { $io->success('No document found'); + return 0; } @@ -82,6 +80,7 @@ protected function onEachDocument(callable $method, SymfonyStyle $io, int $batch } $manager->flush(); $io->progressFinish(); + return 0; } } diff --git a/lib/Documents/src/Console/DocumentAverageColorCommand.php b/lib/Documents/src/Console/DocumentAverageColorCommand.php index 7663654f..fb6750be 100644 --- a/lib/Documents/src/Console/DocumentAverageColorCommand.php +++ b/lib/Documents/src/Console/DocumentAverageColorCommand.php @@ -52,7 +52,7 @@ private function updateDocumentColor(DocumentInterface $document): void * Do nothing * just return 0 width and height */ - $this->io->error($mountPath . ' is not a readable image.'); + $this->io->error($mountPath.' is not a readable image.'); } } } diff --git a/lib/Documents/src/Console/DocumentClearFolderCommand.php b/lib/Documents/src/Console/DocumentClearFolderCommand.php index 026ffa52..13c0881a 100644 --- a/lib/Documents/src/Console/DocumentClearFolderCommand.php +++ b/lib/Documents/src/Console/DocumentClearFolderCommand.php @@ -28,6 +28,7 @@ protected function configure(): void protected function getDocumentQueryBuilder(FolderInterface $folder): QueryBuilder { $qb = $this->getDocumentRepository()->createQueryBuilder('d'); + return $qb->innerJoin('d.folders', 'f') ->andWhere($qb->expr()->eq('f.id', ':folderId')) ->setParameter(':folderId', $folder); @@ -44,7 +45,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $em = $this->getManager(); /** @var FolderInterface|null $folder */ $folder = $em->find(FolderInterface::class, $folderId); - if ($folder === null) { + if (null === $folder) { throw new \InvalidArgumentException(sprintf('Folder #%d does not exist.', $folderId)); } @@ -58,6 +59,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($count <= 0) { $this->io->warning('No documents were found in this folder.'); + return 0; } diff --git a/lib/Documents/src/Console/DocumentDownscaleCommand.php b/lib/Documents/src/Console/DocumentDownscaleCommand.php index bfbf17b8..ad3834be 100644 --- a/lib/Documents/src/Console/DocumentDownscaleCommand.php +++ b/lib/Documents/src/Console/DocumentDownscaleCommand.php @@ -31,7 +31,7 @@ public function __construct( private readonly ?int $maxPixelSize, private readonly DownscaleImageManager $downscaler, private readonly EventDispatcherInterface $dispatcher, - ?string $name = null + ?string $name = null, ) { parent::__construct($managerRegistry, $imageManager, $documentsStorage, $name); } @@ -52,11 +52,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (null === $this->maxPixelSize || $this->maxPixelSize <= 0) { $io->warning('Your configuration is not set for downscaling documents.'); $io->note('Add assetsProcessing.maxPixelSize parameter in your config.yml file.'); + return 1; } $confirmation = new ConfirmationQuestion( - 'Are you sure to downscale all your image documents to ' . $this->maxPixelSize . 'px?', + 'Are you sure to downscale all your image documents to '.$this->maxPixelSize.'px?', false ); if ($input->isInteractive() && !$io->askQuestion($confirmation)) { @@ -90,7 +91,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int /** @var array $processes */ $processes = []; - for ($i = 0; $i < $processCount; $i++) { + for ($i = 0; $i < $processCount; ++$i) { $offset = $i * $documentsPerProcess; $limit = $documentsPerProcess; @@ -99,8 +100,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'documents:downscale', '-n', '--process-count=1', - '--limit=' . $limit, - '--offset=' . $offset, + '--limit='.$limit, + '--offset='.$offset, ]; $process = new PhpSubprocess($command); @@ -116,6 +117,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $io->success('All processes have finished.'); + return 0; } @@ -132,7 +134,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int try { $this->downscaler->processDocumentFromExistingRaw($document); } catch (NotReadableException $exception) { - $io->error($exception->getMessage() . ' - ' . (string) $document); + $io->error($exception->getMessage().' - '.(string) $document); } $io->progressAdvance(); } @@ -141,6 +143,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $io->success('Every documents have been downscaled, a raw version has been kept.'); $this->dispatcher->dispatch(new CachePurgeAssetsRequestEvent()); + return 0; } } diff --git a/lib/Documents/src/Console/DocumentDuplicatesCommand.php b/lib/Documents/src/Console/DocumentDuplicatesCommand.php index 527857cf..f26007d6 100644 --- a/lib/Documents/src/Console/DocumentDuplicatesCommand.php +++ b/lib/Documents/src/Console/DocumentDuplicatesCommand.php @@ -29,12 +29,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $count = \count($documents); $rows = []; - if ($count === 0) { + if (0 === $count) { $this->io->success('No duplicated documents were found.'); + return 0; } - /** @var DocumentInterface & FileHashInterface $document */ + /** @var DocumentInterface&FileHashInterface $document */ foreach ($documents as $document) { $rows[] = [ 'ID' => (string) $document, @@ -45,7 +46,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $this->io->table([ - 'ID', 'Filename', 'Hash', 'Algo' + 'ID', 'Filename', 'Hash', 'Algo', ], $rows); return 0; diff --git a/lib/Documents/src/Console/DocumentFileHashCommand.php b/lib/Documents/src/Console/DocumentFileHashCommand.php index 9266f55f..416372f8 100644 --- a/lib/Documents/src/Console/DocumentFileHashCommand.php +++ b/lib/Documents/src/Console/DocumentFileHashCommand.php @@ -39,11 +39,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $defaultAlgorithm = 'sha256'; } if (!\in_array($defaultAlgorithm, \hash_algos())) { - throw new \RuntimeException(sprintf( - '“%s” algorithm is not available. Choose one from \hash_algos() method (%s)', - $defaultAlgorithm, - implode(', ', \hash_algos()) - )); + throw new \RuntimeException(sprintf('“%s” algorithm is not available. Choose one from \hash_algos() method (%s)', $defaultAlgorithm, implode(', ', \hash_algos()))); } $em = $this->getManager(); @@ -52,6 +48,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($count <= 0) { $this->io->success('All document files have hash.'); + return 0; } @@ -65,7 +62,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $algorithm = $document->getFileHashAlgorithm() ?? $defaultAlgorithm; - # https://flysystem.thephpleague.com/docs/usage/checksums/ + // https://flysystem.thephpleague.com/docs/usage/checksums/ $this->documentsStorage->checksum($mountPath, ['checksum_algo' => $algorithm]); if ($this->documentsStorage->fileExists($mountPath)) { $fileHash = $this->documentsStorage->checksum($mountPath, ['checksum_algo' => $algorithm]); diff --git a/lib/Documents/src/Console/DocumentPruneCommand.php b/lib/Documents/src/Console/DocumentPruneCommand.php index 5f716d56..008b0cd6 100644 --- a/lib/Documents/src/Console/DocumentPruneCommand.php +++ b/lib/Documents/src/Console/DocumentPruneCommand.php @@ -36,6 +36,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($count <= 0) { $this->io->warning('All documents are used.'); + return 0; } @@ -44,6 +45,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int '%d documents are not used by a node-source, a tag, a setting, a custom-form answer or an attribute.', $count )); + return 0; } diff --git a/lib/Documents/src/Console/DocumentPruneOrphansCommand.php b/lib/Documents/src/Console/DocumentPruneOrphansCommand.php index 6193f1a2..a3e9e85f 100644 --- a/lib/Documents/src/Console/DocumentPruneOrphansCommand.php +++ b/lib/Documents/src/Console/DocumentPruneOrphansCommand.php @@ -39,21 +39,18 @@ protected function execute(InputInterface $input, OutputInterface $output): int }, new SymfonyStyle($input, $output)); $this->io->success(sprintf('%d documents were deleted.', $deleteCount)); + return 0; } /** - * @param DocumentInterface $document - * @param ObjectManager $entityManager - * @param int $deleteCount - * @param bool $dryRun * @throws FilesystemException */ private function checkDocumentFilesystem( DocumentInterface $document, ObjectManager $entityManager, int &$deleteCount, - bool $dryRun = false + bool $dryRun = false, ): void { /* * Do not prune embed documents which may not have any file @@ -75,7 +72,7 @@ private function checkDocumentFilesystem( } if (!$dryRun) { $entityManager->remove($document); - $deleteCount++; + ++$deleteCount; } } } diff --git a/lib/Documents/src/Console/DocumentSizeCommand.php b/lib/Documents/src/Console/DocumentSizeCommand.php index 75121a2f..466b9f9f 100644 --- a/lib/Documents/src/Console/DocumentSizeCommand.php +++ b/lib/Documents/src/Console/DocumentSizeCommand.php @@ -61,7 +61,7 @@ private function updateDocumentSize(DocumentInterface $document): void * Do nothing * just return 0 width and height */ - $this->io->error($document->getMountPath() . ' is not a readable image.'); + $this->io->error($document->getMountPath().' is not a readable image.'); } } } diff --git a/lib/Documents/src/DocumentArchiver.php b/lib/Documents/src/DocumentArchiver.php index e29f7462..e4cc8f8b 100644 --- a/lib/Documents/src/DocumentArchiver.php +++ b/lib/Documents/src/DocumentArchiver.php @@ -22,15 +22,15 @@ public function __construct(private readonly FilesystemOperator $documentsStorag /** * @param iterable $documents - * @param string $name - * @param bool $keepFolders + * * @return string Zip file path + * * @throws FilesystemException */ 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; + $filename = (new AsciiSlugger())->slug($name.' '.date('YmdHis'), '_').'.zip'; + $tmpFileName = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename; $zip = new \ZipArchive(); $zip->open($tmpFileName, \ZipArchive::CREATE); @@ -44,7 +44,7 @@ public function archive(iterable $documents, string $name, bool $keepFolders = t $mountPath = $document->getMountPath(); if (null !== $mountPath && $this->documentsStorage->fileExists($mountPath)) { if ($keepFolders) { - $zipPathname = $document->getFolder() . DIRECTORY_SEPARATOR . $document->getFilename(); + $zipPathname = $document->getFolder().DIRECTORY_SEPARATOR.$document->getFilename(); } else { $zipPathname = $document->getFilename(); } @@ -59,17 +59,14 @@ public function archive(iterable $documents, string $name, bool $keepFolders = t /** * @param iterable $documents - * @param string $name - * @param bool $keepFolders - * @param bool $unlink - * @return BinaryFileResponse + * * @throws FilesystemException */ public function archiveAndServe( iterable $documents, string $name, bool $keepFolders = true, - bool $unlink = true + bool $unlink = true, ): BinaryFileResponse { $filename = $this->archive($documents, $name, $keepFolders); $response = new BinaryFileResponse( @@ -80,6 +77,7 @@ public function archiveAndServe( 'attachment' ); $response->deleteFileAfterSend($unlink); + return $response; } } diff --git a/lib/Documents/src/DocumentFinderInterface.php b/lib/Documents/src/DocumentFinderInterface.php index 336f23ab..a446de40 100644 --- a/lib/Documents/src/DocumentFinderInterface.php +++ b/lib/Documents/src/DocumentFinderInterface.php @@ -16,37 +16,24 @@ interface DocumentFinderInterface public function findAllByFilenames(array $fileNames): iterable; /** - * @param string $fileName - * * @return iterable */ public function findVideosWithFilename(string $fileName): iterable; /** - * @param string $fileName - * * @return iterable */ public function findAudiosWithFilename(string $fileName): iterable; /** - * @param string $fileName - * * @return iterable */ public function findPicturesWithFilename(string $fileName): iterable; /** * @param array $fileNames - * - * @return DocumentInterface|null */ public function findOneByFilenames(array $fileNames): ?DocumentInterface; - /** - * @param string $hash - * @param string $algorithm - * @return DocumentInterface|null - */ public function findOneByHashAndAlgorithm(string $hash, string $algorithm): ?DocumentInterface; } diff --git a/lib/Documents/src/DownloadedFile.php b/lib/Documents/src/DownloadedFile.php index 9677fa09..faa977f7 100644 --- a/lib/Documents/src/DownloadedFile.php +++ b/lib/Documents/src/DownloadedFile.php @@ -13,19 +13,11 @@ class DownloadedFile extends File { protected ?string $originalFilename; - /** - * @return string|null - */ public function getOriginalFilename(): ?string { return $this->originalFilename; } - /** - * @param string|null $originalFilename - * - * @return DownloadedFile - */ public function setOriginalFilename(?string $originalFilename): DownloadedFile { $this->originalFilename = $originalFilename; @@ -34,10 +26,7 @@ public function setOriginalFilename(?string $originalFilename): DownloadedFile } /** - * Final constructor for safe usage in DownloadedFile::fromUrl - * - * @param string $path - * @param bool $checkPath + * Final constructor for safe usage in DownloadedFile::fromUrl. */ final public function __construct(string $path, bool $checkPath = true) { @@ -46,10 +35,6 @@ final public function __construct(string $path, bool $checkPath = true) /** * Transform to lowercase and replace every non-alpha character with an underscore. - * - * @param string|null $string - * - * @return string */ public static function sanitizeFilename(?string $string): string { @@ -66,12 +51,6 @@ public static function sanitizeFilename(?string $string): string ; } - /** - * @param string $url - * @param string|null $originalName - * - * @return DownloadedFile|null - */ public static function fromUrl(string $url, ?string $originalName = null): ?DownloadedFile { try { @@ -99,8 +78,8 @@ public static function fromUrl(string $url, ?string $originalName = null): ?Down /* * Some OEmbed providers won't add any extension in original filename. */ - if ($file->getExtension() === '' && null !== $guessedExtension = $file->guessExtension()) { - $file->setOriginalFilename($file->getOriginalFilename() . '.' . $guessedExtension); + if ('' === $file->getExtension() && null !== $guessedExtension = $file->guessExtension()) { + $file->setOriginalFilename($file->getOriginalFilename().'.'.$guessedExtension); } if ($file->isReadable() && filesize($file->getPathname()) > 0) { @@ -111,6 +90,7 @@ public static function fromUrl(string $url, ?string $originalName = null): ?Down } catch (\ErrorException $e) { return null; } + return null; } } diff --git a/lib/Documents/src/DownscaleImageManager.php b/lib/Documents/src/DownscaleImageManager.php index f141b3a6..af555add 100644 --- a/lib/Documents/src/DownscaleImageManager.php +++ b/lib/Documents/src/DownscaleImageManager.php @@ -22,14 +22,13 @@ public function __construct( private readonly ImageManager $imageManager, private readonly ?LoggerInterface $logger = null, private readonly int $maxPixelSize = 0, - private readonly string $rawImageSuffix = ".raw" + private readonly string $rawImageSuffix = '.raw', ) { } /** * Downscale document if needed, overriding raw document. * - * @param DocumentInterface|null $document * @throws FilesystemException */ public function processAndOverrideDocument(?DocumentInterface $document = null): void @@ -50,7 +49,7 @@ public function processAndOverrideDocument(?DocumentInterface $document = null): $this->logger->info( 'Document has been downscaled.', [ - 'path' => $mountPath + 'path' => $mountPath, ] ); } @@ -61,7 +60,6 @@ public function processAndOverrideDocument(?DocumentInterface $document = null): /** * Downscale document if needed, keeping existing raw document. * - * @param DocumentInterface|null $document * @throws FilesystemException */ public function processDocumentFromExistingRaw(?DocumentInterface $document = null): void @@ -93,14 +91,11 @@ public function processDocumentFromExistingRaw(?DocumentInterface $document = nu /** * Get downscaled image if size is higher than limit, * returns original image if lower or if image is a GIF. - * - * @param Image $processImage - * @return Image|null */ protected function getDownscaledImage(Image $processImage): ?Image { if ( - $processImage->mime() !== 'image/gif' + 'image/gif' !== $processImage->mime() && ($processImage->width() > $this->maxPixelSize || $processImage->height() > $this->maxPixelSize) ) { // prevent possible upsizing @@ -112,25 +107,23 @@ function (Constraint $constraint) { $constraint->upsize(); } ); + return $processImage; } + return null; } - /** - * @param DocumentInterface $document - * @return void - */ protected function updateDocumentFileHash(DocumentInterface $document): void { /* * We need to re-hash file after being downscaled */ if ( - $document instanceof FileHashInterface && - null !== $document->getFileHashAlgorithm() + $document instanceof FileHashInterface + && null !== $document->getFileHashAlgorithm() ) { - /** @var DocumentInterface & FileHashInterface $document */ + /** @var DocumentInterface&FileHashInterface $document */ $mountPath = $document->getMountPath(); if (null === $mountPath) { return; @@ -143,20 +136,16 @@ protected function updateDocumentFileHash(DocumentInterface $document): void } /** - * @param DocumentInterface $originalDocument - * @param Image|null $processImage - * @param bool $keepExistingRaw - * @return DocumentInterface|null * @throws FilesystemException */ protected function createDocumentFromImage( DocumentInterface $originalDocument, - Image $processImage = null, - bool $keepExistingRaw = false + ?Image $processImage = null, + bool $keepExistingRaw = false, ): ?DocumentInterface { if ( - false === $keepExistingRaw && - null !== $formerRawDoc = $originalDocument->getRawDocument() + false === $keepExistingRaw + && null !== $formerRawDoc = $originalDocument->getRawDocument() ) { /* * When document already exists with a raw doc reference. @@ -173,7 +162,7 @@ protected function createDocumentFromImage( $this->em->flush(); } - if (null === $originalDocument->getRawDocument() || $keepExistingRaw === false) { + if (null === $originalDocument->getRawDocument() || false === $keepExistingRaw) { if (null === $processImage) { return $originalDocument; } @@ -186,7 +175,7 @@ protected function createDocumentFromImage( $rawDocument = clone $originalDocument; $rawDocumentName = preg_replace( '#\.(jpe?g|gif|tiff?|png|psd|webp|avif|heic|heif)$#', - $this->rawImageSuffix . '.$1', + $this->rawImageSuffix.'.$1', $originalDocument->getFilename() ); if (null === $rawDocumentName) { @@ -197,10 +186,10 @@ protected function createDocumentFromImage( $rawDocumentPath = $rawDocument->getMountPath(); if ( - null !== $originalDocumentPath && - null !== $rawDocumentPath && - $this->documentsStorage->fileExists($originalDocumentPath) && - !$this->documentsStorage->fileExists($rawDocumentPath) + null !== $originalDocumentPath + && null !== $rawDocumentPath + && $this->documentsStorage->fileExists($originalDocumentPath) + && !$this->documentsStorage->fileExists($rawDocumentPath) ) { /* * Original document path becomes raw document path. Rename it. @@ -226,6 +215,7 @@ protected function createDocumentFromImage( return $originalDocument; } + return null; } elseif (null !== $processImage) { /* diff --git a/lib/Documents/src/Events/DocumentCreatedEvent.php b/lib/Documents/src/Events/DocumentCreatedEvent.php index 0a15eace..aaa68903 100644 --- a/lib/Documents/src/Events/DocumentCreatedEvent.php +++ b/lib/Documents/src/Events/DocumentCreatedEvent.php @@ -5,7 +5,7 @@ namespace RZ\Roadiz\Documents\Events; /** - * Event dispatched on document creation AFTER DB flushed + * Event dispatched on document creation AFTER DB flushed. */ final class DocumentCreatedEvent extends FilterDocumentEvent { diff --git a/lib/Documents/src/Events/DocumentDeletedEvent.php b/lib/Documents/src/Events/DocumentDeletedEvent.php index c5825bdf..1337647e 100644 --- a/lib/Documents/src/Events/DocumentDeletedEvent.php +++ b/lib/Documents/src/Events/DocumentDeletedEvent.php @@ -5,7 +5,7 @@ namespace RZ\Roadiz\Documents\Events; /** - * Event dispatched on document deletion BEFORE DB flushed + * Event dispatched on document deletion BEFORE DB flushed. */ final class DocumentDeletedEvent extends FilterDocumentEvent { diff --git a/lib/Documents/src/Events/DocumentFileUpdatedEvent.php b/lib/Documents/src/Events/DocumentFileUpdatedEvent.php index 5879c51c..123d21de 100644 --- a/lib/Documents/src/Events/DocumentFileUpdatedEvent.php +++ b/lib/Documents/src/Events/DocumentFileUpdatedEvent.php @@ -5,7 +5,7 @@ namespace RZ\Roadiz\Documents\Events; /** - * Event dispatched on document file updated AFTER DB flushed + * Event dispatched on document file updated AFTER DB flushed. */ final class DocumentFileUpdatedEvent extends FilterDocumentEvent { diff --git a/lib/Documents/src/Events/DocumentLifeCycleSubscriber.php b/lib/Documents/src/Events/DocumentLifeCycleSubscriber.php index 8865ff52..45a24fa7 100644 --- a/lib/Documents/src/Events/DocumentLifeCycleSubscriber.php +++ b/lib/Documents/src/Events/DocumentLifeCycleSubscriber.php @@ -40,14 +40,14 @@ public function preUpdate(PreUpdateEventArgs $args): void $args->hasChangedField('filename') && is_string($args->getOldValue('filename')) && is_string($args->getNewValue('filename')) - && $args->getOldValue('filename') !== '' + && '' !== $args->getOldValue('filename') ) { // This method must not throw any exception // because filename WILL change if document file is updated too. $this->renameDocumentFilename($document, $args); } if ($args->hasChangedField('private')) { - if ($document->isPrivate() === true) { + if (true === $document->isPrivate()) { $this->makePrivate($document); } else { $this->makePublic($document); @@ -113,7 +113,6 @@ private function makePrivate(DocumentInterface $document): void /** * Unlink file after document has been deleted. * - * @param PostRemoveEventArgs $args * @throws FilesystemException */ public function postRemove(PostRemoveEventArgs $args): void @@ -141,8 +140,6 @@ public function postRemove(PostRemoveEventArgs $args): void /** * Remove document directory if there is no other file in it. * - * @param string $documentFolderPath - * @return void * @throws FilesystemException */ private function cleanFileDirectory(string $documentFolderPath): void @@ -155,37 +152,22 @@ private function cleanFileDirectory(string $documentFolderPath): void } } - /** - * @param DocumentInterface $document - * @param string $filename - * - * @return string - */ private function getDocumentRelativePathForFilename(DocumentInterface $document, string $filename): string { $this->validateDocument($document); - return $document->getFolder() . DIRECTORY_SEPARATOR . $filename; + return $document->getFolder().DIRECTORY_SEPARATOR.$filename; } - /** - * @param DocumentInterface $document - * @param string $filename - * - * @return string - */ private function getDocumentMountPathForFilename(DocumentInterface $document, string $filename): string { if ($document->isPrivate()) { - return 'private://' . $this->getDocumentRelativePathForFilename($document, $filename); + return 'private://'.$this->getDocumentRelativePathForFilename($document, $filename); } - return 'public://' . $this->getDocumentRelativePathForFilename($document, $filename); + + return 'public://'.$this->getDocumentRelativePathForFilename($document, $filename); } - /** - * @param DocumentInterface $document - * @return string - */ private function getDocumentPath(DocumentInterface $document): string { $this->validateDocument($document); @@ -193,59 +175,40 @@ private function getDocumentPath(DocumentInterface $document): string if ($document->isPrivate()) { return $this->getDocumentPrivatePath($document); } + return $this->getDocumentPublicPath($document); } - /** - * @param DocumentInterface $document - * @return string - */ private function getDocumentPublicPath(DocumentInterface $document): string { - return 'public://' . $document->getRelativePath(); + return 'public://'.$document->getRelativePath(); } - /** - * @param DocumentInterface $document - * @return string - */ private function getDocumentPrivatePath(DocumentInterface $document): string { - return 'private://' . $document->getRelativePath(); + return 'private://'.$document->getRelativePath(); } - /** - * @param DocumentInterface $document - * @return string - */ private function getDocumentFolderPath(DocumentInterface $document): string { if ($document->isPrivate()) { return $this->getDocumentPrivateFolderPath($document); } + return $this->getDocumentPublicFolderPath($document); } - /** - * @param DocumentInterface $document - * @return string - */ private function getDocumentPublicFolderPath(DocumentInterface $document): string { - return 'public://' . $document->getFolder(); + return 'public://'.$document->getFolder(); } - /** - * @param DocumentInterface $document - * @return string - */ private function getDocumentPrivateFolderPath(DocumentInterface $document): string { - return 'private://' . $document->getFolder(); + return 'private://'.$document->getFolder(); } /** - * @param DocumentInterface $document * @throws DocumentWithoutFileException */ private function validateDocument(DocumentInterface $document): void diff --git a/lib/Documents/src/Events/DocumentUpdatedEvent.php b/lib/Documents/src/Events/DocumentUpdatedEvent.php index 8289f347..085512a0 100644 --- a/lib/Documents/src/Events/DocumentUpdatedEvent.php +++ b/lib/Documents/src/Events/DocumentUpdatedEvent.php @@ -5,7 +5,7 @@ namespace RZ\Roadiz\Documents\Events; /** - * Event dispatched on document updated AFTER DB flushed + * Event dispatched on document updated AFTER DB flushed. */ final class DocumentUpdatedEvent extends FilterDocumentEvent { diff --git a/lib/Documents/src/Exceptions/EmbedDocumentAlreadyExistsException.php b/lib/Documents/src/Exceptions/EmbedDocumentAlreadyExistsException.php index fef5487b..54c3a934 100644 --- a/lib/Documents/src/Exceptions/EmbedDocumentAlreadyExistsException.php +++ b/lib/Documents/src/Exceptions/EmbedDocumentAlreadyExistsException.php @@ -4,14 +4,12 @@ namespace RZ\Roadiz\Documents\Exceptions; -use Throwable; - class EmbedDocumentAlreadyExistsException extends \InvalidArgumentException { public function __construct( - string $message = "embed.document.already_exists", + string $message = 'embed.document.already_exists', int $code = 0, - ?Throwable $previous = null + ?\Throwable $previous = null, ) { parent::__construct($message, $code, $previous); } diff --git a/lib/Documents/src/Exceptions/InvalidEmbedId.php b/lib/Documents/src/Exceptions/InvalidEmbedId.php index 292aa2a5..ff48dab3 100644 --- a/lib/Documents/src/Exceptions/InvalidEmbedId.php +++ b/lib/Documents/src/Exceptions/InvalidEmbedId.php @@ -18,17 +18,11 @@ public function __construct(?string $embedId = null, ?string $platform = null) $this->platform = $platform; } - /** - * @return string|null - */ public function getEmbedId(): ?string { return $this->embedId; } - /** - * @return string|null - */ public function getPlatform(): ?string { return $this->platform; diff --git a/lib/Documents/src/MediaFinders/AbstractDailymotionEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractDailymotionEmbedFinder.php index 7eeb90c2..27dcc315 100644 --- a/lib/Documents/src/MediaFinders/AbstractDailymotionEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractDailymotionEmbedFinder.php @@ -4,6 +4,7 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; /** @@ -12,7 +13,6 @@ abstract class AbstractDailymotionEmbedFinder extends AbstractEmbedFinder { /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'dailymotion'; @@ -22,8 +22,8 @@ abstract class AbstractDailymotionEmbedFinder extends AbstractEmbedFinder public static function supportEmbedUrl(string $embedUrl): bool { - return str_starts_with($embedUrl, 'https://dailymotion.com') || - str_starts_with($embedUrl, 'https://www.dailymotion.com'); + return str_starts_with($embedUrl, 'https://dailymotion.com') + || str_starts_with($embedUrl, 'https://www.dailymotion.com'); } public static function getPlatform(): string @@ -31,53 +31,38 @@ public static function getPlatform(): string return static::$platform; } - /** - * @inheritDoc - */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match(static::$idPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; } - if (preg_match(static::$realIdPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$realIdPattern, $embedId, $matches)) { return $embedId; } throw new InvalidEmbedId($embedId, static::$platform); } - /** - * {@inheritdoc} - */ public function getMediaTitle(): string { return $this->getFeed()['title'] ?? ''; } - /** - * {@inheritdoc} - */ + public function getMediaDescription(): string { return $this->getFeed()['description'] ?? ''; } - /** - * {@inheritdoc} - */ + public function getMediaCopyright(): string { return $this->getFeed()['author_name'] ?? ''; } - /** - * {@inheritdoc} - */ + public function getThumbnailURL(): string { return $this->getFeed()['thumbnail_url'] ?? ''; } - /** - * @inheritDoc - */ - public function getFeed() + public function getFeed(): array|\SimpleXMLElement|null { $oEmbedIframePattern = '#src\=\"https\:\/\/(?:www\.|geo\.)?dailymotion\.com\/(?:embed\/video\/|player\.html\?video\=)(?[a-zA-Z0-9\_\-]+)#'; $feed = parent::getFeed(); @@ -96,29 +81,23 @@ public function getFeed() return $feed; } - /** - * {@inheritdoc} - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { if (preg_match(static::$realIdPattern, $this->embedId, $matches)) { - $url = 'https://www.dailymotion.com/video/' . $this->embedId; + $url = 'https://www.dailymotion.com/video/'.$this->embedId; } else { $url = $this->embedId; } - $endpoint = "https://www.dailymotion.com/services/oembed"; + $endpoint = 'https://www.dailymotion.com/services/oembed'; $query = [ 'url' => $url, 'format' => 'json', ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } - /** - * @inheritDoc - */ public function getThumbnailName(string $pathinfo): string { if (null === $this->embedUrl) { @@ -126,16 +105,16 @@ public function getThumbnailName(string $pathinfo): string } else { $embed = $this->embedUrl; } - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $matches) === 1) { - $pathinfo = '.' . $matches['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $matches)) { + $pathinfo = '.'.$matches['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$realIdPattern, $embed, $matches) === 1) { - return 'dailymotion_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$realIdPattern, $embed, $matches)) { + return 'dailymotion_'.$matches['id'].$pathinfo; } - if (preg_match(static::$idPattern, $embed, $matches) === 1) { - return 'dailymotion_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $embed, $matches)) { + return 'dailymotion_'.$matches['id'].$pathinfo; } throw new InvalidEmbedId($embed, static::$platform); } @@ -148,10 +127,6 @@ public function getThumbnailName(string $pathinfo): string * * loop * * autoplay * * controls - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { @@ -165,6 +140,6 @@ public function getSource(array &$options = []): string $queryString['muted'] = (int) $options['muted']; $queryString['video'] = $this->embedId; - return 'https://geo.dailymotion.com/player.html?' . http_build_query($queryString); + return 'https://geo.dailymotion.com/player.html?'.http_build_query($queryString); } } diff --git a/lib/Documents/src/MediaFinders/AbstractDeezerEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractDeezerEmbedFinder.php index 27f23bf3..b44ace77 100644 --- a/lib/Documents/src/MediaFinders/AbstractDeezerEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractDeezerEmbedFinder.php @@ -4,12 +4,12 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; abstract class AbstractDeezerEmbedFinder extends AbstractEmbedFinder { /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'deezer'; @@ -33,40 +33,34 @@ public function isEmptyThumbnailAllowed(): bool return true; } - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match(static::$idPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; } - if (preg_match(static::$realIdPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$realIdPattern, $embedId, $matches)) { return $embedId; } throw new InvalidEmbedId($embedId, static::$platform); } - /** - * @inheritDoc - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { if (preg_match(static::$realIdPattern, $this->embedId)) { - $url = 'https://www.deezer.com/fr/' . $this->embedId; + $url = 'https://www.deezer.com/fr/'.$this->embedId; } else { $url = $this->embedId; } - $endpoint = "https://api.deezer.com/oembed"; + $endpoint = 'https://api.deezer.com/oembed'; $query = [ 'url' => $url, 'format' => 'json', ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } - /** - * @inheritDoc - */ - public function getFeed() + public function getFeed(): array|\SimpleXMLElement|null { $feed = parent::getFeed(); /* @@ -74,7 +68,7 @@ public function getFeed() */ $this->embedUrl = $this->embedId; if (preg_match(static::$idPattern, $this->embedId, $matches)) { - $this->embedId = $matches['type'] . '/' . $matches['id']; + $this->embedId = $matches['type'].'/'.$matches['id']; } return $feed; @@ -92,7 +86,7 @@ public function getMediaDescription(): string public function getMediaCopyright(): string { - return ($this->getFeed()['provider_name'] ?? '') . ' (' . ($this->getFeed()['provider_url'] ?? '') . ')'; + return ($this->getFeed()['provider_name'] ?? '').' ('.($this->getFeed()['provider_url'] ?? '').')'; } public function getThumbnailURL(): string @@ -100,39 +94,32 @@ public function getThumbnailURL(): string return $this->getFeed()['thumbnail_url'] ?? ''; } - /** - * @inheritDoc - */ public function getThumbnailName(string $pathinfo): string { - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext) === 1) { - $pathinfo = '.' . $ext['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext)) { + $pathinfo = '.'.$ext['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$idPattern, $this->embedId, $matches) === 1) { - return $matches['type'] . '_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $this->embedId, $matches)) { + return $matches['type'].'_'.$matches['id'].$pathinfo; } - if (preg_match(static::$realIdPattern, $this->embedId, $matches) === 1) { - return $matches['type'] . '_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$realIdPattern, $this->embedId, $matches)) { + return $matches['type'].'_'.$matches['id'].$pathinfo; } throw new InvalidEmbedId($this->embedId, static::$platform); } /** * Get embed media source URL. - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { parent::getSource($options); $queryString = [ - 'id' => $this->embedId + 'id' => $this->embedId, ]; if (key_exists('autoplay', $options)) { @@ -155,15 +142,15 @@ public function getSource(array &$options = []): string $queryString['mute'] = (int) $options['muted']; if (preg_match(static::$realIdPattern, $this->embedId, $matches)) { - $baseUri = 'https://widget.deezer.com/widget/auto/' . $this->embedId; + $baseUri = 'https://widget.deezer.com/widget/auto/'.$this->embedId; } elseif (preg_match(static::$idPattern, $this->embedId, $matches)) { - $baseUri = 'https://widget.deezer.com/widget/auto/' . $matches['type'] . '/' . $matches['id']; + $baseUri = 'https://widget.deezer.com/widget/auto/'.$matches['type'].'/'.$matches['id']; } else { $baseUri = 'https://widget.deezer.com/widget/auto/'; } // https://widget.deezer.com/widget/dark/playlist/9313425622 - return $baseUri . '?' . http_build_query($queryString); + return $baseUri.'?'.http_build_query($queryString); } protected function areDuplicatesAllowed(): bool diff --git a/lib/Documents/src/MediaFinders/AbstractEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractEmbedFinder.php index 84ca2301..1ae4f5e2 100644 --- a/lib/Documents/src/MediaFinders/AbstractEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractEmbedFinder.php @@ -18,7 +18,6 @@ use RZ\Roadiz\Documents\Models\SizeableInterface; use RZ\Roadiz\Documents\Models\TimeableInterface; use RZ\Roadiz\Documents\OptionsResolver\ViewOptionsResolver; -use SimpleXMLElement; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\Response; @@ -27,16 +26,13 @@ */ abstract class AbstractEmbedFinder implements EmbedFinderInterface { - /** - * @var array|SimpleXMLElement|null - */ - protected $feed = null; + protected array|\SimpleXMLElement|null $feed; protected string $embedId; protected ?string $key = null; /** - * @param string $embedId - * @param bool $validate Validate the embed id passed at the constructor [default: true]. + * @param bool $validate validate the embed id passed at the constructor [default: true] + * * @throws InvalidEmbedId When embedId string is malformed */ public function __construct(string $embedId = '', bool $validate = true) @@ -58,35 +54,26 @@ public function isEmptyThumbnailAllowed(): bool return false; } - /** - * @return string - */ public function getEmbedId(): string { return $this->embedId; } - /** - * @param string $embedId - * - * @return AbstractEmbedFinder - */ public function setEmbedId(string $embedId): AbstractEmbedFinder { $this->embedId = $this->validateEmbedId($embedId); + return $this; } /** * Validate extern Id against platform naming policy. * - * @param string $embedId - * @return string * @throws InvalidEmbedId When embedId string is malformed */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match('#(?[^\/^=^?]+)$#', $embedId, $matches) === 1) { + if (1 === preg_match('#(?[^\/^=^?]+)$#', $embedId, $matches)) { return $matches['id']; } throw new InvalidEmbedId($embedId); @@ -94,8 +81,6 @@ protected function validateEmbedId(string $embedId = ""): string /** * Tell if embed media exists after its API feed. - * - * @return bool */ public function exists(): bool { @@ -104,10 +89,8 @@ public function exists(): bool /** * Crawl and parse an API json feed for current embedID. - * - * @return array|SimpleXMLElement|null */ - public function getFeed() + public function getFeed(): array|\SimpleXMLElement|null { if (null === $this->feed) { $rawFeed = $this->getMediaFeed(); @@ -123,43 +106,30 @@ public function getFeed() } } } + return $this->feed; } /** * Get embed media source URL. - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { $resolver = new ViewOptionsResolver(); $options = $resolver->resolve($options); - return ""; + return ''; } /** * Crawl an embed API to get a Json feed. - * - * @param string|bool|null $search - * - * @return string|StreamInterface */ - abstract public function getMediaFeed($search = null); + abstract public function getMediaFeed(?string $search = null): StreamInterface; /** * Crawl an embed API to get a Json feed against a search query. - * - * @param string $searchTerm - * @param ?string $author - * @param int $maxResults - * - * @return string|StreamInterface|null */ - public function getSearchFeed(string $searchTerm, ?string $author = null, int $maxResults = 15) + public function getSearchFeed(string $searchTerm, ?string $author = null, int $maxResults = 15): ?StreamInterface { return null; } @@ -173,9 +143,7 @@ public function getSearchFeed(string $searchTerm, ?string $author = null, int $m * * id * * class * - * @param array $options * @final - * @return string */ public function getIFrame(array &$options = []): string { @@ -188,7 +156,7 @@ public function getIFrame(array &$options = []): string 'accelerometer', 'encrypted-media', 'gyroscope', - 'picture-in-picture' + 'picture-in-picture', ]; if ($options['width'] > 0) { @@ -197,8 +165,8 @@ public function getIFrame(array &$options = []): string /* * Default height is defined to 16:10 */ - if ($options['height'] === 0) { - $attributes['height'] = (int)(($options['width'] * 10) / 16); + if (0 === $options['height']) { + $attributes['height'] = (int) (($options['width'] * 10) / 16); } } @@ -229,14 +197,14 @@ public function getIFrame(array &$options = []): string $htmlAttrs = []; foreach ($attributes as $key => $value) { - if ($value == '' || $value === true) { + if ('' == $value || true === $value) { $htmlAttrs[] = $key; } else { - $htmlAttrs[] = $key . '="' . addslashes((string) $value) . '"'; + $htmlAttrs[] = $key.'="'.addslashes((string) $value).'"'; } } - return ''; + return ''; } /** @@ -244,15 +212,14 @@ public function getIFrame(array &$options = []): string * * Be careful, this method does not flush. * - * @param ObjectManager $objectManager - * @param AbstractDocumentFactory $documentFactory * @return DocumentInterface|array + * * @throws FilesystemException */ public function createDocumentFromFeed( ObjectManager $objectManager, - AbstractDocumentFactory $documentFactory - ) { + AbstractDocumentFactory $documentFactory, + ): DocumentInterface|array { if ($this->documentExists($objectManager, $this->getEmbedId(), $this->getPlatform())) { throw new EmbedDocumentAlreadyExistsException(); } @@ -278,10 +245,10 @@ public function createDocumentFromFeed( } } catch (APINeedsAuthentificationException $exception) { $document = $documentFactory->getDocument(true, $this->areDuplicatesAllowed()); - $document?->setFilename($this->getPlatform() . '_' . $this->embedId . '.jpg'); + $document?->setFilename($this->getPlatform().'_'.$this->embedId.'.jpg'); } catch (RequestException $exception) { $document = $documentFactory->getDocument(true, $this->areDuplicatesAllowed()); - $document?->setFilename($this->getPlatform() . '_' . $this->embedId . '.jpg'); + $document?->setFilename($this->getPlatform().'_'.$this->embedId.'.jpg'); } if (null === $document) { @@ -303,74 +270,47 @@ public function createDocumentFromFeed( return $document; } - /** - * @param ObjectManager $objectManager - * @param string $embedId - * @param string|null $embedPlatform - * @return bool - */ abstract protected function documentExists( ObjectManager $objectManager, string $embedId, - ?string $embedPlatform + ?string $embedPlatform, ): bool; /** * Store additional information into Document. - * - * @param ObjectManager $objectManager - * @param DocumentInterface $document - * @return DocumentInterface */ abstract protected function injectMetaInDocument(ObjectManager $objectManager, DocumentInterface $document): DocumentInterface; /** * Get media title from feed. - * - * @return string|null */ abstract public function getMediaTitle(): ?string; /** * Get media description from feed. - * - * @return string|null */ abstract public function getMediaDescription(): ?string; /** * Get media copyright from feed. - * - * @return string|null */ abstract public function getMediaCopyright(): ?string; /** * Get media thumbnail external URL from its feed. - * - * @return string|null */ abstract public function getThumbnailURL(): ?string; - /** - * @return int|null - */ public function getMediaWidth(): ?int { return null; } - /** - * @return int|null - */ public function getMediaHeight(): ?int { return null; } - /** - * @return int|null - */ public function getMediaDuration(): ?int { return null; @@ -379,9 +319,6 @@ public function getMediaDuration(): ?int /** * Send a CURL request and get its string output. * - * @param string $url - * - * @return StreamInterface * @throws \RuntimeException */ public function downloadFeedFromAPI(string $url): StreamInterface @@ -396,21 +333,14 @@ public function downloadFeedFromAPI(string $url): StreamInterface throw new \RuntimeException($response->getReasonPhrase()); } - /** - * @param string $pathinfo - * - * @return string - */ public function getThumbnailName(string $pathinfo): string { - return $this->getEmbedId() . '_' . $pathinfo; + return $this->getEmbedId().'_'.$pathinfo; } /** * Download a picture from the embed media platform * to get a thumbnail. - * - * @return File|null */ public function downloadThumbnail(): ?File { @@ -418,6 +348,7 @@ public function downloadThumbnail(): ?File if (null !== $url && '' !== $url) { $thumbnailName = $this->getThumbnailName(basename($url)); + return DownloadedFile::fromUrl($url, $thumbnailName); } @@ -430,8 +361,6 @@ public function downloadThumbnail(): ?File * Key is the access_token which could be asked to consume an API. * For example, for Youtube it must be your API server key. For SoundCloud * it should be you app client Id. - * - * @return string|null */ public function getKey(): ?string { @@ -447,11 +376,12 @@ public function getKey(): ?string * * @param string|null $key the key * - * @return self + * @return $this */ - public function setKey(?string $key) + public function setKey(?string $key): self { $this->key = $key; + return $this; } diff --git a/lib/Documents/src/MediaFinders/AbstractMixcloudEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractMixcloudEmbedFinder.php index 3d3f1cab..8be8e686 100644 --- a/lib/Documents/src/MediaFinders/AbstractMixcloudEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractMixcloudEmbedFinder.php @@ -4,12 +4,12 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; abstract class AbstractMixcloudEmbedFinder extends AbstractEmbedFinder { /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'mixcloud'; @@ -25,75 +25,54 @@ public static function getPlatform(): string return static::$platform; } - /** - * @inheritDoc - */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match(static::$idPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; } throw new InvalidEmbedId($embedId, static::$platform); } - /** - * @inheritDoc - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { - $endpoint = "https://www.mixcloud.com/oembed/"; + $endpoint = 'https://www.mixcloud.com/oembed/'; $query = [ 'url' => $this->embedId, 'format' => 'json', ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } - /** - * @inheritDoc - */ public function getMediaTitle(): string { return $this->getFeed()['title'] ?? ''; } - /** - * @inheritDoc - */ public function getMediaDescription(): string { return $this->getFeed()['description'] ?? ''; } - /** - * @inheritDoc - */ public function getMediaCopyright(): string { - return ($this->getFeed()['author_name'] ?? '') . ' (' . ($this->getFeed()['author_url'] ?? '') . ')'; + return ($this->getFeed()['author_name'] ?? '').' ('.($this->getFeed()['author_url'] ?? '').')'; } - /** - * @inheritDoc - */ public function getThumbnailURL(): string { return $this->getFeed()['image'] ?? ''; } - /** - * @inheritDoc - */ public function getThumbnailName(string $pathinfo): string { - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext) === 1) { - $pathinfo = '.' . $ext['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext)) { + $pathinfo = '.'.$ext['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$idPattern, $this->embedId, $matches) === 1) { - return $matches['author'] . '_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $this->embedId, $matches)) { + return $matches['author'].'_'.$matches['id'].$pathinfo; } throw new InvalidEmbedId($this->embedId, static::$platform); } @@ -107,10 +86,6 @@ public function getThumbnailName(string $pathinfo): string * * end * * mini * * hide_cover - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { @@ -130,20 +105,20 @@ public function getSource(array &$options = []): string if ($options['end']) { $queryString['end'] = (int) $options['end']; } - if ($options['mini'] === true) { + if (true === $options['mini']) { $queryString['mini'] = 1; } - if ($options['hide_cover'] === true) { + if (true === $options['hide_cover']) { $queryString['hide_cover'] = 1; } - if ($options['hide_artwork'] === true) { + if (true === $options['hide_artwork']) { $queryString['hide_artwork'] = 1; } - if ($options['light'] === true) { + if (true === $options['light']) { $queryString['light'] = 1; } - return 'https://www.mixcloud.com/widget/iframe/?' . http_build_query($queryString); + return 'https://www.mixcloud.com/widget/iframe/?'.http_build_query($queryString); } protected function areDuplicatesAllowed(): bool diff --git a/lib/Documents/src/MediaFinders/AbstractPodcastFinder.php b/lib/Documents/src/MediaFinders/AbstractPodcastFinder.php index fa238d0b..63e60815 100644 --- a/lib/Documents/src/MediaFinders/AbstractPodcastFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractPodcastFinder.php @@ -12,7 +12,6 @@ use RZ\Roadiz\Documents\DownloadedFile; use RZ\Roadiz\Documents\Models\DocumentInterface; use RZ\Roadiz\Documents\Models\TimeableInterface; -use SimpleXMLElement; use Symfony\Component\HttpFoundation\Response; abstract class AbstractPodcastFinder extends AbstractEmbedFinder @@ -27,18 +26,12 @@ public static function getPlatform(): string return 'podcast'; } - /** - * @inheritDoc - */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { return $embedId; } - /** - * @return array|SimpleXMLElement|null - */ - public function getFeed() + public function getFeed(): array|\SimpleXMLElement|null { if (null === $this->feed) { $rawFeed = $this->getMediaFeed(); @@ -47,22 +40,19 @@ public function getFeed() } if (null !== $rawFeed) { try { - $this->feed = new SimpleXMLElement($rawFeed); + $this->feed = new \SimpleXMLElement($rawFeed); + return $this->feed; } catch (\Exception $errorException) { throw new \RuntimeException('Feed content is not a valid Podcast XML'); } } } + return $this->feed; } - /** - * @param SimpleXMLElement $item - * - * @return string - */ - protected function getAudioName(SimpleXMLElement $item): string + protected function getAudioName(\SimpleXMLElement $item): string { if (null !== $item->enclosure->attributes()) { $url = (string) $item->enclosure->attributes()->url; @@ -72,8 +62,10 @@ protected function getAudioName(SimpleXMLElement $item): string if (!empty((string) $item->title)) { $extension = pathinfo($url, PATHINFO_EXTENSION); - return ((string) $item->title) . '.' . $extension; + + return ((string) $item->title).'.'.$extension; } + return pathinfo($url, PATHINFO_BASENAME); } @@ -82,18 +74,17 @@ protected function getAudioName(SimpleXMLElement $item): string * * Be careful, this method does not flush. * - * @param ObjectManager $objectManager - * @param AbstractDocumentFactory $documentFactory * @return array + * * @throws FilesystemException */ public function createDocumentFromFeed( ObjectManager $objectManager, - AbstractDocumentFactory $documentFactory - ) { + AbstractDocumentFactory $documentFactory, + ): array { $documents = []; $feed = $this->getFeed(); - if ($feed instanceof SimpleXMLElement) { + if ($feed instanceof \SimpleXMLElement) { foreach ($feed->channel->item as $item) { if ( !empty($item->enclosure->attributes()->url) @@ -145,12 +136,12 @@ public function createDocumentFromFeed( abstract protected function injectMetaFromPodcastItem( ObjectManager $objectManager, DocumentInterface $document, - \SimpleXMLElement $item + \SimpleXMLElement $item, ): void; protected function getPodcastItemTitle(\SimpleXMLElement $item): ?string { - return (string) $item->title . ' – ' . $this->getMediaTitle(); + return (string) $item->title.' – '.$this->getMediaTitle(); } protected function getPodcastItemDescription(\SimpleXMLElement $item): ?string @@ -169,13 +160,11 @@ protected function getPodcastItemCopyright(\SimpleXMLElement $item): ?string if (empty($copyright)) { return $this->getMediaCopyright(); } - return $copyright . ' – ' . $this->getMediaCopyright(); + + return $copyright.' – '.$this->getMediaCopyright(); } - /** - * @inheritDoc - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { $url = $this->embedId; $client = new Client(); @@ -188,55 +177,47 @@ public function getMediaFeed($search = null) throw new \RuntimeException($response->getReasonPhrase()); } - /** - * @inheritDoc - */ public function getMediaTitle(): ?string { $feed = $this->getFeed(); - if ($feed instanceof SimpleXMLElement && $feed->channel instanceof SimpleXMLElement) { + if ($feed instanceof \SimpleXMLElement && $feed->channel instanceof \SimpleXMLElement) { return (string) ($feed->channel->title ?? null); } + return null; } - /** - * @inheritDoc - */ public function getMediaDescription(): ?string { $feed = $this->getFeed(); - if ($feed instanceof SimpleXMLElement && $feed->channel instanceof SimpleXMLElement) { + if ($feed instanceof \SimpleXMLElement && $feed->channel instanceof \SimpleXMLElement) { return (string) ($feed->channel->description ?? null); } + return null; } - /** - * @inheritDoc - */ public function getMediaCopyright(): ?string { $feed = $this->getFeed(); - if ($feed instanceof SimpleXMLElement && $feed->channel instanceof SimpleXMLElement) { + if ($feed instanceof \SimpleXMLElement && $feed->channel instanceof \SimpleXMLElement) { return (string) ($feed->channel->copyright ?? null); } + return null; } - /** - * @inheritDoc - */ public function getThumbnailURL(): ?string { $feed = $this->getFeed(); if ( - $feed instanceof SimpleXMLElement - && $feed->channel instanceof SimpleXMLElement - && $feed->channel->image instanceof SimpleXMLElement + $feed instanceof \SimpleXMLElement + && $feed->channel instanceof \SimpleXMLElement + && $feed->channel->image instanceof \SimpleXMLElement ) { return (string) ($feed->channel->image->url ?? null); } + return null; } diff --git a/lib/Documents/src/MediaFinders/AbstractSoundcloudEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractSoundcloudEmbedFinder.php index 3d15b3dd..d1788559 100644 --- a/lib/Documents/src/MediaFinders/AbstractSoundcloudEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractSoundcloudEmbedFinder.php @@ -4,6 +4,7 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; /** @@ -12,7 +13,6 @@ abstract class AbstractSoundcloudEmbedFinder extends AbstractEmbedFinder { /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'soundcloud'; @@ -22,9 +22,9 @@ abstract class AbstractSoundcloudEmbedFinder extends AbstractEmbedFinder public static function supportEmbedUrl(string $embedUrl): bool { - return str_starts_with($embedUrl, 'https://api.soundcloud.com') || - str_starts_with($embedUrl, 'https://www.soundcloud.com') || - str_starts_with($embedUrl, 'https://soundcloud.com'); + return str_starts_with($embedUrl, 'https://api.soundcloud.com') + || str_starts_with($embedUrl, 'https://www.soundcloud.com') + || str_starts_with($embedUrl, 'https://soundcloud.com'); } public static function getPlatform(): string @@ -32,38 +32,29 @@ public static function getPlatform(): string return static::$platform; } - /** - * @inheritDoc - */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match(static::$idPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; } - if (preg_match(static::$realIdPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$realIdPattern, $embedId, $matches)) { return $embedId; } throw new InvalidEmbedId($embedId, static::$platform); } - /** - * @inheritDoc - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { - $endpoint = "https://soundcloud.com/oembed"; + $endpoint = 'https://soundcloud.com/oembed'; $query = [ 'url' => $this->embedId, 'format' => 'json', ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } - /** - * @inheritDoc - */ - public function getFeed() + public function getFeed(): array|\SimpleXMLElement|null { $feed = parent::getFeed(); /* @@ -89,7 +80,7 @@ public function getMediaDescription(): string public function getMediaCopyright(): string { - return ($this->getFeed()['author_name'] ?? '') . ' (' . ($this->getFeed()['author_url'] ?? '') . ')'; + return ($this->getFeed()['author_name'] ?? '').' ('.($this->getFeed()['author_url'] ?? '').')'; } public function getThumbnailURL(): string @@ -97,9 +88,6 @@ public function getThumbnailURL(): string return $this->getFeed()['thumbnail_url'] ?? ''; } - /** - * @inheritDoc - */ public function getThumbnailName(string $pathinfo): string { if (null === $this->embedUrl) { @@ -107,13 +95,13 @@ public function getThumbnailName(string $pathinfo): string } else { $embed = $this->embedUrl; } - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext) === 1) { - $pathinfo = '.' . $ext['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext)) { + $pathinfo = '.'.$ext['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$idPattern, $embed, $matches) === 1) { - return 'soundcloud_' . $matches['user'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $embed, $matches)) { + return 'soundcloud_'.$matches['user'].$pathinfo; } throw new InvalidEmbedId($embed, static::$platform); } @@ -128,10 +116,6 @@ public function getThumbnailName(string $pathinfo): string * * show_user * * show_reposts * * visual - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { @@ -152,7 +136,7 @@ public function getSource(array &$options = []): string } $queryString['controls'] = (int) $options['controls']; - return 'https://w.soundcloud.com/player/?' . http_build_query($queryString); + return 'https://w.soundcloud.com/player/?'.http_build_query($queryString); } protected function areDuplicatesAllowed(): bool diff --git a/lib/Documents/src/MediaFinders/AbstractSpotifyEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractSpotifyEmbedFinder.php index 1fed0b8d..1a059767 100644 --- a/lib/Documents/src/MediaFinders/AbstractSpotifyEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractSpotifyEmbedFinder.php @@ -4,12 +4,12 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; abstract class AbstractSpotifyEmbedFinder extends AbstractEmbedFinder { /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'spotify'; @@ -29,43 +29,34 @@ public static function getPlatform(): string return static::$platform; } - /** - * @inheritDoc - */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match(static::$idPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; } - if (preg_match(static::$realIdPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$realIdPattern, $embedId, $matches)) { return $embedId; } throw new InvalidEmbedId($embedId, static::$platform); } - /** - * @inheritDoc - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { if (preg_match(static::$realIdPattern, $this->embedId, $matches)) { - $url = 'https://open.spotify.com/' . $this->embedId; + $url = 'https://open.spotify.com/'.$this->embedId; } else { $url = $this->embedId; } - $endpoint = "https://embed.spotify.com/oembed"; + $endpoint = 'https://embed.spotify.com/oembed'; $query = [ 'url' => $url, 'format' => 'json', ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } - /** - * @inheritDoc - */ - public function getFeed() + public function getFeed(): array|\SimpleXMLElement|null { $feed = parent::getFeed(); /* @@ -73,82 +64,66 @@ public function getFeed() */ $this->embedUrl = $this->embedId; if (preg_match(static::$idPattern, $this->embedId, $matches)) { - $this->embedId = $matches['type'] . '/' . $matches['id']; + $this->embedId = $matches['type'].'/'.$matches['id']; } return $feed; } - /** - * @inheritDoc - */ public function getMediaTitle(): string { $feed = $this->getFeed(); + return is_array($feed) && isset($feed['title']) ? $feed['title'] : ''; } - /** - * @inheritDoc - */ public function getMediaDescription(): string { $feed = $this->getFeed(); + return is_array($feed) && isset($feed['description']) ? $feed['description'] : ''; } - /** - * @inheritDoc - */ public function getMediaCopyright(): string { $feed = $this->getFeed(); - return is_array($feed) ? $feed['provider_name'] . ' (' . $feed['provider_url'] . ')' : ''; + + return is_array($feed) ? $feed['provider_name'].' ('.$feed['provider_url'].')' : ''; } - /** - * @inheritDoc - */ public function getThumbnailURL(): string { return $this->getFeed()['thumbnail_url'] ?? ''; } - /** - * @inheritDoc - */ public function getThumbnailName(string $pathinfo): string { - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext) === 1) { - $pathinfo = '.' . $ext['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext)) { + $pathinfo = '.'.$ext['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$idPattern, $this->embedId, $matches) === 1) { - return $matches['type'] . '_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $this->embedId, $matches)) { + return $matches['type'].'_'.$matches['id'].$pathinfo; } - if (preg_match(static::$realIdPattern, $this->embedId, $matches) === 1) { - return $matches['type'] . '_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$realIdPattern, $this->embedId, $matches)) { + return $matches['type'].'_'.$matches['id'].$pathinfo; } throw new InvalidEmbedId($this->embedId, static::$platform); } /** * Get embed media source URL. - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { parent::getSource($options); if (preg_match(static::$realIdPattern, $this->embedId, $matches)) { - return 'https://open.spotify.com/embed/' . $this->embedId; + return 'https://open.spotify.com/embed/'.$this->embedId; } if (preg_match(static::$idPattern, $this->embedId, $matches)) { - return 'https://open.spotify.com/embed/' . $matches['type'] . '/' . $matches['id']; + return 'https://open.spotify.com/embed/'.$matches['type'].'/'.$matches['id']; } return $this->embedId; diff --git a/lib/Documents/src/MediaFinders/AbstractTedEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractTedEmbedFinder.php index 1c71110b..e679c439 100644 --- a/lib/Documents/src/MediaFinders/AbstractTedEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractTedEmbedFinder.php @@ -4,12 +4,12 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; abstract class AbstractTedEmbedFinder extends AbstractEmbedFinder { /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'ted'; @@ -25,7 +25,7 @@ public static function getPlatform(): string return static::$platform; } - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { if (preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; @@ -33,14 +33,14 @@ protected function validateEmbedId(string $embedId = ""): string throw new InvalidEmbedId($embedId, static::$platform); } - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { - $endpoint = "https://www.ted.com/services/v1/oembed.json"; + $endpoint = 'https://www.ted.com/services/v1/oembed.json'; $query = [ 'url' => $this->embedId, ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } public function getMediaTitle(): string @@ -55,7 +55,7 @@ public function getMediaDescription(): string public function getMediaCopyright(): string { - return ($this->getFeed()['author_name'] ?? '') . ' - ' . ($this->getFeed()['provider_name'] ?? '') . ' (' . ($this->getFeed()['author_url'] ?? '') . ')'; + return ($this->getFeed()['author_name'] ?? '').' - '.($this->getFeed()['provider_name'] ?? '').' ('.($this->getFeed()['author_url'] ?? '').')'; } public function getThumbnailURL(): string @@ -65,30 +65,26 @@ public function getThumbnailURL(): string public function getThumbnailName(string $pathinfo): string { - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext) === 1) { - $pathinfo = '.' . $ext['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext)) { + $pathinfo = '.'.$ext['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$idPattern, $this->embedId, $matches) === 1) { - return 'ted_talk_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $this->embedId, $matches)) { + return 'ted_talk_'.$matches['id'].$pathinfo; } throw new InvalidEmbedId($this->embedId, static::$platform); } /** * Get embed media source URL. - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { parent::getSource($options); if (preg_match(static::$idPattern, $this->embedId, $matches)) { - return 'https://embed.ted.com/talks/' . $matches['id']; + return 'https://embed.ted.com/talks/'.$matches['id']; } return $this->embedId; diff --git a/lib/Documents/src/MediaFinders/AbstractTwitchEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractTwitchEmbedFinder.php index 2088076e..cff532cd 100644 --- a/lib/Documents/src/MediaFinders/AbstractTwitchEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractTwitchEmbedFinder.php @@ -4,12 +4,12 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; abstract class AbstractTwitchEmbedFinder extends AbstractEmbedFinder { /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'twitch'; @@ -17,8 +17,8 @@ abstract class AbstractTwitchEmbedFinder extends AbstractEmbedFinder public static function supportEmbedUrl(string $embedUrl): bool { - return str_starts_with($embedUrl, 'https://twitch.tv') || - str_starts_with($embedUrl, 'https://www.twitch.tv'); + return str_starts_with($embedUrl, 'https://twitch.tv') + || str_starts_with($embedUrl, 'https://www.twitch.tv'); } public static function getPlatform(): string @@ -26,28 +26,22 @@ public static function getPlatform(): string return static::$platform; } - /** - * @inheritDoc - */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match(static::$idPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; } throw new InvalidEmbedId($embedId, static::$platform); } - /** - * @inheritDoc - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { - $endpoint = "https://api.twitch.tv/v4/oembed"; + $endpoint = 'https://api.twitch.tv/v4/oembed'; $query = [ 'url' => $this->embedId, ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } public function getMediaTitle(): string @@ -62,7 +56,7 @@ public function getMediaDescription(): string public function getMediaCopyright(): string { - return ($this->getFeed()['author_name'] ?? '') . ' - ' . ($this->getFeed()['provider_name'] ?? '') . ' (' . ($this->getFeed()['author_url'] ?? '') . ')'; + return ($this->getFeed()['author_name'] ?? '').' - '.($this->getFeed()['provider_name'] ?? '').' ('.($this->getFeed()['author_url'] ?? '').')'; } public function getThumbnailURL(): string @@ -72,23 +66,19 @@ public function getThumbnailURL(): string public function getThumbnailName(string $pathinfo): string { - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext) === 1) { - $pathinfo = '.' . $ext['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $ext)) { + $pathinfo = '.'.$ext['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$idPattern, $this->embedId, $matches) === 1) { - return 'twitch_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $this->embedId, $matches)) { + return 'twitch_'.$matches['id'].$pathinfo; } throw new InvalidEmbedId($this->embedId, static::$platform); } /** * Get embed media source URL. - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { @@ -105,7 +95,7 @@ public function getSource(array &$options = []): string $queryString['playsinline'] = (int) $options['autoplay']; } - return 'https://player.twitch.tv/?' . http_build_query($queryString); + return 'https://player.twitch.tv/?'.http_build_query($queryString); } return $this->embedId; diff --git a/lib/Documents/src/MediaFinders/AbstractUnsplashPictureFinder.php b/lib/Documents/src/MediaFinders/AbstractUnsplashPictureFinder.php index 80d27746..4f2d06f8 100644 --- a/lib/Documents/src/MediaFinders/AbstractUnsplashPictureFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractUnsplashPictureFinder.php @@ -6,13 +6,12 @@ use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; -use GuzzleHttp\Exception\GuzzleException; +use Psr\Http\Message\StreamInterface; abstract class AbstractUnsplashPictureFinder extends AbstractEmbedFinder implements RandomImageFinder { protected Client $client; /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'unsplash'; @@ -32,37 +31,30 @@ public static function getPlatform(): string return static::$platform; } - /** - * @param string $clientId - * @param string $embedId - */ public function __construct(string $clientId, string $embedId = '') { parent::__construct($embedId); $this->client = new Client( [ - // Base URI is used with relative requests - 'base_uri' => 'https://api.unsplash.com', - // You can set any number of default request options. - 'timeout' => 3.0, - 'headers' => [ - 'Authorization' => 'Client-ID ' . $clientId - ] + // Base URI is used with relative requests + 'base_uri' => 'https://api.unsplash.com', + // You can set any number of default request options. + 'timeout' => 3.0, + 'headers' => [ + 'Authorization' => 'Client-ID '.$clientId, + ], ] ); } - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { return $embedId; } /** - * @see https://unsplash.com/documentation#get-a-random-photo - * @param array $options - * @return array|null - * @throws GuzzleException + * @see https://unsplash.com/documentation#get-a-random-photo */ public function getRandom(array $options = []): ?array { @@ -70,13 +62,13 @@ public function getRandom(array $options = []): ?array $response = $this->client->get( '/photos/random', [ - 'query' => array_merge( - [ - 'content_filter' => 'high', - 'orientation' => 'landscape' - ], - $options - ) + 'query' => array_merge( + [ + 'content_filter' => 'high', + 'orientation' => 'landscape', + ], + $options + ), ] ); $feed = json_decode($response->getBody()->getContents(), true) ?? null; @@ -89,85 +81,59 @@ public function getRandom(array $options = []): ?array if (null !== $url) { $this->embedId = (string) $feed['id']; $this->feed = $feed; + return $this->feed; } + return null; } catch (ClientException $e) { return null; } } - /** - * @param string $keyword - * @param array $options - * @return array|null - * @throws GuzzleException - */ - public function getRandomBySearch(string $keyword, array $options = []) + public function getRandomBySearch(string $keyword, array $options = []): ?array { return $this->getRandom( [ - 'query' => $keyword + 'query' => $keyword, ] ); } - - /** - * {@inheritdoc} - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { - return ''; + throw new \LogicException('Unsplash API does not provide a feed.'); } - /** - * {@inheritdoc} - */ public function getMediaTitle(): string { return $this->feed['description'] ?? ''; } - /** - * @return int|null - */ public function getMediaWidth(): ?int { return $this->feed['width'] ?? null; } - /** - * @return int|null - */ public function getMediaHeight(): ?int { return $this->feed['height'] ?? null; } - /** - * {@inheritdoc} - */ public function getMediaDescription(): string { return $this->feed['alt_description'] ?? ''; } - /** - * {@inheritdoc} - */ public function getMediaCopyright(): string { if (isset($this->feed['user'])) { - return trim(($this->feed['user']['name'] ?? '') . ', Unsplash', " \t\n\r\0\x0B-"); + return trim(($this->feed['user']['name'] ?? '').', Unsplash', " \t\n\r\0\x0B-"); } + return 'Unsplash'; } - /** - * @inheritdoc - * @throws GuzzleException - */ public function getThumbnailURL(): ?string { if (null === $this->feed) { @@ -180,19 +146,16 @@ public function getThumbnailURL(): ?string if (is_array($this->feed)) { return $this->getBestUrl($this->feed); } + return null; } - /** - * @param array|null $feed - * - * @return string|null - */ protected function getBestUrl(?array $feed): ?string { if (null === $feed) { return null; } + return $feed['urls']['full'] ?? $feed['urls']['raw'] ?? null; } } diff --git a/lib/Documents/src/MediaFinders/AbstractVimeoEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractVimeoEmbedFinder.php index 5d0db9f1..19a544d0 100644 --- a/lib/Documents/src/MediaFinders/AbstractVimeoEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractVimeoEmbedFinder.php @@ -4,6 +4,7 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; /** @@ -13,7 +14,6 @@ abstract class AbstractVimeoEmbedFinder extends AbstractEmbedFinder { protected static string $realIdPattern = '#(?[0-9]+)$#'; /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'vimeo'; @@ -25,13 +25,13 @@ public static function getPlatform(): string public static function supportEmbedUrl(string $embedUrl): bool { - return str_starts_with($embedUrl, 'https://vimeo.com/') || - str_starts_with($embedUrl, 'https://www.vimeo.com/'); + return str_starts_with($embedUrl, 'https://vimeo.com/') + || str_starts_with($embedUrl, 'https://www.vimeo.com/'); } - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match('#(?[0-9]+)$#', $embedId, $matches) === 1) { + if (1 === preg_match('#(?[0-9]+)$#', $embedId, $matches)) { return $matches['id']; } throw new InvalidEmbedId($embedId, static::$platform); @@ -47,12 +47,11 @@ public function isEmptyThumbnailAllowed(): bool /** * Tell if embed media exists after its API feed. - * - * @return bool */ public function exists(): bool { $feed = $this->getFeed(); + return is_array($feed) && isset($feed['video_id']); } @@ -91,18 +90,15 @@ public function getMediaDuration(): ?int return $this->getFeed()['duration'] ?? null; } - public function getSearchFeed(string $searchTerm, ?string $author = null, int $maxResults = 15) + public function getSearchFeed(string $searchTerm, ?string $author = null, int $maxResults = 15): ?StreamInterface { return null; } - /** - * {@inheritdoc} - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { if (preg_match(static::$realIdPattern, $this->embedId, $matches)) { - $url = 'https://vimeo.com/video/' . $this->embedId; + $url = 'https://vimeo.com/video/'.$this->embedId; } else { $url = $this->embedId; } @@ -112,7 +108,7 @@ public function getMediaFeed($search = null) 'format' => 'json', ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } /** @@ -128,10 +124,6 @@ public function getMediaFeed($search = null) * * muted * * autopause * * automute - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { @@ -169,6 +161,6 @@ public function getSource(array &$options = []): string $queryString['muted'] = (int) $options['muted']; } - return 'https://player.vimeo.com/video/' . $this->embedId . '?' . http_build_query($queryString); + return 'https://player.vimeo.com/video/'.$this->embedId.'?'.http_build_query($queryString); } } diff --git a/lib/Documents/src/MediaFinders/AbstractYoutubeEmbedFinder.php b/lib/Documents/src/MediaFinders/AbstractYoutubeEmbedFinder.php index e67f5bae..833b7fd1 100644 --- a/lib/Documents/src/MediaFinders/AbstractYoutubeEmbedFinder.php +++ b/lib/Documents/src/MediaFinders/AbstractYoutubeEmbedFinder.php @@ -4,6 +4,7 @@ namespace RZ\Roadiz\Documents\MediaFinders; +use Psr\Http\Message\StreamInterface; use RZ\Roadiz\Documents\Exceptions\APINeedsAuthentificationException; use RZ\Roadiz\Documents\Exceptions\InvalidEmbedId; @@ -14,7 +15,6 @@ abstract class AbstractYoutubeEmbedFinder extends AbstractEmbedFinder { protected const YOUTUBE_EMBED_DOMAIN = 'https://www.youtube-nocookie.com'; /** - * @var string * @internal Use getPlatform() instead */ protected static string $platform = 'youtube'; @@ -29,48 +29,39 @@ public static function getPlatform(): string public static function supportEmbedUrl(string $embedUrl): bool { - return str_starts_with($embedUrl, 'https://www.youtube.com/') || - str_starts_with($embedUrl, 'https://youtube.com/') || - str_starts_with($embedUrl, 'https://youtu.be/'); + return str_starts_with($embedUrl, 'https://www.youtube.com/') + || str_starts_with($embedUrl, 'https://youtube.com/') + || str_starts_with($embedUrl, 'https://youtu.be/'); } - /** - * @inheritDoc - */ - protected function validateEmbedId(string $embedId = ""): string + protected function validateEmbedId(string $embedId = ''): string { - if (preg_match(static::$idPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$idPattern, $embedId, $matches)) { return $embedId; } - if (preg_match(static::$realIdPattern, $embedId, $matches) === 1) { + if (1 === preg_match(static::$realIdPattern, $embedId, $matches)) { return $embedId; } throw new InvalidEmbedId($embedId, static::$platform); } - /** - * @inheritDoc - */ - public function getMediaFeed($search = null) + public function getMediaFeed(?string $search = null): StreamInterface { if (preg_match(static::$realIdPattern, $this->embedId, $matches)) { - $url = 'https://www.youtube.com/watch?v=' . $this->embedId; + $url = 'https://www.youtube.com/watch?v='.$this->embedId; } else { $url = $this->embedId; } - $endpoint = "https://www.youtube.com/oembed"; + $endpoint = 'https://www.youtube.com/oembed'; $query = [ 'url' => $url, 'format' => 'json', ]; - return $this->downloadFeedFromAPI($endpoint . '?' . http_build_query($query)); + return $this->downloadFeedFromAPI($endpoint.'?'.http_build_query($query)); } - /** - * @inheritDoc - */ - public function getFeed() + public function getFeed(): array|\SimpleXMLElement|null { $feed = parent::getFeed(); /* @@ -96,12 +87,13 @@ public function getMediaTitle(): string public function getMediaDescription(): string { $feed = $this->getFeed(); + return (is_array($feed) && isset($feed['description'])) ? ($feed['description']) : (''); } public function getMediaCopyright(): string { - return ($this->getFeed()['author_name'] ?? '') . ' (' . ($this->getFeed()['author_url'] ?? '') . ')'; + return ($this->getFeed()['author_name'] ?? '').' ('.($this->getFeed()['author_url'] ?? '').')'; } public function getThumbnailURL(): string @@ -109,17 +101,11 @@ public function getThumbnailURL(): string return $this->getFeed()['thumbnail_url'] ?? ''; } - /** - * @inheritDoc - */ public function getMediaWidth(): ?int { return $this->getFeed()['width'] ?? null; } - /** - * @inheritDoc - */ public function getMediaHeight(): ?int { return $this->getFeed()['height'] ?? null; @@ -132,34 +118,34 @@ public function getThumbnailName(string $pathinfo): string } else { $embed = $this->embedUrl; } - if (preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $matches) === 1) { - $pathinfo = '.' . $matches['extension']; + if (1 === preg_match('#\.(?[jpe?g|png|gif])$#', $pathinfo, $matches)) { + $pathinfo = '.'.$matches['extension']; } else { $pathinfo = '.jpg'; } - if (preg_match(static::$realIdPattern, $embed, $matches) === 1) { - return 'youtube_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$realIdPattern, $embed, $matches)) { + return 'youtube_'.$matches['id'].$pathinfo; } - if (preg_match(static::$idPattern, $embed, $matches) === 1) { - return 'youtube_' . $matches['id'] . $pathinfo; + if (1 === preg_match(static::$idPattern, $embed, $matches)) { + return 'youtube_'.$matches['id'].$pathinfo; } throw new InvalidEmbedId($embed, static::$platform); } /** - * @inheritdoc - * @throws APINeedsAuthentificationException + * @throws APINeedsAuthentificationException */ - public function getSearchFeed(string $searchTerm, ?string $author = null, int $maxResults = 15) + public function getSearchFeed(string $searchTerm, ?string $author = null, int $maxResults = 15): ?StreamInterface { - if (null !== $this->getKey() && $this->getKey() != "") { - $url = "https://www.googleapis.com/youtube/v3/search?q=" . $searchTerm . "&part=snippet&key=" . $this->getKey() . "&maxResults=" . $maxResults; - if (null !== $author && !empty($author)) { - $url .= '&author=' . $author; + if (null !== $this->getKey() && '' != $this->getKey()) { + $url = 'https://www.googleapis.com/youtube/v3/search?q='.$searchTerm.'&part=snippet&key='.$this->getKey().'&maxResults='.$maxResults; + if (!empty($author)) { + $url .= '&author='.$author; } + return $this->downloadFeedFromAPI($url); } else { - throw new APINeedsAuthentificationException("YoutubeEmbedFinder needs a Google server key, create a “google_server_id” setting.", 1); + throw new APINeedsAuthentificationException('YoutubeEmbedFinder needs a Google server key, create a “google_server_id” setting.', 1); } } @@ -174,10 +160,6 @@ public function getSearchFeed(string $searchTerm, ?string $author = null, int $m * * start * * enablejsapi * * muted - * - * @param array $options - * - * @return string */ public function getSource(array &$options = []): string { @@ -218,6 +200,6 @@ public function getSource(array &$options = []): string $queryString['enablejsapi'] = (int) $options['enablejsapi']; $queryString['mute'] = (int) $options['muted']; - return static::YOUTUBE_EMBED_DOMAIN . '/embed/' . $this->embedId . '?' . http_build_query($queryString); + return static::YOUTUBE_EMBED_DOMAIN.'/embed/'.$this->embedId.'?'.http_build_query($queryString); } } diff --git a/lib/Documents/src/MediaFinders/EmbedFinderFactory.php b/lib/Documents/src/MediaFinders/EmbedFinderFactory.php index 3694d188..985fe21b 100644 --- a/lib/Documents/src/MediaFinders/EmbedFinderFactory.php +++ b/lib/Documents/src/MediaFinders/EmbedFinderFactory.php @@ -26,18 +26,14 @@ public function __construct(array $embedPlatforms = []) $this->embedPlatforms = $embedPlatforms; } - /** - * @param string|null $mediaPlatform - * @param string|null $embedId - * - * @return EmbedFinderInterface|null - */ public function createForPlatform(?string $mediaPlatform, ?string $embedId): ?EmbedFinderInterface { if (null !== $embedId && $this->supports($mediaPlatform)) { $class = $this->embedPlatforms[$mediaPlatform]; + return new $class($embedId); } + return null; } @@ -56,14 +52,14 @@ public function createForUrl(?string $embedUrl): ?EmbedFinderInterface } /** - * @var string $platform + * @var string $platform * @var class-string $class */ foreach ($this->embedPlatforms as $platform => $class) { $callback = [$class, 'supportEmbedUrl']; if ( - is_callable($callback) && - call_user_func($callback, $embedUrl) + is_callable($callback) + && call_user_func($callback, $embedUrl) ) { return $this->createForPlatform($platform, $embedUrl); } @@ -72,16 +68,11 @@ public function createForUrl(?string $embedUrl): ?EmbedFinderInterface return null; } - /** - * @param string|null $mediaPlatform - * - * @return bool - */ public function supports(?string $mediaPlatform): bool { return - null !== $mediaPlatform && - in_array( + null !== $mediaPlatform + && in_array( $mediaPlatform, array_keys($this->embedPlatforms) ); diff --git a/lib/Documents/src/MediaFinders/EmbedFinderInterface.php b/lib/Documents/src/MediaFinders/EmbedFinderInterface.php index c0388f4d..1ffcff7b 100644 --- a/lib/Documents/src/MediaFinders/EmbedFinderInterface.php +++ b/lib/Documents/src/MediaFinders/EmbedFinderInterface.php @@ -6,18 +6,8 @@ interface EmbedFinderInterface { - /** - * @param array $options - * - * @return string - */ public function getIFrame(array &$options = []): string; - /** - * @param array $options - * - * @return string - */ public function getSource(array &$options = []): string; public static function supportEmbedUrl(string $embedUrl): bool; diff --git a/lib/Documents/src/MediaFinders/FacebookPictureFinder.php b/lib/Documents/src/MediaFinders/FacebookPictureFinder.php index 3a76670f..90df60eb 100644 --- a/lib/Documents/src/MediaFinders/FacebookPictureFinder.php +++ b/lib/Documents/src/MediaFinders/FacebookPictureFinder.php @@ -6,37 +6,27 @@ use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; -use Psr\Http\Message\ResponseInterface; /** * Util to grab a facebook profile picture from userAlias. */ -class FacebookPictureFinder +final class FacebookPictureFinder { - protected string $facebookUserAlias; - protected ResponseInterface $response; - - /** - * @param string $facebookUserAlias - */ - public function __construct(string $facebookUserAlias) - { - $this->facebookUserAlias = $facebookUserAlias; - } - /** * @return string|null Facebook profile image URL + * * @throws GuzzleException */ - public function getPictureUrl(): ?string + public function getPictureUrl(string $facebookUserAlias): ?string { $client = new Client(); - $this->response = $client->get('https://graph.facebook.com/' . $this->facebookUserAlias . '/picture?redirect=false&width=200&height=200'); - $json = json_decode($this->response->getBody()->getContents(), true); + $response = $client->get('https://graph.facebook.com/'.$facebookUserAlias.'/picture?redirect=false&width=200&height=200'); + $json = json_decode($response->getBody()->getContents(), true); if (is_array($json) && isset($json['data']) && !empty($json['data']['url'])) { return $json['data']['url']; } + return null; } } diff --git a/lib/Documents/src/MediaFinders/RandomImageFinder.php b/lib/Documents/src/MediaFinders/RandomImageFinder.php index d510b44b..6c522461 100644 --- a/lib/Documents/src/MediaFinders/RandomImageFinder.php +++ b/lib/Documents/src/MediaFinders/RandomImageFinder.php @@ -7,15 +7,12 @@ interface RandomImageFinder { /** - * @param array $options - * @return array|null A data feed for a random image. + * @return array|null a data feed for a random image */ public function getRandom(array $options = []): ?array; /** - * @param string $keyword - * @param array $options * @return array|bool|mixed A data feed for a random image by keyword */ - public function getRandomBySearch(string $keyword, array $options = []); + public function getRandomBySearch(string $keyword, array $options = []): mixed; } diff --git a/lib/Documents/src/Models/AdvancedDocumentInterface.php b/lib/Documents/src/Models/AdvancedDocumentInterface.php index f86ca2ba..1e3bf320 100644 --- a/lib/Documents/src/Models/AdvancedDocumentInterface.php +++ b/lib/Documents/src/Models/AdvancedDocumentInterface.php @@ -6,13 +6,9 @@ interface AdvancedDocumentInterface extends DocumentInterface, SizeableInterface, DisplayableInterface { - /** - * @return int|null - */ public function getFilesize(): ?int; /** - * @param int|null $filesize * @return $this */ public function setFilesize(?int $filesize): static; diff --git a/lib/Documents/src/Models/DisplayableInterface.php b/lib/Documents/src/Models/DisplayableInterface.php index aeb4a9ea..8b7f99a8 100644 --- a/lib/Documents/src/Models/DisplayableInterface.php +++ b/lib/Documents/src/Models/DisplayableInterface.php @@ -6,13 +6,9 @@ interface DisplayableInterface { - /** - * @return string|null - */ public function getImageAverageColor(): ?string; /** - * @param string|null $imageAverageColor * @return $this */ public function setImageAverageColor(?string $imageAverageColor): static; diff --git a/lib/Documents/src/Models/DocumentInterface.php b/lib/Documents/src/Models/DocumentInterface.php index 1f990bf5..4ab2789b 100644 --- a/lib/Documents/src/Models/DocumentInterface.php +++ b/lib/Documents/src/Models/DocumentInterface.php @@ -11,82 +11,60 @@ interface DocumentInterface public function getFilename(): string; /** - * @param string $filename * @return $this */ public function setFilename(string $filename): static; - /** - * @return string|null - */ public function getMimeType(): ?string; /** - * @param string|null $mimeType * @return $this */ public function setMimeType(?string $mimeType): static; /** * Get short type name for current document Mime type. - * - * @return string */ public function getShortType(): string; /** * Get short Mime type. - * - * @return string */ public function getShortMimeType(): string; /** * Is current document an image. - * - * @return bool */ public function isImage(): bool; /** * Is current document a vector SVG file. - * - * @return bool */ public function isSvg(): bool; /** * Is current document a Webp image. - * - * @return bool */ public function isWebp(): bool; /** * Is current document a video. - * - * @return bool */ public function isVideo(): bool; /** * Is current document an audio file. - * - * @return bool */ public function isAudio(): bool; /** * Is current document a PDF file. - * - * @return bool */ public function isPdf(): bool; public function getFolder(): string; /** - * @param string $folder * @return $this */ public function setFolder(string $folder): static; @@ -109,7 +87,6 @@ public function getMountFolderPath(): ?string; public function getEmbedId(): ?string; /** - * @param string|null $embedId * @return $this */ public function setEmbedId(?string $embedId): static; @@ -117,25 +94,18 @@ public function setEmbedId(?string $embedId): static; public function getEmbedPlatform(): ?string; /** - * @param string|null $embedPlatform * @return $this */ public function setEmbedPlatform(?string $embedPlatform): static; /** * Tells if current document has embed media information. - * - * @return bool */ public function isEmbed(): bool; - /** - * @return bool - */ public function isPrivate(): bool; /** - * @param bool $private * @return $this */ public function setPrivate(bool $private): static; @@ -144,27 +114,25 @@ public function getRawDocument(): ?DocumentInterface; /** * @param DocumentInterface|null $rawDocument the raw document + * * @return $this */ public function setRawDocument(?DocumentInterface $rawDocument = null): static; /** * Is document a raw one. - * - * @return bool */ public function isRaw(): bool; /** * @param bool $raw the raw + * * @return $this */ public function setRaw(bool $raw): static; /** * Gets the downscaledDocument. - * - * @return DocumentInterface|null */ public function getDownscaledDocument(): ?DocumentInterface; @@ -174,27 +142,22 @@ public function getDownscaledDocument(): ?DocumentInterface; public function getFolders(): Collection; /** - * @param FolderInterface $folder * @return $this */ public function addFolder(FolderInterface $folder): static; /** - * @param FolderInterface $folder * @return $this */ public function removeFolder(FolderInterface $folder): static; /** - * Return false if no local file is linked to document. i.e no filename, no folder - * - * @return bool + * Return false if no local file is linked to document. i.e no filename, no folder. */ public function isLocal(): bool; + /** * Return true if current document can be processed by intervention-image (GD, Imagick…). - * - * @return bool */ public function isProcessable(): bool; diff --git a/lib/Documents/src/Models/DocumentTrait.php b/lib/Documents/src/Models/DocumentTrait.php index 9ed46e32..4677043f 100644 --- a/lib/Documents/src/Models/DocumentTrait.php +++ b/lib/Documents/src/Models/DocumentTrait.php @@ -26,6 +26,7 @@ trait DocumentTrait * - 3d * * @var array + * * @internal */ #[SymfonySerializer\Ignore()] @@ -136,7 +137,8 @@ trait DocumentTrait ]; /** - * @var string[] Processable file mime type by GD or Imagick. + * @var string[] processable file mime type by GD or Imagick + * * @internal */ #[SymfonySerializer\Ignore()] @@ -153,8 +155,6 @@ trait DocumentTrait /** * Get short type name for current document Mime type. - * - * @return string */ #[SymfonySerializer\Ignore()] public function getShortType(): string @@ -168,99 +168,86 @@ public function getShortType(): string /** * Get short Mime type. - * - * @return string */ #[SymfonySerializer\Ignore()] public function getShortMimeType(): string { if (!empty($this->getMimeType())) { $mime = explode('/', $this->getMimeType()); + return $mime[\count($mime) - 1]; } + return 'unknown'; } /** * Is current document an image. - * - * @return bool */ #[SymfonySerializer\Ignore()] public function isImage(): bool { - return static::getShortType() === 'image'; + return 'image' === static::getShortType(); } /** * Is current document a vector SVG file. - * - * @return bool */ #[SymfonySerializer\Ignore()] public function isSvg(): bool { - return $this->getMimeType() === 'image/svg+xml' || $this->getMimeType() === 'image/svg'; + return 'image/svg+xml' === $this->getMimeType() || 'image/svg' === $this->getMimeType(); } /** * Is current document a video. - * - * @return bool */ #[SymfonySerializer\Ignore()] public function isVideo(): bool { - return static::getShortType() === 'video'; + return 'video' === static::getShortType(); } /** * Is current document an audio file. - * - * @return bool */ #[SymfonySerializer\Ignore()] public function isAudio(): bool { - return static::getShortType() === 'audio'; + return 'audio' === static::getShortType(); } /** * Is current document a PDF file. - * - * @return bool */ #[SymfonySerializer\Ignore()] public function isPdf(): bool { - return static::getShortType() === 'pdf'; + return 'pdf' === static::getShortType(); } - /** - * @return bool - */ #[SymfonySerializer\Ignore()] public function isWebp(): bool { - return $this->getMimeType() === 'image/webp'; + return 'image/webp' === $this->getMimeType(); } #[ - SymfonySerializer\Groups(["document", "document_display", "nodes_sources", "tag", "attribute"]), - SymfonySerializer\SerializedName("relativePath"), + SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute']), + SymfonySerializer\SerializedName('relativePath'), ] public function getRelativePath(): ?string { if ($this->isLocal()) { - return $this->getFolder() . '/' . $this->getFilename(); + return $this->getFolder().'/'.$this->getFilename(); } else { return null; } } #[ - SymfonySerializer\Groups(["document_mount"]), - SymfonySerializer\SerializedName("mountPath"), + SymfonySerializer\Groups(['document_mount']), + SymfonySerializer\SerializedName('mountPath'), ] public function getMountPath(): ?string { @@ -268,9 +255,9 @@ public function getMountPath(): ?string return null; } if ($this->isPrivate()) { - return 'private://' . $relativePath; + return 'private://'.$relativePath; } else { - return 'public://' . $relativePath; + return 'public://'.$relativePath; } } @@ -284,31 +271,29 @@ public function getMountFolderPath(): ?string return null; } if ($this->isPrivate()) { - return 'private://' . $folder; + return 'private://'.$folder; } else { - return 'public://' . $folder; + return 'public://'.$folder; } } /** * Tells if current document has embed media information. - * - * @return bool */ #[SymfonySerializer\Ignore()] public function isEmbed(): bool { - return (!empty($this->getEmbedId()) && !empty($this->getEmbedPlatform())); + return !empty($this->getEmbedId()) && !empty($this->getEmbedPlatform()); } protected function initDocumentTrait(): void { - $this->setFolder(\mb_substr(hash("crc32b", date('YmdHi')), 0, 12)); + $this->setFolder(\mb_substr(hash('crc32b', date('YmdHi')), 0, 12)); } #[ - SymfonySerializer\Groups(["document", "document_display", "nodes_sources", "tag", "attribute"]), - SymfonySerializer\SerializedName("processable"), + SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute']), + SymfonySerializer\SerializedName('processable'), ApiProperty( description: 'Document can be processed as an image for resampling and other image operations.', writable: false, @@ -320,8 +305,8 @@ public function isProcessable(): bool } #[ - SymfonySerializer\Groups(["document", "document_display", "nodes_sources", "tag", "attribute"]), - SymfonySerializer\SerializedName("alt"), + SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute']), + SymfonySerializer\SerializedName('alt'), ] public function getAlternativeText(): string { @@ -329,13 +314,11 @@ public function getAlternativeText(): string } /** - * Return false if no local file is linked to document. i.e no filename, no folder - * - * @return bool + * Return false if no local file is linked to document. i.e no filename, no folder. */ #[SymfonySerializer\Ignore()] public function isLocal(): bool { - return $this->getFilename() !== '' && $this->getFolder() !== ''; + return '' !== $this->getFilename() && '' !== $this->getFolder(); } } diff --git a/lib/Documents/src/Models/FileAwareInterface.php b/lib/Documents/src/Models/FileAwareInterface.php index d63bb07e..0570588d 100644 --- a/lib/Documents/src/Models/FileAwareInterface.php +++ b/lib/Documents/src/Models/FileAwareInterface.php @@ -10,12 +10,12 @@ interface FileAwareInterface { /** - * @return string Return absolute path to public files folder. + * @return string return absolute path to public files folder */ public function getPublicFilesPath(): string; /** - * @return string Return relative path to public files folder. + * @return string return relative path to public files folder */ public function getPublicFilesBasePath(): string; @@ -25,7 +25,7 @@ public function getPublicFilesBasePath(): string; public function getPrivateFilesPath(): string; /** - * @return string Return relative path to private files folder. + * @return string return relative path to private files folder */ public function getPrivateFilesBasePath(): string; @@ -35,17 +35,17 @@ public function getPrivateFilesBasePath(): string; public function getFontsFilesPath(): string; /** - * @return string Return relative path to private font files folder. + * @return string return relative path to private font files folder */ public function getFontsFilesBasePath(): string; /** - * @return string Return absolute path to public images cache. + * @return string return absolute path to public images cache */ public function getPublicCachePath(): string; /** - * @return string Return relative path to public images cache. + * @return string return relative path to public images cache */ public function getPublicCacheBasePath(): string; } diff --git a/lib/Documents/src/Models/FileHashInterface.php b/lib/Documents/src/Models/FileHashInterface.php index 49e76e30..8b1d8ed1 100644 --- a/lib/Documents/src/Models/FileHashInterface.php +++ b/lib/Documents/src/Models/FileHashInterface.php @@ -7,7 +7,10 @@ interface FileHashInterface { public function setFileHash(?string $hash): static; + public function getFileHash(): ?string; + public function setFileHashAlgorithm(?string $algorithm): static; + public function getFileHashAlgorithm(): ?string; } diff --git a/lib/Documents/src/Models/FolderInterface.php b/lib/Documents/src/Models/FolderInterface.php index f5555fd6..f1e483e4 100644 --- a/lib/Documents/src/Models/FolderInterface.php +++ b/lib/Documents/src/Models/FolderInterface.php @@ -14,49 +14,36 @@ interface FolderInterface public function getDocuments(): Collection; /** - * @param DocumentInterface $document * @return $this */ public function addDocument(DocumentInterface $document): static; /** - * @param DocumentInterface $document * @return $this */ public function removeDocument(DocumentInterface $document): static; public function getVisible(): bool; + public function isVisible(): bool; /** - * @param bool $visible * @return $this */ public function setVisible(bool $visible): static; - /** - * @return string - */ public function getFolderName(): string; - /** - * @return string|null - */ public function getName(): ?string; /** - * @param string $folderName * @return $this */ public function setFolderName(string $folderName): static; - /** - * @return string - */ public function getDirtyFolderName(): string; /** - * @param string $dirtyFolderName * @return $this */ public function setDirtyFolderName(string $dirtyFolderName): static; diff --git a/lib/Documents/src/Models/HasThumbnailInterface.php b/lib/Documents/src/Models/HasThumbnailInterface.php index 66844306..a4f6b82a 100644 --- a/lib/Documents/src/Models/HasThumbnailInterface.php +++ b/lib/Documents/src/Models/HasThumbnailInterface.php @@ -8,13 +8,9 @@ interface HasThumbnailInterface { - /** - * @return HasThumbnailInterface|null - */ public function getOriginal(): ?HasThumbnailInterface; /** - * @param HasThumbnailInterface|null $original * @return $this */ public function setOriginal(?HasThumbnailInterface $original): static; @@ -26,22 +22,14 @@ public function getThumbnails(): Collection; /** * @param Collection $thumbnails + * * @return $this */ public function setThumbnails(Collection $thumbnails): static; - /** - * @return bool - */ public function isThumbnail(): bool; - /** - * @return bool - */ public function hasThumbnails(): bool; - /** - * @return bool - */ public function needsThumbnail(): bool; } diff --git a/lib/Documents/src/Models/SimpleDocument.php b/lib/Documents/src/Models/SimpleDocument.php index 58315a95..142c5c14 100644 --- a/lib/Documents/src/Models/SimpleDocument.php +++ b/lib/Documents/src/Models/SimpleDocument.php @@ -31,9 +31,6 @@ public function __construct() $this->folders = new ArrayCollection(); } - /** - * @return string - */ public function getFilename(): string { return $this->filename; @@ -42,6 +39,7 @@ public function getFilename(): string public function setFilename(string $filename): static { $this->filename = $filename; + return $this; } @@ -53,12 +51,10 @@ public function getMimeType(): ?string public function setMimeType(?string $mimeType): static { $this->mimeType = $mimeType; + return $this; } - /** - * @return string - */ public function getFolder(): string { return $this->folder; @@ -71,9 +67,6 @@ public function setFolder(string $folder): static return $this; } - /** - * @return string|null - */ public function getEmbedId(): ?string { return $this->embedId; @@ -86,9 +79,6 @@ public function setEmbedId(?string $embedId): static return $this; } - /** - * @return string|null - */ public function getEmbedPlatform(): ?string { return $this->embedPlatform; @@ -101,9 +91,6 @@ public function setEmbedPlatform(?string $embedPlatform): static return $this; } - /** - * @return bool - */ public function isPrivate(): bool { return $this->private; @@ -116,9 +103,6 @@ public function setPrivate(bool $private): static return $this; } - /** - * @return DocumentInterface|null - */ public function getRawDocument(): ?DocumentInterface { return $this->rawDocument; @@ -131,9 +115,6 @@ public function setRawDocument(?DocumentInterface $rawDocument = null): static return $this; } - /** - * @return bool - */ public function isRaw(): bool { return $this->raw; @@ -158,9 +139,6 @@ public function setDownscaledDocument(?DocumentInterface $downscaledDocument): s return $this; } - /** - * @return Collection - */ public function getFolders(): Collection { return $this->folders; @@ -169,18 +147,21 @@ public function getFolders(): Collection public function setFolders(Collection $folders): static { $this->folders = $folders; + return $this; } public function addFolder(FolderInterface $folder): static { $this->folders->add($folder); + return $this; } public function removeFolder(FolderInterface $folder): static { $this->folders->removeElement($folder); + return $this; } diff --git a/lib/Documents/src/Models/SimpleFileAware.php b/lib/Documents/src/Models/SimpleFileAware.php index 0f6f0ce9..bbff6527 100644 --- a/lib/Documents/src/Models/SimpleFileAware.php +++ b/lib/Documents/src/Models/SimpleFileAware.php @@ -11,9 +11,6 @@ class SimpleFileAware implements FileAwareInterface { private string $basePath; - /** - * @param string $basePath - */ public function __construct(string $basePath) { $this->basePath = $basePath; @@ -21,7 +18,7 @@ public function __construct(string $basePath) public function getPublicFilesPath(): string { - return $this->basePath . $this->getPublicFilesBasePath(); + return $this->basePath.$this->getPublicFilesBasePath(); } public function getPublicFilesBasePath(): string @@ -31,7 +28,7 @@ public function getPublicFilesBasePath(): string public function getPrivateFilesPath(): string { - return $this->basePath . $this->getPrivateFilesBasePath(); + return $this->basePath.$this->getPrivateFilesBasePath(); } public function getPrivateFilesBasePath(): string @@ -41,7 +38,7 @@ public function getPrivateFilesBasePath(): string public function getFontsFilesPath(): string { - return $this->basePath . $this->getPrivateFilesBasePath(); + return $this->basePath.$this->getPrivateFilesBasePath(); } public function getFontsFilesBasePath(): string diff --git a/lib/Documents/src/Models/SizeableInterface.php b/lib/Documents/src/Models/SizeableInterface.php index 5bf55a7e..bdbcca9b 100644 --- a/lib/Documents/src/Models/SizeableInterface.php +++ b/lib/Documents/src/Models/SizeableInterface.php @@ -6,30 +6,19 @@ interface SizeableInterface { - /** - * @return int - */ public function getImageWidth(): int; /** - * @param int $imageWidth * @return $this */ public function setImageWidth(int $imageWidth): static; - /** - * @return int - */ public function getImageHeight(): int; /** - * @param int $imageHeight * @return $this */ public function setImageHeight(int $imageHeight): static; - /** - * @return float|null - */ public function getImageRatio(): ?float; } diff --git a/lib/Documents/src/Models/TimeableInterface.php b/lib/Documents/src/Models/TimeableInterface.php index 25fc81f5..4951c77a 100644 --- a/lib/Documents/src/Models/TimeableInterface.php +++ b/lib/Documents/src/Models/TimeableInterface.php @@ -6,13 +6,9 @@ interface TimeableInterface { - /** - * @return int - */ public function getMediaDuration(): int; /** - * @param int $duration * @return $this */ public function setMediaDuration(int $duration): static; diff --git a/lib/Documents/src/OptionsResolver/UrlOptionsResolver.php b/lib/Documents/src/OptionsResolver/UrlOptionsResolver.php index ac34da79..834428ab 100644 --- a/lib/Documents/src/OptionsResolver/UrlOptionsResolver.php +++ b/lib/Documents/src/OptionsResolver/UrlOptionsResolver.php @@ -41,16 +41,16 @@ public function __construct() $this->setAllowedValues( 'align', [ - null, - 'top-left', - 'top', - 'top-right', - 'left', - 'center', - 'right', - 'bottom-left', - 'bottom', - 'bottom-right', + null, + 'top-left', + 'top', + 'top-right', + 'left', + 'center', + 'right', + 'bottom-left', + 'bottom', + 'bottom-right', ] ); $this->setAllowedTypes('background', ['null', 'string']); @@ -73,6 +73,7 @@ function (Options $options) { if (1 === preg_match('#(?[0-9]+)[x:\.](?[0-9]+)#', $compositing, $matches)) { return ((float) $matches['width']) / ((float) $matches['height']); } + return null; } ); @@ -86,9 +87,10 @@ function (Options $options) { $compositing = $options['fit'] ?? ''; if (1 === preg_match('#(?[0-9]+)[x:\.](?[0-9]+)#', $compositing, $matches)) { return (int) $matches['width']; - } elseif (null !== $options['ratio'] && $options['height'] !== 0 && $options['ratio'] !== 0) { + } elseif (null !== $options['ratio'] && 0 !== $options['height'] && 0 !== $options['ratio']) { return (int) (intval($options['height']) * floatval($options['ratio'])); } + return 0; } ); @@ -99,9 +101,10 @@ function (Options $options) { $compositing = $options['fit'] ?? ''; if (1 === preg_match('#(?[0-9]+)[x:\.](?[0-9]+)#', $compositing, $matches)) { return (int) $matches['height']; - } elseif (null !== $options['ratio'] && $options['width'] !== 0 && $options['ratio'] !== 0) { + } elseif (null !== $options['ratio'] && 0 !== $options['width'] && 0 !== $options['ratio']) { return (int) (intval($options['width']) / floatval($options['ratio'])); } + return 0; } ); diff --git a/lib/Documents/src/Renderer/AbstractImageRenderer.php b/lib/Documents/src/Renderer/AbstractImageRenderer.php index 4c7c60ca..2bd767de 100644 --- a/lib/Documents/src/Renderer/AbstractImageRenderer.php +++ b/lib/Documents/src/Renderer/AbstractImageRenderer.php @@ -20,7 +20,7 @@ public function __construct( EmbedFinderFactory $embedFinderFactory, Environment $templating, DocumentUrlGeneratorInterface $documentUrlGenerator, - string $templateBasePath = 'documents' + string $templateBasePath = 'documents', ) { parent::__construct($documentsStorage, $templating, $documentUrlGenerator, $templateBasePath); $this->embedFinderFactory = $embedFinderFactory; @@ -28,23 +28,19 @@ public function __construct( public function supports(DocumentInterface $document, array $options): bool { - return $document->isImage() && - !empty($document->getRelativePath()) && - !$this->isEmbeddable($document, $options); + return $document->isImage() + && !empty($document->getRelativePath()) + && !$this->isEmbeddable($document, $options); } public function isEmbeddable(DocumentInterface $document, array $options): bool { - return isset($options['embed']) && - $options['embed'] === true && - null !== $document->getEmbedPlatform() && - $this->embedFinderFactory->supports($document->getEmbedPlatform()); + return isset($options['embed']) + && true === $options['embed'] + && null !== $document->getEmbedPlatform() + && $this->embedFinderFactory->supports($document->getEmbedPlatform()); } - /** - * @param array $options - * @return string|null - */ protected function parseSizes(array $options = []): ?string { if (count($options['sizes']) > 0) { @@ -56,52 +52,38 @@ protected function parseSizes(array $options = []): ?string protected function willResample(array &$assignation): bool { - return !empty($assignation['fit']) || - !empty($assignation['crop']) || - !empty($assignation['rotate']) || - !empty($assignation['width']) || - !empty($assignation['height']); + return !empty($assignation['fit']) + || !empty($assignation['crop']) + || !empty($assignation['rotate']) + || !empty($assignation['width']) + || !empty($assignation['height']); } - /** - * @param DocumentInterface $document - * @param array $options - * @param bool $convertToWebP - * - * @return string|null - */ protected function parseSrcSet( DocumentInterface $document, array $options = [], - bool $convertToWebP = false + bool $convertToWebP = false, ): ?string { if (count($options['srcset']) > 0) { return $this->parseSrcSetInner($document, $options['srcset'], $convertToWebP, $options['absolute']); } + return null; } - /** - * @param DocumentInterface $document - * @param array $srcSetArray - * @param bool $convertToWebP - * @param bool $absolute - * - * @return string - */ protected function parseSrcSetInner( DocumentInterface $document, array $srcSetArray = [], bool $convertToWebP = false, - bool $absolute = false + bool $absolute = false, ): string { $output = []; foreach ($srcSetArray as $set) { if ( - isset($set['format']) && - isset($set['rule']) && - !$document->isPrivate() && - !empty($document->getRelativePath()) + isset($set['format']) + && isset($set['rule']) + && !$document->isPrivate() + && !empty($document->getRelativePath()) ) { $this->documentUrlGenerator->setOptions($this->urlOptionsResolver->resolve($set['format'])); $this->documentUrlGenerator->setDocument($document); @@ -109,65 +91,55 @@ protected function parseSrcSetInner( if ($convertToWebP) { $path .= '.webp'; } - $output[] = $path . ' ' . $set['rule']; + $output[] = $path.' '.$set['rule']; } } + return implode(', ', $output); } - /** - * @param string $hexColor - * @param int $width - * @param int $height - * @return string - */ protected function createTransparentDataURI(string $hexColor, int $width = 1, int $height = 1): string { - $hexColorArray = \sscanf($hexColor, "#%02x%02x%02x"); + $hexColorArray = \sscanf($hexColor, '#%02x%02x%02x'); if (null === $hexColorArray) { throw new \RuntimeException('Color is not a valid hexadecimal RGB format'); } [$r, $g, $b] = $hexColorArray; - $im = \imageCreateTrueColor($width, $height); + $im = \imagecreatetruecolor($width, $height); if ($im) { - \imageFill( + \imagefill( $im, 0, 0, - \imageColorAllocate($im, $r ?? 0, $g ?? 0, $b ?? 0) ?: 0 + \imagecolorallocate($im, $r ?? 0, $g ?? 0, $b ?? 0) ?: 0 ); \ob_start(); \imagejpeg($im, null, 30); $img = \ob_get_contents(); \ob_end_clean(); if ($img) { - return 'data:image/jpeg;base64,' . \base64_encode($img); + return 'data:image/jpeg;base64,'.\base64_encode($img); } } throw new \RuntimeException('Cannot generate imageCreateTrueColor'); } - /** - * @param DocumentInterface $document - * @param array $options - * @param array $assignation - */ protected function additionalAssignation(DocumentInterface $document, array $options, array &$assignation): void { if ($document instanceof AdvancedDocumentInterface) { - if (null !== $options['ratio'] && $options['ratio'] !== 0) { + if (null !== $options['ratio'] && 0 !== $options['ratio']) { $assignation['ratio'] = $options['ratio']; } elseif (null !== $document->getImageRatio()) { $assignation['ratio'] = $document->getImageRatio(); } if ( null !== $document->getImageAverageColor() - && $document->getImageAverageColor() !== '#ffffff' - && $document->getImageAverageColor() !== '#000000' + && '#ffffff' !== $document->getImageAverageColor() + && '#000000' !== $document->getImageAverageColor() ) { $assignation['averageColor'] = $document->getImageAverageColor(); } - if ($options['blurredFallback'] === true) { + if (true === $options['blurredFallback']) { if (!empty($options['fit'])) { // Both Fit and Width cannot be explicitly set // need to revert on Crop @@ -183,7 +155,7 @@ protected function additionalAssignation(DocumentInterface $document, array $opt $options, [ 'quality' => 10, - 'width' => 60 + 'width' => 60, ] ) ); diff --git a/lib/Documents/src/Renderer/AbstractRenderer.php b/lib/Documents/src/Renderer/AbstractRenderer.php index 71abbcee..dabd17ac 100644 --- a/lib/Documents/src/Renderer/AbstractRenderer.php +++ b/lib/Documents/src/Renderer/AbstractRenderer.php @@ -25,7 +25,7 @@ public function __construct( FilesystemOperator $documentsStorage, Environment $templating, DocumentUrlGeneratorInterface $documentUrlGenerator, - string $templateBasePath = 'documents' + string $templateBasePath = 'documents', ) { $this->documentsStorage = $documentsStorage; $this->templating = $templating; @@ -35,12 +35,6 @@ public function __construct( $this->viewOptionsResolver = new ViewOptionsResolver(); } - /** - * @param DocumentInterface $document - * @param array $options - * - * @return string - */ protected function getSource(DocumentInterface $document, array $options): string { if (empty($document->getRelativePath())) { @@ -48,27 +42,22 @@ protected function getSource(DocumentInterface $document, array $options): strin } $this->documentUrlGenerator->setOptions($options); $this->documentUrlGenerator->setDocument($document); + return $this->documentUrlGenerator->getUrl($options['absolute']); } /** - * @param string $template - * @param array $assignation - * - * @return string * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ protected function renderHtmlElement(string $template, array $assignation): string { - return $this->templating->render($this->templateBasePath . '/' . $template, $assignation); + return $this->templating->render($this->templateBasePath.'/'.$template, $assignation); } /** - * @param DocumentInterface $document * @param iterable $sourcesDocs - * @return array */ protected function getSourcesFilesArray(DocumentInterface $document, iterable $sourcesDocs): array { @@ -88,7 +77,7 @@ protected function getSourcesFilesArray(DocumentInterface $document, iterable $s } krsort($sources); - if (count($sources) === 0) { + if (0 === count($sources)) { // If exotic extension, fallbacks using original file $documentMountPath = $document->getMountPath(); if (null !== $documentMountPath) { diff --git a/lib/Documents/src/Renderer/AudioRenderer.php b/lib/Documents/src/Renderer/AudioRenderer.php index f63dc0e1..694f5121 100644 --- a/lib/Documents/src/Renderer/AudioRenderer.php +++ b/lib/Documents/src/Renderer/AudioRenderer.php @@ -19,7 +19,7 @@ public function __construct( DocumentFinderInterface $documentFinder, Environment $templating, DocumentUrlGeneratorInterface $documentUrlGenerator, - string $templateBasePath = 'documents' + string $templateBasePath = 'documents', ) { parent::__construct($documentsStorage, $templating, $documentUrlGenerator, $templateBasePath); $this->documentFinder = $documentFinder; @@ -31,10 +31,6 @@ public function supports(DocumentInterface $document, array $options): bool } /** - * @param DocumentInterface $document - * @param array $options - * - * @return string * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError @@ -53,10 +49,6 @@ public function render(DocumentInterface $document, array $options): string * * This method will search for document which filename is the same * except the extension. If you choose an MP4 file, it will look for a OGV and WEBM file. - * - * @param DocumentInterface $document - * - * @return array */ protected function getSourcesFiles(DocumentInterface $document): array { diff --git a/lib/Documents/src/Renderer/ChainRenderer.php b/lib/Documents/src/Renderer/ChainRenderer.php index 50dac812..0de8b7af 100644 --- a/lib/Documents/src/Renderer/ChainRenderer.php +++ b/lib/Documents/src/Renderer/ChainRenderer.php @@ -13,9 +13,6 @@ class ChainRenderer implements RendererInterface */ private array $renderers; - /** - * @param array $renderers - */ public function __construct(array $renderers) { /** @@ -30,13 +27,12 @@ public function __construct(array $renderers) } /** - * @param RendererInterface $renderer - * * @return $this */ public function addRenderer(RendererInterface $renderer): ChainRenderer { $this->renderers[] = $renderer; + return $this; } diff --git a/lib/Documents/src/Renderer/EmbedRenderer.php b/lib/Documents/src/Renderer/EmbedRenderer.php index 7ed8c2b2..de82d0fb 100644 --- a/lib/Documents/src/Renderer/EmbedRenderer.php +++ b/lib/Documents/src/Renderer/EmbedRenderer.php @@ -12,9 +12,6 @@ class EmbedRenderer implements RendererInterface { protected EmbedFinderFactory $embedFinderFactory; - /** - * @param EmbedFinderFactory $embedFinderFactory - */ public function __construct(EmbedFinderFactory $embedFinderFactory) { $this->embedFinderFactory = $embedFinderFactory; @@ -26,7 +23,7 @@ public function supports(DocumentInterface $document, array $options): bool $document->isEmbed() && $this->embedFinderFactory->supports($document->getEmbedPlatform()) && isset($options['embed']) - && $options['embed'] === true + && true === $options['embed'] ) { return true; } else { @@ -44,9 +41,10 @@ public function render(DocumentInterface $document, array $options): string if (null !== $finder) { return $finder->getIFrame($options); } + return ''; } catch (InvalidEmbedId $exception) { - return '

' . $exception->getMessage() . '

'; + return '

'.$exception->getMessage().'

'; } } } diff --git a/lib/Documents/src/Renderer/ImageRenderer.php b/lib/Documents/src/Renderer/ImageRenderer.php index f862a0d4..b5d54a2f 100644 --- a/lib/Documents/src/Renderer/ImageRenderer.php +++ b/lib/Documents/src/Renderer/ImageRenderer.php @@ -12,8 +12,8 @@ class ImageRenderer extends AbstractImageRenderer { public function supports(DocumentInterface $document, array $options): bool { - return (!isset($options['picture']) || $options['picture'] === false) && - parent::supports($document, $options); + return (!isset($options['picture']) || false === $options['picture']) + && parent::supports($document, $options); } public function render(DocumentInterface $document, array $options): string @@ -24,9 +24,9 @@ public function render(DocumentInterface $document, array $options): string * Override image by its first thumbnail if existing */ if ( - !$options['no_thumbnail'] && - $document instanceof HasThumbnailInterface && - $thumbnail = $document->getThumbnails()->first() + !$options['no_thumbnail'] + && $document instanceof HasThumbnailInterface + && $thumbnail = $document->getThumbnails()->first() ) { if ($thumbnail instanceof DocumentInterface) { $document = $thumbnail; @@ -38,7 +38,7 @@ public function render(DocumentInterface $document, array $options): string [ 'mimetype' => $document->getMimeType(), 'url' => $this->getSource($document, $options), - 'media' => null + 'media' => null, ] ); $assignation['alt'] = !empty($options['alt']) ? $options['alt'] : $document->getAlternativeText(); diff --git a/lib/Documents/src/Renderer/InlineSvgRenderer.php b/lib/Documents/src/Renderer/InlineSvgRenderer.php index 13a39a00..b6497a0b 100644 --- a/lib/Documents/src/Renderer/InlineSvgRenderer.php +++ b/lib/Documents/src/Renderer/InlineSvgRenderer.php @@ -23,13 +23,10 @@ public function __construct(FilesystemOperator $documentsStorage) public function supports(DocumentInterface $document, array $options): bool { - return $document->isLocal() && $document->isSvg() && (isset($options['inline']) && $options['inline'] === true); + return $document->isLocal() && $document->isSvg() && (isset($options['inline']) && true === $options['inline']); } /** - * @param DocumentInterface $document - * @param array $options - * @return string * @throws FilesystemException */ public function render(DocumentInterface $document, array $options): string @@ -43,9 +40,10 @@ public function render(DocumentInterface $document, array $options): string $document, $assignation ); + return trim($this->htmlTidy($viewer->getContent())); } catch (\Exception $e) { - return '

' . $e->getMessage() . '

'; + return '

'.$e->getMessage().'

'; } } diff --git a/lib/Documents/src/Renderer/PdfRenderer.php b/lib/Documents/src/Renderer/PdfRenderer.php index 4ab5de0d..d61f685f 100644 --- a/lib/Documents/src/Renderer/PdfRenderer.php +++ b/lib/Documents/src/Renderer/PdfRenderer.php @@ -10,9 +10,9 @@ class PdfRenderer extends AbstractRenderer { public function supports(DocumentInterface $document, array $options): bool { - return $document->isPdf() && - key_exists('embed', $options) && - $options['embed'] === true; + return $document->isPdf() + && key_exists('embed', $options) + && true === $options['embed']; } /** diff --git a/lib/Documents/src/Renderer/PictureRenderer.php b/lib/Documents/src/Renderer/PictureRenderer.php index 9ed7fa89..78dd6634 100644 --- a/lib/Documents/src/Renderer/PictureRenderer.php +++ b/lib/Documents/src/Renderer/PictureRenderer.php @@ -11,9 +11,9 @@ class PictureRenderer extends AbstractImageRenderer { public function supports(DocumentInterface $document, array $options): bool { - return isset($options['picture']) && - $options['picture'] === true && - parent::supports($document, $options); + return isset($options['picture']) + && true === $options['picture'] + && parent::supports($document, $options); } /** @@ -29,9 +29,9 @@ public function render(DocumentInterface $document, array $options): string * Override image by its first thumbnail if existing */ if ( - !$options['no_thumbnail'] && - $document instanceof HasThumbnailInterface && - $thumbnail = $document->getThumbnails()->first() + !$options['no_thumbnail'] + && $document instanceof HasThumbnailInterface + && $thumbnail = $document->getThumbnails()->first() ) { if ($thumbnail instanceof DocumentInterface) { $document = $thumbnail; @@ -80,9 +80,10 @@ private function parseMedia(DocumentInterface $document, array $options = []): a $mediaList[] = [ 'srcset' => $this->parseSrcSetInner($document, $media['srcset'], false, $options['absolute']), 'webp_srcset' => !$document->isWebp() ? $this->parseSrcSetInner($document, $media['srcset'], true, $options['absolute']) : null, - 'rule' => $media['rule'] + 'rule' => $media['rule'], ]; } + return $mediaList; } } diff --git a/lib/Documents/src/Renderer/RendererInterface.php b/lib/Documents/src/Renderer/RendererInterface.php index 76e4402e..f0004636 100644 --- a/lib/Documents/src/Renderer/RendererInterface.php +++ b/lib/Documents/src/Renderer/RendererInterface.php @@ -8,19 +8,7 @@ interface RendererInterface { - /** - * @param DocumentInterface $document - * @param array $options - * - * @return bool - */ public function supports(DocumentInterface $document, array $options): bool; - /** - * @param DocumentInterface $document - * @param array $options - * - * @return string - */ public function render(DocumentInterface $document, array $options): string; } diff --git a/lib/Documents/src/Renderer/SvgRenderer.php b/lib/Documents/src/Renderer/SvgRenderer.php index 06eaef98..a5f26be1 100644 --- a/lib/Documents/src/Renderer/SvgRenderer.php +++ b/lib/Documents/src/Renderer/SvgRenderer.php @@ -22,7 +22,7 @@ public function __construct(FilesystemOperator $documentsStorage) public function supports(DocumentInterface $document, array $options): bool { - return $document->isSvg() && (!isset($options['inline']) || $options['inline'] === false); + return $document->isSvg() && (!isset($options['inline']) || false === $options['inline']); } public function render(DocumentInterface $document, array $options): string @@ -41,17 +41,12 @@ public function render(DocumentInterface $document, array $options): string if (is_string($value)) { $value = htmlspecialchars($value); } - $attrs[] = $key . '="' . $value . '"'; + $attrs[] = $key.'="'.$value.'"'; } - return ''; + return ''; } - /** - * @param array $options - * - * @return array - */ protected function getAttributes(array $options): array { $attributes = []; @@ -59,18 +54,19 @@ protected function getAttributes(array $options): array SvgDocumentViewer::$allowedAttributes, [ 'loading', - 'alt' + 'alt', ] ); foreach ($options as $key => $value) { if (in_array($key, $allowedAttributes)) { - if ($key === 'identifier') { + if ('identifier' === $key) { $attributes['id'] = $value; } else { $attributes[$key] = $value; } } } + return $attributes; } } diff --git a/lib/Documents/src/Renderer/ThumbnailRenderer.php b/lib/Documents/src/Renderer/ThumbnailRenderer.php index 72bddca0..157701ba 100644 --- a/lib/Documents/src/Renderer/ThumbnailRenderer.php +++ b/lib/Documents/src/Renderer/ThumbnailRenderer.php @@ -14,47 +14,33 @@ class ThumbnailRenderer implements RendererInterface { protected ?ChainRenderer $chainRenderer = null; - /** - * @param ChainRenderer|null $chainRenderer - */ public function __construct(?ChainRenderer $chainRenderer = null) { $this->chainRenderer = $chainRenderer; } - /** - * @param DocumentInterface $document - * @param array $options - * - * @return bool - */ public function supports(DocumentInterface $document, array $options): bool { - return null !== $this->chainRenderer && - (!key_exists('embed', $options) || - $options['embed'] !== true) && - $document instanceof HasThumbnailInterface && - $document->hasThumbnails() && - false !== $document->getThumbnails()->first(); + return null !== $this->chainRenderer + && (!key_exists('embed', $options) + || true !== $options['embed']) + && $document instanceof HasThumbnailInterface + && $document->hasThumbnails() + && false !== $document->getThumbnails()->first(); } - /** - * @param DocumentInterface $document - * @param array $options - * - * @return string - */ public function render(DocumentInterface $document, array $options): string { if ( - null !== $this->chainRenderer && - $document instanceof HasThumbnailInterface + null !== $this->chainRenderer + && $document instanceof HasThumbnailInterface ) { $thumbnail = $document->getThumbnails()->first(); if ($thumbnail instanceof DocumentInterface) { return $this->chainRenderer->render($thumbnail, $options); } } + return ''; } } diff --git a/lib/Documents/src/Renderer/VideoRenderer.php b/lib/Documents/src/Renderer/VideoRenderer.php index 15a84e4b..c979e355 100644 --- a/lib/Documents/src/Renderer/VideoRenderer.php +++ b/lib/Documents/src/Renderer/VideoRenderer.php @@ -20,7 +20,7 @@ public function __construct( DocumentFinderInterface $documentFinder, Environment $templating, DocumentUrlGeneratorInterface $documentUrlGenerator, - string $templateBasePath = 'documents' + string $templateBasePath = 'documents', ) { parent::__construct($documentsStorage, $templating, $documentUrlGenerator, $templateBasePath); $this->documentFinder = $documentFinder; @@ -54,33 +54,28 @@ public function render(DocumentInterface $document, array $options): string */ $assignation['poster'] = $this->getPosterUrl($document, $options, $options['absolute']); } + return $this->renderHtmlElement('video.html.twig', $assignation); } - /** - * @param DocumentInterface $document - * @param array $options - * @param bool $absolute - * - * @return string|null - */ protected function getPosterUrl( DocumentInterface $document, array $options = [], - bool $absolute = false + bool $absolute = false, ): ?string { /* * Use document thumbnail first */ if ( - !$options['no_thumbnail'] && - $document instanceof HasThumbnailInterface && - $document->hasThumbnails() + !$options['no_thumbnail'] + && $document instanceof HasThumbnailInterface + && $document->hasThumbnails() ) { $thumbnail = $document->getThumbnails()->first(); if (false !== $thumbnail) { $this->documentUrlGenerator->setOptions($options); $this->documentUrlGenerator->setDocument($thumbnail); + return $this->documentUrlGenerator->getUrl($absolute); } } @@ -96,6 +91,7 @@ protected function getPosterUrl( foreach ($sourcesDocs as $sourcesDoc) { $this->documentUrlGenerator->setOptions($options); $this->documentUrlGenerator->setDocument($sourcesDoc); + return $this->documentUrlGenerator->getUrl($absolute); } @@ -107,10 +103,6 @@ protected function getPosterUrl( * * This method will search for document which filename is the same * except the extension. If you choose an MP4 file, it will look for a OGV and WEBM file. - * - * @param DocumentInterface $document - * - * @return array */ protected function getSourcesFiles(DocumentInterface $document): array { diff --git a/lib/Documents/src/Repository/DocumentRepositoryInterface.php b/lib/Documents/src/Repository/DocumentRepositoryInterface.php index d6bd01c0..1de60ae6 100644 --- a/lib/Documents/src/Repository/DocumentRepositoryInterface.php +++ b/lib/Documents/src/Repository/DocumentRepositoryInterface.php @@ -8,7 +8,9 @@ /** * @template T of \RZ\Roadiz\Documents\Models\DocumentInterface + * * @template-extends ObjectRepository + * * @extends ObjectRepository */ interface DocumentRepositoryInterface extends ObjectRepository diff --git a/lib/Documents/src/SvgSizeResolver.php b/lib/Documents/src/SvgSizeResolver.php index b460c56e..bf07b87a 100644 --- a/lib/Documents/src/SvgSizeResolver.php +++ b/lib/Documents/src/SvgSizeResolver.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\Documents; -use DOMNamedNodeMap; use League\Flysystem\FilesystemException; use League\Flysystem\FilesystemOperator; use RZ\Roadiz\Documents\Models\DocumentInterface; @@ -16,7 +15,7 @@ final class SvgSizeResolver public function __construct( private readonly DocumentInterface $document, - private readonly FilesystemOperator $documentsStorage + private readonly FilesystemOperator $documentsStorage, ) { } @@ -27,7 +26,7 @@ protected function getViewBoxAttributes(): ?array { try { $viewBox = $this->getSvgNodeAttributes()->getNamedItem('viewBox'); - if (null !== $viewBox && $viewBox->textContent !== "") { + if (null !== $viewBox && '' !== $viewBox->textContent) { return explode(' ', $viewBox->textContent); } } catch (\RuntimeException $exception) { @@ -37,17 +36,13 @@ protected function getViewBoxAttributes(): ?array return null; } - /** - * @param string $name - * @return int|null - */ protected function getIntegerAttribute(string $name): ?int { try { $attribute = $this->getSvgNodeAttributes()->getNamedItem($name); if ( null !== $attribute - && $attribute->textContent !== "" + && '' !== $attribute->textContent && !\str_contains($attribute->textContent, '%') ) { return (int) $attribute->textContent; @@ -55,13 +50,12 @@ protected function getIntegerAttribute(string $name): ?int } catch (\RuntimeException $exception) { return null; } + return null; } /** * First, find width attr, then resolve width from viewBox. - * - * @return int */ public function getWidth(): int { @@ -73,6 +67,7 @@ public function getWidth(): int $viewBoxAttr = $this->getViewBoxAttributes(); if (null !== $viewBoxAttr) { [$x, $y, $width, $height] = $viewBoxAttr; + return (int) $width; } @@ -81,8 +76,6 @@ public function getWidth(): int /** * First, find height attr, then resolve height from viewBox. - * - * @return int */ public function getHeight(): int { @@ -93,6 +86,7 @@ public function getHeight(): int $viewBoxAttr = $this->getViewBoxAttributes(); if (null !== $viewBoxAttr) { [$x, $y, $width, $height] = $viewBoxAttr; + return (int) $height; } @@ -114,7 +108,7 @@ private function getSvgNode(): \DOMElement private function getSvgNodeAttributes(): \DOMNamedNodeMap { - /** @var DOMNamedNodeMap|null $attributes */ + /** @var \DOMNamedNodeMap|null $attributes */ $attributes = $this->getSvgNode()->attributes; if (null === $attributes) { throw new \RuntimeException('SVG tag does not contain any attribute'); @@ -139,6 +133,7 @@ private function getDOMDocument(): \DOMDocument throw new \RuntimeException(sprintf('SVG (%s) could not be loaded.', $mountPath)); } } + return $this->xmlDocument; } } diff --git a/lib/Documents/src/TwigExtension/DocumentExtension.php b/lib/Documents/src/TwigExtension/DocumentExtension.php index 390944ed..381b2a15 100644 --- a/lib/Documents/src/TwigExtension/DocumentExtension.php +++ b/lib/Documents/src/TwigExtension/DocumentExtension.php @@ -23,22 +23,16 @@ final class DocumentExtension extends AbstractExtension { /** - * @param RendererInterface $renderer - * @param EmbedFinderFactory $embedFinderFactory - * @param FilesystemOperator $documentsStorage * @param bool $throwExceptions Trigger exception if using filter on NULL values (default: false) */ public function __construct( private readonly RendererInterface $renderer, private readonly EmbedFinderFactory $embedFinderFactory, private readonly FilesystemOperator $documentsStorage, - private readonly bool $throwExceptions = false + private readonly bool $throwExceptions = false, ) { } - /** - * @return array - */ public function getFilters(): array { return [ @@ -49,28 +43,25 @@ public function getFilters(): array new TwigFilter('path', [$this, 'getPath']), new TwigFilter('exists', [$this, 'exists']), new TwigFilter('embedFinder', [$this, 'getEmbedFinder']), - new TwigFilter('formatBytes', array($this, 'formatBytes')), + new TwigFilter('formatBytes', [$this, 'formatBytes']), ]; } /** - * @param string|int $bytes - * @param int $precision - * @return string + * @param string|int $bytes */ public function formatBytes($bytes, int $precision = 2): string { - $size = ['B','kB','MB','GB','TB','PB','EB','ZB','YB']; + $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; $factor = floor((\mb_strlen((string) $bytes) - 1) / 3); - return sprintf("%.{$precision}f", (int) $bytes / pow(1024, $factor)) . @$size[$factor]; + + return sprintf("%.{$precision}f", (int) $bytes / pow(1024, $factor)).@$size[$factor]; } /** - * @param DocumentInterface|null $document - * @return null|EmbedFinderInterface * @throws RuntimeError */ - public function getEmbedFinder(DocumentInterface $document = null): ?EmbedFinderInterface + public function getEmbedFinder(?DocumentInterface $document = null): ?EmbedFinderInterface { if (null === $document) { if ($this->throwExceptions) { @@ -102,19 +93,15 @@ public function getEmbedFinder(DocumentInterface $document = null): ?EmbedFinder } /** - * @param DocumentInterface|null $document - * @param array|null $options - * - * @return string * @throws RuntimeError */ - public function display(DocumentInterface $document = null, ?array $options = []): string + public function display(?DocumentInterface $document = null, ?array $options = []): string { if (null === $document) { if ($this->throwExceptions) { throw new RuntimeError('Document can’t be null to be displayed.'); } else { - return ""; + return ''; } } if (null === $options) { @@ -126,7 +113,7 @@ public function display(DocumentInterface $document = null, ?array $options = [] if ($this->throwExceptions) { throw new RuntimeError($embedException->getMessage()); } else { - return '

' . $embedException->getMessage() . '

'; + return '

'.$embedException->getMessage().'

'; } } catch (InvalidArgumentException $e) { throw new RuntimeError($e->getMessage(), -1, null, $e); @@ -140,11 +127,9 @@ public function display(DocumentInterface $document = null, ?array $options = [] * - Return `'landscape'` if width is higher or equal to height * - Return `'portrait'` if height is strictly lower to width * - * @param SizeableInterface |null $document - * @return null|string * @throws RuntimeError */ - public function getImageOrientation(SizeableInterface $document = null): ?string + public function getImageOrientation(?SizeableInterface $document = null): ?string { if (null === $document) { if ($this->throwExceptions) { @@ -154,15 +139,16 @@ public function getImageOrientation(SizeableInterface $document = null): ?string } } $size = $this->getImageSize($document); + return $size['width'] >= $size['height'] ? 'landscape' : 'portrait'; } /** - * @param SizeableInterface |null $document * @return array + * * @throws RuntimeError */ - public function getImageSize(SizeableInterface $document = null): array + public function getImageSize(?SizeableInterface $document = null): array { if (null === $document) { if ($this->throwExceptions) { @@ -174,6 +160,7 @@ public function getImageSize(SizeableInterface $document = null): array ]; } } + return [ 'width' => $document->getImageWidth(), 'height' => $document->getImageHeight(), @@ -181,11 +168,9 @@ public function getImageSize(SizeableInterface $document = null): array } /** - * @param SizeableInterface|null $document - * @return float * @throws RuntimeError */ - public function getImageRatio(SizeableInterface $document = null): float + public function getImageRatio(?SizeableInterface $document = null): float { if (null === $document) { if ($this->throwExceptions) { @@ -202,17 +187,13 @@ public function getImageRatio(SizeableInterface $document = null): float return 0.0; } - /** - * @param DocumentInterface|null $document - * @return null|string - */ - public function getPath(DocumentInterface $document = null): ?string + public function getPath(?DocumentInterface $document = null): ?string { if ( - null !== $document && - $document->isLocal() && - !$document->isPrivate() && - null !== $mountPath = $document->getMountPath() + null !== $document + && $document->isLocal() + && !$document->isPrivate() + && null !== $mountPath = $document->getMountPath() ) { return $this->documentsStorage->publicUrl($mountPath); } @@ -221,11 +202,9 @@ public function getPath(DocumentInterface $document = null): ?string } /** - * @param DocumentInterface|null $document - * @return bool * @throws FilesystemException */ - public function exists(DocumentInterface $document = null): bool + public function exists(?DocumentInterface $document = null): bool { if (null !== $document && $document->isLocal() && null !== $mountPath = $document->getMountPath()) { return $this->documentsStorage->fileExists($mountPath); diff --git a/lib/Documents/src/UrlGenerators/AbstractDocumentUrlGenerator.php b/lib/Documents/src/UrlGenerators/AbstractDocumentUrlGenerator.php index 2c05f7f6..21f11b48 100644 --- a/lib/Documents/src/UrlGenerators/AbstractDocumentUrlGenerator.php +++ b/lib/Documents/src/UrlGenerators/AbstractDocumentUrlGenerator.php @@ -23,7 +23,7 @@ public function __construct( protected FilesystemOperator $documentsStorage, protected UrlHelper $urlHelper, protected CacheItemPoolInterface $optionsCacheAdapter, - array $options = [] + array $options = [], ) { $this->viewOptionsResolver = new ViewOptionsResolver(); $this->optionCompiler = new OptionsCompiler(); @@ -31,8 +31,8 @@ public function __construct( } /** - * @param array $options * @return $this + * * @throws InvalidArgumentException */ public function setOptions(array $options = []): static @@ -50,22 +50,18 @@ public function setOptions(array $options = []): static return $this; } - /** - * @return DocumentInterface|null - */ public function getDocument(): ?DocumentInterface { return $this->document; } /** - * @param DocumentInterface $document - * * @return $this */ public function setDocument(DocumentInterface $document): static { $this->document = $document; + return $this; } @@ -80,7 +76,7 @@ public function getUrl(bool $absolute = false): string $mountPath = $this->document->getMountPath(); - if (null !== $mountPath && ($this->options['noProcess'] === true || !$this->document->isProcessable())) { + if (null !== $mountPath && (true === $this->options['noProcess'] || !$this->document->isProcessable())) { $publicUrl = $this->documentsStorage->publicUrl($mountPath); if ($absolute && \str_starts_with($publicUrl, '/')) { return $this->urlHelper->getAbsoluteUrl($publicUrl); @@ -92,9 +88,5 @@ public function getUrl(bool $absolute = false): string return $this->getProcessedDocumentUrlByArray($absolute); } - /** - * @param bool $absolute - * @return string - */ abstract protected function getProcessedDocumentUrlByArray(bool $absolute = false): string; } diff --git a/lib/Documents/src/UrlGenerators/DocumentUrlGeneratorInterface.php b/lib/Documents/src/UrlGenerators/DocumentUrlGeneratorInterface.php index 1e1dd5f3..612688e7 100644 --- a/lib/Documents/src/UrlGenerators/DocumentUrlGeneratorInterface.php +++ b/lib/Documents/src/UrlGenerators/DocumentUrlGeneratorInterface.php @@ -8,23 +8,14 @@ interface DocumentUrlGeneratorInterface { - /** - * @param bool $absolute - * - * @return string - */ public function getUrl(bool $absolute = false): string; /** - * @param DocumentInterface $document - * * @return $this */ public function setDocument(DocumentInterface $document): static; /** - * @param array $options - * * @return $this */ public function setOptions(array $options = []): static; diff --git a/lib/Documents/src/UrlGenerators/DummyDocumentUrlGenerator.php b/lib/Documents/src/UrlGenerators/DummyDocumentUrlGenerator.php index e896b61a..fb596dbd 100644 --- a/lib/Documents/src/UrlGenerators/DummyDocumentUrlGenerator.php +++ b/lib/Documents/src/UrlGenerators/DummyDocumentUrlGenerator.php @@ -20,30 +20,33 @@ public function getUrl(bool $absolute = false): string throw new \BadMethodCallException('noProcess option is not set'); } - if ($this->options['noProcess'] === true || !$this->document->isProcessable()) { - $path = '/files/' . $this->document->getRelativePath(); + if (true === $this->options['noProcess'] || !$this->document->isProcessable()) { + $path = '/files/'.$this->document->getRelativePath(); - return ($absolute) ? ('http://dummy.test' . $path) : ($path); + return ($absolute) ? ('http://dummy.test'.$path) : ($path); } $compiler = new OptionsCompiler(); $compiledOptions = $compiler->compile($this->options); if ($absolute) { - return 'http://dummy.test/assets/' . $compiledOptions . '/' . $this->document->getRelativePath(); + return 'http://dummy.test/assets/'.$compiledOptions.'/'.$this->document->getRelativePath(); } - return '/assets/' . $compiledOptions . '/' . $this->document->getRelativePath(); + + return '/assets/'.$compiledOptions.'/'.$this->document->getRelativePath(); } public function setDocument(DocumentInterface $document): static { $this->document = $document; + return $this; } public function setOptions(array $options = []): static { $this->options = $options; + return $this; } } diff --git a/lib/Documents/src/UrlGenerators/OptionsCompiler.php b/lib/Documents/src/UrlGenerators/OptionsCompiler.php index b1864091..cd02b66d 100644 --- a/lib/Documents/src/UrlGenerators/OptionsCompiler.php +++ b/lib/Documents/src/UrlGenerators/OptionsCompiler.php @@ -14,8 +14,7 @@ class OptionsCompiler /** * Compile Intervention Request options into a single query string. * - * @param array $options Resolved options - * @return string + * @param array $options Resolved options */ public function compile(array $options): string { @@ -27,40 +26,40 @@ public function compile(array $options): string $shortOptions = []; if (null === $this->options['fit'] && $this->options['width'] > 0) { - $shortOptions['w'] = 'w' . (int) $this->options['width']; + $shortOptions['w'] = 'w'.(int) $this->options['width']; } if (null === $this->options['fit'] && $this->options['height'] > 0) { - $shortOptions['h'] = 'h' . (int) $this->options['height']; + $shortOptions['h'] = 'h'.(int) $this->options['height']; } if (null !== $this->options['crop']) { - $shortOptions['c'] = 'c' . strip_tags($this->options['crop']); + $shortOptions['c'] = 'c'.strip_tags($this->options['crop']); } if ($this->options['blur'] > 0) { - $shortOptions['l'] = 'l' . ($this->options['blur']); + $shortOptions['l'] = 'l'.$this->options['blur']; } if (null !== $this->options['fit']) { - $shortOptions['f'] = 'f' . strip_tags($this->options['fit']); + $shortOptions['f'] = 'f'.strip_tags($this->options['fit']); } if (null !== $this->options['flip']) { - $shortOptions['m'] = 'm' . trim(strip_tags($this->options['flip'])); + $shortOptions['m'] = 'm'.trim(strip_tags($this->options['flip'])); } if ($this->options['rotate'] > 0) { - $shortOptions['r'] = 'r' . ($this->options['rotate']); + $shortOptions['r'] = 'r'.$this->options['rotate']; } if ($this->options['sharpen'] > 0) { - $shortOptions['s'] = 's' . ($this->options['sharpen']); + $shortOptions['s'] = 's'.$this->options['sharpen']; } if ($this->options['contrast'] > 0) { - $shortOptions['k'] = 'k' . ($this->options['contrast']); + $shortOptions['k'] = 'k'.$this->options['contrast']; } if ($this->options['grayscale']) { $shortOptions['g'] = 'g1'; } if ($this->options['quality'] > 0) { - $shortOptions['q'] = 'q' . $this->options['quality']; + $shortOptions['q'] = 'q'.$this->options['quality']; } if (null !== $this->options['background']) { - $shortOptions['b'] = 'b' . strip_tags($this->options['background']); + $shortOptions['b'] = 'b'.strip_tags($this->options['background']); } if ($this->options['progressive']) { $shortOptions['p'] = 'p1'; @@ -85,7 +84,7 @@ public function compile(array $options): string null !== $this->options['align'] && isset($availablePositionShort[$this->options['align']]) ) { - $shortOptions['a'] = 'a' . $availablePositionShort[$this->options['align']]; + $shortOptions['a'] = 'a'.$availablePositionShort[$this->options['align']]; } return implode('-', $shortOptions); diff --git a/lib/Documents/src/Viewers/SvgDocumentViewer.php b/lib/Documents/src/Viewers/SvgDocumentViewer.php index 15746a04..6545e8dc 100644 --- a/lib/Documents/src/Viewers/SvgDocumentViewer.php +++ b/lib/Documents/src/Viewers/SvgDocumentViewer.php @@ -29,18 +29,15 @@ class SvgDocumentViewer ]; /** - * @param FilesystemOperator $documentsStorage - * @param DocumentInterface $document - * @param array $attributes - * @param bool $asObject Default false - * @param string $imageUrl Only needed if you set $asObject to true. + * @param bool $asObject Default false + * @param string $imageUrl only needed if you set $asObject to true */ public function __construct( FilesystemOperator $documentsStorage, DocumentInterface $document, array $attributes = [], bool $asObject = false, - string $imageUrl = "" + string $imageUrl = '', ) { $this->imageUrl = $imageUrl; $this->attributes = $attributes; @@ -52,7 +49,6 @@ public function __construct( /** * Get SVG string to be used inside HTML content. * - * @return string * @throws FilesystemException */ public function getContent(): string @@ -64,26 +60,23 @@ public function getContent(): string } } - /** - * @return array - */ protected function getAllowedAttributes(): array { $attributes = []; foreach ($this->attributes as $key => $value) { if (in_array($key, static::$allowedAttributes)) { - if ($key === 'identifier') { + if ('identifier' === $key) { $attributes['id'] = $value; } else { $attributes[$key] = $value; } } } + return $attributes; } /** - * @return string * @throws FilesystemException */ protected function getInlineSvg(): string @@ -95,7 +88,7 @@ protected function getInlineSvg(): string } if (!$this->documentsStorage->fileExists($mountPath)) { - throw new FileNotFoundException('SVG file does not exist: ' . $mountPath); + throw new FileNotFoundException('SVG file does not exist: '.$mountPath); } // Create a new sanitizer instance $sanitizer = new Sanitizer(); @@ -111,12 +104,11 @@ protected function getInlineSvg(): string // Pass it to the sanitizer and get it back clean return $this->injectAttributes($cleanSVG); } + return $dirtySVG; } /** - * @param string $svg - * @return string * @throws \Exception */ protected function injectAttributes(string $svg): string @@ -155,8 +147,7 @@ protected function injectAttributes(string $svg): string } /** - * @return string - * @deprecated Use SvgRenderer to render HTML object. + * @deprecated use SvgRenderer to render HTML object */ protected function getObjectSvg(): string { @@ -176,9 +167,9 @@ protected function getObjectSvg(): string $attrs = []; foreach ($attributes as $key => $value) { - $attrs[] = $key . '="' . htmlspecialchars($value) . '"'; + $attrs[] = $key.'="'.htmlspecialchars($value).'"'; } - return ''; + return ''; } } diff --git a/lib/Documents/tests/MediaFinders/SimpleVimeoEmbedFinder.php b/lib/Documents/tests/MediaFinders/SimpleVimeoEmbedFinder.php index 050b3826..d2c87d1e 100644 --- a/lib/Documents/tests/MediaFinders/SimpleVimeoEmbedFinder.php +++ b/lib/Documents/tests/MediaFinders/SimpleVimeoEmbedFinder.php @@ -10,17 +10,11 @@ final class SimpleVimeoEmbedFinder extends AbstractVimeoEmbedFinder { - /** - * @inheritDoc - */ protected function documentExists(ObjectManager $objectManager, string $embedId, ?string $embedPlatform): bool { throw new \RuntimeException('Not implemented'); } - /** - * @inheritDoc - */ protected function injectMetaInDocument(ObjectManager $objectManager, DocumentInterface $document): DocumentInterface { throw new \RuntimeException('Not implemented'); diff --git a/lib/Documents/tests/MediaFinders/SimpleYoutubeEmbedFinder.php b/lib/Documents/tests/MediaFinders/SimpleYoutubeEmbedFinder.php index 571e158f..5c1fc0f3 100644 --- a/lib/Documents/tests/MediaFinders/SimpleYoutubeEmbedFinder.php +++ b/lib/Documents/tests/MediaFinders/SimpleYoutubeEmbedFinder.php @@ -10,17 +10,11 @@ final class SimpleYoutubeEmbedFinder extends AbstractYoutubeEmbedFinder { - /** - * @inheritDoc - */ protected function documentExists(ObjectManager $objectManager, string $embedId, ?string $embedPlatform): bool { throw new \RuntimeException('Not implemented'); } - /** - * @inheritDoc - */ protected function injectMetaInDocument(ObjectManager $objectManager, DocumentInterface $document): DocumentInterface { throw new \RuntimeException('Not implemented'); diff --git a/lib/Documents/tests/Renderer/AbstractRendererTestCase.php b/lib/Documents/tests/Renderer/AbstractRendererTestCase.php index 659fd719..e82c008c 100644 --- a/lib/Documents/tests/Renderer/AbstractRendererTestCase.php +++ b/lib/Documents/tests/Renderer/AbstractRendererTestCase.php @@ -24,8 +24,9 @@ abstract class AbstractRendererTestCase extends TestCase protected function htmlTidy(string $body): string { $body = preg_replace('#[\n\r\t\s]{2,}#', ' ', $body); - $body = str_replace("/", '/', $body); + $body = str_replace('/', '/', $body); $body = html_entity_decode($body); + return preg_replace('#\>[\n\r\t\s]+\<#', '><', $body); } @@ -38,43 +39,37 @@ protected function getFilesystemOperator(): FilesystemOperator { return new MountManager([ 'public' => new Filesystem( - new LocalFilesystemAdapter(dirname(__DIR__) . '/../files/'), - publicUrlGenerator: new class () implements PublicUrlGenerator - { + new LocalFilesystemAdapter(dirname(__DIR__).'/../files/'), + publicUrlGenerator: new class implements PublicUrlGenerator { public function publicUrl(string $path, Config $config): string { - return '/files/' . $path; + return '/files/'.$path; } } ), 'private' => new Filesystem( - new LocalFilesystemAdapter(dirname(__DIR__) . '/../files/'), - publicUrlGenerator: new class () implements PublicUrlGenerator - { + new LocalFilesystemAdapter(dirname(__DIR__).'/../files/'), + publicUrlGenerator: new class implements PublicUrlGenerator { public function publicUrl(string $path, Config $config): string { - return '/files/' . $path; + return '/files/'.$path; } } - ) + ), ]); } protected function getEnvironment(): Environment { $loader = new FilesystemLoader([ - dirname(__DIR__) . '/../src/Resources/views' + dirname(__DIR__).'/../src/Resources/views', ]); + return new Environment($loader, [ - 'autoescape' => false + 'autoescape' => false, ]); } - - - /** - * @return EmbedFinderFactory - */ protected function getEmbedFinderFactory(): EmbedFinderFactory { return new EmbedFinderFactory([ diff --git a/lib/Documents/tests/Renderer/AudioRendererTest.php b/lib/Documents/tests/Renderer/AudioRendererTest.php index e97a7013..55b8f663 100644 --- a/lib/Documents/tests/Renderer/AudioRendererTest.php +++ b/lib/Documents/tests/Renderer/AudioRendererTest.php @@ -61,56 +61,49 @@ public function testRender(): void $mockDocument2->setFolder('folder'); $mockDocument2->setMimeType('audio/mpeg'); - $renderer = $this->getRenderer(); - $this->assertHtmlTidyEquals((<<assertHtmlTidyEquals(<<

Your browser does not support native audio.

EOT - ), ($renderer->render($mockDocument, []))); - + , $renderer->render($mockDocument, [])); - $this->assertHtmlTidyEquals((<<assertHtmlTidyEquals(<<

Your browser does not support native audio.

EOT - ), ($renderer->render($mockDocument2, []))); + , $renderer->render($mockDocument2, [])); - - $this->assertHtmlTidyEquals((<<assertHtmlTidyEquals(<<

Your browser does not support native audio.

EOT - ), ($renderer->render($mockDocument, [ - 'controls' => true, - 'loop' => true, - 'autoplay' => true, - ]))); - + , $renderer->render($mockDocument, [ + 'controls' => true, + 'loop' => true, + 'autoplay' => true, + ])); - $this->assertHtmlTidyEquals((<<assertHtmlTidyEquals(<<

Your browser does not support native audio.

EOT - ), ($renderer->render($mockDocument, [ - 'controls' => false - ]))); + , $renderer->render($mockDocument, [ + 'controls' => false, + ])); } - /** - * @return DocumentFinderInterface - */ private function getDocumentFinder(): DocumentFinderInterface { $finder = new ArrayDocumentFinder(); diff --git a/lib/Documents/tests/Renderer/ChainRendererTest.php b/lib/Documents/tests/Renderer/ChainRendererTest.php index 5fb5eac8..941b1d9f 100644 --- a/lib/Documents/tests/Renderer/ChainRendererTest.php +++ b/lib/Documents/tests/Renderer/ChainRendererTest.php @@ -48,57 +48,57 @@ public function testRender(): void $this->assertHtmlTidyEquals( '

Your browser does not support PDF native viewer.

', - ($renderer->render($mockPdfDocument, [ - 'embed' => true - ])) + $renderer->render($mockPdfDocument, [ + 'embed' => true, + ]) ); $this->assertHtmlTidyEquals( '

Your browser does not support PDF native viewer.

', - ($renderer->render($mockPdfDocument, ['absolute' => true, 'embed' => true])) + $renderer->render($mockPdfDocument, ['absolute' => true, 'embed' => true]) ); $this->assertHtmlTidyEquals( '', - ($renderer->render($mockSvgDocument, [])) + $renderer->render($mockSvgDocument, []) ); $this->assertHtmlTidyEquals( - (<< EOT - ), - ($renderer->render($mockSvgDocument, ['inline' => true])) + , + $renderer->render($mockSvgDocument, ['inline' => true]) ); $this->assertIsBool($mockDocumentYoutube->isEmbed()); $this->assertTrue($mockDocumentYoutube->isEmbed()); $this->assertHtmlTidyEquals( - (<< EOT - ), - ($renderer->render($mockDocumentYoutube, ['embed' => true])) + , + $renderer->render($mockDocumentYoutube, ['embed' => true]) ); $this->assertHtmlTidyEquals( - (<< file.jpg EOT - ), - ($renderer->render($mockPictureDocument, [ + , + $renderer->render($mockPictureDocument, [ 'width' => 300, - 'picture' => true - ])) + 'picture' => true, + ]) ); } } diff --git a/lib/Documents/tests/Renderer/EmbedRendererTest.php b/lib/Documents/tests/Renderer/EmbedRendererTest.php index 60b6e184..b332af8a 100644 --- a/lib/Documents/tests/Renderer/EmbedRendererTest.php +++ b/lib/Documents/tests/Renderer/EmbedRendererTest.php @@ -65,91 +65,90 @@ public function testRender(): void $this->assertTrue($mockDocumentYoutube->isEmbed()); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentYoutube, ['embed' => true]) ); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentYoutube, [ 'embed' => true, - 'loading' => 'lazy' + 'loading' => 'lazy', ]) ); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentYoutube, [ 'embed' => true, - 'width' => 500 + 'width' => 500, // height is auto calculated based on 16/10 ratio ]) ); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentYoutube, [ 'embed' => true, 'width' => 500, - 'height' => 500 + 'height' => 500, ]) ); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentYoutube, [ 'embed' => true, 'autoplay' => true, ]) ); - $this->assertIsBool($mockDocumentVimeo->isEmbed()); $this->assertTrue($mockDocumentVimeo->isEmbed()); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentVimeo, ['embed' => true]) ); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentVimeo, [ 'embed' => true, 'autoplay' => true, @@ -158,16 +157,16 @@ public function testRender(): void ); $this->assertHtmlTidyEquals( - (<< EOT - ), + , $renderer->render($mockDocumentVimeo, [ 'embed' => true, 'autoplay' => true, - 'background' => "1", // Hack background conflict option with background color + 'background' => '1', // Hack background conflict option with background color ]) ); } diff --git a/lib/Documents/tests/Renderer/ImageRendererTest.php b/lib/Documents/tests/Renderer/ImageRendererTest.php index a0be9914..7d70def5 100644 --- a/lib/Documents/tests/Renderer/ImageRendererTest.php +++ b/lib/Documents/tests/Renderer/ImageRendererTest.php @@ -82,7 +82,7 @@ public function testRender(): void EOT, $renderer->render($mockDocument, [ 'width' => 300, - 'absolute' => true + 'absolute' => true, ]) ); @@ -96,7 +96,7 @@ class="awesome-image responsive" /> $renderer->render($mockDocument, [ 'width' => 300, 'class' => 'awesome-image responsive', - 'absolute' => true + 'absolute' => true, ]) ); @@ -115,7 +115,7 @@ class="lazyload" /> EOT, $renderer->render($mockDocument, [ 'width' => 300, - 'lazyload' => true + 'lazyload' => true, ]) ); @@ -135,7 +135,7 @@ class="lazyload" /> $renderer->render($mockDocument, [ 'width' => 300, 'lazyload' => true, - 'fallback' => 'https://test.test/fallback.png' + 'fallback' => 'https://test.test/fallback.png', ]) ); @@ -147,7 +147,7 @@ class="lazyload" /> EOT, $renderer->render($mockDocument, [ 'width' => 300, - 'fallback' => 'https://test.test/fallback.png' + 'fallback' => 'https://test.test/fallback.png', ]) ); @@ -161,7 +161,7 @@ class="lazyload" /> EOT, $renderer->render($mockDocument, [ 'fit' => '600x400', - 'quality' => 70 + 'quality' => 70, ]) ); @@ -197,15 +197,15 @@ class="awesome-image responsive" /> 'width' => 300, 'srcset' => [[ 'format' => [ - 'width' => 300 + 'width' => 300, ], - 'rule' => '1x' - ],[ + 'rule' => '1x', + ], [ 'format' => [ - 'width' => 600 + 'width' => 600, ], - 'rule' => '2x' - ]] + 'rule' => '2x', + ]], ]) ); @@ -220,19 +220,19 @@ class="awesome-image responsive" /> 'width' => 300, 'srcset' => [[ 'format' => [ - 'width' => 300 + 'width' => 300, ], - 'rule' => '1x' - ],[ + 'rule' => '1x', + ], [ 'format' => [ - 'width' => 600 + 'width' => 600, ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' - ] + '(min-width: 768px) 400px', + ], ]) ); @@ -250,17 +250,17 @@ class="awesome-image responsive" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' - ],[ + 'rule' => '1x', + ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' - ] + '(min-width: 768px) 400px', + ], ]) ); @@ -280,17 +280,17 @@ class="awesome-image responsive" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' - ],[ + 'rule' => '1x', + ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' - ] + '(min-width: 768px) 400px', + ], ]) ); @@ -318,17 +318,17 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' - ],[ + 'rule' => '1x', + ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' - ] + '(min-width: 768px) 400px', + ], ]) ); @@ -359,17 +359,17 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' - ],[ + 'rule' => '1x', + ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' - ] + '(min-width: 768px) 400px', + ], ]) ); } diff --git a/lib/Documents/tests/Renderer/PdfRendererTest.php b/lib/Documents/tests/Renderer/PdfRendererTest.php index 931a04c0..10da4c28 100644 --- a/lib/Documents/tests/Renderer/PdfRendererTest.php +++ b/lib/Documents/tests/Renderer/PdfRendererTest.php @@ -17,6 +17,7 @@ protected function getRenderer(): PdfRenderer $this->getUrlGenerator() ); } + public function testSupports(): void { $mockValidDocument = new SimpleDocument(); @@ -35,7 +36,7 @@ public function testSupports(): void ); $this->assertTrue( $renderer->supports($mockValidDocument, [ - 'embed' => true + 'embed' => true, ]) ); @@ -64,7 +65,7 @@ public function testRender(): void $this->assertHtmlTidyEquals( '

Your browser does not support PDF native viewer.

', $renderer->render($mockDocument, [ - 'embed' => true + 'embed' => true, ]) ); } diff --git a/lib/Documents/tests/Renderer/PictureRendererTest.php b/lib/Documents/tests/Renderer/PictureRendererTest.php index 829ce0ee..829e0874 100644 --- a/lib/Documents/tests/Renderer/PictureRendererTest.php +++ b/lib/Documents/tests/Renderer/PictureRendererTest.php @@ -133,7 +133,7 @@ public function testRender(): void , $renderer->render($mockDocument, [ 'noProcess' => true, - 'picture' => true + 'picture' => true, ]) ); @@ -163,7 +163,7 @@ public function testRender(): void , $renderer->render($mockWebpDocument, [ 'noProcess' => true, - 'picture' => true + 'picture' => true, ]) ); @@ -179,7 +179,7 @@ public function testRender(): void $renderer->render($mockDocument, [ 'absolute' => true, 'noProcess' => true, - 'picture' => true + 'picture' => true, ]) ); @@ -187,7 +187,7 @@ public function testRender(): void $renderer->render($mockDocument, [ 'width' => 300, 'absolute' => true, - 'picture' => true + 'picture' => true, ]), << @@ -203,7 +203,7 @@ public function testRender(): void 'width' => 300, 'class' => 'awesome-image responsive', 'absolute' => true, - 'picture' => true + 'picture' => true, ]), << @@ -218,7 +218,7 @@ public function testRender(): void $renderer->render($mockDocument, [ 'width' => 300, 'lazyload' => true, - 'picture' => true + 'picture' => true, ]), << @@ -253,7 +253,7 @@ class="lazyload" /> 'width' => 300, 'lazyload' => true, 'picture' => true, - 'fallback' => 'https://test.test/fallback.png' + 'fallback' => 'https://test.test/fallback.png', ]), << @@ -280,7 +280,7 @@ class="lazyload" /> $renderer->render($mockDocument, [ 'width' => 300, 'fallback' => 'https://test.test/fallback.png', - 'picture' => true + 'picture' => true, ]), << @@ -297,7 +297,7 @@ class="lazyload" /> 'width' => 300, 'lazyload' => true, 'class' => 'awesome-image responsive', - 'picture' => true + 'picture' => true, ]), << @@ -332,16 +332,16 @@ class="awesome-image responsive" /> 'width' => 300, 'srcset' => [[ 'format' => [ - 'width' => 300 + 'width' => 300, ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ - 'width' => 600 + 'width' => 600, ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'picture' => true + 'picture' => true, ]), << @@ -361,20 +361,20 @@ class="awesome-image responsive" /> 'width' => 300, 'srcset' => [[ 'format' => [ - 'width' => 300 + 'width' => 300, ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ - 'width' => 600 + 'width' => 600, ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' + '(min-width: 768px) 400px', ], - 'picture' => true + 'picture' => true, ]), << @@ -398,18 +398,18 @@ class="awesome-image responsive" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' + '(min-width: 768px) 400px', ], - 'picture' => true + 'picture' => true, ]), << @@ -436,18 +436,18 @@ class="awesome-image responsive" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], 'sizes' => [ '(max-width: 767px) 300px', - '(min-width: 768px) 400px' + '(min-width: 768px) 400px', ], - 'picture' => true + 'picture' => true, ]), << @@ -474,14 +474,14 @@ class="awesome-image responsive" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'picture' => true + 'picture' => true, ]), << @@ -525,14 +525,14 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'picture' => true + 'picture' => true, ]), << @@ -576,16 +576,16 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 600px)' + 'rule' => '(min-width: 600px)', ]], - 'picture' => true + 'picture' => true, ]), << @@ -612,29 +612,29 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 600px)' + 'rule' => '(min-width: 600px)', ], [ 'srcset' => [[ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '2400x1600', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 1200px)' + 'rule' => '(min-width: 1200px)', ]], - 'picture' => true + 'picture' => true, ]), << @@ -670,29 +670,29 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 600px)' + 'rule' => '(min-width: 600px)', ], [ 'srcset' => [[ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '2400x1600', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 1200px)' + 'rule' => '(min-width: 1200px)', ]], - 'picture' => true + 'picture' => true, ]), << @@ -729,29 +729,29 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 600px)' + 'rule' => '(min-width: 600px)', ], [ 'srcset' => [[ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '2400x1600', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 1200px)' + 'rule' => '(min-width: 1200px)', ]], - 'picture' => true + 'picture' => true, ]), << @@ -803,29 +803,29 @@ class="lazyload" /> 'format' => [ 'fit' => '600x400', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 600px)' + 'rule' => '(min-width: 600px)', ], [ 'srcset' => [[ 'format' => [ 'fit' => '1200x800', ], - 'rule' => '1x' + 'rule' => '1x', ], [ 'format' => [ 'fit' => '2400x1600', ], - 'rule' => '2x' + 'rule' => '2x', ]], - 'rule' => '(min-width: 1200px)' + 'rule' => '(min-width: 1200px)', ]], - 'picture' => true + 'picture' => true, ]), << diff --git a/lib/Documents/tests/Renderer/VideoRendererTest.php b/lib/Documents/tests/Renderer/VideoRendererTest.php index e311a4e7..7d80fe08 100644 --- a/lib/Documents/tests/Renderer/VideoRendererTest.php +++ b/lib/Documents/tests/Renderer/VideoRendererTest.php @@ -134,14 +134,11 @@ public function testRender(): void EOT , $renderer->render($mockDocument, [ - 'controls' => false + 'controls' => false, ]) ); } - /** - * @return DocumentFinderInterface - */ private function getDocumentFinder(): DocumentFinderInterface { $finder = new ArrayDocumentFinder(); diff --git a/lib/DtsGenerator/src/DeclarationGeneratorFactory.php b/lib/DtsGenerator/src/DeclarationGeneratorFactory.php index 2e5095e4..318706b1 100644 --- a/lib/DtsGenerator/src/DeclarationGeneratorFactory.php +++ b/lib/DtsGenerator/src/DeclarationGeneratorFactory.php @@ -21,9 +21,6 @@ public function __construct(private readonly ParameterBag $nodeTypesBag) { } - /** - * @return ParameterBag - */ public function getNodeTypesBag(): ParameterBag { return $this->nodeTypesBag; @@ -34,11 +31,6 @@ public function getHumanBool(bool $bool): string return $bool ? 'true' : 'false'; } - /** - * @param NodeTypeInterface $nodeType - * - * @return NodeTypeGenerator - */ public function createForNodeType(NodeTypeInterface $nodeType): NodeTypeGenerator { return new NodeTypeGenerator( @@ -47,11 +39,6 @@ public function createForNodeType(NodeTypeInterface $nodeType): NodeTypeGenerato ); } - /** - * @param NodeTypeFieldInterface $field - * - * @return AbstractFieldGenerator - */ public function createForNodeTypeField(NodeTypeFieldInterface $field): AbstractFieldGenerator { return match (true) { diff --git a/lib/DtsGenerator/src/Generators/AbstractFieldGenerator.php b/lib/DtsGenerator/src/Generators/AbstractFieldGenerator.php index f4c2ed54..e5bdb56b 100644 --- a/lib/DtsGenerator/src/Generators/AbstractFieldGenerator.php +++ b/lib/DtsGenerator/src/Generators/AbstractFieldGenerator.php @@ -15,13 +15,9 @@ abstract class AbstractFieldGenerator protected NodeTypeFieldInterface $field; protected ParameterBag $nodeTypesBag; - /** - * @param NodeTypeFieldInterface $field - * @param ParameterBag $nodeTypesBag - */ public function __construct( NodeTypeFieldInterface $field, - ParameterBag $nodeTypesBag + ParameterBag $nodeTypesBag, ) { $this->field = $field; $this->nodeTypesBag = $nodeTypesBag; @@ -36,18 +32,18 @@ abstract protected function getType(): string; private function getDeclaration(): string { - return static::INDENTATION_MARK . - $this->field->getVarName() . - $this->getNullableAssertion() . ': ' . + return static::INDENTATION_MARK. + $this->field->getVarName(). + $this->getNullableAssertion().': '. $this->getType(); } public function getContents(): string { return implode(PHP_EOL, [ - $this->getIntroduction(), - $this->getDeclaration() - ]); + $this->getIntroduction(), + $this->getDeclaration(), + ]); } protected function getIntroductionLines(): array @@ -60,19 +56,16 @@ protected function getIntroductionLines(): array } if (!empty($this->field->getGroupName())) { - $lines[] = 'Group: ' . $this->field->getGroupName(); + $lines[] = 'Group: '.$this->field->getGroupName(); } return $lines; } - /** - * @return string - */ public function getIntroduction(): string { return implode(PHP_EOL, array_map(function (string $line) { - return static::INDENTATION_MARK . '// ' . $line; + return static::INDENTATION_MARK.'// '.$line; }, $this->getIntroductionLines())); } } diff --git a/lib/DtsGenerator/src/Generators/ChildrenNodeFieldGenerator.php b/lib/DtsGenerator/src/Generators/ChildrenNodeFieldGenerator.php index eb499d26..5042e2dc 100644 --- a/lib/DtsGenerator/src/Generators/ChildrenNodeFieldGenerator.php +++ b/lib/DtsGenerator/src/Generators/ChildrenNodeFieldGenerator.php @@ -12,14 +12,16 @@ public function getContents(): string $this->getIntroduction(), ]); } + protected function getIntroductionLines(): array { $lines = [ - 'This node-type uses "blocks" which are available through parent RoadizNodesSources.blocks' + 'This node-type uses "blocks" which are available through parent RoadizNodesSources.blocks', ]; if (!empty($this->field->getDefaultValues())) { - $lines[] = 'Possible block node-types: ' . $this->field->getDefaultValues(); + $lines[] = 'Possible block node-types: '.$this->field->getDefaultValues(); } + return $lines; } diff --git a/lib/DtsGenerator/src/Generators/DeclarationGenerator.php b/lib/DtsGenerator/src/Generators/DeclarationGenerator.php index 7e625772..713731a0 100644 --- a/lib/DtsGenerator/src/Generators/DeclarationGenerator.php +++ b/lib/DtsGenerator/src/Generators/DeclarationGenerator.php @@ -15,12 +15,11 @@ final class DeclarationGenerator private array $nodeTypes; /** - * @param DeclarationGeneratorFactory $generatorFactory * @param NodeTypeInterface[] $nodeTypes */ public function __construct( private readonly DeclarationGeneratorFactory $generatorFactory, - array $nodeTypes = [] + array $nodeTypes = [], ) { if (empty($nodeTypes)) { $this->nodeTypes = array_unique($this->generatorFactory->getNodeTypesBag()->all()); @@ -41,7 +40,7 @@ public function getContents(): string $blocks[] = $this->getAllTypesInterface(); - return implode(PHP_EOL . PHP_EOL, $blocks); + return implode(PHP_EOL.PHP_EOL, $blocks); } private function getAllTypesInterface(): string diff --git a/lib/DtsGenerator/src/Generators/EnumFieldGenerator.php b/lib/DtsGenerator/src/Generators/EnumFieldGenerator.php index ad89244f..540532de 100644 --- a/lib/DtsGenerator/src/Generators/EnumFieldGenerator.php +++ b/lib/DtsGenerator/src/Generators/EnumFieldGenerator.php @@ -19,11 +19,13 @@ protected function getType(): string ); if (count($defaultValues) > 0) { $defaultValues = array_map(function (string $value) { - return '\'' . $value . '\''; + return '\''.$value.'\''; }, $defaultValues); - return implode(' | ', $defaultValues) . ' | null'; + + return implode(' | ', $defaultValues).' | null'; } } + return 'string'; case $this->field->isMultiple(): return 'Array'; @@ -36,8 +38,9 @@ protected function getIntroductionLines(): array { $lines = parent::getIntroductionLines(); if (!empty($this->field->getDefaultValues())) { - $lines[] = 'Possible values: ' . $this->field->getDefaultValues(); + $lines[] = 'Possible values: '.$this->field->getDefaultValues(); } + return $lines; } } diff --git a/lib/DtsGenerator/src/Generators/NodeReferencesFieldGenerator.php b/lib/DtsGenerator/src/Generators/NodeReferencesFieldGenerator.php index 38332fe5..e61a606a 100644 --- a/lib/DtsGenerator/src/Generators/NodeReferencesFieldGenerator.php +++ b/lib/DtsGenerator/src/Generators/NodeReferencesFieldGenerator.php @@ -15,7 +15,7 @@ protected function getNullableAssertion(): string protected function getType(): string { - return 'Array<' . $this->getUnionType() . '>'; + return 'Array<'.$this->getUnionType().'>'; } /** @@ -27,8 +27,10 @@ private function getLinkedNodeTypes(): array return []; } $nodeTypeNames = explode(',', $this->field->getDefaultValues()); + return array_values(array_filter(array_map(function (string $name) { $nodeType = $this->nodeTypesBag->get(trim($name)); + return $nodeType instanceof NodeTypeInterface ? $nodeType : null; }, $nodeTypeNames))); } @@ -50,8 +52,9 @@ protected function getIntroductionLines(): array { $lines = parent::getIntroductionLines(); if (!empty($this->field->getDefaultValues())) { - $lines[] = 'Possible values: ' . $this->field->getDefaultValues(); + $lines[] = 'Possible values: '.$this->field->getDefaultValues(); } + return $lines; } } diff --git a/lib/DtsGenerator/src/Generators/NodeTypeGenerator.php b/lib/DtsGenerator/src/Generators/NodeTypeGenerator.php index 7584e7da..4c2b2053 100644 --- a/lib/DtsGenerator/src/Generators/NodeTypeGenerator.php +++ b/lib/DtsGenerator/src/Generators/NodeTypeGenerator.php @@ -18,7 +18,7 @@ final class NodeTypeGenerator public function __construct( private readonly NodeTypeInterface $nodeType, - private readonly DeclarationGeneratorFactory $generatorFactory + private readonly DeclarationGeneratorFactory $generatorFactory, ) { $this->fieldGenerators = []; @@ -47,16 +47,16 @@ public function getContents(): string */ return implode(PHP_EOL, [ $this->getIntroduction(), - $this->getInterfaceBody() + $this->getInterfaceBody(), ]); } protected function getInterfaceBody(): string { $lines = [ - 'export interface ' . $this->nodeType->getSourceEntityClassName() . ' extends RoadizNodesSources {', + 'export interface '.$this->nodeType->getSourceEntityClassName().' extends RoadizNodesSources {', $this->getFieldsContents(), - '}' + '}', ]; return implode(PHP_EOL, $lines); @@ -67,18 +67,18 @@ protected function getIntroduction(): string $lines = [ '', $this->nodeType->getLabel(), - '' + '', ]; if (!empty($this->nodeType->getDescription())) { $lines[] = $this->nodeType->getDescription(); } - $lines[] = 'Reachable: ' . $this->generatorFactory->getHumanBool($this->nodeType->isReachable()); - $lines[] = 'Publishable: ' . $this->generatorFactory->getHumanBool($this->nodeType->isPublishable()); - $lines[] = 'Visible: ' . $this->generatorFactory->getHumanBool($this->nodeType->isVisible()); + $lines[] = 'Reachable: '.$this->generatorFactory->getHumanBool($this->nodeType->isReachable()); + $lines[] = 'Publishable: '.$this->generatorFactory->getHumanBool($this->nodeType->isPublishable()); + $lines[] = 'Visible: '.$this->generatorFactory->getHumanBool($this->nodeType->isVisible()); return implode(PHP_EOL, array_map(function (string $line) { - return '// ' . $line; + return '// '.$line; }, $lines)); } diff --git a/lib/EntityGenerator/src/EntityGenerator.php b/lib/EntityGenerator/src/EntityGenerator.php index 26810696..1be938e1 100644 --- a/lib/EntityGenerator/src/EntityGenerator.php +++ b/lib/EntityGenerator/src/EntityGenerator.php @@ -39,7 +39,7 @@ public function __construct( private readonly NodeTypeInterface $nodeType, private readonly NodeTypeResolverInterface $nodeTypeResolver, private readonly DefaultValuesResolverInterface $defaultValuesResolver, - array $options = [] + array $options = [], ) { $resolver = new OptionsResolver(); $this->configureOptions($resolver); @@ -53,9 +53,6 @@ public function __construct( $this->fieldGenerators = array_filter($this->fieldGenerators); } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -73,7 +70,7 @@ public function configureOptions(OptionsResolver $resolver): void 'repository_class', 'namespace', 'use_native_json', - 'use_api_platform_filters' + 'use_api_platform_filters', ]); $resolver->setAllowedTypes('parent_class', 'string'); $resolver->setAllowedTypes('node_class', 'string'); @@ -90,7 +87,7 @@ public function configureOptions(OptionsResolver $resolver): void $normalizeClassName = function (OptionsResolver $resolver, string $className) { return (new UnicodeString($className))->startsWith('\\') ? $className : - '\\' . $className; + '\\'.$className; }; $resolver->setNormalizer('parent_class', $normalizeClassName); @@ -104,10 +101,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setNormalizer('namespace', $normalizeClassName); } - /** - * @param NodeTypeFieldInterface $field - * @return AbstractFieldGenerator|null - */ private function getFieldGenerator(NodeTypeFieldInterface $field): ?AbstractFieldGenerator { if ($field->isYaml()) { @@ -128,9 +121,9 @@ private function getFieldGenerator(NodeTypeFieldInterface $field): ?AbstractFiel if ($field->isManyToMany()) { $configuration = Yaml::parse($field->getDefaultValues() ?? ''); if ( - is_array($configuration) && - isset($configuration['proxy']) && - !empty($configuration['proxy']['classname']) + is_array($configuration) + && isset($configuration['proxy']) + && !empty($configuration['proxy']['classname']) ) { /* * Manually create a Many-to-Many relation using a proxy class @@ -138,6 +131,7 @@ private function getFieldGenerator(NodeTypeFieldInterface $field): ?AbstractFiel */ return new ProxiedManyToManyFieldGenerator($field, $this->defaultValuesResolver, $this->options); } + return new ManyToManyFieldGenerator($field, $this->defaultValuesResolver, $this->options); } if ($field->isNodes()) { @@ -150,9 +144,6 @@ private function getFieldGenerator(NodeTypeFieldInterface $field): ?AbstractFiel return null; } - /** - * @return string - */ public function getClassContent(): string { $file = new PhpFile(); @@ -179,7 +170,7 @@ public function getClassContent(): string $classType = $namespace->addClass($this->nodeType->getSourceEntityClassName()) ->setExtends($this->options['parent_class']) - ->addComment($this->nodeType->getName() . ' node-source entity.') + ->addComment($this->nodeType->getName().' node-source entity.') ->addComment($this->nodeType->getDescription() ?? ''); $this @@ -189,6 +180,7 @@ public function getClassContent(): string ->addClassCloneMethod($classType) ->addClassMethods($classType) ; + return (new PsrPrinter())->printFile($file); } @@ -201,7 +193,7 @@ private function addClassAttributes(ClassType $classType, PhpNamespace $namespac ) ->addAttribute( 'Doctrine\ORM\Mapping\Entity', - ['repositoryClass' => new Literal($namespace->simplifyName($this->options['repository_class']) . '::class')] + ['repositoryClass' => new Literal($namespace->simplifyName($this->options['repository_class']).'::class')] ) ->addAttribute( 'Doctrine\ORM\Mapping\Table', @@ -213,26 +205,25 @@ private function addClassAttributes(ClassType $classType, PhpNamespace $namespac $fieldGenerator->addFieldIndex($classType); } - if ($this->options['use_api_platform_filters'] === true) { + if (true === $this->options['use_api_platform_filters']) { $classType->addAttribute( 'ApiPlatform\Metadata\ApiFilter', - [new Literal($namespace->simplifyName('\ApiPlatform\Serializer\Filter\PropertyFilter') . '::class')] + [new Literal($namespace->simplifyName('\ApiPlatform\Serializer\Filter\PropertyFilter').'::class')] ); } return $this; } - private function addClassFields(ClassType $classType, PhpNamespace $namespace): self { foreach ($this->fieldGenerators as $fieldGenerator) { $fieldGenerator->addField($classType, $namespace); } + return $this; } - private function addClassCloneMethod(ClassType $classType): self { $cloneStatements = []; @@ -242,7 +233,7 @@ private function addClassCloneMethod(ClassType $classType): self } $cloneStatements = array_filter($cloneStatements); - if (count($cloneStatements) === 0) { + if (0 === count($cloneStatements)) { return $this; } @@ -293,9 +284,9 @@ private function addClassMethods(ClassType $classType): self ->addAttribute('JMS\Serializer\Annotation\SerializedName', ['@type']) ->addAttribute('Symfony\Component\Serializer\Attribute\Groups', [['nodes_sources', 'nodes_sources_default']]) ->addAttribute('Symfony\Component\Serializer\Attribute\SerializedName', [ - 'serializedName' => '@type' + 'serializedName' => '@type', ]) - ->setBody('return \'' . $this->nodeType->getName() . '\';') + ->setBody('return \''.$this->nodeType->getName().'\';') ; $classType->addMethod('isReachable') @@ -303,7 +294,7 @@ private function addClassMethods(ClassType $classType): self ->addComment('@return bool Does this nodeSource is reachable over network?') ->setReturnType('bool') ->addAttribute('JMS\Serializer\Annotation\VirtualProperty') - ->setBody('return ' . ($this->nodeType->isReachable() ? 'true' : 'false') . ';') + ->setBody('return '.($this->nodeType->isReachable() ? 'true' : 'false').';') ; $classType->addMethod('isPublishable') @@ -311,12 +302,12 @@ private function addClassMethods(ClassType $classType): self ->addComment('@return bool Does this nodeSource is publishable with date and time?') ->setReturnType('bool') ->addAttribute('JMS\Serializer\Annotation\VirtualProperty') - ->setBody('return ' . ($this->nodeType->isPublishable() ? 'true' : 'false') . ';') + ->setBody('return '.($this->nodeType->isPublishable() ? 'true' : 'false').';') ; $classType->addMethod('__toString') ->setReturnType('string') - ->setBody('return \'[' . $this->nodeType->getSourceEntityClassName() . '] \' . parent::__toString();') + ->setBody('return \'['.$this->nodeType->getSourceEntityClassName().'] \' . parent::__toString();') ; return $this; diff --git a/lib/EntityGenerator/src/EntityGeneratorFactory.php b/lib/EntityGenerator/src/EntityGeneratorFactory.php index da1facae..a5be0936 100644 --- a/lib/EntityGenerator/src/EntityGeneratorFactory.php +++ b/lib/EntityGenerator/src/EntityGeneratorFactory.php @@ -13,7 +13,7 @@ public function __construct( private NodeTypeResolverInterface $nodeTypeResolverBag, private DefaultValuesResolverInterface $defaultValuesResolver, - private array $options + private array $options, ) { } @@ -26,9 +26,9 @@ public function createWithCustomRepository(NodeTypeInterface $nodeType): EntityG { $options = $this->options; $options['repository_class'] = - $options['namespace'] . - '\\Repository\\' . - $nodeType->getSourceEntityClassName() . 'Repository'; + $options['namespace']. + '\\Repository\\'. + $nodeType->getSourceEntityClassName().'Repository'; return new EntityGenerator($nodeType, $this->nodeTypeResolverBag, $this->defaultValuesResolver, $options); } @@ -39,8 +39,8 @@ public function createCustomRepository(NodeTypeInterface $nodeType): RepositoryG 'entity_namespace' => $this->options['namespace'], 'parent_class' => 'RZ\Roadiz\CoreBundle\Repository\NodesSourcesRepository', ]; - $options['namespace'] = $this->options['namespace'] . '\\Repository'; - $options['class_name'] = $nodeType->getSourceEntityClassName() . 'Repository'; + $options['namespace'] = $this->options['namespace'].'\\Repository'; + $options['class_name'] = $nodeType->getSourceEntityClassName().'Repository'; return new RepositoryGenerator($nodeType, $options); } diff --git a/lib/EntityGenerator/src/Field/AbstractConfigurableFieldGenerator.php b/lib/EntityGenerator/src/Field/AbstractConfigurableFieldGenerator.php index 12b20d2e..032ce88e 100644 --- a/lib/EntityGenerator/src/Field/AbstractConfigurableFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/AbstractConfigurableFieldGenerator.php @@ -14,27 +14,25 @@ abstract class AbstractConfigurableFieldGenerator extends AbstractFieldGenerator public function __construct( NodeTypeFieldInterface $field, DefaultValuesResolverInterface $defaultValuesResolver, - array $options = [] + array $options = [], ) { parent::__construct($field, $defaultValuesResolver, $options); if (empty($this->field->getDefaultValues())) { - throw new \LogicException('Default values must be a valid YAML for ' . static::class); + throw new \LogicException('Default values must be a valid YAML for '.static::class); } $conf = Yaml::parse($this->field->getDefaultValues()); if (!is_array($conf)) { - throw new \LogicException('YAML for ' . static::class . ' must be an associative array'); + throw new \LogicException('YAML for '.static::class.' must be an associative array'); } $this->configuration = $conf; } /** * Ensure configured classname has a starting backslash. - * - * @return string */ protected function getFullyQualifiedClassName(): string { - return '\\' . trim($this->configuration['classname'], '\\'); + return '\\'.trim($this->configuration['classname'], '\\'); } } diff --git a/lib/EntityGenerator/src/Field/AbstractFieldGenerator.php b/lib/EntityGenerator/src/Field/AbstractFieldGenerator.php index 18c6f4ec..c27d46bc 100644 --- a/lib/EntityGenerator/src/Field/AbstractFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/AbstractFieldGenerator.php @@ -18,7 +18,7 @@ abstract class AbstractFieldGenerator public function __construct( protected readonly NodeTypeFieldInterface $field, protected readonly DefaultValuesResolverInterface $defaultValuesResolver, - protected array $options = [] + protected array $options = [], ) { } @@ -49,18 +49,19 @@ protected function getFieldProperty(ClassType $classType): Property protected function addFieldAutodoc(Property $property): self { - $property->addComment($this->field->getLabel() . '.'); + $property->addComment($this->field->getLabel().'.'); if (!empty($this->field->getDescription())) { - $property->addComment($this->field->getDescription() . '.'); + $property->addComment($this->field->getDescription().'.'); } if (!empty($this->field->getDefaultValues())) { $property->addComment('Default values:'); $property->addComment($this->field->getDefaultValues()); } if (!empty($this->field->getGroupName())) { - $property->addComment('Group: ' . $this->field->getGroupName() . '.'); + $property->addComment('Group: '.$this->field->getGroupName().'.'); } + return $this; } @@ -69,6 +70,7 @@ protected function addFieldAnnotation(Property $property): self $this->addFieldAutodoc($property); $property->addComment('(Virtual field, this var is a buffer)'); + return $this; } @@ -80,6 +82,7 @@ protected function getFieldTypeDeclaration(): string protected function toPhpDocType(string $typeHint): string { $unicode = new UnicodeString($typeHint); + return $unicode->startsWith('?') ? $unicode->trimStart('?')->append('|null')->toString() : $typeHint; @@ -100,15 +103,15 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac */ if (!$this->excludeFromSerialization()) { $property->addAttribute('Symfony\Component\Serializer\Attribute\SerializedName', [ - 'serializedName' => $this->field->getVarName() + 'serializedName' => $this->field->getVarName(), ]); $property->addAttribute('Symfony\Component\Serializer\Attribute\Groups', [ - $this->getSerializationGroups() + $this->getSerializationGroups(), ]); $description = $this->field->getLabel(); if (!empty($this->field->getDescription())) { - $description .= ': ' . $this->field->getDescription(); + $description .= ': '.$this->field->getDescription(); } if ($this->field->isEnum() && null !== $defaultValues = $this->field->getDefaultValues()) { $enumValues = explode(',', $defaultValues); @@ -128,68 +131,68 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac if ($this->getSerializationMaxDepth() > 0) { $property->addAttribute('Symfony\Component\Serializer\Attribute\MaxDepth', [ - $this->getSerializationMaxDepth() + $this->getSerializationMaxDepth(), ]); } } if ( - $this->field->isIndexed() && - $this->options['use_api_platform_filters'] === true + $this->field->isIndexed() + && true === $this->options['use_api_platform_filters'] ) { switch (true) { case $this->field->isString(): $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter') . '::class'), - 'strategy' => 'partial' + 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter').'::class'), + 'strategy' => 'partial', ]); $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\RZ\Roadiz\CoreBundle\Api\Filter\NotFilter') . '::class') + new Literal($namespace->simplifyName('\RZ\Roadiz\CoreBundle\Api\Filter\NotFilter').'::class'), ]); break; case $this->field->isMultiple(): case $this->field->isEnum(): $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter') . '::class'), - 'strategy' => 'exact' + 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter').'::class'), + 'strategy' => 'exact', ]); $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\RZ\Roadiz\CoreBundle\Api\Filter\NotFilter') . '::class') + new Literal($namespace->simplifyName('\RZ\Roadiz\CoreBundle\Api\Filter\NotFilter').'::class'), ]); break; case $this->field->isBool(): $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\OrderFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\OrderFilter').'::class'), ]); $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\BooleanFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\BooleanFilter').'::class'), ]); break; case $this->field->isManyToOne(): case $this->field->isManyToMany(): $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\ExistsFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\ExistsFilter').'::class'), ]); break; case $this->field->isInteger(): case $this->field->isDecimal(): $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\OrderFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\OrderFilter').'::class'), ]); $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\NumericFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\NumericFilter').'::class'), ]); $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\RangeFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\RangeFilter').'::class'), ]); break; case $this->field->isDate(): case $this->field->isDateTime(): $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\OrderFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\OrderFilter').'::class'), ]); $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\DateFilter') . '::class'), + new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\DateFilter').'::class'), ]); break; } @@ -219,9 +222,6 @@ protected function addFieldSetter(ClassType $classType): self return $this; } - /** - * @return string - */ public function getCloneStatements(): string { return ''; @@ -237,30 +237,26 @@ public function addFieldIndex(ClassType $classType): self /** * Generate PHP property initialization for class constructor. - * - * @return string */ public function getFieldConstructorInitialization(): string { return ''; } - /** - * @return bool - */ protected function excludeFromSerialization(): bool { if ($this->field instanceof SerializableInterface) { return $this->field->isExcludedFromSerialization(); } + return false; } protected function getSerializationExclusionExpression(): ?string { if ( - $this->field instanceof SerializableInterface && - null !== $this->field->getSerializationExclusionExpression() + $this->field instanceof SerializableInterface + && null !== $this->field->getSerializationExclusionExpression() ) { return (new UnicodeString($this->field->getSerializationExclusionExpression())) ->replace('"', '') @@ -268,6 +264,7 @@ protected function getSerializationExclusionExpression(): ?string ->trim() ->toString(); } + return null; } @@ -276,6 +273,7 @@ protected function getSerializationMaxDepth(): int if ($this->field instanceof SerializableInterface && $this->field->getSerializationMaxDepth() > 0) { return $this->field->getSerializationMaxDepth(); } + return 2; } @@ -283,7 +281,7 @@ protected function getDefaultSerializationGroups(): array { return [ 'nodes_sources', - 'nodes_sources_' . ($this->field->getGroupNameCanonical() ?: 'default') + 'nodes_sources_'.($this->field->getGroupNameCanonical() ?: 'default'), ]; } @@ -294,6 +292,7 @@ protected function getSerializationGroups(): array } else { $groups = $this->getDefaultSerializationGroups(); } + return array_map(function (string $group): string { return (new UnicodeString($group)) ->replaceMatches('/[^A-Za-z0-9]++/', '_') @@ -306,39 +305,40 @@ protected function addSerializationAttributes(Property|Method $property): self if ($this->excludeFromSerialization()) { $property->addAttribute('JMS\Serializer\Annotation\Exclude'); $property->addAttribute('Symfony\Component\Serializer\Attribute\Ignore'); + return $this; } $property->addAttribute('JMS\Serializer\Annotation\Groups', [ - $this->getSerializationGroups() + $this->getSerializationGroups(), ]); if ($this->getSerializationMaxDepth() > 0) { $property->addAttribute('JMS\Serializer\Annotation\MaxDepth', [ - $this->getSerializationMaxDepth() + $this->getSerializationMaxDepth(), ]); } if (null !== $this->getSerializationExclusionExpression()) { $property->addAttribute('JMS\Serializer\Annotation\Exclude', [ - 'if' => $this->getSerializationExclusionExpression() + 'if' => $this->getSerializationExclusionExpression(), ]); } switch (true) { case $this->field->isBool(): $property->addAttribute('JMS\Serializer\Annotation\Type', [ - 'bool' + 'bool', ]); break; case $this->field->isInteger(): $property->addAttribute('JMS\Serializer\Annotation\Type', [ - 'int' + 'int', ]); break; case $this->field->isDecimal(): $property->addAttribute('JMS\Serializer\Annotation\Type', [ - 'double' + 'double', ]); break; case $this->field->isColor(): @@ -350,13 +350,13 @@ protected function addSerializationAttributes(Property|Method $property): self case $this->field->isRichText(): case $this->field->isEnum(): $property->addAttribute('JMS\Serializer\Annotation\Type', [ - 'string' + 'string', ]); break; case $this->field->isDateTime(): case $this->field->isDate(): $property->addAttribute('JMS\Serializer\Annotation\Type', [ - 'DateTime' + 'DateTime', ]); break; } diff --git a/lib/EntityGenerator/src/Field/CustomFormsFieldGenerator.php b/lib/EntityGenerator/src/Field/CustomFormsFieldGenerator.php index b09c1d5c..31e2977f 100644 --- a/lib/EntityGenerator/src/Field/CustomFormsFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/CustomFormsFieldGenerator.php @@ -17,7 +17,7 @@ protected function addSerializationAttributes(Property|Method $property): self parent::addSerializationAttributes($property); $property->addAttribute('JMS\Serializer\Annotation\VirtualProperty'); $property->addAttribute('JMS\Serializer\Annotation\SerializedName', [ - $this->field->getVarName() + $this->field->getVarName(), ]); return $this; @@ -27,6 +27,7 @@ protected function getDefaultSerializationGroups(): array { $groups = parent::getDefaultSerializationGroups(); $groups[] = 'nodes_sources_custom_forms'; + return $groups; } @@ -46,7 +47,7 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s ->addMethod($this->field->getGetterName()) ->setReturnType('array') ->setVisibility('public') - ->addComment('@return ' . $this->options['custom_form_class'] . '[] CustomForm array') + ->addComment('@return '.$this->options['custom_form_class'].'[] CustomForm array') ; $this->addSerializationAttributes($method); @@ -73,7 +74,7 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s protected function addFieldSetter(ClassType $classType): self { $method = $classType - ->addMethod('add' . ucfirst($this->field->getVarName())) + ->addMethod('add'.ucfirst($this->field->getVarName())) ->setReturnType('static') ->setVisibility('public') ->addComment('@return $this') @@ -93,6 +94,7 @@ protected function addFieldSetter(ClassType $classType): self return \$this; EOF ); + return $this; } } diff --git a/lib/EntityGenerator/src/Field/DefaultValuesResolverInterface.php b/lib/EntityGenerator/src/Field/DefaultValuesResolverInterface.php index 5ec89188..a8401353 100644 --- a/lib/EntityGenerator/src/Field/DefaultValuesResolverInterface.php +++ b/lib/EntityGenerator/src/Field/DefaultValuesResolverInterface.php @@ -9,14 +9,12 @@ interface DefaultValuesResolverInterface { /** - * @param NodeTypeFieldInterface $field - * @return array All possible default values for given field name across all node-types. + * @return array all possible default values for given field name across all node-types */ public function getDefaultValuesAmongAllFields(NodeTypeFieldInterface $field): array; /** - * @param NodeTypeFieldInterface $field - * @return int Max length of all possible default values for given field name across all node-types. + * @return int max length of all possible default values for given field name across all node-types */ public function getMaxDefaultValuesLengthAmongAllFields(NodeTypeFieldInterface $field): int; } diff --git a/lib/EntityGenerator/src/Field/DocumentsFieldGenerator.php b/lib/EntityGenerator/src/Field/DocumentsFieldGenerator.php index c750129d..56adc5f3 100644 --- a/lib/EntityGenerator/src/Field/DocumentsFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/DocumentsFieldGenerator.php @@ -18,12 +18,12 @@ protected function addSerializationAttributes(Property|Method $property): self parent::addSerializationAttributes($property); $property->addAttribute('JMS\Serializer\Annotation\VirtualProperty'); $property->addAttribute('JMS\Serializer\Annotation\SerializedName', [ - $this->field->getVarName() + $this->field->getVarName(), ]); $property->addAttribute('JMS\Serializer\Annotation\Type', [ - 'array<' . - (new UnicodeString($this->options['document_class']))->trimStart('\\')->toString() . - '>' + 'array<'. + (new UnicodeString($this->options['document_class']))->trimStart('\\')->toString(). + '>', ]); return $this; @@ -33,6 +33,7 @@ protected function getDefaultSerializationGroups(): array { $groups = parent::getDefaultSerializationGroups(); $groups[] = 'nodes_sources_documents'; + return $groups; } @@ -50,7 +51,7 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s { $getter = $classType->addMethod($this->field->getGetterName()) ->setReturnType('array') - ->addComment('@return ' . $this->options['document_class'] . '[]'); + ->addComment('@return '.$this->options['document_class'].'[]'); $this->addSerializationAttributes($getter); $getter->setBody(<<{$this->field->getVarName()}) { @@ -74,7 +75,7 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s protected function addFieldSetter(ClassType $classType): self { - $setter = $classType->addMethod('add' . ucfirst($this->field->getVarName())) + $setter = $classType->addMethod('add'.ucfirst($this->field->getVarName())) ->setReturnType('static') ->addComment('@return $this') ->setPublic(); @@ -98,6 +99,7 @@ protected function addFieldSetter(ClassType $classType): self return \$this; PHP ); + return $this; } } diff --git a/lib/EntityGenerator/src/Field/ManyToManyFieldGenerator.php b/lib/EntityGenerator/src/Field/ManyToManyFieldGenerator.php index 5bb5388d..ecc9742b 100644 --- a/lib/EntityGenerator/src/Field/ManyToManyFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/ManyToManyFieldGenerator.php @@ -20,7 +20,6 @@ protected function getFieldProperty(ClassType $classType): Property ->setType($this->getFieldTypeDeclaration()); } - protected function addFieldAttributes(Property $property, PhpNamespace $namespace, bool $exclude = false): self { parent::addFieldAttributes($property, $namespace, $exclude); @@ -43,21 +42,21 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac ; $entityB = $this->field->getName(); $joinColumnParams = [ - 'name' => $entityA . '_id', + 'name' => $entityA.'_id', 'referencedColumnName' => 'id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', ]; $inverseJoinColumns = [ - 'name' => $entityB . '_id', + 'name' => $entityB.'_id', 'referencedColumnName' => 'id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', ]; $property->addAttribute('Doctrine\ORM\Mapping\ManyToMany', [ - 'targetEntity' => new Literal($this->getFullyQualifiedClassName() . '::class') + 'targetEntity' => new Literal($this->getFullyQualifiedClassName().'::class'), ]); $property->addAttribute('Doctrine\ORM\Mapping\JoinTable', [ - 'name' => $entityA . '_' . $entityB + 'name' => $entityA.'_'.$entityB, ]); $property->addAttribute('Doctrine\ORM\Mapping\JoinColumn', $joinColumnParams); $property->addAttribute('Doctrine\ORM\Mapping\InverseJoinColumn', $inverseJoinColumns); @@ -68,14 +67,14 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac $orderBy[$order['field']] = $order['direction']; } $property->addAttribute('Doctrine\ORM\Mapping\OrderBy', [ - $orderBy + $orderBy, ]); } - if ($this->options['use_api_platform_filters'] === true) { + if (true === $this->options['use_api_platform_filters']) { $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter') . '::class'), - 'strategy' => 'exact' + 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter').'::class'), + 'strategy' => 'exact', ]); } @@ -88,8 +87,9 @@ public function addFieldAnnotation(Property $property): self { $this->addFieldAutodoc($property); $property->addComment( - '@var \Doctrine\Common\Collections\CollectiongetFullyQualifiedClassName() . '>' + '@var \Doctrine\Common\Collections\CollectiongetFullyQualifiedClassName().'>' ); + return $this; } @@ -103,13 +103,14 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s $classType->addMethod($this->field->getGetterName()) ->setReturnType('\Doctrine\Common\Collections\Collection') ->setPublic() - ->setBody('return $this->' . $this->field->getVarName() . ';') + ->setBody('return $this->'.$this->field->getVarName().';') ->addComment( - '@return ' . - $namespace->simplifyName('\Doctrine\Common\Collections\Collection') . - 'getFullyQualifiedClassName() . + '@return '. + $namespace->simplifyName('\Doctrine\Common\Collections\Collection'). + 'getFullyQualifiedClassName(). '>' ); + return $this; } @@ -118,8 +119,8 @@ public function addFieldSetter(ClassType $classType): self $setter = $classType->addMethod($this->field->getSetterName()) ->setReturnType('static') ->addComment( - '@param \Doctrine\Common\Collections\CollectiongetFullyQualifiedClassName() . - '>|array<' . $this->getFullyQualifiedClassName() . '> $' . $this->field->getVarName() + '@param \Doctrine\Common\Collections\CollectiongetFullyQualifiedClassName(). + '>|array<'.$this->getFullyQualifiedClassName().'> $'.$this->field->getVarName() ) ->addComment('@return $this') ->setPublic(); @@ -145,11 +146,8 @@ protected function isExcludingFieldFromJmsSerialization(): bool return false; } - /** - * @inheritDoc - */ public function getFieldConstructorInitialization(): string { - return '$this->' . $this->field->getVarName() . ' = new \Doctrine\Common\Collections\ArrayCollection();'; + return '$this->'.$this->field->getVarName().' = new \Doctrine\Common\Collections\ArrayCollection();'; } } diff --git a/lib/EntityGenerator/src/Field/ManyToOneFieldGenerator.php b/lib/EntityGenerator/src/Field/ManyToOneFieldGenerator.php index a35bad08..04d81ebc 100644 --- a/lib/EntityGenerator/src/Field/ManyToOneFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/ManyToOneFieldGenerator.php @@ -21,23 +21,24 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac * @\Doctrine\ORM\Mapping\JoinColumn(name="address_id", referencedColumnName="id", onDelete="SET NULL") */ $ormParams = [ - 'name' => $this->field->getName() . '_id', + 'name' => $this->field->getName().'_id', 'referencedColumnName' => 'id', 'onDelete' => 'SET NULL', ]; $property->addAttribute('Doctrine\ORM\Mapping\ManyToOne', [ - 'targetEntity' => new Literal($this->getFullyQualifiedClassName() . '::class') + 'targetEntity' => new Literal($this->getFullyQualifiedClassName().'::class'), ]); $property->addAttribute('Doctrine\ORM\Mapping\JoinColumn', $ormParams); - if ($this->options['use_api_platform_filters'] === true) { + if (true === $this->options['use_api_platform_filters']) { $property->addAttribute('ApiPlatform\Metadata\ApiFilter', [ - 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter') . '::class'), - 'strategy' => 'exact' + 0 => new Literal($namespace->simplifyName('\ApiPlatform\Doctrine\Orm\Filter\SearchFilter').'::class'), + 'strategy' => 'exact', ]); } $this->addSerializationAttributes($property); + return $this; } @@ -49,12 +50,13 @@ protected function isExcludingFieldFromJmsSerialization(): bool public function addFieldAnnotation(Property $property): self { $this->addFieldAutodoc($property); + return $this; } protected function getFieldTypeDeclaration(): string { - return '?' . $this->getFullyQualifiedClassName(); + return '?'.$this->getFullyQualifiedClassName(); } protected function getFieldDefaultValueDeclaration(): Literal|string|null @@ -71,6 +73,7 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s return \$this->{$this->field->getVarName()}; PHP ); + return $this; } @@ -89,6 +92,7 @@ public function addFieldSetter(ClassType $classType): self return \$this; PHP ); + return $this; } } diff --git a/lib/EntityGenerator/src/Field/NodesFieldGenerator.php b/lib/EntityGenerator/src/Field/NodesFieldGenerator.php index 9a64c213..3cbcd582 100644 --- a/lib/EntityGenerator/src/Field/NodesFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/NodesFieldGenerator.php @@ -34,12 +34,12 @@ protected function addSerializationAttributes(Property|Method $property): self parent::addSerializationAttributes($property); $property->addAttribute('JMS\Serializer\Annotation\VirtualProperty'); $property->addAttribute('JMS\Serializer\Annotation\SerializedName', [ - $this->field->getVarName() + $this->field->getVarName(), ]); $property->addAttribute('JMS\Serializer\Annotation\Type', [ - 'array<' . - (new UnicodeString($this->options['parent_class']))->trimStart('\\')->toString() . - '>' + 'array<'. + (new UnicodeString($this->options['parent_class']))->trimStart('\\')->toString(). + '>', ]); return $this; @@ -49,43 +49,39 @@ protected function getDefaultSerializationGroups(): array { $groups = parent::getDefaultSerializationGroups(); $groups[] = 'nodes_sources_nodes'; + return $groups; } - /** - * @return string - */ protected function getFieldSourcesName(): string { - return $this->field->getVarName() . 'Sources'; + return $this->field->getVarName().'Sources'; } - /** - * @return bool - */ + protected function hasOnlyOneNodeType(): bool { if (!empty($this->field->getDefaultValues())) { - return count(explode(',', $this->field->getDefaultValues())) === 1; + return 1 === count(explode(',', $this->field->getDefaultValues())); } + return false; } - /** - * @return string - */ protected function getRepositoryClass(): string { - if (!empty($this->field->getDefaultValues()) && $this->hasOnlyOneNodeType() === true) { + if (!empty($this->field->getDefaultValues()) && true === $this->hasOnlyOneNodeType()) { $nodeTypeName = trim(explode(',', $this->field->getDefaultValues())[0]); $nodeType = $this->nodeTypeResolver->get($nodeTypeName); if (null !== $nodeType) { $className = $nodeType->getSourceEntityFullQualifiedClassName(); + return (new UnicodeString($className))->startsWith('\\') ? $className : - '\\' . $className; + '\\'.$className; } } + return $this->options['parent_class']; } @@ -95,16 +91,15 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s ->setType('?array') ->setPrivate() ->setValue(null) - ->addComment($this->getFieldSourcesName() . ' NodesSources direct field buffer.') - ->addComment('@var ' . $this->getRepositoryClass() . '[]|null'); + ->addComment($this->getFieldSourcesName().' NodesSources direct field buffer.') + ->addComment('@var '.$this->getRepositoryClass().'[]|null'); $this->addFieldAutodoc($property); $this->addFieldAttributes($property, $namespace, $this->isExcludingFieldFromJmsSerialization()); - - $getter = $classType->addMethod($this->field->getGetterName() . 'Sources') + $getter = $classType->addMethod($this->field->getGetterName().'Sources') ->setReturnType('array') - ->addComment('@return ' . $this->getRepositoryClass() . '[]') + ->addComment('@return '.$this->getRepositoryClass().'[]') ->setPublic(); $this->addSerializationAttributes($getter); $getter->setBody(<<{$this->getFieldSourcesName()}; PHP ); + return $this; } public function addFieldSetter(ClassType $classType): self { - $setter = $classType->addMethod($this->field->getSetterName() . 'Sources') + $setter = $classType->addMethod($this->field->getSetterName().'Sources') ->setReturnType('static') - ->addComment('@param ' . $this->getRepositoryClass() . '[]|null $' . $this->getFieldSourcesName()) + ->addComment('@param '.$this->getRepositoryClass().'[]|null $'.$this->getFieldSourcesName()) ->addComment('@return $this') ->setPublic(); $setter->addParameter($this->getFieldSourcesName()) @@ -140,6 +136,7 @@ public function addFieldSetter(ClassType $classType): self return \$this; PHP ); + return $this; } } diff --git a/lib/EntityGenerator/src/Field/NonVirtualFieldGenerator.php b/lib/EntityGenerator/src/Field/NonVirtualFieldGenerator.php index 3a2c5241..e53a7713 100644 --- a/lib/EntityGenerator/src/Field/NonVirtualFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/NonVirtualFieldGenerator.php @@ -21,8 +21,8 @@ public function addFieldIndex(ClassType $classType): self 'Doctrine\ORM\Mapping\Index', [ 'columns' => [ - $this->field->getName() - ] + $this->field->getName(), + ], ] ); } @@ -30,25 +30,23 @@ public function addFieldIndex(ClassType $classType): self return $this; } - /** - * @return string - */ protected function getDoctrineType(): string { return $this->field->getDoctrineType(); } /** - * @return int|null String field length, returns NULL if length is irrelevant. + * @return int|null string field length, returns NULL if length is irrelevant */ protected function getFieldLength(): ?int { /* * Only set length for string (VARCHAR) type */ - if ($this->getDoctrineType() !== 'string') { + if ('string' !== $this->getDoctrineType()) { return null; } + return match (true) { $this->field->isColor() => 10, $this->field->isCountry() => 5, @@ -99,7 +97,7 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac } elseif ($this->field->isBool()) { $ormParams['nullable'] = false; $ormParams['options'] = [ - 'default' => false + 'default' => false, ]; } @@ -116,6 +114,7 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac public function addFieldAnnotation(Property $property): self { $this->addFieldAutodoc($property); + return $this; } @@ -154,26 +153,23 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s $method = $classType->addMethod($this->field->getGetterName()) ->setPublic() ->setReturnType($type) - ->addComment('@return ' . $this->toPhpDocType($type)); + ->addComment('@return '.$this->toPhpDocType($type)); if ($this->field->isMultiple()) { $method->setBody( - 'return null !== $this->' . - $this->field->getVarName() . ' ? array_values($this->' . $this->field->getVarName() . ') : null;' + 'return null !== $this->'. + $this->field->getVarName().' ? array_values($this->'.$this->field->getVarName().') : null;' ); } else { - $method->setBody('return $this->' . $this->field->getVarName() . ';'); + $method->setBody('return $this->'.$this->field->getVarName().';'); } return $this; } - /** - * @inheritDoc - */ public function addFieldSetter(ClassType $classType): self { - $assignation = '$' . $this->field->getVarName(); + $assignation = '$'.$this->field->getVarName(); $nullable = true; $casting = ''; @@ -200,11 +196,11 @@ public function addFieldSetter(ClassType $classType): self $type = $this->getFieldTypeDeclaration(); if ($nullable && !empty($casting)) { - $assignation = '$this->' . $this->field->getVarName() . ' = null !== $' . $this->field->getVarName() . ' ? - ' . $casting . $assignation . ' : + $assignation = '$this->'.$this->field->getVarName().' = null !== $'.$this->field->getVarName().' ? + '.$casting.$assignation.' : null;'; } else { - $assignation = '$this->' . $this->field->getVarName() . ' = ' . $assignation . ';'; + $assignation = '$this->'.$this->field->getVarName().' = '.$assignation.';'; } $method = $classType->addMethod($this->field->getSetterName())->setPublic(); diff --git a/lib/EntityGenerator/src/Field/ProxiedManyToManyFieldGenerator.php b/lib/EntityGenerator/src/Field/ProxiedManyToManyFieldGenerator.php index 6bd62f3e..22e1499e 100644 --- a/lib/EntityGenerator/src/Field/ProxiedManyToManyFieldGenerator.php +++ b/lib/EntityGenerator/src/Field/ProxiedManyToManyFieldGenerator.php @@ -22,19 +22,20 @@ protected function addSerializationAttributes(Property|Method $property): self $property->addAttribute('JMS\Serializer\Annotation\VirtualProperty'); $property->addAttribute('JMS\Serializer\Annotation\SerializedName', [ - $this->field->getVarName() + $this->field->getVarName(), ]); $property->addAttribute('Symfony\Component\Serializer\Attribute\SerializedName', [ - 'serializedName' => $this->field->getVarName() + 'serializedName' => $this->field->getVarName(), ]); $property->addAttribute('Symfony\Component\Serializer\Attribute\Groups', [ - $this->getSerializationGroups() + $this->getSerializationGroups(), ]); if ($this->getSerializationMaxDepth() > 0) { $property->addAttribute('Symfony\Component\Serializer\Attribute\MaxDepth', [ - $this->getSerializationMaxDepth() + $this->getSerializationMaxDepth(), ]); } + return $this; } @@ -63,10 +64,10 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac * inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id")} */ $ormParams = [ - 'targetEntity' => new Literal('\\' . trim($this->getProxyClassname(), '\\') . '::class'), + 'targetEntity' => new Literal('\\'.trim($this->getProxyClassname(), '\\').'::class'), 'mappedBy' => $this->configuration['proxy']['self'], 'orphanRemoval' => true, - 'cascade' => ['persist', 'remove'] + 'cascade' => ['persist', 'remove'], ]; $property->addAttribute('Doctrine\ORM\Mapping\OneToMany', $ormParams); @@ -78,7 +79,7 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac $orderBy[$order['field']] = $order['direction']; } $property->addAttribute('Doctrine\ORM\Mapping\OrderBy', [ - $orderBy + $orderBy, ]); } @@ -87,8 +88,9 @@ protected function addFieldAttributes(Property $property, PhpNamespace $namespac public function addFieldAnnotation(Property $property): self { - $property->addComment($this->field->getLabel() . '.'); - $property->addComment('@var \Doctrine\Common\Collections\CollectiongetProxyClassname() . '>'); + $property->addComment($this->field->getLabel().'.'); + $property->addComment('@var \Doctrine\Common\Collections\CollectiongetProxyClassname().'>'); + return $this; } @@ -97,12 +99,12 @@ public function addFieldGetter(ClassType $classType, PhpNamespace $namespace): s $classType->addMethod($this->getProxiedGetterName()) ->setReturnType('\Doctrine\Common\Collections\Collection') ->setPublic() - ->setBody('return $this->' . $this->getProxiedVarName() . ';') + ->setBody('return $this->'.$this->getProxiedVarName().';') ->addComment( - '@return ' . - $namespace->simplifyName('\Doctrine\Common\Collections\Collection') . - 'getProxyClassname() . + '@return '. + $namespace->simplifyName('\Doctrine\Common\Collections\Collection'). + 'getProxyClassname(). '>' ); @@ -126,7 +128,7 @@ public function addFieldSetter(ClassType $classType): self $proxySetter = $classType->addMethod($this->getProxiedSetterName()) ->setReturnType('static') ->setPublic() - ->addComment('@param \Doctrine\Common\Collections\CollectiongetProxyClassname() . '> $' . $this->getProxiedVarName()) + ->addComment('@param \Doctrine\Common\Collections\CollectiongetProxyClassname().'> $'.$this->getProxiedVarName()) ->addComment('@return $this') ; $proxySetter->addParameter($this->getProxiedVarName()) @@ -174,70 +176,48 @@ public function addFieldSetter(ClassType $classType): self return $this; } - /** - * @inheritDoc - */ public function getFieldConstructorInitialization(): string { - return '$this->' . $this->getProxiedVarName() . ' = new \Doctrine\Common\Collections\ArrayCollection();'; + return '$this->'.$this->getProxiedVarName().' = new \Doctrine\Common\Collections\ArrayCollection();'; } - /** - * @return string - */ protected function getProxiedVarName(): string { - return $this->field->getVarName() . 'Proxy'; + return $this->field->getVarName().'Proxy'; } - /** - * @return string - */ + protected function getProxiedSetterName(): string { - return $this->field->getSetterName() . 'Proxy'; + return $this->field->getSetterName().'Proxy'; } - /** - * @return string - */ + protected function getProxiedGetterName(): string { - return $this->field->getGetterName() . 'Proxy'; + return $this->field->getGetterName().'Proxy'; } - /** - * @return string - */ + protected function getProxySelfSetterName(): string { - return 'set' . ucwords($this->configuration['proxy']['self']); + return 'set'.ucwords($this->configuration['proxy']['self']); } - /** - * @return string - */ + protected function getProxyRelationSetterName(): string { - return 'set' . ucwords($this->configuration['proxy']['relation']); + return 'set'.ucwords($this->configuration['proxy']['relation']); } - /** - * @return string - */ + protected function getProxyRelationGetterName(): string { - return 'get' . ucwords($this->configuration['proxy']['relation']); + return 'get'.ucwords($this->configuration['proxy']['relation']); } - /** - * @return string - */ protected function getProxyClassname(): string { return (new UnicodeString($this->configuration['proxy']['classname']))->startsWith('\\') ? $this->configuration['proxy']['classname'] : - '\\' . $this->configuration['proxy']['classname']; + '\\'.$this->configuration['proxy']['classname']; } - /** - * @return string - */ public function getCloneStatements(): string { return <<excludeFromSerialization()) { $property->addAttribute('JMS\Serializer\Annotation\VirtualProperty'); $property->addAttribute('JMS\Serializer\Annotation\SerializedName', [ - $this->field->getVarName() + $this->field->getVarName(), ]); $property->addAttribute('Symfony\Component\Serializer\Attribute\SerializedName', [ - 'serializedName' => $this->field->getVarName() + 'serializedName' => $this->field->getVarName(), ]); $property->addAttribute('Symfony\Component\Serializer\Attribute\Groups', [ - $this->getSerializationGroups() + $this->getSerializationGroups(), ]); if ($this->getSerializationMaxDepth() > 0) { $property->addAttribute('Symfony\Component\Serializer\Attribute\MaxDepth', [ - $this->getSerializationMaxDepth() + $this->getSerializationMaxDepth(), ]); } } + return $this; } @@ -37,6 +38,7 @@ protected function getDefaultSerializationGroups(): array { $groups = parent::getDefaultSerializationGroups(); $groups[] = 'nodes_sources_yaml'; + return $groups; } @@ -52,9 +54,9 @@ protected function hasFieldAlternativeGetter(): bool public function addFieldAlternativeGetter(ClassType $classType): self { - $assignation = '$this->' . $this->field->getVarName(); + $assignation = '$this->'.$this->field->getVarName(); - $method = $classType->addMethod($this->field->getGetterName() . 'AsObject') + $method = $classType->addMethod($this->field->getGetterName().'AsObject') ->setReturnType('object|array|null') ->setVisibility('public') ; diff --git a/lib/EntityGenerator/src/RepositoryGenerator.php b/lib/EntityGenerator/src/RepositoryGenerator.php index c20e1af6..e28365ed 100644 --- a/lib/EntityGenerator/src/RepositoryGenerator.php +++ b/lib/EntityGenerator/src/RepositoryGenerator.php @@ -29,8 +29,7 @@ public function getClassContent(): string $file->addComment('THIS IS A GENERATED FILE, DO NOT EDIT IT.'); $file->addComment('IT WILL BE RECREATED AT EACH NODE-TYPE UPDATE.'); - - $fqcn = $this->options['entity_namespace'] . '\\' . $this->nodeType->getSourceEntityClassName(); + $fqcn = $this->options['entity_namespace'].'\\'.$this->nodeType->getSourceEntityClassName(); $namespace = $file ->addNamespace(trim($this->options['namespace'], '\\')) ->addUse('\Doctrine\Persistence\ManagerRegistry') @@ -50,16 +49,16 @@ public function getClassContent(): string $simplifiedFqcn = $namespace->simplifyName($fqcn); $class - ->addComment('@extends ' . $namespace->simplifyName($this->options['parent_class']) . '<' . $simplifiedFqcn . '>') - ->addComment('@method ' . $simplifiedFqcn . '|null find($id, $lockMode = null, $lockVersion = null)') - ->addComment('@method ' . $simplifiedFqcn . '|null findOneBy(array $criteria, array $orderBy = null)') - ->addComment('@method ' . $simplifiedFqcn . '[] findAll()') - ->addComment('@method ' . $simplifiedFqcn . '[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)') + ->addComment('@extends '.$namespace->simplifyName($this->options['parent_class']).'<'.$simplifiedFqcn.'>') + ->addComment('@method '.$simplifiedFqcn.'|null find($id, $lockMode = null, $lockVersion = null)') + ->addComment('@method '.$simplifiedFqcn.'|null findOneBy(array $criteria, array $orderBy = null)') + ->addComment('@method '.$simplifiedFqcn.'[] findAll()') + ->addComment('@method '.$simplifiedFqcn.'[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)') ; $constructor = $class->addMethod('__construct') ->setBody( - 'parent::__construct($registry, $previewResolver, $dispatcher, $security, $nodeSourceSearchHandler, ' . $simplifiedFqcn . '::class);' + 'parent::__construct($registry, $previewResolver, $dispatcher, $security, $nodeSourceSearchHandler, '.$simplifiedFqcn.'::class);' ); $constructor->addParameter('registry') @@ -92,7 +91,7 @@ public function configureOptions(OptionsResolver $resolver): void $normalizeClassName = function (OptionsResolver $resolver, string $className) { return (new UnicodeString($className))->startsWith('\\') ? $className : - '\\' . $className; + '\\'.$className; }; $resolver->setNormalizer('parent_class', $normalizeClassName); diff --git a/lib/EntityGenerator/tests/EntityGeneratorFactoryTest.php b/lib/EntityGenerator/tests/EntityGeneratorFactoryTest.php index dff56b7b..e77e6ee1 100644 --- a/lib/EntityGenerator/tests/EntityGeneratorFactoryTest.php +++ b/lib/EntityGenerator/tests/EntityGeneratorFactoryTest.php @@ -37,7 +37,7 @@ public function testCreate(): void $generator = $this->getEntityGeneratorFactory(); $this->assertEquals( - file_get_contents(dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSources/NSMock.php'), + file_get_contents(dirname(__DIR__).'/tests/Mocks/GeneratedNodesSources/NSMock.php'), $generator->create($this->getMockNodeType())->getClassContent() ); } @@ -61,13 +61,13 @@ public function testCreateWithCustomRepository(): void /* * Uncomment for generating a mock file from tests */ -// file_put_contents( -// dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSourcesWithRepository/NSMock.php', -// $generator->createWithCustomRepository($this->getMockNodeType())->getClassContent() -// ); + // file_put_contents( + // dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSourcesWithRepository/NSMock.php', + // $generator->createWithCustomRepository($this->getMockNodeType())->getClassContent() + // ); $this->assertEquals( - file_get_contents(dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSourcesWithRepository/NSMock.php'), + file_get_contents(dirname(__DIR__).'/tests/Mocks/GeneratedNodesSourcesWithRepository/NSMock.php'), $generator->createWithCustomRepository($this->getMockNodeType())->getClassContent() ); } @@ -91,13 +91,13 @@ public function testCreateCustomRepository(): void /* * Uncomment for generating a mock file from tests */ -// file_put_contents( -// dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSourcesWithRepository/Repository/NSMockRepository.php', -// $generator->createCustomRepository($this->getMockNodeType())->getClassContent() -// ); + // file_put_contents( + // dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSourcesWithRepository/Repository/NSMockRepository.php', + // $generator->createCustomRepository($this->getMockNodeType())->getClassContent() + // ); $this->assertEquals( - file_get_contents(dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSourcesWithRepository/Repository/NSMockRepository.php'), + file_get_contents(dirname(__DIR__).'/tests/Mocks/GeneratedNodesSourcesWithRepository/Repository/NSMockRepository.php'), $generator->createCustomRepository($this->getMockNodeType())->getClassContent() ); } diff --git a/lib/EntityGenerator/tests/EntityGeneratorTest.php b/lib/EntityGenerator/tests/EntityGeneratorTest.php index 5741180c..e49cbc23 100644 --- a/lib/EntityGenerator/tests/EntityGeneratorTest.php +++ b/lib/EntityGenerator/tests/EntityGeneratorTest.php @@ -42,18 +42,18 @@ public function testGetClassContent(): void /* * Uncomment for generating a mock file from tests */ -// file_put_contents( -// dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSources/NSMock.php', -// $generator->getClassContent() -// ); + // file_put_contents( + // dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSources/NSMock.php', + // $generator->getClassContent() + // ); $this->assertEquals( - file_get_contents(dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSources/NSMock.php'), + file_get_contents(dirname(__DIR__).'/tests/Mocks/GeneratedNodesSources/NSMock.php'), $generator->getClassContent() ); /** - * TEST without leading slashs + * TEST without leading slashs. */ $generatorWithoutLeadingSlashes = $this->getEntityGenerator($mockNodeType, [ 'parent_class' => 'mock\Entity\NodesSources', @@ -69,7 +69,7 @@ public function testGetClassContent(): void 'use_api_platform_filters' => true, ]); $this->assertEquals( - file_get_contents(dirname(__DIR__) . '/tests/Mocks/GeneratedNodesSources/NSMock.php'), + file_get_contents(dirname(__DIR__).'/tests/Mocks/GeneratedNodesSources/NSMock.php'), $generatorWithoutLeadingSlashes->getClassContent() ); } diff --git a/lib/EntityGenerator/tests/NodeTypeAwareTestTrait.php b/lib/EntityGenerator/tests/NodeTypeAwareTestTrait.php index 6a64ef8c..c6b99626 100644 --- a/lib/EntityGenerator/tests/NodeTypeAwareTestTrait.php +++ b/lib/EntityGenerator/tests/NodeTypeAwareTestTrait.php @@ -17,177 +17,177 @@ protected function getMockNodeType(): NodeTypeInterface ->method('getFields') ->willReturn( new ArrayCollection([ - (new SimpleNodeTypeField()) - ->setName('foo_datetime') - ->setTypeName('datetime') - ->setDoctrineType('datetime') - ->setSerializationGroups([ - 'nodes_sources', - 'nodes_sources_default', - 'foo_datetime' - ]) - ->setVirtual(false) - ->setLabel('Foo DateTime field') - ->setIndexed(true), - (new SimpleNodeTypeField()) - ->setName('foo') - ->setTypeName('string') - ->setVirtual(false) - ->setSerializationMaxDepth(1) - ->setLabel('Foo field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('fooIndexed') - ->setTypeName('string') - ->setVirtual(false) - ->setSerializationMaxDepth(1) - ->setLabel('Foo indexed field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setIndexed(true), - (new SimpleNodeTypeField()) - ->setName('boolIndexed') - ->setTypeName('bool') - ->setDoctrineType('boolean') - ->setVirtual(false) - ->setSerializationMaxDepth(1) - ->setLabel('Bool indexed field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setIndexed(true), - (new SimpleNodeTypeField()) - ->setName('foo_markdown') - ->setTypeName('markdown') - ->setDoctrineType('text') - ->setVirtual(false) - ->setSerializationMaxDepth(1) - ->setLabel('Foo markdown field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setDefaultValues("allow_h2: false\r\nallow_h3: false\r\nallow_h4: false\r\nallow_h5: false\r\nallow_h6: false\r\nallow_bold: true\r\nallow_italic: true\r\nallow_blockquote: false\r\nallow_image: false\r\nallow_list: false\r\nallow_nbsp: true\r\nallow_nb_hyphen: true\r\nallow_return: true\r\nallow_link: false\r\nallow_hr: false\r\nallow_preview: true") - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('foo_markdown_excluded') - ->setTypeName('markdown') - ->setDoctrineType('text') - ->setVirtual(false) - ->setExcludedFromSerialization(true) - ->setLabel('Foo excluded markdown field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setDefaultValues("allow_h2: false\r\nallow_h3: false\r\nallow_h4: false\r\nallow_h5: false\r\nallow_h6: false\r\nallow_bold: true\r\nallow_italic: true\r\nallow_blockquote: false\r\nallow_image: false\r\nallow_list: false\r\nallow_nbsp: true\r\nallow_nb_hyphen: true\r\nallow_return: true\r\nallow_link: false\r\nallow_hr: false\r\nallow_preview: true") - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('foo_decimal_excluded') - ->setTypeName('decimal') - ->setDoctrineType('decimal') - ->setVirtual(false) - ->setSerializationExclusionExpression('object.foo == \'test\'') - ->setLabel('Foo expression excluded decimal') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setIndexed(true), - (new SimpleNodeTypeField()) - ->setName('single_event_reference') - ->setTypeName('many_to_one') - ->setVirtual(false) - ->setLabel("Référence à l'événement") - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC") - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('event_references') - ->setTypeName('many_to_many') - ->setVirtual(false) - ->setLabel("Remontée d'événements manuelle") - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC") - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('event_references_proxied') - ->setTypeName('many_to_many') - ->setVirtual(false) - ->setLabel("Remontée d'événements manuelle") - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC\r\n# Use a proxy entity\r\nproxy:\r\n classname: \\App\\Entity\\PositionedCity\r\n self: nodeSource\r\n relation: city\r\n # This order will preserve position\r\n orderBy:\r\n - field: position\r\n direction: ASC") - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('event_references_excluded') - ->setTypeName('many_to_many') - ->setVirtual(false) - ->setExcludedFromSerialization(true) - ->setLabel("Remontée d'événements manuelle exclue") - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC") - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('bar') - ->setTypeName('documents') - ->setSerializationMaxDepth(1) - ->setVirtual(true) - ->setLabel('Bar documents field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('the_forms') - ->setTypeName('custom_forms') - ->setVirtual(true) - ->setLabel('Custom forms field') - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('foo_bar') - ->setTypeName('nodes') - ->setVirtual(true) - ->setLabel('ForBar nodes field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('foo_bar_hidden') - ->setTypeName('nodes') - ->setVirtual(true) - ->setExcludedFromSerialization(true) - ->setLabel('ForBar hidden nodes field') - ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') - ->setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('foo_bar_typed') - ->setTypeName('nodes') - ->setVirtual(true) - ->setLabel('ForBar nodes typed field') - ->setIndexed(false) - ->setDefaultValues('MockTwo'), - (new SimpleNodeTypeField()) - ->setName('layout') - ->setTypeName('enum') - ->setLabel('ForBar layout enum') - ->setIndexed(true) - ->setDefaultValues('light, dark, transparent'), - (new SimpleNodeTypeField()) - ->setName('foo_many_to_one') - ->setTypeName('many_to_one') - ->setVirtual(false) - ->setLabel('For many_to_one field') - ->setDefaultValues(<<setName('foo_datetime') + ->setTypeName('datetime') + ->setDoctrineType('datetime') + ->setSerializationGroups([ + 'nodes_sources', + 'nodes_sources_default', + 'foo_datetime', + ]) + ->setVirtual(false) + ->setLabel('Foo DateTime field') + ->setIndexed(true), + (new SimpleNodeTypeField()) + ->setName('foo') + ->setTypeName('string') + ->setVirtual(false) + ->setSerializationMaxDepth(1) + ->setLabel('Foo field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('fooIndexed') + ->setTypeName('string') + ->setVirtual(false) + ->setSerializationMaxDepth(1) + ->setLabel('Foo indexed field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setIndexed(true), + (new SimpleNodeTypeField()) + ->setName('boolIndexed') + ->setTypeName('bool') + ->setDoctrineType('boolean') + ->setVirtual(false) + ->setSerializationMaxDepth(1) + ->setLabel('Bool indexed field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setIndexed(true), + (new SimpleNodeTypeField()) + ->setName('foo_markdown') + ->setTypeName('markdown') + ->setDoctrineType('text') + ->setVirtual(false) + ->setSerializationMaxDepth(1) + ->setLabel('Foo markdown field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setDefaultValues("allow_h2: false\r\nallow_h3: false\r\nallow_h4: false\r\nallow_h5: false\r\nallow_h6: false\r\nallow_bold: true\r\nallow_italic: true\r\nallow_blockquote: false\r\nallow_image: false\r\nallow_list: false\r\nallow_nbsp: true\r\nallow_nb_hyphen: true\r\nallow_return: true\r\nallow_link: false\r\nallow_hr: false\r\nallow_preview: true") + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('foo_markdown_excluded') + ->setTypeName('markdown') + ->setDoctrineType('text') + ->setVirtual(false) + ->setExcludedFromSerialization(true) + ->setLabel('Foo excluded markdown field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setDefaultValues("allow_h2: false\r\nallow_h3: false\r\nallow_h4: false\r\nallow_h5: false\r\nallow_h6: false\r\nallow_bold: true\r\nallow_italic: true\r\nallow_blockquote: false\r\nallow_image: false\r\nallow_list: false\r\nallow_nbsp: true\r\nallow_nb_hyphen: true\r\nallow_return: true\r\nallow_link: false\r\nallow_hr: false\r\nallow_preview: true") + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('foo_decimal_excluded') + ->setTypeName('decimal') + ->setDoctrineType('decimal') + ->setVirtual(false) + ->setSerializationExclusionExpression('object.foo == \'test\'') + ->setLabel('Foo expression excluded decimal') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setIndexed(true), + (new SimpleNodeTypeField()) + ->setName('single_event_reference') + ->setTypeName('many_to_one') + ->setVirtual(false) + ->setLabel("Référence à l'événement") + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC") + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('event_references') + ->setTypeName('many_to_many') + ->setVirtual(false) + ->setLabel("Remontée d'événements manuelle") + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC") + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('event_references_proxied') + ->setTypeName('many_to_many') + ->setVirtual(false) + ->setLabel("Remontée d'événements manuelle") + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC\r\n# Use a proxy entity\r\nproxy:\r\n classname: \\App\\Entity\\PositionedCity\r\n self: nodeSource\r\n relation: city\r\n # This order will preserve position\r\n orderBy:\r\n - field: position\r\n direction: ASC") + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('event_references_excluded') + ->setTypeName('many_to_many') + ->setVirtual(false) + ->setExcludedFromSerialization(true) + ->setLabel("Remontée d'événements manuelle exclue") + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setDefaultValues("# Entity class name\r\nclassname: \\App\\Entity\\Base\\Event\r\n# Displayable is the method used to display entity name\r\ndisplayable: getName\r\n# Same as Displayable but for a secondary information\r\nalt_displayable: getSortingFirstDateTime\r\n# Same as Displayable but for a secondary information\r\nthumbnail: getMainDocument\r\n# Searchable entity fields\r\nsearchable:\r\n - name\r\n - slug\r\n# This order will only be used for explorer\r\norderBy:\r\n - field: sortingLastDateTime\r\n direction: DESC") + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('bar') + ->setTypeName('documents') + ->setSerializationMaxDepth(1) + ->setVirtual(true) + ->setLabel('Bar documents field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('the_forms') + ->setTypeName('custom_forms') + ->setVirtual(true) + ->setLabel('Custom forms field') + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('foo_bar') + ->setTypeName('nodes') + ->setVirtual(true) + ->setLabel('ForBar nodes field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('foo_bar_hidden') + ->setTypeName('nodes') + ->setVirtual(true) + ->setExcludedFromSerialization(true) + ->setLabel('ForBar hidden nodes field') + ->setDescription('Maecenas sed diam eget risus varius blandit sit amet non magna') + ->setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('foo_bar_typed') + ->setTypeName('nodes') + ->setVirtual(true) + ->setLabel('ForBar nodes typed field') + ->setIndexed(false) + ->setDefaultValues('MockTwo'), + (new SimpleNodeTypeField()) + ->setName('layout') + ->setTypeName('enum') + ->setLabel('ForBar layout enum') + ->setIndexed(true) + ->setDefaultValues('light, dark, transparent'), + (new SimpleNodeTypeField()) + ->setName('foo_many_to_one') + ->setTypeName('many_to_one') + ->setVirtual(false) + ->setLabel('For many_to_one field') + ->setDefaultValues(<<setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('foo_many_to_many') - ->setTypeName('many_to_many') - ->setVirtual(false) - ->setLabel('For many_to_many field') - ->setDefaultValues(<<setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('foo_many_to_many') + ->setTypeName('many_to_many') + ->setVirtual(false) + ->setLabel('For many_to_many field') + ->setDefaultValues(<<setIndexed(false), - (new SimpleNodeTypeField()) - ->setName('foo_many_to_many_proxied') - ->setTypeName('many_to_many') - ->setVirtual(false) - ->setSerializationMaxDepth(1) - ->setLabel('For many_to_many proxied field') - ->setDefaultValues(<<setIndexed(false), + (new SimpleNodeTypeField()) + ->setName('foo_many_to_many_proxied') + ->setTypeName('many_to_many') + ->setVirtual(false) + ->setSerializationMaxDepth(1) + ->setLabel('For many_to_many proxied field') + ->setDefaultValues(<<setIndexed(false), + ->setIndexed(false), ]) ); @@ -222,6 +222,7 @@ classname: Themes\MyTheme\Entities\PositionedCity $mockNodeType ->method('isPublishable') ->willReturn(true); + return $mockNodeType; } @@ -233,11 +234,13 @@ function (string $nodeTypeName): NodeTypeInterface { $mockNodeType = $this->createStub(NodeTypeInterface::class); $mockNodeType ->method('getSourceEntityFullQualifiedClassName') - ->willReturn('tests\mocks\GeneratedNodesSources\NS' . $nodeTypeName) + ->willReturn('tests\mocks\GeneratedNodesSources\NS'.$nodeTypeName) ; + return $mockNodeType; } ); + return $mockNodeTypeResolver; } diff --git a/lib/EntityGenerator/tests/SimpleNodeTypeField.php b/lib/EntityGenerator/tests/SimpleNodeTypeField.php index befe9ca5..9ac846fc 100644 --- a/lib/EntityGenerator/tests/SimpleNodeTypeField.php +++ b/lib/EntityGenerator/tests/SimpleNodeTypeField.php @@ -32,309 +32,207 @@ final class SimpleNodeTypeField implements NodeTypeFieldInterface, SerializableI private string $nodeTypeName = 'NodeType'; private string $doctrineType = 'string'; - /** - * @return string|null - */ public function getDescription(): ?string { return $this->description; } - /** - * @param string|null $description - * @return SimpleNodeTypeField - */ public function setDescription(?string $description): SimpleNodeTypeField { $this->description = $description; + return $this; } - /** - * @return string - */ public function getLabel(): string { return $this->label ?? ''; } - /** - * @param string|null $label - * @return SimpleNodeTypeField - */ public function setLabel(?string $label): SimpleNodeTypeField { $this->label = $label; + return $this; } - /** - * @return string - */ public function getName(): string { return $this->name ?? ''; } - /** - * @param string|null $name - * @return SimpleNodeTypeField - */ public function setName(?string $name): SimpleNodeTypeField { $this->name = $name; + return $this; } - /** - * @return string|null - */ public function getPlaceholder(): ?string { return $this->placeholder; } - /** - * @param string|null $placeholder - * @return SimpleNodeTypeField - */ public function setPlaceholder(?string $placeholder): SimpleNodeTypeField { $this->placeholder = $placeholder; + return $this; } - /** - * @return string|null - */ public function getDefaultValues(): ?string { return $this->defaultValues; } - /** - * @param string|null $defaultValues - * @return SimpleNodeTypeField - */ public function setDefaultValues(?string $defaultValues): SimpleNodeTypeField { $this->defaultValues = $defaultValues; + return $this; } - /** - * @return string|null - */ public function getGroupName(): ?string { return $this->groupName; } - /** - * @param string|null $groupName - * @return SimpleNodeTypeField - */ public function setGroupName(?string $groupName): SimpleNodeTypeField { $this->groupName = $groupName; + return $this; } - /** - * @return int|null - */ public function getMinLength(): ?int { return $this->minLength; } - /** - * @param int|null $minLength - * @return SimpleNodeTypeField - */ public function setMinLength(?int $minLength): SimpleNodeTypeField { $this->minLength = $minLength; + return $this; } - /** - * @return int|null - */ public function getMaxLength(): ?int { return $this->maxLength; } - /** - * @param int|null $maxLength - * @return SimpleNodeTypeField - */ public function setMaxLength(?int $maxLength): SimpleNodeTypeField { $this->maxLength = $maxLength; + return $this; } - /** - * @return bool - */ public function isVisible(): bool { return $this->visible; } - /** - * @param bool $visible - * @return SimpleNodeTypeField - */ public function setVisible(bool $visible): SimpleNodeTypeField { $this->visible = $visible; + return $this; } - /** - * @return bool - */ public function isUniversal(): bool { return $this->universal; } - /** - * @param bool $universal - * @return SimpleNodeTypeField - */ public function setUniversal(bool $universal): SimpleNodeTypeField { $this->universal = $universal; + return $this; } - /** - * @return bool - */ public function isSearchable(): bool { return $this->searchable; } - /** - * @param bool $searchable - * @return SimpleNodeTypeField - */ public function setSearchable(bool $searchable): SimpleNodeTypeField { $this->searchable = $searchable; + return $this; } - /** - * @return bool - */ public function isVirtual(): bool { return $this->virtual; } - /** - * @param bool $virtual - * @return SimpleNodeTypeField - */ public function setVirtual(bool $virtual): SimpleNodeTypeField { $this->virtual = $virtual; + return $this; } - /** - * @return bool - */ public function isIndexed(): bool { return $this->indexed; } - /** - * @param bool $indexed - * @return SimpleNodeTypeField - */ public function setIndexed(bool $indexed): SimpleNodeTypeField { $this->indexed = $indexed; + return $this; } - /** - * @return bool - */ public function isExpanded(): bool { return $this->expanded; } - /** - * @param bool $expanded - * @return SimpleNodeTypeField - */ public function setExpanded(bool $expanded): SimpleNodeTypeField { $this->expanded = $expanded; + return $this; } - /** - * @return string - */ public function getTypeName(): string { return $this->typeName; } - /** - * @param string $typeName - * @return SimpleNodeTypeField - */ public function setTypeName(string $typeName): SimpleNodeTypeField { $this->typeName = $typeName; + return $this; } - /** - * @return string - */ public function getNodeTypeName(): string { return $this->nodeTypeName; } - /** - * @param string $nodeTypeName - * @return SimpleNodeTypeField - */ public function setNodeTypeName(string $nodeTypeName): SimpleNodeTypeField { $this->nodeTypeName = $nodeTypeName; + return $this; } - /** - * @return string - */ public function getDoctrineType(): string { return $this->doctrineType; } - /** - * @param string $doctrineType - * @return SimpleNodeTypeField - */ public function setDoctrineType(string $doctrineType): SimpleNodeTypeField { $this->doctrineType = $doctrineType; + return $this; } @@ -345,12 +243,12 @@ public function getVarName(): string public function getGetterName(): string { - return (new UnicodeString('get ' . $this->getName()))->camel()->toString(); + return (new UnicodeString('get '.$this->getName()))->camel()->toString(); } public function getSetterName(): string { - return (new UnicodeString('set ' . $this->getName()))->camel()->toString(); + return (new UnicodeString('set '.$this->getName()))->camel()->toString(); } public function getGroupNameCanonical(): ?string @@ -365,223 +263,199 @@ public function getType() public function isString(): bool { - return $this->typeName === 'string'; + return 'string' === $this->typeName; } public function isText(): bool { - return $this->typeName === 'text'; + return 'text' === $this->typeName; } public function isDate(): bool { - return $this->typeName === 'date'; + return 'date' === $this->typeName; } public function isDateTime(): bool { - return $this->typeName === 'datetime'; + return 'datetime' === $this->typeName; } public function isRichText(): bool { - return $this->typeName === 'richtext'; + return 'richtext' === $this->typeName; } public function isMarkdown(): bool { - return $this->typeName === 'markdown'; + return 'markdown' === $this->typeName; } public function isBool(): bool { - return $this->typeName === 'bool'; + return 'bool' === $this->typeName; } public function isInteger(): bool { - return $this->typeName === 'integer'; + return 'integer' === $this->typeName; } public function isDecimal(): bool { - return $this->typeName === 'decimal'; + return 'decimal' === $this->typeName; } public function isEmail(): bool { - return $this->typeName === 'email'; + return 'email' === $this->typeName; } public function isDocuments(): bool { - return $this->typeName === 'documents'; + return 'documents' === $this->typeName; } public function isPassword(): bool { - return $this->typeName === 'password'; + return 'password' === $this->typeName; } public function isColor(): bool { - return $this->typeName === 'color'; + return 'color' === $this->typeName; } public function isGeoTag(): bool { - return $this->typeName === 'geotag'; + return 'geotag' === $this->typeName; } public function isNodes(): bool { - return $this->typeName === 'nodes'; + return 'nodes' === $this->typeName; } public function isUser(): bool { - return $this->typeName === 'user'; + return 'user' === $this->typeName; } public function isEnum(): bool { - return $this->typeName === 'enum'; + return 'enum' === $this->typeName; } public function isChildrenNodes(): bool { - return $this->typeName === 'children'; + return 'children' === $this->typeName; } public function isCustomForms(): bool { - return $this->typeName === 'custom_forms'; + return 'custom_forms' === $this->typeName; } public function isMultiple(): bool { - return $this->typeName === 'multiple'; + return 'multiple' === $this->typeName; } public function isMultiGeoTag(): bool { - return $this->typeName === 'multi_geotag'; + return 'multi_geotag' === $this->typeName; } public function isJson(): bool { - return $this->typeName === 'json'; + return 'json' === $this->typeName; } public function isYaml(): bool { - return $this->typeName === 'yaml'; + return 'yaml' === $this->typeName; } public function isCss(): bool { - return $this->typeName === 'css'; + return 'css' === $this->typeName; } public function isManyToMany(): bool { - return $this->typeName === 'many_to_many'; + return 'many_to_many' === $this->typeName; } public function isManyToOne(): bool { - return $this->typeName === 'many_to_one'; + return 'many_to_one' === $this->typeName; } public function isCountry(): bool { - return $this->typeName === 'country'; + return 'country' === $this->typeName; } public function isSingleProvider(): bool { - return $this->typeName === 'single_provider'; + return 'single_provider' === $this->typeName; } public function isMultiProvider(): bool { - return $this->typeName === 'multi_provider'; + return 'multi_provider' === $this->typeName; } public function isCollection(): bool { - return $this->typeName === 'collection'; + return 'collection' === $this->typeName; } - /** - * @return array - */ public function getSerializationGroups(): array { return $this->serializationGroups; } - /** - * @param array $serializationGroups - * @return SimpleNodeTypeField - */ public function setSerializationGroups(array $serializationGroups): SimpleNodeTypeField { $this->serializationGroups = $serializationGroups; + return $this; } - /** - * @return bool - */ public function isExcludedFromSerialization(): bool { return $this->excludedFromSerialization; } - /** - * @param bool $excludedFromSerialization - * @return SimpleNodeTypeField - */ public function setExcludedFromSerialization(bool $excludedFromSerialization): SimpleNodeTypeField { $this->excludedFromSerialization = $excludedFromSerialization; + return $this; } - /** - * @return string|null - */ public function getSerializationExclusionExpression(): ?string { return $this->serializationExclusionExpression; } - /** - * @param string|null $serializationExclusionExpression - * @return SimpleNodeTypeField - */ public function setSerializationExclusionExpression(?string $serializationExclusionExpression): SimpleNodeTypeField { $this->serializationExclusionExpression = $serializationExclusionExpression; + return $this; } - /** - * @return int|null - */ public function getSerializationMaxDepth(): ?int { return $this->serializationMaxDepth; } - /** - * @param int|null $serializationMaxDepth - * @return SimpleNodeTypeField - */ public function setSerializationMaxDepth(?int $serializationMaxDepth): SimpleNodeTypeField { $this->serializationMaxDepth = $serializationMaxDepth; + return $this; } } diff --git a/lib/Jwt/src/Validation/Constraint/HostedDomain.php b/lib/Jwt/src/Validation/Constraint/HostedDomain.php index c11b443d..f1342ef6 100644 --- a/lib/Jwt/src/Validation/Constraint/HostedDomain.php +++ b/lib/Jwt/src/Validation/Constraint/HostedDomain.php @@ -18,17 +18,13 @@ public function assert(Token $token): void { if ($token instanceof Token\Plain && !empty($this->hostedDomain)) { if (!$token->claims()->has('hd')) { - throw new ConstraintViolation( - 'Token does not expose any Hosted Domain.' - ); + throw new ConstraintViolation('Token does not expose any Hosted Domain.'); } /* * Check that Hosted Domain is the same as required by Roadiz */ if ($token->claims()->get('hd') !== $this->hostedDomain) { - throw new ConstraintViolation( - 'User (' . $token->claims()->get('hd') . ') does not belong to Hosted Domain.' - ); + throw new ConstraintViolation('User ('.$token->claims()->get('hd').') does not belong to Hosted Domain.'); } } } diff --git a/lib/Jwt/src/Validation/Constraint/UserInfoEndpoint.php b/lib/Jwt/src/Validation/Constraint/UserInfoEndpoint.php index 1a1a5782..2c5002f6 100644 --- a/lib/Jwt/src/Validation/Constraint/UserInfoEndpoint.php +++ b/lib/Jwt/src/Validation/Constraint/UserInfoEndpoint.php @@ -23,15 +23,13 @@ public function assert(Token $token): void try { $response = $this->client->request('GET', $this->userInfoEndpoint, [ 'headers' => [ - 'Authorization' => 'Bearer ' . $token->toString(), + 'Authorization' => 'Bearer '.$token->toString(), ], ]); // Trigger lazy request $response->getContent(); } catch (ExceptionInterface $e) { - throw new ConstraintViolation( - 'Userinfo cannot be fetch from Identity provider' - ); + throw new ConstraintViolation('Userinfo cannot be fetch from Identity provider'); } } } diff --git a/lib/Markdown/src/CommonMark.php b/lib/Markdown/src/CommonMark.php index 486b505a..0ab838d9 100644 --- a/lib/Markdown/src/CommonMark.php +++ b/lib/Markdown/src/CommonMark.php @@ -13,40 +13,43 @@ public function __construct( private readonly MarkdownConverter $textConverter, private readonly MarkdownConverter $textExtraConverter, private readonly MarkdownConverter $lineConverter, - private readonly ?Stopwatch $stopwatch = null + private readonly ?Stopwatch $stopwatch = null, ) { } - public function text(string $markdown = null): string + public function text(?string $markdown = null): string { if (null === $markdown) { return ''; } - $this->stopwatch?->start(CommonMark::class . '::text'); + $this->stopwatch?->start(CommonMark::class.'::text'); $html = $this->textConverter->convert($markdown)->getContent(); - $this->stopwatch?->stop(CommonMark::class . '::text'); + $this->stopwatch?->stop(CommonMark::class.'::text'); + return $html; } - public function textExtra(string $markdown = null): string + public function textExtra(?string $markdown = null): string { if (null === $markdown) { return ''; } - $this->stopwatch?->start(CommonMark::class . '::textExtra'); + $this->stopwatch?->start(CommonMark::class.'::textExtra'); $html = $this->textExtraConverter->convert($markdown)->getContent(); - $this->stopwatch?->stop(CommonMark::class . '::textExtra'); + $this->stopwatch?->stop(CommonMark::class.'::textExtra'); + return $html; } - public function line(string $markdown = null): string + public function line(?string $markdown = null): string { if (null === $markdown) { return ''; } - $this->stopwatch?->start(CommonMark::class . '::line'); + $this->stopwatch?->start(CommonMark::class.'::line'); $html = $this->lineConverter->convert($markdown)->getContent(); - $this->stopwatch?->stop(CommonMark::class . '::line'); + $this->stopwatch?->stop(CommonMark::class.'::line'); + return $html; } } diff --git a/lib/Markdown/src/MarkdownInterface.php b/lib/Markdown/src/MarkdownInterface.php index 4435a5fd..c9e5f0d4 100644 --- a/lib/Markdown/src/MarkdownInterface.php +++ b/lib/Markdown/src/MarkdownInterface.php @@ -8,28 +8,16 @@ interface MarkdownInterface { /** * Convert Markdown to HTML using standard Markdown syntax. - * - * @param string|null $markdown - * - * @return string */ - public function text(string $markdown = null): string; + public function text(?string $markdown = null): string; /** * Convert Markdown to HTML using standard Markdown Extra syntax. - * - * @param string|null $markdown - * - * @return string */ - public function textExtra(string $markdown = null): string; + public function textExtra(?string $markdown = null): string; /** * Convert Markdown to HTML using only inline HTML elements. - * - * @param string|null $markdown - * - * @return string */ - public function line(string $markdown = null): string; + public function line(?string $markdown = null): string; } diff --git a/lib/Markdown/src/Twig/MarkdownExtension.php b/lib/Markdown/src/Twig/MarkdownExtension.php index 01f432b1..bee79ffa 100644 --- a/lib/Markdown/src/Twig/MarkdownExtension.php +++ b/lib/Markdown/src/Twig/MarkdownExtension.php @@ -25,42 +25,30 @@ public function getFilters(): array ]; } - /** - * @param string|null $input - * - * @return string - */ public function markdown(?string $input): string { if (null === $input) { return ''; } + return $this->markdown->text($input); } - /** - * @param string|null $input - * - * @return string - */ public function inlineMarkdown(?string $input): string { if (null === $input) { return ''; } + return $this->markdown->line($input); } - /** - * @param string|null $input - * - * @return string - */ public function markdownExtra(?string $input): string { if (null === $input) { return ''; } + return $this->markdown->textExtra($input); } } diff --git a/lib/Models/src/Bag/LazyParameterBag.php b/lib/Models/src/Bag/LazyParameterBag.php index a258d5b7..ad295439 100644 --- a/lib/Models/src/Bag/LazyParameterBag.php +++ b/lib/Models/src/Bag/LazyParameterBag.php @@ -19,8 +19,8 @@ public function __construct() } /** - * @param string $key * @param mixed|null $default + * * @return mixed|null */ public function get(string $key, $default = null): mixed @@ -32,11 +32,7 @@ public function get(string $key, $default = null): mixed return parent::get($key, $default); } - /** - * @param string|null $key - * @return array - */ - public function all(string $key = null): array + public function all(?string $key = null): array { if (!$this->ready) { $this->populateParameters(); @@ -45,11 +41,6 @@ public function all(string $key = null): array return parent::all(); } - /** - * @param string $key - * - * @return bool - */ public function has(string $key): bool { if (!$this->ready) { @@ -59,9 +50,6 @@ public function has(string $key): bool return parent::has($key); } - /** - * @return array - */ public function keys(): array { if (!$this->ready) { @@ -71,9 +59,6 @@ public function keys(): array return parent::keys(); } - /** - * @return \ArrayIterator - */ #[\ReturnTypeWillChange] public function getIterator(): \ArrayIterator { @@ -84,9 +69,6 @@ public function getIterator(): \ArrayIterator return parent::getIterator(); } - /** - * @return int - */ #[\ReturnTypeWillChange] public function count(): int { @@ -98,12 +80,8 @@ public function count(): int } /** - * @param string $key - * @param null $default - * @param int $filter - * @param array $options - * - * @return mixed + * @param null $default + * @param array $options */ public function filter(string $key, $default = null, int $filter = \FILTER_DEFAULT, $options = []): mixed { diff --git a/lib/Models/src/Core/AbstractEntities/AbstractDateTimed.php b/lib/Models/src/Core/AbstractEntities/AbstractDateTimed.php index a52cb816..90449e32 100644 --- a/lib/Models/src/Core/AbstractEntities/AbstractDateTimed.php +++ b/lib/Models/src/Core/AbstractEntities/AbstractDateTimed.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\Core\AbstractEntities; -use DateTime; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation as SymfonySerializer; @@ -12,104 +11,87 @@ /** * An AbstractEntity with datetime fields to keep track of time with your items. */ - #[ ORM\MappedSuperclass, ORM\HasLifecycleCallbacks, ORM\Table, - ORM\Index(columns: ["created_at"]), - ORM\Index(columns: ["updated_at"]), + ORM\Index(columns: ['created_at']), + ORM\Index(columns: ['updated_at']), ] abstract class AbstractDateTimed extends AbstractEntity { - /** - * @var DateTime|null - */ #[ - ORM\Column(name: "created_at", type: "datetime", nullable: true), - Serializer\Groups(["timestamps"]), - SymfonySerializer\Groups(["timestamps"]), + ORM\Column(name: 'created_at', type: 'datetime', nullable: true), + Serializer\Groups(['timestamps']), + SymfonySerializer\Groups(['timestamps']), ] - protected ?DateTime $createdAt = null; + protected ?\DateTime $createdAt = null; - /** - * @var DateTime|null - */ #[ - ORM\Column(name: "updated_at", type: "datetime", nullable: true), - Serializer\Groups(["timestamps"]), - SymfonySerializer\Groups(["timestamps"]), + ORM\Column(name: 'updated_at', type: 'datetime', nullable: true), + Serializer\Groups(['timestamps']), + SymfonySerializer\Groups(['timestamps']), ] - protected ?DateTime $updatedAt = null; + protected ?\DateTime $updatedAt = null; - /** - * @return DateTime|null - */ - public function getCreatedAt(): ?DateTime + public function getCreatedAt(): ?\DateTime { return $this->createdAt; } /** - * @param DateTime|null $createdAt * @return $this */ - public function setCreatedAt(?DateTime $createdAt) + public function setCreatedAt(?\DateTime $createdAt): self { $this->createdAt = $createdAt; + return $this; } - /** - * @return DateTime|null - */ - public function getUpdatedAt(): ?DateTime + public function getUpdatedAt(): ?\DateTime { return $this->updatedAt; } /** - * @param DateTime|null $updatedAt * @return $this */ - public function setUpdatedAt(?DateTime $updatedAt) + public function setUpdatedAt(?\DateTime $updatedAt): self { $this->updatedAt = $updatedAt; + return $this; } protected function initAbstractDateTimed(): void { - $this->setUpdatedAt(new DateTime("now")); - $this->setCreatedAt(new DateTime("now")); + $this->setUpdatedAt(new \DateTime('now')); + $this->setCreatedAt(new \DateTime('now')); } - /** - * @return void - */ #[ORM\PreUpdate] - public function preUpdate() + public function preUpdate(): void { - $this->setUpdatedAt(new DateTime("now")); + $this->setUpdatedAt(new \DateTime('now')); } - /** - * @return void - */ + #[ORM\PrePersist] - public function prePersist() + public function prePersist(): void { - $this->setUpdatedAt(new DateTime("now")); - $this->setCreatedAt(new DateTime("now")); + $this->setUpdatedAt(new \DateTime('now')); + $this->setCreatedAt(new \DateTime('now')); } + /** * Set creation and update date to *now*. * - * @return AbstractEntity + * @return $this */ - public function resetDates() + public function resetDates(): self { - $this->setCreatedAt(new DateTime("now")); - $this->setUpdatedAt(new DateTime("now")); + $this->setCreatedAt(new \DateTime('now')); + $this->setUpdatedAt(new \DateTime('now')); return $this; } diff --git a/lib/Models/src/Core/AbstractEntities/AbstractEntity.php b/lib/Models/src/Core/AbstractEntities/AbstractEntity.php index 7eee795e..49b5b870 100644 --- a/lib/Models/src/Core/AbstractEntities/AbstractEntity.php +++ b/lib/Models/src/Core/AbstractEntities/AbstractEntity.php @@ -17,34 +17,25 @@ ] abstract class AbstractEntity implements PersistableInterface { - /** - * @var int|string|null - */ #[ ORM\Id, - ORM\Column(type: "integer"), + ORM\Column(type: 'integer'), ORM\GeneratedValue, - Serializer\Groups(["id"]), - Serializer\Type("integer"), - SymfonySerializer\Groups(["id"]) + Serializer\Groups(['id']), + Serializer\Type('integer'), + SymfonySerializer\Groups(['id']) ] protected int|string|null $id = null; - /** - * @return int|string|null - */ public function getId(): int|string|null { return $this->id; } - /** - * @param int|string|null $id - * @return AbstractEntity - */ public function setId(int|string|null $id): self { $this->id = $id; + return $this; } } diff --git a/lib/Models/src/Core/AbstractEntities/AbstractField.php b/lib/Models/src/Core/AbstractEntities/AbstractField.php index ba5c48b3..2915da82 100644 --- a/lib/Models/src/Core/AbstractEntities/AbstractField.php +++ b/lib/Models/src/Core/AbstractEntities/AbstractField.php @@ -5,18 +5,18 @@ namespace RZ\Roadiz\Core\AbstractEntities; use Doctrine\ORM\Mapping as ORM; -use RZ\Roadiz\Utils\StringHandler; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Utils\StringHandler; use Symfony\Component\Serializer\Annotation as SymfonySerializer; use Symfony\Component\Validator\Constraints as Assert; #[ ORM\MappedSuperclass, ORM\Table, - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["group_name"]), - ORM\Index(columns: ["group_name_canonical"]), - Serializer\ExclusionPolicy("all") + ORM\Index(columns: ['position']), + ORM\Index(columns: ['group_name']), + ORM\Index(columns: ['group_name_canonical']), + Serializer\ExclusionPolicy('all') ] abstract class AbstractField extends AbstractPositioned { @@ -109,12 +109,14 @@ abstract class AbstractField extends AbstractPositioned /** * Radio group field is like ENUM_T but rendered as a radio * button group. + * * @deprecated This option does not mean any data type, just presentation */ public const RADIO_GROUP_T = 19; /** * Check group field is like MULTIPLE_T but rendered as * a checkbox group. + * * @deprecated This option does not mean any data type, just presentation */ public const CHECK_GROUP_T = 20; @@ -128,19 +130,19 @@ abstract class AbstractField extends AbstractPositioned */ public const DATE_T = 22; /** - * Textarea to write Json syntax code + * Textarea to write Json syntax code. */ public const JSON_T = 23; /** - * Textarea to write CSS syntax code + * Textarea to write CSS syntax code. */ public const CSS_T = 24; /** - * Select-box to choose ISO Country + * Select-box to choose ISO Country. */ public const COUNTRY_T = 25; /** - * Textarea to write YAML syntax text + * Textarea to write YAML syntax text. */ public const YAML_T = 26; /** @@ -160,7 +162,7 @@ abstract class AbstractField extends AbstractPositioned */ public const SINGLE_PROVIDER_T = 30; /** - * Collection field + * Collection field. */ public const COLLECTION_T = 31; @@ -170,6 +172,7 @@ abstract class AbstractField extends AbstractPositioned * These string will be used as translation key. * * @var array + * * @internal */ #[SymfonySerializer\Ignore] @@ -206,6 +209,7 @@ abstract class AbstractField extends AbstractPositioned * Associates abstract field type to a Doctrine type. * * @var array + * * @internal */ #[SymfonySerializer\Ignore] @@ -244,6 +248,7 @@ abstract class AbstractField extends AbstractPositioned * List searchable fields types in a searchEngine such as Solr. * * @var array + * * @internal */ #[SymfonySerializer\Ignore] @@ -255,43 +260,43 @@ abstract class AbstractField extends AbstractPositioned ]; #[ - ORM\Column(name: "group_name", type: "string", length: 250, nullable: true), + ORM\Column(name: 'group_name', type: 'string', length: 250, nullable: true), Assert\Length(max: 250), - SymfonySerializer\Groups(["node_type", "setting"]), - Serializer\Groups(["node_type", "setting"]), - Serializer\Type("string"), + SymfonySerializer\Groups(['node_type', 'setting']), + Serializer\Groups(['node_type', 'setting']), + Serializer\Type('string'), Serializer\Expose ] protected ?string $groupName = null; #[ - ORM\Column(name: "group_name_canonical", type: "string", length: 250, nullable: true), - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), + ORM\Column(name: 'group_name_canonical', type: 'string', length: 250, nullable: true), + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), Assert\Length(max: 250), - Serializer\Type("string"), + Serializer\Type('string'), Serializer\Expose ] protected ?string $groupNameCanonical = null; #[ - ORM\Column(type: "string", length: 250), + ORM\Column(type: 'string', length: 250), Serializer\Expose, - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), Assert\Length(max: 250), - Serializer\Type("string"), + Serializer\Type('string'), Assert\NotBlank(), Assert\NotNull() ] protected string $name; #[ - ORM\Column(type: "string", length: 250), + ORM\Column(type: 'string', length: 250), Serializer\Expose, - Serializer\Groups(["node_type", "setting"]), - Serializer\Type("string"), - SymfonySerializer\Groups(["node_type", "setting"]), + Serializer\Groups(['node_type', 'setting']), + Serializer\Type('string'), + SymfonySerializer\Groups(['node_type', 'setting']), Assert\Length(max: 250), Assert\NotBlank(), Assert\NotNull() @@ -299,38 +304,38 @@ abstract class AbstractField extends AbstractPositioned protected ?string $label; #[ - ORM\Column(type: "string", length: 250, nullable: true), + ORM\Column(type: 'string', length: 250, nullable: true), Serializer\Expose, - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), Assert\Length(max: 250), - Serializer\Type("string") + Serializer\Type('string') ] protected ?string $placeholder = null; #[ - ORM\Column(type: "text", nullable: true), + ORM\Column(type: 'text', nullable: true), Serializer\Expose, - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), - Serializer\Type("string") + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), + Serializer\Type('string') ] protected ?string $description = null; #[ - ORM\Column(name: "default_values", type: "text", nullable: true), - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), - Serializer\Type("string"), + ORM\Column(name: 'default_values', type: 'text', nullable: true), + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), + Serializer\Type('string'), Serializer\Expose ] protected ?string $defaultValues = null; #[ - ORM\Column(type: "integer"), - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), - Serializer\Type("int"), + ORM\Column(type: 'integer'), + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), + Serializer\Type('int'), Serializer\Expose ] protected int $type = AbstractField::STRING_T; @@ -339,10 +344,10 @@ abstract class AbstractField extends AbstractPositioned * If current field data should be expanded (for choices and country types). */ #[ - ORM\Column(name: "expanded", type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), - Serializer\Type("bool"), + ORM\Column(name: 'expanded', type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), + Serializer\Type('bool'), Serializer\Expose ] protected bool $expanded = false; @@ -370,13 +375,12 @@ public function getName(): string } /** - * @param string|null $name - * * @return $this */ public function setName(?string $name) { $this->name = StringHandler::variablize($name ?? ''); + return $this; } @@ -385,7 +389,7 @@ public function setName(?string $name) */ public function getGetterName(): string { - return StringHandler::camelCase('get ' . $this->getName()); + return StringHandler::camelCase('get '.$this->getName()); } /** @@ -393,122 +397,99 @@ public function getGetterName(): string */ public function getSetterName(): string { - return StringHandler::camelCase('set ' . $this->getName()); + return StringHandler::camelCase('set '.$this->getName()); } - /** - * @return string - */ public function getLabel(): string { return $this->label ?? ''; } /** - * @param string|null $label - * * @return self */ public function setLabel(?string $label) { $this->label = $label ?? ''; + return $this; } - /** - * @return string|null - */ public function getPlaceholder(): ?string { return $this->placeholder; } /** - * @param string|null $placeholder * @return AbstractField */ public function setPlaceholder(?string $placeholder) { $this->placeholder = $placeholder; + return $this; } - /** - * @return string|null - */ public function getDescription(): ?string { return $this->description; } /** - * @param string|null $description - * * @return $this */ public function setDescription(?string $description) { $this->description = $description; + return $this; } - /** - * @return string|null - */ public function getDefaultValues(): ?string { return $this->defaultValues; } /** - * @param string|null $defaultValues - * * @return $this */ public function setDefaultValues(?string $defaultValues) { $this->defaultValues = $defaultValues; + return $this; } - /** - * @return string - */ public function getTypeName(): string { if (!key_exists($this->getType(), static::$typeToHuman)) { - throw new \InvalidArgumentException($this->getType() . ' cannot be mapped to human label.'); + throw new \InvalidArgumentException($this->getType().' cannot be mapped to human label.'); } + return static::$typeToHuman[$this->type]; } - /** - * @return int - */ public function getType(): int { return $this->type; } /** - * @param int $type - * * @return $this */ public function setType(int $type) { $this->type = $type; + return $this; } - /** - * @return string - */ public function getDoctrineType(): string { if (!key_exists($this->getType(), static::$typeToDoctrine)) { - throw new \InvalidArgumentException($this->getType() . ' cannot be mapped to Doctrine.'); + throw new \InvalidArgumentException($this->getType().' cannot be mapped to Doctrine.'); } + return static::$typeToDoctrine[$this->getType()] ?? ''; } @@ -517,7 +498,7 @@ public function getDoctrineType(): string */ public function isVirtual(): bool { - return static::$typeToDoctrine[$this->getType()] === null; + return null === static::$typeToDoctrine[$this->getType()]; } /** @@ -530,8 +511,6 @@ public function isSearchable(): bool /** * Gets the value of groupName. - * - * @return string|null */ public function getGroupName(): ?string { @@ -542,6 +521,7 @@ public function getGroupName(): ?string * Sets the value of groupName. * * @param string|null $groupName the group name + * * @return static */ public function setGroupName(?string $groupName) @@ -553,294 +533,190 @@ public function setGroupName(?string $groupName) $this->groupName = trim(strip_tags($groupName)); $this->groupNameCanonical = StringHandler::slugify($this->getGroupName()); } + return $this; } - /** - * @return string|null - */ public function getGroupNameCanonical(): ?string { return $this->groupNameCanonical; } - /** - * @return bool - */ public function isExpanded(): bool { return $this->expanded; } /** - * @param bool $expanded * @return AbstractField */ public function setExpanded(bool $expanded) { $this->expanded = $expanded; + return $this; } - /** - * @return bool - */ public function isString(): bool { return $this->getType() === static::STRING_T; } - /** - * @return bool - */ public function isText(): bool { return $this->getType() === static::TEXT_T; } - /** - * @return bool - */ public function isDate(): bool { return $this->getType() === static::DATE_T; } - /** - * @return bool - */ public function isDateTime(): bool { return $this->getType() === static::DATETIME_T; } - /** - * @return bool - */ public function isRichText(): bool { return $this->getType() === static::RICHTEXT_T; } - /** - * @return bool - */ public function isMarkdown(): bool { return $this->getType() === static::MARKDOWN_T; } - /** - * @return bool - */ public function isBool(): bool { return $this->isBoolean(); } - /** - * @return bool - */ public function isBoolean(): bool { return $this->getType() === static::BOOLEAN_T; } - /** - * @return bool - */ public function isInteger(): bool { return $this->getType() === static::INTEGER_T; } - /** - * @return bool - */ public function isDecimal(): bool { return $this->getType() === static::DECIMAL_T; } - /** - * @return bool - */ public function isEmail(): bool { return $this->getType() === static::EMAIL_T; } - /** - * @return bool - */ public function isDocuments(): bool { return $this->getType() === static::DOCUMENTS_T; } - /** - * @return bool - */ public function isPassword(): bool { return $this->getType() === static::PASSWORD_T; } - /** - * @return bool - */ public function isColor(): bool { return $this->isColour(); } - /** - * @return bool - */ public function isColour(): bool { return $this->getType() === static::COLOUR_T; } - /** - * @return bool - */ public function isGeoTag(): bool { return $this->getType() === static::GEOTAG_T; } - /** - * @return bool - */ public function isNodes(): bool { return $this->getType() === static::NODES_T; } - /** - * @return bool - */ public function isUser(): bool { return $this->getType() === static::USER_T; } - /** - * @return bool - */ public function isEnum(): bool { return $this->getType() === static::ENUM_T; } - /** - * @return bool - */ public function isChildrenNodes(): bool { return $this->getType() === static::CHILDREN_T; } - /** - * @return bool - */ public function isCustomForms(): bool { return $this->getType() === static::CUSTOM_FORMS_T; } - /** - * @return bool - */ public function isMultiple(): bool { return $this->getType() === static::MULTIPLE_T; } - /** - * @return bool - */ public function isMultiGeoTag(): bool { return $this->getType() === static::MULTI_GEOTAG_T; } - /** - * @return bool - */ public function isJson(): bool { return $this->getType() === static::JSON_T; } - /** - * @return bool - */ public function isYaml(): bool { return $this->getType() === static::YAML_T; } - /** - * @return bool - */ public function isCss(): bool { return $this->getType() === static::CSS_T; } - /** - * @return bool - */ public function isManyToMany(): bool { return $this->getType() === static::MANY_TO_MANY_T; } - /** - * @return bool - */ public function isManyToOne(): bool { return $this->getType() === static::MANY_TO_ONE_T; } - /** - * @return bool - */ public function isCountry(): bool { return $this->getType() === static::COUNTRY_T; } - /** - * @return bool - */ public function isSingleProvider(): bool { return $this->getType() === static::SINGLE_PROVIDER_T; } - /** - * @return bool - */ public function isMultipleProvider(): bool { return $this->isMultiProvider(); } - /** - * @return bool - */ public function isMultiProvider(): bool { return $this->getType() === static::MULTI_PROVIDER_T; } - /** - * @return bool - */ public function isCollection(): bool { return $this->getType() === static::COLLECTION_T; diff --git a/lib/Models/src/Core/AbstractEntities/AbstractHuman.php b/lib/Models/src/Core/AbstractEntities/AbstractHuman.php index 72725d76..682bff6c 100644 --- a/lib/Models/src/Core/AbstractEntities/AbstractHuman.php +++ b/lib/Models/src/Core/AbstractEntities/AbstractHuman.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\Core\AbstractEntities; -use DateTime; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation as SymfonySerializer; @@ -23,9 +22,9 @@ abstract class AbstractHuman extends AbstractDateTimed { #[ - ORM\Column(type: "string", length: 200, unique: true), - Serializer\Groups(["user_personal", "human"]), - SymfonySerializer\Groups(["user_personal", "human"]), + ORM\Column(type: 'string', length: 200, unique: true), + Serializer\Groups(['user_personal', 'human']), + SymfonySerializer\Groups(['user_personal', 'human']), Assert\NotNull(), Assert\NotBlank(), Assert\Length(max: 200), @@ -37,206 +36,172 @@ abstract class AbstractHuman extends AbstractDateTimed * Public name (pseudonyme) that can be displayed to a public audience. */ #[ - ORM\Column(name: "publicName", type: "string", length: 250, nullable: true), - Serializer\Groups(["user_public", "human"]), - SymfonySerializer\Groups(["user_public", "human"]), + ORM\Column(name: 'publicName', type: 'string', length: 250, nullable: true), + Serializer\Groups(['user_public', 'human']), + SymfonySerializer\Groups(['user_public', 'human']), Assert\Length(max: 250) ] protected ?string $publicName = null; #[ - ORM\Column(name: "firstName", type: "string", length: 250, nullable: true), - Serializer\Groups(["user_personal", "human"]), - SymfonySerializer\Groups(["user_personal", "human"]), + ORM\Column(name: 'firstName', type: 'string', length: 250, nullable: true), + Serializer\Groups(['user_personal', 'human']), + SymfonySerializer\Groups(['user_personal', 'human']), Assert\Length(max: 250) ] protected ?string $firstName = null; #[ - ORM\Column(name: "lastName", type: "string", length: 250, nullable: true), - Serializer\Groups(["user_personal", "human"]), - SymfonySerializer\Groups(["user_personal", "human"]), + ORM\Column(name: 'lastName', type: 'string', length: 250, nullable: true), + Serializer\Groups(['user_personal', 'human']), + SymfonySerializer\Groups(['user_personal', 'human']), Assert\Length(max: 250) ] protected ?string $lastName = null; #[ - ORM\Column(type: "string", length: 50, nullable: true), - Serializer\Groups(["user_personal", "human"]), - SymfonySerializer\Groups(["user_personal", "human"]), + ORM\Column(type: 'string', length: 50, nullable: true), + Serializer\Groups(['user_personal', 'human']), + SymfonySerializer\Groups(['user_personal', 'human']), Assert\Length(max: 50) ] protected ?string $phone = null; #[ - ORM\Column(type: "string", length: 250, nullable: true), - Serializer\Groups(["user_personal", "human"]), - SymfonySerializer\Groups(["user_personal", "human"]), + ORM\Column(type: 'string', length: 250, nullable: true), + Serializer\Groups(['user_personal', 'human']), + SymfonySerializer\Groups(['user_personal', 'human']), Assert\Length(max: 250) ] protected ?string $company = null; #[ - ORM\Column(type: "string", length: 250, nullable: true), - Serializer\Groups(["user_personal", "human"]), - SymfonySerializer\Groups(["user_personal", "human"]), + ORM\Column(type: 'string', length: 250, nullable: true), + Serializer\Groups(['user_personal', 'human']), + SymfonySerializer\Groups(['user_personal', 'human']), Assert\Length(max: 250) ] protected ?string $job = null; #[ - ORM\Column(type: "datetime", nullable: true), - Serializer\Groups(["user_personal", "human"]), - SymfonySerializer\Groups(["user_personal", "human"]) + ORM\Column(type: 'datetime', nullable: true), + Serializer\Groups(['user_personal', 'human']), + SymfonySerializer\Groups(['user_personal', 'human']) ] - protected ?DateTime $birthday = null; + protected ?\DateTime $birthday = null; - /** - * @return string|null - */ public function getEmail(): ?string { return $this->email; } /** - * @param string|null $email - * * @return $this */ public function setEmail(?string $email) { - if (filter_var($email ?? '', FILTER_VALIDATE_EMAIL) !== false) { + if (false !== filter_var($email ?? '', FILTER_VALIDATE_EMAIL)) { $this->email = $email; } return $this; } - /** - * @return string|null - */ public function getFirstName(): ?string { return $this->firstName; } /** - * @param string|null $firstName - * * @return $this */ public function setFirstName(?string $firstName) { $this->firstName = $firstName; + return $this; } - /** - * @return string|null - */ public function getLastName(): ?string { return $this->lastName; } /** - * @param string|null $lastName - * * @return $this */ public function setLastName(?string $lastName) { $this->lastName = $lastName; + return $this; } - /** - * @return string|null - */ public function getCompany(): ?string { return $this->company; } /** - * @param string|null $company - * * @return $this */ public function setCompany(?string $company) { $this->company = $company; + return $this; } - /** - * @return string|null - */ public function getJob(): ?string { return $this->job; } /** - * @param string|null $job - * * @return $this */ public function setJob(?string $job) { $this->job = $job; + return $this; } - /** - * @return DateTime|null - */ - public function getBirthday(): ?DateTime + public function getBirthday(): ?\DateTime { return $this->birthday; } + /** - * @param DateTime|null $birthday - * * @return $this */ - public function setBirthday(?DateTime $birthday = null) + public function setBirthday(?\DateTime $birthday = null) { $this->birthday = $birthday; + return $this; } - /** - * @return string|null - */ public function getPhone(): ?string { return $this->phone; } /** - * @param string|null $phone - * * @return self */ public function setPhone(?string $phone) { $this->phone = $phone; + return $this; } - /** - * @return string|null - */ public function getPublicName(): ?string { return $this->publicName; } - /** - * @param string|null $publicName - */ public function setPublicName(?string $publicName): void { $this->publicName = $publicName; diff --git a/lib/Models/src/Core/AbstractEntities/AbstractPositioned.php b/lib/Models/src/Core/AbstractEntities/AbstractPositioned.php index db394b15..e0b934c7 100644 --- a/lib/Models/src/Core/AbstractEntities/AbstractPositioned.php +++ b/lib/Models/src/Core/AbstractEntities/AbstractPositioned.php @@ -16,17 +16,17 @@ ORM\MappedSuperclass, ORM\HasLifecycleCallbacks, ORM\Table, - ORM\Index(columns: ["position"]) + ORM\Index(columns: ['position']) ] abstract class AbstractPositioned extends AbstractEntity implements PositionedInterface, Comparable { use PositionedTrait; #[ - ORM\Column(type: "float"), - Serializer\Groups(["position"]), - SymfonySerializer\Groups(["position"]), - Serializer\Type("float") + ORM\Column(type: 'float'), + Serializer\Groups(['position']), + SymfonySerializer\Groups(['position']), + Serializer\Type('float') ] protected float $position = 0.0; } diff --git a/lib/Models/src/Core/AbstractEntities/LeafInterface.php b/lib/Models/src/Core/AbstractEntities/LeafInterface.php index 898a0ade..924b9b79 100644 --- a/lib/Models/src/Core/AbstractEntities/LeafInterface.php +++ b/lib/Models/src/Core/AbstractEntities/LeafInterface.php @@ -13,12 +13,14 @@ public function getChildren(): Collection; /** * @param static $child + * * @return $this */ public function addChild(LeafInterface $child): static; /** * @param static $child + * * @return $this */ public function removeChild(LeafInterface $child): static; @@ -36,15 +38,12 @@ public function getParent(): ?LeafInterface; public function getParents(): array; /** - * @param LeafInterface|null $parent * @return $this */ public function setParent(?LeafInterface $parent = null): static; /** * Gets the leaf depth. - * - * @return int */ public function getDepth(): int; } diff --git a/lib/Models/src/Core/AbstractEntities/LeafTrait.php b/lib/Models/src/Core/AbstractEntities/LeafTrait.php index f9068a9c..2f174c99 100644 --- a/lib/Models/src/Core/AbstractEntities/LeafTrait.php +++ b/lib/Models/src/Core/AbstractEntities/LeafTrait.php @@ -11,7 +11,7 @@ trait LeafTrait use PositionedTrait; /** - * @return Collection + * @return Collection */ public function getChildren(): Collection { @@ -25,11 +25,11 @@ public function setChildren(Collection $children): static foreach ($this->children as $child) { $child->setParent($this); } + return $this; } /** - * @param LeafInterface $child * @return $this */ public function addChild(LeafInterface $child): static @@ -41,8 +41,8 @@ public function addChild(LeafInterface $child): static return $this; } + /** - * @param LeafInterface $child * @return $this */ public function removeChild(LeafInterface $child): static @@ -63,7 +63,7 @@ public function removeChild(LeafInterface $child): static */ public function getParent(): ?LeafInterface { - /** @phpstan-ignore-next-line */ + /* @phpstan-ignore-next-line */ return $this->parent; } @@ -77,24 +77,23 @@ public function getParents(): array do { $parent = $parent->getParent(); - if ($parent !== null) { + if (null !== $parent) { $parentsArray[] = $parent; } - } while ($parent !== null); + } while (null !== $parent); return array_reverse($parentsArray); } /** * Gets the nodes' depth. - * - * @return int */ public function getDepth(): int { - if ($this->getParent() === null) { + if (null === $this->getParent()) { return 0; } + return $this->getParent()->getDepth() + 1; } } diff --git a/lib/Models/src/Core/AbstractEntities/NodeInterface.php b/lib/Models/src/Core/AbstractEntities/NodeInterface.php index eec342fb..78838887 100644 --- a/lib/Models/src/Core/AbstractEntities/NodeInterface.php +++ b/lib/Models/src/Core/AbstractEntities/NodeInterface.php @@ -12,9 +12,14 @@ interface NodeInterface extends PersistableInterface { public function getChildrenOrder(): string; + public function getChildrenOrderDirection(): string; + public function isDraft(): bool; + public function isPending(): bool; + public function isPublished(): bool; + public function getNodeType(): NodeTypeInterface; } diff --git a/lib/Models/src/Core/AbstractEntities/PersistableInterface.php b/lib/Models/src/Core/AbstractEntities/PersistableInterface.php index 2fad6286..865b72aa 100644 --- a/lib/Models/src/Core/AbstractEntities/PersistableInterface.php +++ b/lib/Models/src/Core/AbstractEntities/PersistableInterface.php @@ -13,8 +13,6 @@ interface PersistableInterface { /** * Get entity unique identifier. - * - * @return int|string|null */ public function getId(): int|string|null; } diff --git a/lib/Models/src/Core/AbstractEntities/PositionedInterface.php b/lib/Models/src/Core/AbstractEntities/PositionedInterface.php index b088f5c6..f3f0aa8b 100644 --- a/lib/Models/src/Core/AbstractEntities/PositionedInterface.php +++ b/lib/Models/src/Core/AbstractEntities/PositionedInterface.php @@ -6,16 +6,12 @@ interface PositionedInterface { - /** - * @return float - */ public function getPosition(): float; /** * Set position as a float to enable increment and decrement by O.5 * to insert an entity between two others. * - * @param float $newPosition * @return PositionedInterface */ public function setPosition(float $newPosition); diff --git a/lib/Models/src/Core/AbstractEntities/PositionedTrait.php b/lib/Models/src/Core/AbstractEntities/PositionedTrait.php index 3572a109..417e9040 100644 --- a/lib/Models/src/Core/AbstractEntities/PositionedTrait.php +++ b/lib/Models/src/Core/AbstractEntities/PositionedTrait.php @@ -5,13 +5,10 @@ namespace RZ\Roadiz\Core\AbstractEntities; /** - * Trait which describe a positioned entity + * Trait which describe a positioned entity. */ trait PositionedTrait { - /** - * @return float - */ public function getPosition(): float { return $this->position; @@ -21,7 +18,6 @@ public function getPosition(): float * Set position as a float to enable increment and decrement by O.5 * to insert a node between two others. * - * @param float $newPosition * @return $this */ public function setPosition(float $newPosition) @@ -33,15 +29,11 @@ public function setPosition(float $newPosition) return $this; } - /** - * @param mixed $other - * @return int - */ public function compareTo($other): int { if ($other instanceof PositionedInterface) { return $this->getPosition() <=> $other->getPosition(); } - throw new \LogicException('Cannot compare object which does not implement ' . PositionedInterface::class); + throw new \LogicException('Cannot compare object which does not implement '.PositionedInterface::class); } } diff --git a/lib/Models/src/Core/AbstractEntities/TranslationInterface.php b/lib/Models/src/Core/AbstractEntities/TranslationInterface.php index ee2d01e4..733fa8b1 100644 --- a/lib/Models/src/Core/AbstractEntities/TranslationInterface.php +++ b/lib/Models/src/Core/AbstractEntities/TranslationInterface.php @@ -6,54 +6,24 @@ interface TranslationInterface extends PersistableInterface { - /** - * @return string - */ public function getName(): string; - /** - * @param string|null $name - * @return TranslationInterface - */ public function setName(?string $name): TranslationInterface; - /** - * @return string - */ public function getLocale(): string; - /** - * @param string $locale - * @return TranslationInterface - */ public function setLocale(string $locale): TranslationInterface; - /** - * @return boolean - */ public function isAvailable(): bool; - /** - * @param boolean $available - * @return TranslationInterface - */ public function setAvailable(bool $available): TranslationInterface; - /** - * @return boolean - */ public function isDefaultTranslation(): bool; - /** - * @param bool $defaultTranslation - * @return TranslationInterface - */ public function setDefaultTranslation(bool $defaultTranslation): TranslationInterface; /** * Gets the value of overrideLocale. - * - * @return string */ public function getOverrideLocale(): ?string; @@ -61,15 +31,11 @@ public function getOverrideLocale(): ?string; * Sets the value of overrideLocale. * * @param string|null $overrideLocale the override locale - * - * @return TranslationInterface */ public function setOverrideLocale(?string $overrideLocale): TranslationInterface; /** * Get preferred locale between overrideLocale or locale. - * - * @return string */ public function getPreferredLocale(): string; diff --git a/lib/Models/src/Core/Events/LeafEntityLifeCycleSubscriber.php b/lib/Models/src/Core/Events/LeafEntityLifeCycleSubscriber.php index f20b40b4..d34d318e 100644 --- a/lib/Models/src/Core/Events/LeafEntityLifeCycleSubscriber.php +++ b/lib/Models/src/Core/Events/LeafEntityLifeCycleSubscriber.php @@ -32,7 +32,7 @@ public function prePersist(PrePersistEventArgs $event): void try { $handler = $this->handlerFactory->getHandler($entity); - if ($entity->getPosition() === 0.0) { + if (0.0 === $entity->getPosition()) { /* * Get the last index after last tag in parent */ @@ -46,7 +46,7 @@ public function prePersist(PrePersistEventArgs $event): void } else { $entity->setPosition($lastPosition); } - } elseif ($entity->getPosition() === 0.5) { + } elseif (0.5 === $entity->getPosition()) { /* * Position is set to 0.5, so we need to * shift all tags to the bottom. diff --git a/lib/Models/src/Core/Handlers/AbstractHandler.php b/lib/Models/src/Core/Handlers/AbstractHandler.php index d7e1fbbe..5b664d9e 100644 --- a/lib/Models/src/Core/Handlers/AbstractHandler.php +++ b/lib/Models/src/Core/Handlers/AbstractHandler.php @@ -8,23 +8,19 @@ abstract class AbstractHandler { - /** - * @return ObjectManager - */ public function getObjectManager(): ObjectManager { return $this->objectManager; } public function __construct( - protected readonly ObjectManager $objectManager + protected readonly ObjectManager $objectManager, ) { } /** * Clean positions for current entity siblings. * - * @param bool $setPositions * @return float Return the next position after the **last** entity */ public function cleanPositions(bool $setPositions = true): float diff --git a/lib/Models/src/Utils/StringHandler.php b/lib/Models/src/Utils/StringHandler.php index eeb0f963..2b0e1d4a 100644 --- a/lib/Models/src/Utils/StringHandler.php +++ b/lib/Models/src/Utils/StringHandler.php @@ -12,8 +12,6 @@ class StringHandler /** * Remove diacritics characters and replace them with their basic alpha letter. * - * @param string|null $string - * @return string * @deprecated Use Symfony\Component\String\UnicodeString::ascii() */ public static function removeDiacritics(?string $string): string @@ -30,9 +28,6 @@ public static function removeDiacritics(?string $string): string /** * Transform to lowercase and replace every non-alpha character with a dash. - * - * @param string|null $string - * @return string */ public static function slugify(?string $string): string { @@ -40,13 +35,13 @@ public static function slugify(?string $string): string return ''; } $slugger = new AsciiSlugger(); + return $slugger->slug($string)->lower()->toString(); } + /** * Transform a string for use as a classname. * - * @param string|null $string - * * @return string Classified string */ public static function classify(?string $string): string @@ -62,12 +57,9 @@ public static function classify(?string $string): string ->toString() ; } + /** * Transform to lowercase and replace every non-alpha character with an underscore. - * - * @param string|null $string - * - * @return string */ public static function cleanForFilename(?string $string): string { @@ -86,10 +78,6 @@ public static function cleanForFilename(?string $string): string /** * Transform to lowercase and replace every non-alpha character with an underscore. - * - * @param string|null $string - * - * @return string */ public static function variablize(?string $string): string { @@ -111,10 +99,6 @@ public static function variablize(?string $string): string /** * Transform to lower camelCase. - * - * @param string|null $string - * - * @return string */ public static function camelCase(?string $string): string { @@ -131,14 +115,12 @@ public static function camelCase(?string $string): string ->toString()); } - /** * Encode a string using website security secret. * - * @param string|null $value String to encode + * @param string|null $value String to encode * @param string|null $secret Secret salt * - * @return string * @throws \InvalidArgumentException */ public static function encodeWithSecret(?string $value, ?string $secret): string @@ -147,19 +129,19 @@ public static function encodeWithSecret(?string $value, ?string $secret): string if (!empty($secret)) { $secret = crypt($secret, $secret); - return base64_encode($secret . base64_encode(strip_tags($value ?? ''))); + + return base64_encode($secret.base64_encode(strip_tags($value ?? ''))); } else { - throw new \InvalidArgumentException("You cannot encode with an empty salt. Did you enter a secret security phrase in your conf/config.json file?", 1); + throw new \InvalidArgumentException('You cannot encode with an empty salt. Did you enter a secret security phrase in your conf/config.json file?', 1); } } /** * Decode a string using website security secret. * - * @param string|null $value Salted base64 string + * @param string|null $value Salted base64 string * @param string|null $secret Secret salt * - * @return string * @throws \InvalidArgumentException */ public static function decodeWithSecret(?string $value, ?string $secret): string @@ -170,23 +152,20 @@ public static function decodeWithSecret(?string $value, ?string $secret): string $secret = crypt($secret, $secret); $salted = base64_decode($value ?? ''); - $nonSalted = str_replace($secret, "", $salted); + $nonSalted = str_replace($secret, '', $salted); return base64_decode($nonSalted); } else { - throw new \InvalidArgumentException("You cannot encode with an empty salt. Did you enter a secret security phrase in your conf/config.json file?", 1); + throw new \InvalidArgumentException('You cannot encode with an empty salt. Did you enter a secret security phrase in your conf/config.json file?', 1); } } /** - * @param string $haystack - * @param string $needle - * @return bool * @deprecated Use UnicodeString::endsWith($needle) */ public static function endsWith(string $haystack, string $needle): bool { - if ($needle === '') { + if ('' === $needle) { return true; } @@ -195,17 +174,11 @@ public static function endsWith(string $haystack, string $needle): bool ; } - /** - * @param string $search - * @param string $replace - * @param string $subject - * @return string - */ public static function replaceLast(string $search, string $replace, string $subject): string { $pos = strrpos($subject, $search); - if ($pos !== false) { + if (false !== $pos) { $subject = \substr_replace($subject, $replace, $pos, \mb_strlen($search)); } diff --git a/lib/Models/tests/StringHandlerTest.php b/lib/Models/tests/StringHandlerTest.php index a1ccaf79..15ed248d 100644 --- a/lib/Models/tests/StringHandlerTest.php +++ b/lib/Models/tests/StringHandlerTest.php @@ -1,5 +1,7 @@ assertEquals($expected, StringHandler::replaceLast($wanted, "", $input)); + $this->assertEquals($expected, StringHandler::replaceLast($wanted, '', $input)); } - /** - * @return array - */ public function replaceLastProvider(): array { return [ - ["testPage", "Locale", "testPage"], - ["localePage", "Locale", "localePage"], - ["testLocalePage", "Locale", "testPage"], - ["testPageLocale", "Locale", "testPage"], - ["testPagelocale", "Locale", "testPagelocale"], - ["testPageGateau", "Locale", "testPageGateau"], - ["testPage", "", "testPage"], - ["LocalePage", "Locale", "Page"], + ['testPage', 'Locale', 'testPage'], + ['localePage', 'Locale', 'localePage'], + ['testLocalePage', 'Locale', 'testPage'], + ['testPageLocale', 'Locale', 'testPage'], + ['testPagelocale', 'Locale', 'testPagelocale'], + ['testPageGateau', 'Locale', 'testPageGateau'], + ['testPage', '', 'testPage'], + ['LocalePage', 'Locale', 'Page'], ]; } @@ -101,23 +100,20 @@ public function testRemoveDiacritics(string $input, string $expected): void $this->assertEquals($expected, StringHandler::removeDiacritics($input)); } - /** - * @return array - */ public function removeDiacriticsProvider(): array { return [ - ["à", "a"], - ["é", "e"], - ["À", "A"], - ["É", "E"], - ["œ", "oe"], - ["ç", "c"], - ["__à", "__a"], - ["--é", "--e"], + ['à', 'a'], + ['é', 'e'], + ['À', 'A'], + ['É', 'E'], + ['œ', 'oe'], + ['ç', 'c'], + ['__à', '__a'], + ['--é', '--e'], [ - "Les-echos_26022015_Les-entrepreneurs-partent-à-lassaut-du-secteur-bancaire.pdf", - "Les-echos_26022015_Les-entrepreneurs-partent-a-lassaut-du-secteur-bancaire.pdf" + 'Les-echos_26022015_Les-entrepreneurs-partent-à-lassaut-du-secteur-bancaire.pdf', + 'Les-echos_26022015_Les-entrepreneurs-partent-a-lassaut-du-secteur-bancaire.pdf', ], ]; } @@ -131,29 +127,26 @@ public function testVariablize(string $input, string $expected): void $this->assertEquals($expected, StringHandler::variablize($input)); } - /** - * @return array - */ public function variablizeProvider(): array { return [ - ["à", "a"], - ["é", "e"], - ["À", "a"], - ["É", "e"], - ["œ", "oe"], - ["ç", "c"], - ["__à", "a"], - ["--é", "e"], - ["Ligula $* _--Egestas Mattis Nullam$* _ ", "ligula_egestas_mattis_nullam"], - ["Véèsti buœlum Rïsus+", "veesti_buoelum_risus"], - ["J'aime les sushis!", "j_aime_les_sushis"], - ["J’aime les sushis!", "j_aime_les_sushis"], - ["J'aime les\n sushis!\t\n", "j_aime_les_sushis"], - ["?header_image", "header_image"], - ["JAime les_sushis", "j_aime_les_sushis"], - ["Ébène", "ebene"], - ["ébène", "ebene"], + ['à', 'a'], + ['é', 'e'], + ['À', 'a'], + ['É', 'e'], + ['œ', 'oe'], + ['ç', 'c'], + ['__à', 'a'], + ['--é', 'e'], + ['Ligula $* _--Egestas Mattis Nullam$* _ ', 'ligula_egestas_mattis_nullam'], + ['Véèsti buœlum Rïsus+', 'veesti_buoelum_risus'], + ["J'aime les sushis!", 'j_aime_les_sushis'], + ['J’aime les sushis!', 'j_aime_les_sushis'], + ["J'aime les\n sushis!\t\n", 'j_aime_les_sushis'], + ['?header_image', 'header_image'], + ['JAime les_sushis', 'j_aime_les_sushis'], + ['Ébène', 'ebene'], + ['ébène', 'ebene'], ]; } @@ -166,17 +159,14 @@ public function testClassify(string $input, string $expected): void $this->assertEquals($expected, StringHandler::classify($input)); } - /** - * @return array - */ public function classifyProvider(): array { return [ - ["Ligula $* _--Egestas Mattis Nullam", "LigulaEgestasMattisNullam"], - ["Véèsti buœlum Rïsus", "VeestiBuoelumRisus"], - ["J'aime les sushis", "JAimeLesSushis"], - ["header_image", "HeaderImage"], - ["JAime les_sushis", "JAimeLesSushis"], + ['Ligula $* _--Egestas Mattis Nullam', 'LigulaEgestasMattisNullam'], + ['Véèsti buœlum Rïsus', 'VeestiBuoelumRisus'], + ["J'aime les sushis", 'JAimeLesSushis'], + ['header_image', 'HeaderImage'], + ['JAime les_sushis', 'JAimeLesSushis'], ]; } @@ -189,17 +179,14 @@ public function testCamelCase(string $input, string $expected): void $this->assertEquals($expected, StringHandler::camelcase($input)); } - /** - * @return array - */ public function camelCaseProvider(): array { return [ - ["Ligula $* _--Egestas Mattis Nullam", "ligulaEgestasMattisNullam"], - ["Véèsti buœlum Rïsus", "veestiBuoelumRisus"], - ["J'aime les sushis", "jAimeLesSushis"], - ["header_image", "headerImage"], - ["JAime les_sushis", "jAimeLesSushis"], + ['Ligula $* _--Egestas Mattis Nullam', 'ligulaEgestasMattisNullam'], + ['Véèsti buœlum Rïsus', 'veestiBuoelumRisus'], + ["J'aime les sushis", 'jAimeLesSushis'], + ['header_image', 'headerImage'], + ['JAime les_sushis', 'jAimeLesSushis'], ]; } @@ -212,28 +199,25 @@ public function testSlugify(string $input, string $expected): void $this->assertEquals($expected, StringHandler::slugify($input)); } - /** - * @return array - */ public function slugifyProvider(): array { return [ - ["Ligula $* _--Egestas Mattis Nullam$* _ ", "ligula-egestas-mattis-nullam"], - ["Véèsti buœlum Rïsus+", "veesti-buoelum-risus"], - ["veesti-buoelum-risus", "veesti-buoelum-risus"], - ["J'aime les sushis!", "j-aime-les-sushis"], - ["J’aime les sushis!", "j-aime-les-sushis"], - ["J'aime les\n sushis!\t\n", "j-aime-les-sushis"], - ["?header_image", "header-image"], - ["JAime les_sushis", "jaime-les-sushis"], - ["Ébène", "ebene"], - ["ébène", "ebene"], - ["Page1 1", "page1-1"], - ["Page3", "page3"], - ["Page 3", "page-3"], - ["Page 3 3", "page-3-3"], - ["12 Page 3 3", "12-page-3-3"], - ["straßburg", "strassburg"] + ['Ligula $* _--Egestas Mattis Nullam$* _ ', 'ligula-egestas-mattis-nullam'], + ['Véèsti buœlum Rïsus+', 'veesti-buoelum-risus'], + ['veesti-buoelum-risus', 'veesti-buoelum-risus'], + ["J'aime les sushis!", 'j-aime-les-sushis'], + ['J’aime les sushis!', 'j-aime-les-sushis'], + ["J'aime les\n sushis!\t\n", 'j-aime-les-sushis'], + ['?header_image', 'header-image'], + ['JAime les_sushis', 'jaime-les-sushis'], + ['Ébène', 'ebene'], + ['ébène', 'ebene'], + ['Page1 1', 'page1-1'], + ['Page3', 'page3'], + ['Page 3', 'page-3'], + ['Page 3 3', 'page-3-3'], + ['12 Page 3 3', '12-page-3-3'], + ['straßburg', 'strassburg'], ]; } @@ -248,17 +232,14 @@ public function testEncodeWithSecret(string $input, string $secret): void $this->assertEquals($input, StringHandler::decodeWithSecret($code, $secret)); } - /** - * @return array - */ public function encodeWithSecretProvider(): array { return [ - ["Ligula $* _--Egestas Mattis Nullam", "Commodo Pellentesque Sem Fusce Quam"], - ["Véèsti buœlum Rïsus ", " change#this#secret#very#important"], - ["J'aime les sushis ", " Fringilla Vulputate Dolor Inceptos"], - ["au " . PHP_EOL . "ietaui.\\eauie@auietsrt.trr", "Sit Vestibulum Dolor Ullamcorper Aenean"], - ["JAime les_sushis", "Sit Vestibulum Dolor"], + ['Ligula $* _--Egestas Mattis Nullam', 'Commodo Pellentesque Sem Fusce Quam'], + ['Véèsti buœlum Rïsus ', ' change#this#secret#very#important'], + ["J'aime les sushis ", ' Fringilla Vulputate Dolor Inceptos'], + ['au '.PHP_EOL.'ietaui.\\eauie@auietsrt.trr', 'Sit Vestibulum Dolor Ullamcorper Aenean'], + ['JAime les_sushis', 'Sit Vestibulum Dolor'], ]; } @@ -275,16 +256,13 @@ public function testEncodeWithSecretNoSalt(string $input, string $secret): void $this->assertEquals($input, StringHandler::decodeWithSecret($code, $secret)); } - /** - * @return array - */ public function encodeWithSecretNoSaltProvider(): array { return [ - ["Ligula $* _--Egestas Mattis Nullam", ""], - ["Véèsti buœlum Rïsus ", " "], - ["J'aime les sushis ", " "], - ["auietauieauie@auietsrt.trr", PHP_EOL], + ['Ligula $* _--Egestas Mattis Nullam', ''], + ['Véèsti buœlum Rïsus ', ' '], + ["J'aime les sushis ", ' '], + ['auietauieauie@auietsrt.trr', PHP_EOL], ]; } } diff --git a/lib/OpenId/src/Authentication/OpenIdAuthenticator.php b/lib/OpenId/src/Authentication/OpenIdAuthenticator.php index 2de6168c..26e96c75 100644 --- a/lib/OpenId/src/Authentication/OpenIdAuthenticator.php +++ b/lib/OpenId/src/Authentication/OpenIdAuthenticator.php @@ -52,34 +52,28 @@ public function __construct( private readonly bool $requiresLocalUsers, private readonly string $usernameClaim = 'email', private readonly string $targetPathParameter = '_target_path', - private readonly array $defaultRoles = [] + private readonly array $defaultRoles = [], ) { $this->client = $client->withOptions([ // You can set any number of default request options. - 'timeout' => 2.0, + 'timeout' => 2.0, ]); } - /** - * @inheritDoc - */ public function supports(Request $request): ?bool { - return null !== $this->discovery && - $this->discovery->isValid() && - $this->httpUtils->checkRequestPath($request, $this->returnPath) && - $request->query->has('state') && - ($request->query->has('code') || $request->query->has('error')); + return null !== $this->discovery + && $this->discovery->isValid() + && $this->httpUtils->checkRequestPath($request, $this->returnPath) + && $request->query->has('state') + && ($request->query->has('code') || $request->query->has('error')); } - /** - * @inheritDoc - */ public function authenticate(Request $request): Passport { if ( - null !== $request->query->get('error') && - null !== $request->query->get('error_description') + null !== $request->query->get('error') + && null !== $request->query->get('error_description') ) { throw new AuthenticationException((string) $request->query->get('error_description')); } @@ -110,7 +104,7 @@ public function authenticate(Request $request): Passport try { $tokenEndpoint = $this->discovery->get('token_endpoint'); - $redirectUri = $request->getSchemeAndHttpHost() . $request->getBaseUrl() . $request->getPathInfo(); + $redirectUri = $request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo(); /* * Redirect URI should always use SSL @@ -128,8 +122,8 @@ public function authenticate(Request $request): Passport 'client_id' => $this->oauthClientId ?? '', 'client_secret' => $this->oauthClientSecret ?? '', 'redirect_uri' => $redirectUri, - 'grant_type' => 'authorization_code' - ] + 'grant_type' => 'authorization_code', + ], ]); /** @var array $jsonResponse */ $jsonResponse = \json_decode(json: $response->getContent(), associative: true, flags: JSON_THROW_ON_ERROR); @@ -139,17 +133,9 @@ public function authenticate(Request $request): Passport $errorTitle = $jsonResponse['error'] ?? $e->getMessage(); $errorDescription = $jsonResponse['error_description'] ?? ''; - throw new OpenIdAuthenticationException( - $errorTitle . ': ' . $errorDescription, - $e->getCode(), - $e - ); + throw new OpenIdAuthenticationException($errorTitle.': '.$errorDescription, $e->getCode(), $e); } catch (ExceptionInterface $e) { - throw new OpenIdAuthenticationException( - $e->getMessage(), - $e->getCode(), - $e - ); + throw new OpenIdAuthenticationException($e->getMessage(), $e->getCode(), $e); } if (!\is_string($jsonResponse['id_token']) || empty($jsonResponse['id_token'])) { @@ -169,22 +155,16 @@ public function authenticate(Request $request): Passport $jwt = $configuration->parser()->parse($jsonResponse['id_token']); if (!($jwt instanceof Plain)) { - throw new OpenIdAuthenticationException( - 'JWT token must be instance of ' . Plain::class - ); + throw new OpenIdAuthenticationException('JWT token must be instance of '.Plain::class); } if (!$jwt->claims()->has($this->usernameClaim)) { - throw new OpenIdAuthenticationException( - 'JWT does not contain “' . $this->usernameClaim . '” claim.' - ); + throw new OpenIdAuthenticationException('JWT does not contain “'.$this->usernameClaim.'” claim.'); } $username = $jwt->claims()->get($this->usernameClaim); if (!\is_string($username) || empty($username)) { - throw new OpenIdAuthenticationException( - 'JWT “' . $this->usernameClaim . '” claim is not valid.' - ); + throw new OpenIdAuthenticationException('JWT “'.$this->usernameClaim.'” claim is not valid.'); } /* @@ -203,6 +183,7 @@ function (Plain $jwt) { } catch (RequiredConstraintsViolated $e) { throw new OpenIdAuthenticationException($e->getMessage(), 0, $e); } + return true; }, $jwt @@ -242,6 +223,7 @@ protected function loadUser(array $payload, string $identity, Plain $jwt): UserI if ($this->roleStrategy->supports()) { $roles = array_merge($roles, $this->roleStrategy->getRoles() ?? []); } + return new OpenIdAccount( $identity, array_unique($roles), @@ -249,9 +231,6 @@ protected function loadUser(array $payload, string $identity, Plain $jwt): UserI ); } - /** - * @inheritDoc - */ public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) { @@ -261,9 +240,6 @@ public function onAuthenticationSuccess(Request $request, TokenInterface $token, return new RedirectResponse($this->urlGenerator->generate($this->defaultRoute)); } - /** - * @inheritDoc - */ public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { if ($request->hasSession()) { diff --git a/lib/OpenId/src/Authentication/Provider/ChainJwtRoleStrategy.php b/lib/OpenId/src/Authentication/Provider/ChainJwtRoleStrategy.php index 027c34a6..617089cf 100644 --- a/lib/OpenId/src/Authentication/Provider/ChainJwtRoleStrategy.php +++ b/lib/OpenId/src/Authentication/Provider/ChainJwtRoleStrategy.php @@ -13,7 +13,7 @@ public function __construct(private readonly array $strategies) { foreach ($this->strategies as $strategy) { if (!($strategy instanceof JwtRoleStrategy)) { - throw new \InvalidArgumentException('Strategy must implement ' . JwtRoleStrategy::class); + throw new \InvalidArgumentException('Strategy must implement '.JwtRoleStrategy::class); } } } @@ -25,6 +25,7 @@ public function supports(): bool return true; } } + return false; } @@ -36,6 +37,7 @@ public function getRoles(): ?array $roles = array_merge($roles, $strategy->getRoles() ?? []); } } + return !empty($roles) ? array_unique($roles) : null; } } diff --git a/lib/OpenId/src/Authentication/Provider/JwtRoleStrategy.php b/lib/OpenId/src/Authentication/Provider/JwtRoleStrategy.php index a65102f1..7a7d8d26 100644 --- a/lib/OpenId/src/Authentication/Provider/JwtRoleStrategy.php +++ b/lib/OpenId/src/Authentication/Provider/JwtRoleStrategy.php @@ -7,5 +7,6 @@ interface JwtRoleStrategy { public function supports(): bool; + public function getRoles(): ?array; } diff --git a/lib/OpenId/src/Authentication/Provider/OpenIdAccountProvider.php b/lib/OpenId/src/Authentication/Provider/OpenIdAccountProvider.php index 31e1c95d..94a313b4 100644 --- a/lib/OpenId/src/Authentication/Provider/OpenIdAccountProvider.php +++ b/lib/OpenId/src/Authentication/Provider/OpenIdAccountProvider.php @@ -13,7 +13,6 @@ class OpenIdAccountProvider implements UserProviderInterface { /** - * @param string $username * @deprecated since Symfony 5.3, use loadUserByIdentifier() instead */ public function loadUserByUsername(string $username): UserInterface @@ -26,15 +25,13 @@ public function loadUserByIdentifier(string $identifier): UserInterface throw new UserNotFoundException('Cannot load an OpenId account with its email.'); } - /** - * @inheritDoc - */ public function refreshUser(UserInterface $user): UserInterface { if ($user instanceof OpenIdAccount) { if ($user->getJwtToken()->isExpired(new \DateTime('now'))) { throw new UserNotFoundException('OpenId token has expired, please authenticate again…'); } + return $user; } @@ -42,11 +39,10 @@ public function refreshUser(UserInterface $user): UserInterface } /** - * @inheritDoc * @param class-string $class */ public function supportsClass(string $class): bool { - return $class === OpenIdAccount::class; + return OpenIdAccount::class === $class; } } diff --git a/lib/OpenId/src/Authentication/Provider/SettingsRoleStrategy.php b/lib/OpenId/src/Authentication/Provider/SettingsRoleStrategy.php index 50605339..b8a6dd35 100644 --- a/lib/OpenId/src/Authentication/Provider/SettingsRoleStrategy.php +++ b/lib/OpenId/src/Authentication/Provider/SettingsRoleStrategy.php @@ -11,7 +11,7 @@ class SettingsRoleStrategy implements JwtRoleStrategy public const SETTING_NAME = 'openid_default_roles'; public function __construct( - protected readonly ParameterBag $settingsBag + protected readonly ParameterBag $settingsBag, ) { } @@ -26,6 +26,7 @@ public function getRoles(): ?array if (!is_string($settings)) { return null; } + return array_map(function ($role) { return trim($role); }, explode(',', $settings)); diff --git a/lib/OpenId/src/Discovery.php b/lib/OpenId/src/Discovery.php index 961420f2..45c7c454 100644 --- a/lib/OpenId/src/Discovery.php +++ b/lib/OpenId/src/Discovery.php @@ -19,7 +19,6 @@ use Symfony\Contracts\HttpClient\HttpClientInterface; /** - * @package RZ\Roadiz\OpenId * @see https://accounts.google.com/.well-known/openid-configuration */ class Discovery extends LazyParameterBag @@ -58,10 +57,12 @@ protected function populateParameters(): void $cacheItem->set($parameters); $this->cacheAdapter->save($cacheItem); } catch (ExceptionInterface $exception) { - $this->logger->warning('Cannot fetch OpenID discovery parameters: ' . $exception->getMessage()); + $this->logger->warning('Cannot fetch OpenID discovery parameters: '.$exception->getMessage()); + return; } catch (\JsonException $exception) { - $this->logger->warning('Cannot fetch OpenID discovery parameters: ' . $exception->getMessage()); + $this->logger->warning('Cannot fetch OpenID discovery parameters: '.$exception->getMessage()); + return; } } @@ -73,9 +74,6 @@ protected function populateParameters(): void $this->ready = true; } - /** - * @return bool - */ public function canVerifySignature(): bool { return $this->isValid() && $this->has('jwks_uri'); @@ -83,6 +81,7 @@ public function canVerifySignature(): bool /** * @return array|null + * * @throws Base64DecodeException * @throws ClientExceptionInterface * @throws InvalidArgumentException @@ -91,6 +90,7 @@ public function canVerifySignature(): bool * @throws ServerExceptionInterface * @throws TransportExceptionInterface * @throws \JsonException + * * @see https://auth0.com/docs/tokens/json-web-tokens/json-web-key-sets */ public function getPems(): ?array @@ -98,13 +98,14 @@ public function getPems(): ?array $jwksData = $this->getJwksData(); if (null !== $jwksData && isset($jwksData['keys'])) { $converter = new JWKConverter(); + return $converter->multipleToPEM($jwksData['keys']); } + return null; } /** - * @return array|null * @throws ClientExceptionInterface * @throws InvalidArgumentException * @throws RedirectionExceptionInterface @@ -119,7 +120,7 @@ protected function getJwksData(): ?array if (!is_string($jwksUri) || empty($jwksUri)) { return null; } - $cacheItem = $this->cacheAdapter->getItem('jwks_uri_' . \md5($jwksUri)); + $cacheItem = $this->cacheAdapter->getItem('jwks_uri_'.\md5($jwksUri)); if ($cacheItem->isHit()) { $data = $cacheItem->get(); if (is_array($data)) { @@ -142,6 +143,7 @@ protected function getJwksData(): ?array $this->cacheAdapter->save($cacheItem); } } + return $this->jwksData; } } diff --git a/lib/OpenId/src/Exception/DiscoveryNotAvailableException.php b/lib/OpenId/src/Exception/DiscoveryNotAvailableException.php index 11e46c0d..7af29cb6 100644 --- a/lib/OpenId/src/Exception/DiscoveryNotAvailableException.php +++ b/lib/OpenId/src/Exception/DiscoveryNotAvailableException.php @@ -4,14 +4,12 @@ namespace RZ\Roadiz\OpenId\Exception; -use Throwable; - final class DiscoveryNotAvailableException extends \RuntimeException { public function __construct( string $message = 'OpenID discovery is not configured', int $code = 0, - Throwable $previous = null + ?\Throwable $previous = null, ) { parent::__construct($message, $code, $previous); } diff --git a/lib/OpenId/src/Exception/OpenIdAuthenticationException.php b/lib/OpenId/src/Exception/OpenIdAuthenticationException.php index dcd0f329..c5df09ba 100644 --- a/lib/OpenId/src/Exception/OpenIdAuthenticationException.php +++ b/lib/OpenId/src/Exception/OpenIdAuthenticationException.php @@ -10,8 +10,6 @@ final class OpenIdAuthenticationException extends AuthenticationException { /** * Message key to be used by the translation component. - * - * @return string */ public function getMessageKey(): string { diff --git a/lib/OpenId/src/Exception/OpenIdConfigurationException.php b/lib/OpenId/src/Exception/OpenIdConfigurationException.php index 4d0d8365..99b61a9f 100644 --- a/lib/OpenId/src/Exception/OpenIdConfigurationException.php +++ b/lib/OpenId/src/Exception/OpenIdConfigurationException.php @@ -4,14 +4,12 @@ namespace RZ\Roadiz\OpenId\Exception; -use Throwable; - final class OpenIdConfigurationException extends \RuntimeException { public function __construct( string $message = 'OpenID configuration is not valid', int $code = 0, - Throwable $previous = null + ?\Throwable $previous = null, ) { parent::__construct($message, $code, $previous); } diff --git a/lib/OpenId/src/OAuth2LinkGenerator.php b/lib/OpenId/src/OAuth2LinkGenerator.php index 1ba870d1..92b29ade 100644 --- a/lib/OpenId/src/OAuth2LinkGenerator.php +++ b/lib/OpenId/src/OAuth2LinkGenerator.php @@ -20,16 +20,11 @@ public function __construct( protected readonly ?string $openIdHostedDomain, protected readonly ?string $oauthClientId, ?array $openIdScopes, - protected readonly bool $forceSslOnRedirectUri + protected readonly bool $forceSslOnRedirectUri, ) { $this->openIdScopes = array_filter($openIdScopes ?? []); } - /** - * @param Request $request - * - * @return bool - */ public function isSupported(Request $request): bool { return null !== $this->discovery && $this->discovery->isValid(); @@ -39,19 +34,15 @@ public function generate( Request $request, string $redirectUri, array $state = [], - string $responseType = 'code' + string $responseType = 'code', ): string { if (null === $this->discovery) { - throw new DiscoveryNotAvailableException( - 'OpenID discovery is not well configured' - ); + throw new DiscoveryNotAvailableException('OpenID discovery is not well configured'); } /** @var array $supportedResponseTypes */ $supportedResponseTypes = $this->discovery->get('response_types_supported', []); if (!in_array($responseType, $supportedResponseTypes)) { - throw new DiscoveryNotAvailableException( - 'OpenID response_type is not supported by your identity provider' - ); + throw new DiscoveryNotAvailableException('OpenID response_type is not supported by your identity provider'); } /* @@ -73,11 +64,12 @@ public function generate( $customScopes = $supportedScopes; } $stateToken = $this->csrfTokenManager->getToken(static::OAUTH_STATE_TOKEN); - return $this->discovery->get('authorization_endpoint') . '?' . http_build_query([ + + return $this->discovery->get('authorization_endpoint').'?'.http_build_query([ 'response_type' => $responseType, 'hd' => $this->openIdHostedDomain, 'state' => http_build_query(array_merge($state, [ - 'token' => $stateToken->getValue() + 'token' => $stateToken->getValue(), ])), 'nonce' => (new TokenGenerator())->generateToken(), 'login_hint' => $request->get('email', null), diff --git a/lib/OpenId/src/OpenIdJwtConfigurationFactory.php b/lib/OpenId/src/OpenIdJwtConfigurationFactory.php index 8b7279f6..de297ae6 100644 --- a/lib/OpenId/src/OpenIdJwtConfigurationFactory.php +++ b/lib/OpenId/src/OpenIdJwtConfigurationFactory.php @@ -24,7 +24,7 @@ public function __construct( private readonly HttpClientInterface $client, private readonly ?string $openIdHostedDomain, private readonly ?string $oauthClientId, - private readonly bool $verifyUserInfo + private readonly bool $verifyUserInfo, ) { } @@ -65,9 +65,9 @@ public function create(): ?Configuration * Verify JWT signature if asymmetric crypto is used and if PHP gmp extension is loaded. */ if ( - null !== $this->discovery && - $this->discovery->canVerifySignature() && - null !== $pems = $this->discovery->getPems() + null !== $this->discovery + && $this->discovery->canVerifySignature() + && null !== $pems = $this->discovery->getPems() ) { /** @var array $signingAlgValuesSupported */ $signingAlgValuesSupported = $this->discovery->get('id_token_signing_alg_values_supported', []); @@ -75,8 +75,8 @@ public function create(): ?Configuration in_array( 'RS256', $signingAlgValuesSupported - ) && - !empty($pems[0]) + ) + && !empty($pems[0]) ) { $configuration = Configuration::forAsymmetricSigner( new Sha256(), @@ -84,6 +84,7 @@ public function create(): ?Configuration InMemory::plainText($pems[0]) ); $configuration->setValidationConstraints(...$this->getValidationConstraints()); + return $configuration; } } diff --git a/lib/OpenId/src/User/OpenIdAccount.php b/lib/OpenId/src/User/OpenIdAccount.php index ce90fb33..575df9dc 100644 --- a/lib/OpenId/src/User/OpenIdAccount.php +++ b/lib/OpenId/src/User/OpenIdAccount.php @@ -18,68 +18,64 @@ class OpenIdAccount implements UserInterface, EquatableInterface { /** * @var array + * * @SymfonySerializer\Groups({"user"}) */ - #[Groups(["user"])] + #[Groups(['user'])] protected array $roles; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $issuer = null; - #[Groups(["user"])] + #[Groups(['user'])] protected string $email; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $name = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $nickname = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $website = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $locale = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $phoneNumber = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?array $address = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $familyName = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $middleName = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $givenName = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $picture = null; - #[Groups(["user"])] + #[Groups(['user'])] protected ?string $profile = null; #[Ignore] protected Token $jwtToken; - /** - * @param string $email - * @param array $roles - * @param Token $jwtToken - */ public function __construct( string $email, array $roles, - Token $jwtToken + Token $jwtToken, ) { $this->roles = $roles; $this->email = $email; $this->jwtToken = $jwtToken; if (!($jwtToken instanceof Token\Plain)) { - throw new \InvalidArgumentException('Token must be an instance of ' . Token\Plain::class); + throw new \InvalidArgumentException('Token must be an instance of '.Token\Plain::class); } /* * https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims @@ -105,19 +101,19 @@ private function getStringClaim(Token\DataSet $claims, string $claimName): ?stri if (!empty($claimName) && $claims->has($claimName) && is_string($claims->get($claimName))) { return $claims->get($claimName); } + return null; } + private function getArrayClaim(Token\DataSet $claims, string $claimName): ?array { if (!empty($claimName) && $claims->has($claimName) && is_array($claims->get($claimName))) { return $claims->get($claimName); } + return null; } - /** - * @inheritDoc - */ public function getRoles(): array { return $this->roles; @@ -138,10 +134,6 @@ public function getUsername(): string return $this->email ?? ''; } - /** - * @inheritDoc - * @return void - */ public function eraseCredentials(): void { return; @@ -172,73 +164,46 @@ public function getPicture(): ?string return $this->picture; } - /** - * @return string|null - */ public function getNickname(): ?string { return $this->nickname; } - /** - * @return string|null - */ public function getWebsite(): ?string { return $this->website; } - /** - * @return string|null - */ public function getLocale(): ?string { return $this->locale; } - /** - * @return string|null - */ public function getPhoneNumber(): ?string { return $this->phoneNumber; } - /** - * @return array|null - */ public function getAddress(): ?array { return $this->address; } - /** - * @return string|null - */ public function getMiddleName(): ?string { return $this->middleName; } - /** - * @return string|null - */ public function getProfile(): ?string { return $this->profile; } - /** - * @return Token - */ public function getJwtToken(): Token { return $this->jwtToken; } - /** - * @return string|null - */ public function getIssuer(): ?string { return $this->issuer; diff --git a/lib/Random/src/PasswordGenerator.php b/lib/Random/src/PasswordGenerator.php index ef24af05..2ee39a80 100644 --- a/lib/Random/src/PasswordGenerator.php +++ b/lib/Random/src/PasswordGenerator.php @@ -14,7 +14,6 @@ class PasswordGenerator extends RandomGenerator implements PasswordGeneratorInte * The available characters in each set are user friendly - there are no ambiguous * characters such as i, l, 1, o, 0, etc. * - * @param int $length * @return string * * @see https://gist.github.com/tylerhall/521810 @@ -35,7 +34,7 @@ public function generatePassword(int $length = 12) } $all = \mb_str_split($all); - for ($i = 0; $i < $length - count($sets); $i++) { + for ($i = 0; $i < $length - count($sets); ++$i) { $password .= $all[array_rand($all)]; } diff --git a/lib/Random/src/PasswordGeneratorInterface.php b/lib/Random/src/PasswordGeneratorInterface.php index 89ebbd51..4fc48a82 100644 --- a/lib/Random/src/PasswordGeneratorInterface.php +++ b/lib/Random/src/PasswordGeneratorInterface.php @@ -7,7 +7,6 @@ interface PasswordGeneratorInterface { /** - * @param int $length * @return string */ public function generatePassword(int $length = 12); diff --git a/lib/Random/src/RandomGenerator.php b/lib/Random/src/RandomGenerator.php index 0efe77ec..4913c0a4 100644 --- a/lib/Random/src/RandomGenerator.php +++ b/lib/Random/src/RandomGenerator.php @@ -11,10 +11,7 @@ class RandomGenerator protected ?LoggerInterface $logger; protected bool $useOpenSsl; - /** - * @param LoggerInterface|null $logger - */ - public function __construct(LoggerInterface $logger = null) + public function __construct(?LoggerInterface $logger = null) { $this->logger = $logger; // determine whether to use OpenSSL @@ -30,10 +27,6 @@ public function __construct(LoggerInterface $logger = null) } } - /** - * @param int $nbBytes - * @return string - */ public function getRandomNumber(int $nbBytes = 32): string { // try OpenSSL diff --git a/lib/RoadizCompatBundle/deprecated.php b/lib/RoadizCompatBundle/deprecated.php index a5e6be9b..e57d320f 100644 --- a/lib/RoadizCompatBundle/deprecated.php +++ b/lib/RoadizCompatBundle/deprecated.php @@ -1,4 +1,5 @@ \RZ\Roadiz\CMS\Controllers\AppController::class, - \RZ\Roadiz\CompatBundle\Controller\Controller::class => \RZ\Roadiz\CMS\Controllers\Controller::class, - \RZ\Roadiz\CompatBundle\Theme\ThemeResolverInterface::class => \RZ\Roadiz\Utils\Theme\ThemeResolverInterface::class, + Controller\AppController::class => \RZ\Roadiz\CMS\Controllers\AppController::class, + Controller\Controller::class => \RZ\Roadiz\CMS\Controllers\Controller::class, + Theme\ThemeResolverInterface::class => \RZ\Roadiz\Utils\Theme\ThemeResolverInterface::class, \RZ\Roadiz\CoreBundle\Bag\NodeTypes::class => \RZ\Roadiz\Core\Bags\NodeTypes::class, \RZ\Roadiz\CoreBundle\Bag\Roles::class => \RZ\Roadiz\Core\Bags\Roles::class, \RZ\Roadiz\CoreBundle\Bag\Settings::class => \RZ\Roadiz\Core\Bags\Settings::class, diff --git a/lib/RoadizCompatBundle/src/Console/ThemeAssetsCommand.php b/lib/RoadizCompatBundle/src/Console/ThemeAssetsCommand.php index 0fb1f5f1..cc07b9a8 100644 --- a/lib/RoadizCompatBundle/src/Console/ThemeAssetsCommand.php +++ b/lib/RoadizCompatBundle/src/Console/ThemeAssetsCommand.php @@ -21,7 +21,7 @@ final class ThemeAssetsCommand extends Command public function __construct( #[Autowire('%kernel.project_dir%')] private readonly string $projectDir, - private readonly ThemeGenerator $themeGenerator + private readonly ThemeGenerator $themeGenerator, ) { parent::__construct(); } @@ -61,18 +61,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int $themeInfo = new ThemeInfo($name, $this->projectDir); if (!$themeInfo->exists()) { - throw new InvalidArgumentException($themeInfo->getThemePath() . ' does not exist.'); + throw new InvalidArgumentException($themeInfo->getThemePath().' does not exist.'); } $io->table([ - 'Description', 'Value' + 'Description', 'Value', ], [ ['Given name', $themeInfo->getName()], ['Theme path', $themeInfo->getThemePath()], - ['Assets path', $themeInfo->getThemePath() . '/static'], + ['Assets path', $themeInfo->getThemePath().'/static'], ]); $this->themeGenerator->installThemeAssets($themeInfo, $expectedMethod); + return 0; } } diff --git a/lib/RoadizCompatBundle/src/Console/ThemeInfoCommand.php b/lib/RoadizCompatBundle/src/Console/ThemeInfoCommand.php index 9b30c52d..deff2f6c 100644 --- a/lib/RoadizCompatBundle/src/Console/ThemeInfoCommand.php +++ b/lib/RoadizCompatBundle/src/Console/ThemeInfoCommand.php @@ -45,20 +45,21 @@ protected function execute(InputInterface $input, OutputInterface $output): int $themeInfo = new ThemeInfo($name, $this->projectDir); if (!$themeInfo->exists()) { - throw new InvalidArgumentException($themeInfo->getClassname() . ' does not exist.'); + throw new InvalidArgumentException($themeInfo->getClassname().' does not exist.'); } if (!$themeInfo->isValid()) { - throw new InvalidArgumentException($themeInfo->getClassname() . ' is not a valid theme.'); + throw new InvalidArgumentException($themeInfo->getClassname().' is not a valid theme.'); } $io->table([ - 'Description', 'Value' + 'Description', 'Value', ], [ ['Given name', $themeInfo->getName()], ['Theme classname', $themeInfo->getClassname()], ['Theme path', $themeInfo->getThemePath()], - ['Assets path', $themeInfo->getThemePath() . '/static'], + ['Assets path', $themeInfo->getThemePath().'/static'], ]); + return 0; } } diff --git a/lib/RoadizCompatBundle/src/Console/ThemesListCommand.php b/lib/RoadizCompatBundle/src/Console/ThemesListCommand.php index 3f1768e2..11329166 100644 --- a/lib/RoadizCompatBundle/src/Console/ThemesListCommand.php +++ b/lib/RoadizCompatBundle/src/Console/ThemesListCommand.php @@ -18,7 +18,7 @@ final class ThemesListCommand extends Command { public function __construct( - private readonly ThemeResolverInterface $themeResolver + private readonly ThemeResolverInterface $themeResolver, ) { parent::__construct(); } @@ -34,12 +34,6 @@ protected function configure(): void ); } - /** - * @param InputInterface $input - * @param OutputInterface $output - * - * @return int - */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); @@ -54,12 +48,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int $name = str_replace('/', '\\', $name); $theme = $this->themeResolver->findThemeByClass($name); if (null === $theme) { - throw new InvalidArgumentException($name . ' theme cannot be found.'); + throw new InvalidArgumentException($name.' theme cannot be found.'); } $tableContent[] = [ str_replace('\\', '/', $theme->getClassName()), - ($theme->isAvailable() ? 'X' : ''), - ($theme->isBackendTheme() ? 'Backend' : 'Frontend'), + $theme->isAvailable() ? 'X' : '', + $theme->isBackendTheme() ? 'Backend' : 'Frontend', ]; } else { $themes = $this->themeResolver->findAll(); @@ -67,8 +61,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int foreach ($themes as $theme) { $tableContent[] = [ str_replace('\\', '/', $theme->getClassName()), - ($theme->isAvailable() ? 'X' : ''), - ($theme->isBackendTheme() ? 'Backend' : 'Frontend'), + $theme->isAvailable() ? 'X' : '', + $theme->isBackendTheme() ? 'Backend' : 'Frontend', ]; } } else { @@ -77,6 +71,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $io->table(['Class (with / instead of \)', 'Enabled', 'Type'], $tableContent); + return 0; } } diff --git a/lib/RoadizCompatBundle/src/Controller/AppController.php b/lib/RoadizCompatBundle/src/Controller/AppController.php index ab8979fc..4c83112f 100644 --- a/lib/RoadizCompatBundle/src/Controller/AppController.php +++ b/lib/RoadizCompatBundle/src/Controller/AppController.php @@ -6,8 +6,6 @@ use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; -use ReflectionClass; -use ReflectionException; use RZ\Roadiz\CompatBundle\Theme\ThemeResolverInterface; use RZ\Roadiz\CoreBundle\Entity\Theme; use RZ\Roadiz\CoreBundle\Exception\ThemeClassNotValidException; @@ -32,32 +30,25 @@ abstract class AppController extends Controller public const SCHEMA_TOKEN_INTENTION = 'update_schema'; /** - * @var int Theme priority to load templates and translation in the right order. + * @var int theme priority to load templates and translation in the right order */ public static int $priority = 0; /** * Theme name. - * - * @var string */ protected static string $themeName = ''; /** * Theme author description. - * - * @var string */ protected static string $themeAuthor = ''; /** * Theme copyright licence. - * - * @var string */ protected static string $themeCopyright = ''; /** * Theme base directory name. * * Example: "MyTheme" will be located in "themes/MyTheme" - * @var string */ protected static string $themeDir = ''; /** @@ -65,14 +56,10 @@ abstract class AppController extends Controller * * Example: "*" will accept any CMS version. Or "3.0.*" will * accept any build version of 3.0. - * - * @var string */ protected static string $themeRequire = '*'; /** * Is theme for backend? - * - * @var bool */ protected static bool $backendTheme = false; protected ?Theme $theme = null; @@ -81,49 +68,31 @@ abstract class AppController extends Controller */ protected array $assignation = []; - /** - * @return string - */ public static function getThemeName(): string { return static::$themeName; } - /** - * @return string - */ public static function getThemeAuthor(): string { return static::$themeAuthor; } - /** - * @return string - */ public static function getThemeCopyright(): string { return static::$themeCopyright; } - /** - * @return int - */ public static function getPriority(): int { return static::$priority; } - /** - * @return string - */ public static function getThemeRequire(): string { return static::$themeRequire; } - /** - * @return boolean - */ public static function isBackendTheme(): bool { return static::$backendTheme; @@ -136,46 +105,44 @@ public static function isBackendTheme(): bool * Uses \ReflectionClass to resolve final theme class folder * whether it’s located in project folder or in vendor folder. * - * @return string - * @throws ReflectionException + * @throws \ReflectionException * @throws ThemeClassNotValidException */ public static function getResourcesFolder(): string { - return static::getThemeFolder() . '/Resources'; + return static::getThemeFolder().'/Resources'; } /** * Return theme root folder. * - * @return string - * @throws ReflectionException|ThemeClassNotValidException + * @throws \ReflectionException|ThemeClassNotValidException */ public static function getThemeFolder(): string { - $class_info = new ReflectionClass(static::getThemeMainClass()); + $class_info = new \ReflectionClass(static::getThemeMainClass()); if (false === $themeFilename = $class_info->getFileName()) { throw new ThemeClassNotValidException('Theme class file is not valid or does not exist'); } + return dirname($themeFilename); } /** * @return class-string Main theme class (FQN class with namespace) + * * @throws ThemeClassNotValidException */ public static function getThemeMainClass(): string { - $mainClassName = '\\Themes\\' . static::getThemeDir() . '\\' . static::getThemeMainClassName(); + $mainClassName = '\\Themes\\'.static::getThemeDir().'\\'.static::getThemeMainClassName(); if (!class_exists($mainClassName)) { throw new ThemeClassNotValidException(sprintf('%s class does not exist', $mainClassName)); } + return $mainClassName; } - /** - * @return string - */ public static function getThemeDir(): string { return static::$themeDir; @@ -186,39 +153,33 @@ public static function getThemeDir(): string */ public static function getThemeMainClassName(): string { - return static::getThemeDir() . 'App'; + return static::getThemeDir().'App'; } /** - * @return string - * @throws ReflectionException + * @throws \ReflectionException */ public static function getTranslationsFolder(): string { - return static::getResourcesFolder() . '/translations'; + return static::getResourcesFolder().'/translations'; } /** - * @return string - * @throws ReflectionException|ThemeClassNotValidException + * @throws \ReflectionException|ThemeClassNotValidException */ public static function getPublicFolder(): string { - return static::getThemeFolder() . '/static'; + return static::getThemeFolder().'/static'; } /** - * @return string - * @throws ReflectionException + * @throws \ReflectionException */ public static function getViewsFolder(): string { - return static::getResourcesFolder() . '/views'; + return static::getResourcesFolder().'/views'; } - /** - * @return array - */ public function getAssignation(): array { return $this->assignation; @@ -255,6 +216,7 @@ public function getAssignation(): array * - securityAuthorizationChecker * * @return $this + * * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ @@ -267,8 +229,8 @@ public function prepareBaseAssignation(): static 'ajax' => $this->getRequest()->isXmlHttpRequest(), 'devMode' => $kernel->isDebug(), 'maintenanceMode' => (bool) $this->getSettingsBag()->get('maintenance_mode'), - 'baseUrl' => $this->getRequest()->getSchemeAndHttpHost() . $this->getRequest()->getBasePath(), - ] + 'baseUrl' => $this->getRequest()->getSchemeAndHttpHost().$this->getRequest()->getBasePath(), + ], ]; return $this; @@ -277,9 +239,8 @@ public function prepareBaseAssignation(): static /** * Return a Response with default backend 404 error page. * - * @param string $message Additional message to describe 404 error. + * @param string $message additional message to describe 404 error * - * @return Response * @throws LoaderError * @throws RuntimeError * @throws SyntaxError @@ -300,9 +261,8 @@ public function throw404(string $message = ''): Response } /** - * Return the current Theme + * Return the current Theme. * - * @return Theme|null * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ @@ -315,7 +275,7 @@ public function getTheme(): ?Theme $className = new UnicodeString(static::getCalledClass()); while (!$className->endsWith('App')) { $className = get_parent_class($className->toString()); - if ($className === false) { + if (false === $className) { $className = new UnicodeString(''); break; } @@ -324,16 +284,13 @@ public function getTheme(): ?Theme $this->theme = $themeResolver->findThemeByClass($className->toString()); } $this->getStopwatch()->stop('getTheme'); + return $this->theme; } /** * Publish a confirmation message in Session flash bag and * logger interface. - * - * @param Request $request - * @param string $msg - * @param object|null $source */ public function publishConfirmMessage(Request $request, string $msg, ?object $source = null): void { @@ -343,17 +300,12 @@ public function publishConfirmMessage(Request $request, string $msg, ?object $so /** * Publish a message in Session flash bag and * logger interface. - * - * @param Request $request - * @param string $msg - * @param string $level - * @param object|null $source */ protected function publishMessage( Request $request, string $msg, - string $level = "confirm", - ?object $source = null + string $level = 'confirm', + ?object $source = null, ): void { $session = $this->getSession(); if ($session instanceof Session) { @@ -374,23 +326,17 @@ protected function publishMessage( /** * Returns the current session. - * - * @return SessionInterface|null */ public function getSession(): ?SessionInterface { $request = $this->getRequest(); + return $request->hasPreviousSession() ? $request->getSession() : null; } /** * Publish an error message in Session flash bag and * logger interface. - * - * @param Request $request - * @param string $msg - * @param object|null $source - * @return void */ public function publishErrorMessage(Request $request, string $msg, ?object $source = null): void { @@ -401,8 +347,6 @@ public function publishErrorMessage(Request $request, string $msg, ?object $sour * Generate a simple view to inform visitors that website is * currently unavailable. * - * @param Request $request - * @return Response * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ @@ -430,19 +374,16 @@ public function maintenanceAction(Request $request): Response * - we are in maintenance mode * - this is a sub-request * - * @param Request $request - * @param Response $response - * @param int $minutes TTL in minutes + * @param int $minutes TTL in minutes * @param bool $allowClientCache Allows browser level cache * - * @return Response * @deprecated Use stateless routes and cache-control headers in your controllers */ public function makeResponseCachable( Request $request, Response $response, int $minutes, - bool $allowClientCache = false + bool $allowClientCache = false, ): Response { /** @var Kernel $kernel */ $kernel = $this->container->get('kernel'); @@ -451,12 +392,12 @@ public function makeResponseCachable( $settings = $this->getSettingsBag(); if ( - !$this->getPreviewResolver()->isPreview() && - !$kernel->isDebug() && - $requestStack->getMainRequest() === $request && - $request->isMethodCacheable() && - $minutes > 0 && - !$settings->get('maintenance_mode', false) + !$this->getPreviewResolver()->isPreview() + && !$kernel->isDebug() + && $requestStack->getMainRequest() === $request + && $request->isMethodCacheable() + && $minutes > 0 + && !$settings->get('maintenance_mode', false) ) { header_remove('Cache-Control'); header_remove('Vary'); @@ -474,7 +415,7 @@ public function makeResponseCachable( if ($request->isXmlHttpRequest()) { $response->headers->add([ - 'X-Partial' => true + 'X-Partial' => true, ]); } } diff --git a/lib/RoadizCompatBundle/src/Controller/Controller.php b/lib/RoadizCompatBundle/src/Controller/Controller.php index 598b7923..b631d4cb 100644 --- a/lib/RoadizCompatBundle/src/Controller/Controller.php +++ b/lib/RoadizCompatBundle/src/Controller/Controller.php @@ -104,12 +104,11 @@ public static function getSubscribedServices(): array TokenStorageInterface::class => TokenStorageInterface::class, TranslatorInterface::class => TranslatorInterface::class, FormFactoryInterface::class => FormFactoryInterface::class, - \RZ\Roadiz\Core\Handlers\HandlerFactoryInterface::class => HandlerFactoryInterface::class, + HandlerFactoryInterface::class => HandlerFactoryInterface::class, ]); } /** - * @return Request * @deprecated */ protected function getRequest(): Request @@ -120,26 +119,26 @@ protected function getRequest(): Request if (null === $request) { throw new BadRequestHttpException('Request is not available in this context'); } + return $request; } /** * Alias for `$this->container['securityTokenStorage']`. * - * @return TokenStorageInterface * @deprecated */ protected function getTokenStorage(): TokenStorageInterface { - /** @var TokenStorageInterface $tokenStorage */ # php-stan hint + /** @var TokenStorageInterface $tokenStorage */ // php-stan hint $tokenStorage = $this->container->get(TokenStorageInterface::class); + return $tokenStorage; } /** * Alias for `$this->container['em']`. * - * @return ObjectManager * @deprecated */ protected function em(): ObjectManager @@ -148,35 +147,35 @@ protected function em(): ObjectManager } /** - * @return TranslatorInterface * @deprecated */ protected function getTranslator(): TranslatorInterface { - /** @var TranslatorInterface $translator */ # php-stan hint + /** @var TranslatorInterface $translator */ // php-stan hint $translator = $this->container->get(TranslatorInterface::class); + return $translator; } /** - * @return Environment * @deprecated */ protected function getTwig(): Environment { - /** @var Environment $twig */ # php-stan hint + /** @var Environment $twig */ // php-stan hint $twig = $this->container->get(Environment::class); + return $twig; } /** - * @return Stopwatch * @deprecated */ protected function getStopwatch(): Stopwatch { /** @var Stopwatch $stopwatch */ $stopwatch = $this->container->get(Stopwatch::class); + return $stopwatch; } @@ -187,13 +186,14 @@ protected function getPreviewResolver(): PreviewResolverInterface { /** @var PreviewResolverInterface $previewResolver */ $previewResolver = $this->container->get(PreviewResolverInterface::class); + return $previewResolver; } /** - * @return ManagerRegistry * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface + * * @deprecated */ protected function getDoctrine(): ManagerRegistry @@ -202,70 +202,69 @@ protected function getDoctrine(): ManagerRegistry } /** - * @param object $event - * @param string|null $eventName * @return object The passed $event MUST be returned + * * @deprecated */ - protected function dispatchEvent(object $event, string $eventName = null): object + protected function dispatchEvent(object $event, ?string $eventName = null): object { - /** @var EventDispatcherInterface $eventDispatcher */ # php-stan hint + /** @var EventDispatcherInterface $eventDispatcher */ // php-stan hint $eventDispatcher = $this->container->get(EventDispatcherInterface::class); + return $eventDispatcher->dispatch($event, $eventName); } /** - * @return Settings * @deprecated */ protected function getSettingsBag(): Settings { - /** @var Settings $settingsBag */ # php-stan hint + /** @var Settings $settingsBag */ // php-stan hint $settingsBag = $this->container->get(Settings::class); + return $settingsBag; } /** - * @return HandlerFactoryInterface * @deprecated */ protected function getHandlerFactory(): HandlerFactoryInterface { - /** @var HandlerFactoryInterface $handlerFactory */ # php-stan hint + /** @var HandlerFactoryInterface $handlerFactory */ // php-stan hint $handlerFactory = $this->container->get(HandlerFactoryInterface::class); + return $handlerFactory; } /** - * @return LoggerInterface * @deprecated */ protected function getLogger(): LoggerInterface { - /** @var LoggerInterface $logger */ # php-stan hint + /** @var LoggerInterface $logger */ // php-stan hint $logger = $this->container->get(LoggerInterface::class); + return $logger; } /** - * Wrap `$this->get('urlGenerator')->generate` + * Wrap `$this->get('urlGenerator')->generate`. * * @param string|NodesSources $route - * @param array $parameters - * @param int $referenceType - * @return string */ protected function generateUrl($route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string { if ($route instanceof NodesSources) { /** @var UrlGeneratorInterface $urlGenerator */ $urlGenerator = $this->container->get(UrlGeneratorInterface::class); + return $urlGenerator->generate( RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, array_merge($parameters, [RouteObjectInterface::ROUTE_OBJECT => $route]), $referenceType ); } + return parent::generateUrl($route, $parameters, $referenceType); } @@ -275,19 +274,16 @@ protected function generateUrl($route, array $parameters = [], int $referenceTyp public static function getCalledClass(): string { $className = get_called_class(); - if (!str_starts_with($className, "\\")) { - $className = "\\" . $className; + if (!str_starts_with($className, '\\')) { + $className = '\\'.$className; } + // @phpstan-ignore-next-line return $className; } /** * Custom route for redirecting routes with a trailing slash. - * - * @param Request $request - * - * @return RedirectResponse */ public function removeTrailingSlashAction(Request $request): RedirectResponse { @@ -300,18 +296,16 @@ public function removeTrailingSlashAction(Request $request): RedirectResponse } /** - * @param string|null $_locale - * - * @return TranslationInterface * @throws NonUniqueResultException */ - protected function findTranslationForLocale(string $_locale = null): TranslationInterface + protected function findTranslationForLocale(?string $_locale = null): TranslationInterface { if (null === $_locale) { $defaultTranslation = $this->getDoctrine()->getRepository(Translation::class)->findDefault(); if (null === $defaultTranslation) { throw new NoTranslationAvailableException(); } + return $defaultTranslation; } /** @var TranslationRepository $repository */ @@ -335,15 +329,14 @@ protected function findTranslationForLocale(string $_locale = null): Translation * * @see http://api.symfony.com/2.6/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_render * - * @param string $view Template file path + * @param string $view Template file path * @param array $parameters Twig assignation array - * @param Response|null $response Optional Response object to customize response parameters - * @param string $namespace Twig loader namespace + * @param Response|null $response Optional Response object to customize response parameters + * @param string $namespace Twig loader namespace * - * @return Response * @throws RuntimeError */ - public function render(string $view, array $parameters = [], Response $response = null, string $namespace = ''): Response + public function render(string $view, array $parameters = [], ?Response $response = null, string $namespace = ''): Response { try { return parent::render($view, $parameters, $response); @@ -356,25 +349,15 @@ public function render(string $view, array $parameters = [], Response $response } } - /** - * @param string $view - * @param string $namespace - * @return string - */ protected function getNamespacedView(string $view, string $namespace = ''): string { - if ($namespace !== "" && $namespace !== "/") { - return '@' . $namespace . '/' . $view; + if ('' !== $namespace && '/' !== $namespace) { + return '@'.$namespace.'/'.$view; } return $view; } - /** - * @param array $data - * @param int $httpStatus - * @return JsonResponse - */ public function renderJson(array $data = [], int $httpStatus = Response::HTTP_OK): JsonResponse { return $this->json($data, $httpStatus); @@ -383,34 +366,31 @@ public function renderJson(array $data = [], int $httpStatus = Response::HTTP_OK /** * Throw a NotFoundException if request format is not accepted. * - * @param Request $request - * @param array $acceptableFormats * @return void */ protected function denyResourceExceptForFormats(Request $request, array $acceptableFormats = ['html']) { if (!in_array($request->get('_format', 'html'), $acceptableFormats)) { - throw $this->createNotFoundException(sprintf( - 'Resource not found for %s format', - $request->get('_format', 'html') - )); + throw $this->createNotFoundException(sprintf('Resource not found for %s format', $request->get('_format', 'html'))); } } /** * Creates and returns a form builder instance. * - * @param string $name Form name - * @param mixed $data The initial data for the form - * @param array $options Options for the form + * @param string $name Form name + * @param mixed $data The initial data for the form + * @param array $options Options for the form * * @return FormBuilderInterface + * * @deprecated Use constructor service injection */ protected function createNamedFormBuilder(string $name = 'form', $data = null, array $options = []) { /** @var FormFactoryInterface $formFactory */ $formFactory = $this->container->get(FormFactoryInterface::class); + return $formFactory->createNamedBuilder($name, FormType::class, $data, $options); } @@ -418,10 +398,6 @@ protected function createNamedFormBuilder(string $name = 'form', $data = null, a * Creates and returns an EntityListManager instance. * * @param class-string $entity Entity class path - * @param array $criteria - * @param array $ordering - * - * @return EntityListManagerInterface */ public function createEntityListManager(string $entity, array $criteria = [], array $ordering = []): EntityListManagerInterface { @@ -437,8 +413,6 @@ public function createEntityListManager(string $entity, array $criteria = [], ar /** * Get a user from the tokenStorage. * - * @return UserInterface|null - * * @throws \LogicException If tokenStorage is not available * * @see TokenInterface::getUser() @@ -447,6 +421,7 @@ protected function getUser(): ?UserInterface { /** @var TokenInterface|null $token */ $token = $this->getTokenStorage()->getToken(); + return $token?->getUser(); } } diff --git a/lib/RoadizCompatBundle/src/DependencyInjection/Compiler/ThemesTranslatorPathsCompilerPass.php b/lib/RoadizCompatBundle/src/DependencyInjection/Compiler/ThemesTranslatorPathsCompilerPass.php index 0e4997b7..09e6cd48 100644 --- a/lib/RoadizCompatBundle/src/DependencyInjection/Compiler/ThemesTranslatorPathsCompilerPass.php +++ b/lib/RoadizCompatBundle/src/DependencyInjection/Compiler/ThemesTranslatorPathsCompilerPass.php @@ -11,9 +11,6 @@ final class ThemesTranslatorPathsCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->hasDefinition('translator.default')) { @@ -51,8 +48,8 @@ private function registerThemeTranslatorResources(ContainerBuilder $container): ->followLinks() ->files() ->filter(function (\SplFileInfo $file) { - return 2 <= \mb_substr_count($file->getBasename(), '.') && - \preg_match('/\.\w+$/', $file->getBasename()); + return 2 <= \mb_substr_count($file->getBasename(), '.') + && \preg_match('/\.\w+$/', $file->getBasename()); }) ->in($translationFolder) ->sortByName() @@ -73,7 +70,7 @@ private function registerThemeTranslatorResources(ContainerBuilder $container): 'scanned_directories' => $scannedDirectories = [$translationFolder], 'cache_vary' => [ 'scanned_directories' => array_map(static function (string $dir) use ($projectDir): string { - return str_starts_with($dir, $projectDir . '/') ? \mb_substr($dir, 1 + \mb_strlen($projectDir)) : $dir; + return str_starts_with($dir, $projectDir.'/') ? \mb_substr($dir, 1 + \mb_strlen($projectDir)) : $dir; }, $scannedDirectories), ], ] diff --git a/lib/RoadizCompatBundle/src/DependencyInjection/Configuration.php b/lib/RoadizCompatBundle/src/DependencyInjection/Configuration.php index a22d94ff..d7461ae7 100644 --- a/lib/RoadizCompatBundle/src/DependencyInjection/Configuration.php +++ b/lib/RoadizCompatBundle/src/DependencyInjection/Configuration.php @@ -16,6 +16,7 @@ public function getConfigTreeBuilder(): TreeBuilder $builder = new TreeBuilder('roadiz_compat'); $root = $builder->getRootNode(); $root->append($this->addThemesNode()); + return $builder; } @@ -36,7 +37,7 @@ protected function addThemesNode() ->isRequired() ->validate() ->ifTrue(function (string $s) { - return preg_match('/^\\\[a-zA-Z\\\]+App$/', trim($s)) !== 1 || !class_exists($s); + return 1 !== preg_match('/^\\\[a-zA-Z\\\]+App$/', trim($s)) || !class_exists($s); }) ->thenInvalid('Theme class does not exist or classname is invalid: must start with \ character and ends with App suffix.') ->end() diff --git a/lib/RoadizCompatBundle/src/DependencyInjection/RoadizCompatExtension.php b/lib/RoadizCompatBundle/src/DependencyInjection/RoadizCompatExtension.php index b6490227..ebaf5412 100644 --- a/lib/RoadizCompatBundle/src/DependencyInjection/RoadizCompatExtension.php +++ b/lib/RoadizCompatBundle/src/DependencyInjection/RoadizCompatExtension.php @@ -20,12 +20,9 @@ class RoadizCompatExtension extends Extension { - /** - * @inheritDoc - */ public function load(array $configs, ContainerBuilder $container): void { - $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__) . '/../config')); + $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__).'/../config')); $loader->load('services.yaml'); $configuration = new Configuration(); @@ -51,7 +48,7 @@ private function registerThemes(array $config, ContainerBuilder $container): voi foreach ($config['themes'] as $index => $themeConfig) { $themeSlug = (new AsciiSlugger())->slug($themeConfig['classname'], '_'); - $serviceId = 'roadiz_compat.themes.' . $themeSlug; + $serviceId = 'roadiz_compat.themes.'.$themeSlug; /** @var class-string $className */ $className = $themeConfig['classname']; $themeDir = $className::getThemeDir(); @@ -73,26 +70,26 @@ private function registerThemes(array $config, ContainerBuilder $container): voi // Register asset packages $container->setDefinition( - 'roadiz_compat.assets._package.' . $themeSlug, + 'roadiz_compat.assets._package.'.$themeSlug, (new Definition()) ->setClass(PathPackage::class) ->setArguments([ - 'themes/' . $themeDir . '/static', + 'themes/'.$themeDir.'/static', new Reference('assets.empty_version_strategy'), - new Reference('assets.context') + new Reference('assets.context'), ]) ->addTag('assets.package', [ - 'package' => $themeDir + 'package' => $themeDir, ]) ); // Add Twig paths $container->getDefinition('roadiz_compat.twig_loader') ->addMethodCall('prependPath', [ - $className::getViewsFolder() + $className::getViewsFolder(), ]) ->addMethodCall('prependPath', [ - $className::getViewsFolder(), $themeDir + $className::getViewsFolder(), $themeDir, ]); } diff --git a/lib/RoadizCompatBundle/src/EventSubscriber/ControllerEventSubscriber.php b/lib/RoadizCompatBundle/src/EventSubscriber/ControllerEventSubscriber.php index ea44f91d..fafecac2 100644 --- a/lib/RoadizCompatBundle/src/EventSubscriber/ControllerEventSubscriber.php +++ b/lib/RoadizCompatBundle/src/EventSubscriber/ControllerEventSubscriber.php @@ -13,9 +13,6 @@ final class ControllerEventSubscriber implements EventSubscriberInterface { - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizCompatBundle/src/EventSubscriber/ExceptionSubscriber.php b/lib/RoadizCompatBundle/src/EventSubscriber/ExceptionSubscriber.php index d0b00ca3..ca9590eb 100644 --- a/lib/RoadizCompatBundle/src/EventSubscriber/ExceptionSubscriber.php +++ b/lib/RoadizCompatBundle/src/EventSubscriber/ExceptionSubscriber.php @@ -21,26 +21,19 @@ use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Security\Core\Exception\AccessDeniedException; -use Throwable; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Error\SyntaxError; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ final class ExceptionSubscriber implements EventSubscriberInterface { public function __construct( private readonly ThemeResolverInterface $themeResolver, private readonly ContainerInterface $serviceLocator, - private readonly bool $debug + private readonly bool $debug, ) { } - /** - * @return array - */ public static function getSubscribedEvents(): array { /* @@ -51,17 +44,13 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param Request $request - * @return bool - */ private function isFormatJson(Request $request): bool { if ( - $request->attributes->has('_format') && - ( - $request->attributes->get('_format') == 'json' || - $request->attributes->get('_format') == 'ld+json' + $request->attributes->has('_format') + && ( + 'json' == $request->attributes->get('_format') + || 'ld+json' == $request->attributes->get('_format') ) ) { return true; @@ -69,18 +58,18 @@ private function isFormatJson(Request $request): bool $contentType = $request->headers->get('Content-Type'); if ( - \is_string($contentType) && - ( - \str_starts_with($contentType, 'application/json') || - \str_starts_with($contentType, 'application/ld+json') + \is_string($contentType) + && ( + \str_starts_with($contentType, 'application/json') + || \str_starts_with($contentType, 'application/ld+json') ) ) { return true; } if ( - in_array('application/json', $request->getAcceptableContentTypes()) || - in_array('application/ld+json', $request->getAcceptableContentTypes()) + in_array('application/json', $request->getAcceptableContentTypes()) + || in_array('application/ld+json', $request->getAcceptableContentTypes()) ) { return true; } @@ -88,11 +77,7 @@ private function isFormatJson(Request $request): bool return false; } - /** - * @param Throwable $exception - * @return int - */ - private function getHttpStatusCode(Throwable $exception): int + private function getHttpStatusCode(\Throwable $exception): int { if ($exception instanceof AccessDeniedException || $exception instanceof AccessDeniedHttpException) { return Response::HTTP_FORBIDDEN; @@ -108,12 +93,11 @@ private function getHttpStatusCode(Throwable $exception): int } /** - * @param ExceptionEvent $event * @throws LoaderError * @throws RuntimeError * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Throwable + * @throws \Throwable * @throws SyntaxError */ public function onKernelException(ExceptionEvent $event): void @@ -139,8 +123,8 @@ public function onKernelException(ExceptionEvent $event): void */ $ctrl = $exception->getController(); if ( - null !== $ctrl && - method_exists($ctrl, 'maintenanceAction') + null !== $ctrl + && method_exists($ctrl, 'maintenanceAction') ) { try { /** @var Response $response */ @@ -148,6 +132,7 @@ public function onKernelException(ExceptionEvent $event): void // Set http code according to status $response->setStatusCode($this->getHttpStatusCode($exception)); $event->setResponse($response); + return; } catch (LoaderError $error) { // Twig template does not exist @@ -160,23 +145,19 @@ public function onKernelException(ExceptionEvent $event): void } } - /** - * @param ExceptionEvent $event - * @return null|Theme - */ protected function isNotFoundExceptionWithTheme(ExceptionEvent $event): ?Theme { $exception = $event->getThrowable(); $request = $event->getRequest(); if ( - $exception instanceof ResourceNotFoundException || - $exception instanceof NotFoundHttpException || - ( - null !== $exception->getPrevious() && - ( - $exception->getPrevious() instanceof ResourceNotFoundException || - $exception->getPrevious() instanceof NotFoundHttpException + $exception instanceof ResourceNotFoundException + || $exception instanceof NotFoundHttpException + || ( + null !== $exception->getPrevious() + && ( + $exception->getPrevious() instanceof ResourceNotFoundException + || $exception->getPrevious() instanceof NotFoundHttpException ) ) ) { @@ -194,19 +175,14 @@ protected function isNotFoundExceptionWithTheme(ExceptionEvent $event): ?Theme } /** - * @param Theme $theme - * @param Throwable $exception - * @param ExceptionEvent $event - * - * @return Response * @throws LoaderError * @throws RuntimeError * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Throwable + * @throws \Throwable * @throws SyntaxError */ - protected function createThemeNotFoundResponse(Theme $theme, Throwable $exception, ExceptionEvent $event): Response + protected function createThemeNotFoundResponse(Theme $theme, \Throwable $exception, ExceptionEvent $event): Response { $ctrlClass = $theme->getClassName(); $controller = new $ctrlClass(); diff --git a/lib/RoadizCompatBundle/src/EventSubscriber/MaintenanceModeSubscriber.php b/lib/RoadizCompatBundle/src/EventSubscriber/MaintenanceModeSubscriber.php index 24bda0cf..88513193 100644 --- a/lib/RoadizCompatBundle/src/EventSubscriber/MaintenanceModeSubscriber.php +++ b/lib/RoadizCompatBundle/src/EventSubscriber/MaintenanceModeSubscriber.php @@ -5,17 +5,17 @@ namespace RZ\Roadiz\CompatBundle\EventSubscriber; use RZ\Roadiz\CompatBundle\Controller\AppController; +use RZ\Roadiz\CompatBundle\Theme\ThemeResolverInterface; use RZ\Roadiz\CoreBundle\Bag\Settings; use RZ\Roadiz\CoreBundle\Entity\Theme; use RZ\Roadiz\CoreBundle\Exception\MaintenanceModeException; -use RZ\Roadiz\CompatBundle\Theme\ThemeResolverInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; -use Symfony\Bundle\SecurityBundle\Security; final class MaintenanceModeSubscriber implements EventSubscriberInterface { @@ -23,13 +23,10 @@ public function __construct( private readonly Settings $settings, private readonly Security $security, private readonly ThemeResolverInterface $themeResolver, - private readonly ContainerInterface $serviceLocator + private readonly ContainerInterface $serviceLocator, ) { } - /** - * @return array - */ private function getAuthorizedRoutes(): array { return [ @@ -59,9 +56,6 @@ private function getAuthorizedRoutes(): array ]; } - /** - * @return array - */ public static function getSubscribedEvents(): array { return [ @@ -70,7 +64,6 @@ public static function getSubscribedEvents(): array } /** - * @param RequestEvent $event * @throws MaintenanceModeException */ public function onRequest(RequestEvent $event): void @@ -82,8 +75,8 @@ public function onRequest(RequestEvent $event): void $maintenanceMode = (bool) $this->settings->get('maintenance_mode', false); if ( - $maintenanceMode === true && - !$this->security->isGranted('ROLE_BACKEND_USER') + true === $maintenanceMode + && !$this->security->isGranted('ROLE_BACKEND_USER') ) { $theme = $this->themeResolver->findTheme(null); if (null !== $theme) { @@ -94,12 +87,6 @@ public function onRequest(RequestEvent $event): void } } - /** - * @param Theme $theme - * @param Request $request - * - * @return AbstractController - */ private function getControllerForTheme(Theme $theme, Request $request): AbstractController { $ctrlClass = $theme->getClassName(); @@ -111,11 +98,7 @@ private function getControllerForTheme(Theme $theme, Request $request): Abstract } if (!$controller instanceof AbstractController) { - throw new \RuntimeException(sprintf( - 'Theme controller %s must extend %s class', - $ctrlClass, - AbstractController::class - )); + throw new \RuntimeException(sprintf('Theme controller %s must extend %s class', $ctrlClass, AbstractController::class)); } if ($controller instanceof AppController) { diff --git a/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeRouter.php b/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeRouter.php index 0edea964..49e08327 100644 --- a/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeRouter.php +++ b/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeRouter.php @@ -18,7 +18,7 @@ final class ThemeAwareNodeRouter implements RouterInterface, RequestMatcherInter { public function __construct( private readonly ThemeResolverInterface $themeResolver, - private readonly NodeRouter $innerRouter + private readonly NodeRouter $innerRouter, ) { } @@ -43,12 +43,12 @@ public function getRouteCollection(): RouteCollection } /** - * @inheritDoc * @throws InvalidArgumentException */ public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string { $this->innerRouter->setTheme($this->themeResolver->findTheme($this->getContext()->getHost())); + return $this->innerRouter->generate($name, $parameters, $referenceType); } @@ -57,9 +57,6 @@ public function match(string $pathinfo): array return $this->innerRouter->match($pathinfo); } - /** - * @inheritDoc - */ public function getRouteDebugMessage(mixed $name, array $parameters = []): string { return $this->innerRouter->getRouteDebugMessage($name, $parameters); diff --git a/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeUrlMatcher.php b/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeUrlMatcher.php index 0c2b1fb6..36f5c9dc 100644 --- a/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeUrlMatcher.php +++ b/lib/RoadizCompatBundle/src/Routing/ThemeAwareNodeUrlMatcher.php @@ -17,16 +17,14 @@ final class ThemeAwareNodeUrlMatcher implements UrlMatcherInterface, RequestMatc { public function __construct( private readonly ThemeResolverInterface $themeResolver, - private readonly NodeUrlMatcher $innerMatcher + private readonly NodeUrlMatcher $innerMatcher, ) { } - /** - * {@inheritdoc} - */ public function match(string $pathinfo): array { $decodedUrl = rawurldecode($pathinfo); + /* * Try nodes routes */ diff --git a/lib/RoadizCompatBundle/src/Theme/StaticThemeResolver.php b/lib/RoadizCompatBundle/src/Theme/StaticThemeResolver.php index 49aeebaf..a2ead7b3 100644 --- a/lib/RoadizCompatBundle/src/Theme/StaticThemeResolver.php +++ b/lib/RoadizCompatBundle/src/Theme/StaticThemeResolver.php @@ -19,8 +19,6 @@ class StaticThemeResolver implements ThemeResolverInterface /** * @param array $themes - * @param Stopwatch $stopwatch - * @param bool $installMode */ public function __construct(array $themes, Stopwatch $stopwatch, bool $installMode = false) { @@ -30,15 +28,13 @@ public function __construct(array $themes, Stopwatch $stopwatch, bool $installMo usort($this->themes, [static::class, 'compareThemePriority']); } - /** - * @inheritDoc - */ public function getBackendTheme(): Theme { $theme = new Theme(); $theme->setAvailable(true); $theme->setClassName($this->getBackendClassName()); $theme->setBackendTheme(true); + return $theme; } @@ -47,15 +43,13 @@ public function getBackendTheme(): Theme */ public function getBackendClassName(): string { - /** @var class-string $className */ # php-stan hint + /** @var class-string $className */ // php-stan hint $className = '\\Themes\\Rozier\\RozierApp'; + return $className; } - /** - * @inheritDoc - */ - public function findTheme(string $host = null): ?Theme + public function findTheme(?string $host = null): ?Theme { $default = null; /* @@ -67,17 +61,15 @@ public function findTheme(string $host = null): ?Theme foreach ($searchThemes as $theme) { if ($theme->getHostname() === $host) { return $theme; - } elseif ($theme->getHostname() === '*') { + } elseif ('*' === $theme->getHostname()) { // Getting high priority theme at last option $default = $theme; } } + return $default; } - /** - * @inheritDoc - */ public function findThemeByClass(string $classname): ?Theme { foreach ($this->getFrontendThemes() as $theme) { @@ -85,12 +77,10 @@ public function findThemeByClass(string $classname): ?Theme return $theme; } } + return null; } - /** - * @inheritDoc - */ public function findAll(): array { $backendThemes = []; @@ -99,34 +89,24 @@ public function findAll(): array $this->getBackendTheme(), ]; } + return array_merge($backendThemes, $this->getFrontendThemes()); } - /** - * @inheritDoc - */ public function findById($id): ?Theme { if (isset($this->getFrontendThemes()[$id])) { return $this->getFrontendThemes()[$id]; } + return null; } - /** - * @inheritDoc - */ public function getFrontendThemes(): array { return $this->themes; } - /** - * @param Theme $themeA - * @param Theme $themeB - * - * @return int - */ public static function compareThemePriority(Theme $themeA, Theme $themeB): int { /** @var class-string $classA */ diff --git a/lib/RoadizCompatBundle/src/Theme/ThemeGenerator.php b/lib/RoadizCompatBundle/src/Theme/ThemeGenerator.php index acbb7303..15b0dfbf 100644 --- a/lib/RoadizCompatBundle/src/Theme/ThemeGenerator.php +++ b/lib/RoadizCompatBundle/src/Theme/ThemeGenerator.php @@ -26,17 +26,11 @@ class ThemeGenerator protected string $cacheDir; protected LoggerInterface $logger; - /** - * @param string $projectDir - * @param string $publicDir - * @param string $cacheDir - * @param LoggerInterface $logger - */ public function __construct( string $projectDir, string $publicDir, string $cacheDir, - LoggerInterface $logger + LoggerInterface $logger, ) { $this->filesystem = new Filesystem(); $this->projectDir = $projectDir; @@ -46,9 +40,6 @@ public function __construct( } /** - * @param ThemeInfo $themeInfo - * @param string $branch - * * @return $this */ public function downloadTheme(ThemeInfo $themeInfo, string $branch = 'master'): ThemeGenerator @@ -61,42 +52,38 @@ public function downloadTheme(ThemeInfo $themeInfo, string $branch = 'master'): ['git', 'clone', '-b', $branch, static::REPOSITORY, $themeInfo->getThemePath()] ); $process->run(); - $this->logger->info('BaseTheme cloned into ' . $themeInfo->getThemePath()); + $this->logger->info('BaseTheme cloned into '.$themeInfo->getThemePath()); } else { - $this->logger->info($themeInfo->getClassname() . ' already exists.'); + $this->logger->info($themeInfo->getClassname().' already exists.'); } return $this; } /** - * @param ThemeInfo $themeInfo - * * @return $this */ public function renameTheme(ThemeInfo $themeInfo): ThemeGenerator { if (!$themeInfo->exists()) { - throw new FileException($themeInfo->getThemePath() . ' theme does not exist.'); + throw new FileException($themeInfo->getThemePath().' theme does not exist.'); } if ($themeInfo->isProtected()) { - throw new \InvalidArgumentException( - $themeInfo->getThemeName() . ' is protected and cannot renamed.' - ); + throw new \InvalidArgumentException($themeInfo->getThemeName().' is protected and cannot renamed.'); } /* * Remove existing Git history. */ - $this->filesystem->remove($themeInfo->getThemePath() . '/.git'); + $this->filesystem->remove($themeInfo->getThemePath().'/.git'); $this->logger->info('Remove Git history.'); /* * Rename main theme class. */ - $mainClassFile = $themeInfo->getThemePath() . '/' . $themeInfo->getThemeName() . 'App.php'; + $mainClassFile = $themeInfo->getThemePath().'/'.$themeInfo->getThemeName().'App.php'; if (!$this->filesystem->exists($mainClassFile)) { $this->filesystem->rename( - $themeInfo->getThemePath() . '/BaseThemeApp.php', + $themeInfo->getThemePath().'/BaseThemeApp.php', $mainClassFile ); /* @@ -111,11 +98,11 @@ public function renameTheme(ThemeInfo $themeInfo): ThemeGenerator $this->logger->info('Rename main theme class.'); } - $serviceProviderFile = $themeInfo->getThemePath() . - '/Services/' . $themeInfo->getThemeName() . 'ServiceProvider.php'; + $serviceProviderFile = $themeInfo->getThemePath(). + '/Services/'.$themeInfo->getThemeName().'ServiceProvider.php'; if (!$this->filesystem->exists($serviceProviderFile)) { $this->filesystem->rename( - $themeInfo->getThemePath() . '/Services/BaseThemeServiceProvider.php', + $themeInfo->getThemePath().'/Services/BaseThemeServiceProvider.php', $serviceProviderFile ); /* @@ -137,7 +124,7 @@ public function renameTheme(ThemeInfo $themeInfo): ThemeGenerator $processes->add(new Process( [ 'find', $themeInfo->getThemePath(), '-type', 'f', '-exec', 'sed', '-i.bak', - '-e', 's/BaseTheme/' . $themeInfo->getThemeName() . '/g', '{}', ';', + '-e', 's/BaseTheme/'.$themeInfo->getThemeName().'/g', '{}', ';', ], null, ['LC_ALL' => 'C'] @@ -145,22 +132,22 @@ public function renameTheme(ThemeInfo $themeInfo): ThemeGenerator $processes->add(new Process( [ 'find', $themeInfo->getThemePath(), '-type', 'f', '-exec', 'sed', '-i.bak', - '-e', 's/Base theme/' . $themeInfo->getName() . ' theme/g', '{}', ';', + '-e', 's/Base theme/'.$themeInfo->getName().' theme/g', '{}', ';', ], null, ['LC_ALL' => 'C'] )); $processes->add(new Process( [ - 'find', $themeInfo->getThemePath() . '/static', '-type', 'f', '-exec', 'sed', '-i.bak', - '-e', 's/Base/' . $themeInfo->getName() . '/g', '{}', ';', + 'find', $themeInfo->getThemePath().'/static', '-type', 'f', '-exec', 'sed', '-i.bak', + '-e', 's/Base/'.$themeInfo->getName().'/g', '{}', ';', ], null, ['LC_ALL' => 'C'] )); $processes->add(new Process( [ - 'find', $themeInfo->getThemePath() , '-type', 'f', '-name', '*.bak', '-exec', 'rm', '-f', '{}', ';', + 'find', $themeInfo->getThemePath(), '-type', 'f', '-name', '*.bak', '-exec', 'rm', '-f', '{}', ';', ], null, ['LC_ALL' => 'C'] @@ -177,19 +164,13 @@ public function renameTheme(ThemeInfo $themeInfo): ThemeGenerator return $this; } - /** - * @param ThemeInfo $themeInfo - * @param string $expectedMethod - * - * @return string|null - */ public function installThemeAssets(ThemeInfo $themeInfo, string $expectedMethod): ?string { if ($themeInfo->exists()) { - $publicThemeDir = $this->publicDir . '/themes/' . $themeInfo->getThemeName(); + $publicThemeDir = $this->publicDir.'/themes/'.$themeInfo->getThemeName(); if ($publicThemeDir !== $themeInfo->getThemePath()) { - $targetDir = $publicThemeDir . '/static'; - $originDir = $themeInfo->getThemePath() . '/static'; + $targetDir = $publicThemeDir.'/static'; + $originDir = $themeInfo->getThemePath().'/static'; $this->filesystem->remove($publicThemeDir); $this->filesystem->mkdir($publicThemeDir); @@ -202,9 +183,10 @@ public function installThemeAssets(ThemeInfo $themeInfo, string $expectedMethod) return $this->hardCopy($originDir, $targetDir); } } else { - $this->logger->info($themeInfo->getThemeName() . ' assets are already public.'); + $this->logger->info($themeInfo->getThemeName().' assets are already public.'); } } + return null; } @@ -212,10 +194,6 @@ public function installThemeAssets(ThemeInfo $themeInfo, string $expectedMethod) * Try to create relative symlink. * * Falling back to absolute symlink and finally hard copy. - * - * @param string $originDir - * @param string $targetDir - * @return string */ private function relativeSymlinkWithFallback(string $originDir, string $targetDir): string { @@ -225,6 +203,7 @@ private function relativeSymlinkWithFallback(string $originDir, string $targetDi } catch (IOException $e) { $method = $this->absoluteSymlinkWithFallback($originDir, $targetDir); } + return $method; } @@ -232,10 +211,6 @@ private function relativeSymlinkWithFallback(string $originDir, string $targetDi * Try to create absolute symlink. * * Falling back to hard copy. - * - * @param string $originDir - * @param string $targetDir - * @return string */ private function absoluteSymlinkWithFallback(string $originDir, string $targetDir): string { @@ -246,15 +221,12 @@ private function absoluteSymlinkWithFallback(string $originDir, string $targetDi // fall back to copy $method = $this->hardCopy($originDir, $targetDir); } + return $method; } /** * Creates symbolic link. - * - * @param string $originDir - * @param string $targetDir - * @param bool $relative */ private function symlink(string $originDir, string $targetDir, bool $relative = false): void { @@ -262,29 +234,18 @@ private function symlink(string $originDir, string $targetDir, bool $relative = $this->filesystem->mkdir(dirname($targetDir)); $realTargetParentDir = realpath(dirname($targetDir)); if (false === $realTargetParentDir) { - throw new IOException( - sprintf('Cannot resolve realpath for "%s" dirname.', $targetDir), - ); + throw new IOException(sprintf('Cannot resolve realpath for "%s" dirname.', $targetDir)); } $originDir = $this->filesystem->makePathRelative($originDir, $realTargetParentDir); } $this->filesystem->symlink($originDir, $targetDir); if (!file_exists($targetDir)) { - throw new IOException( - sprintf('Symbolic link "%s" was created but appears to be broken.', $targetDir), - 0, - null, - $targetDir - ); + throw new IOException(sprintf('Symbolic link "%s" was created but appears to be broken.', $targetDir), 0, null, $targetDir); } } /** * Copies origin to target. - * - * @param string $originDir - * @param string $targetDir - * @return string */ private function hardCopy(string $originDir, string $targetDir): string { diff --git a/lib/RoadizCompatBundle/src/Theme/ThemeInfo.php b/lib/RoadizCompatBundle/src/Theme/ThemeInfo.php index cbff7db2..89df90cb 100644 --- a/lib/RoadizCompatBundle/src/Theme/ThemeInfo.php +++ b/lib/RoadizCompatBundle/src/Theme/ThemeInfo.php @@ -4,9 +4,6 @@ namespace RZ\Roadiz\CompatBundle\Theme; -use ReflectionClass; -use ReflectionException; -use RuntimeException; use RZ\Roadiz\CompatBundle\Controller\AppController; use RZ\Roadiz\CoreBundle\Exception\ThemeClassNotValidException; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; @@ -27,7 +24,7 @@ final class ThemeInfo /** * @param string $name Short theme name or FQN classname - * @param string $projectDir + * * @throws ThemeClassNotValidException */ public function __construct(string $name, private readonly string $projectDir) @@ -48,36 +45,31 @@ public function __construct(string $name, private readonly string $projectDir) public function isProtected(): bool { - return in_array($this->getThemeName(), self::$protectedThemeNames) && $this->getThemeName() !== 'Rozier'; + return in_array($this->getThemeName(), self::$protectedThemeNames) && 'Rozier' !== $this->getThemeName(); } /** - * @param string $themeName - * * @return class-string + * * @throws ThemeClassNotValidException */ protected function guessClassnameFromThemeName(string $themeName): string { $className = match ($themeName) { 'RozierApp', 'RozierTheme', 'Rozier' => '\\Themes\\Rozier\\RozierApp', - default => '\\Themes\\' . $themeName . '\\' . $themeName . 'App', + default => '\\Themes\\'.$themeName.'\\'.$themeName.'App', }; if (class_exists($className)) { return $className; } else { - throw new ThemeClassNotValidException(sprintf( - '“%s” theme is not available in your project.', - $className - )); + throw new ThemeClassNotValidException(sprintf('“%s” theme is not available in your project.', $className)); } } /** * @param class-string $classname * - * @return string * @throws ThemeClassNotValidException */ protected function extractNameFromClassname(string $classname): string @@ -89,7 +81,9 @@ protected function extractNameFromClassname(string $classname): string /** * @param class-string $classname + * * @return class-string + * * @throws ThemeClassNotValidException */ protected function validateClassname(string $classname): string @@ -101,13 +95,9 @@ protected function validateClassname(string $classname): string return $class::getThemeMainClass(); } } - throw new RuntimeException('Theme class ' . $classname . ' does not exist.'); + throw new \RuntimeException('Theme class '.$classname.' does not exist.'); } - /** - * @param string $name - * @return string - */ protected function validateName(string $name): string { if (1 !== preg_match('#^[A-Z][a-zA-Z]+$#', $name)) { @@ -122,7 +112,6 @@ protected function validateName(string $name): string } /** - * @return bool * @throws ThemeClassNotValidException */ public function exists(): bool @@ -131,8 +120,8 @@ public function exists(): bool return true; } if ( - $this->filesystem->exists($this->getThemePath()) || - $this->filesystem->exists($this->projectDir . '/vendor/roadiz/' . $this->getThemeName()) + $this->filesystem->exists($this->getThemePath()) + || $this->filesystem->exists($this->projectDir.'/vendor/roadiz/'.$this->getThemeName()) ) { return true; } @@ -142,12 +131,12 @@ public function exists(): bool protected function getProtectedThemePath(): string { - if ($this->filesystem->exists($this->projectDir . '/vendor/roadiz/' . $this->getThemeName())) { - return $this->projectDir . '/vendor/roadiz/' . $this->getThemeName(); - } elseif ($this->filesystem->exists($this->projectDir . '/themes/' . $this->getThemeName())) { - return $this->projectDir . '/themes/' . $this->getThemeName(); + if ($this->filesystem->exists($this->projectDir.'/vendor/roadiz/'.$this->getThemeName())) { + return $this->projectDir.'/vendor/roadiz/'.$this->getThemeName(); + } elseif ($this->filesystem->exists($this->projectDir.'/themes/'.$this->getThemeName())) { + return $this->projectDir.'/themes/'.$this->getThemeName(); } - throw new \InvalidArgumentException($this->getThemeName() . ' does not exist in project and vendor.'); + throw new \InvalidArgumentException($this->getThemeName().' does not exist in project and vendor.'); } /** @@ -155,7 +144,8 @@ protected function getProtectedThemePath(): string * * Attention: theme could be located in vendor folder (/vendor/roadiz/roadiz) * - * @return string Theme absolute path. + * @return string theme absolute path + * * @throws ThemeClassNotValidException */ public function getThemePath(): string @@ -169,45 +159,42 @@ public function getThemePath(): string $this->themePath = $className::getThemeFolder(); } } else { - $this->themePath = $this->projectDir . '/themes/' . $this->getThemeName(); + $this->themePath = $this->projectDir.'/themes/'.$this->getThemeName(); } } + return $this->themePath; } /** * @param class-string|null $className * - * @return null|ReflectionClass * @throws ThemeClassNotValidException */ - public function getThemeReflectionClass(string $className = null): ?ReflectionClass + public function getThemeReflectionClass(?string $className = null): ?\ReflectionClass { try { if (null === $className) { $className = $this->getClassname(); } - $reflection = new ReflectionClass($className); + $reflection = new \ReflectionClass($className); if ($reflection->isSubclassOf(AbstractController::class)) { return $reflection; } - } catch (ReflectionException $Exception) { + } catch (\ReflectionException $Exception) { return null; } return null; } - /** - * @return string - */ protected function getThemeNameFromName(): string { if (in_array($this->name, self::$protectedThemeNames)) { return $this->name; } - return $this->name . 'Theme'; + return $this->name.'Theme'; } /** @@ -228,6 +215,7 @@ public function getThemeName(): string /** * @return class-string Theme class FQN + * * @throws ThemeClassNotValidException */ public function getClassname(): string @@ -235,24 +223,25 @@ public function getClassname(): string if (null === $this->classname) { $this->classname = $this->guessClassnameFromThemeName($this->getThemeName()); } + return $this->classname; } /** - * @return bool * @throws ThemeClassNotValidException */ public function isValid(): bool { try { $className = $this->getClassname(); - $reflection = new ReflectionClass($className); + $reflection = new \ReflectionClass($className); if ($reflection->isSubclassOf(AbstractController::class)) { return true; } - } catch (ReflectionException $Exception) { + } catch (\ReflectionException $Exception) { return false; } + return false; } } diff --git a/lib/RoadizCompatBundle/src/Theme/ThemeResolverInterface.php b/lib/RoadizCompatBundle/src/Theme/ThemeResolverInterface.php index 58846a4b..39662532 100644 --- a/lib/RoadizCompatBundle/src/Theme/ThemeResolverInterface.php +++ b/lib/RoadizCompatBundle/src/Theme/ThemeResolverInterface.php @@ -8,9 +8,6 @@ interface ThemeResolverInterface { - /** - * @return Theme - */ public function getBackendTheme(): Theme; /** @@ -18,18 +15,8 @@ public function getBackendTheme(): Theme; */ public function getBackendClassName(): string; - /** - * @param string|null $host - * - * @return Theme|null - */ - public function findTheme(string $host = null): ?Theme; + public function findTheme(?string $host = null): ?Theme; - /** - * @param string $classname - * - * @return Theme|null - */ public function findThemeByClass(string $classname): ?Theme; /** @@ -39,8 +26,6 @@ public function findAll(): array; /** * @param int $id - * - * @return Theme|null */ public function findById($id): ?Theme; diff --git a/lib/RoadizCoreBundle/config/services.yaml b/lib/RoadizCoreBundle/config/services.yaml index d4b1e318..7feb7953 100644 --- a/lib/RoadizCoreBundle/config/services.yaml +++ b/lib/RoadizCoreBundle/config/services.yaml @@ -542,6 +542,7 @@ services: tags: [ 'roadiz_core.document_renderer' ] RZ\Roadiz\Documents\Renderer\RendererInterface: alias: RZ\Roadiz\Documents\Renderer\ChainRenderer + RZ\Roadiz\Documents\MediaFinders\FacebookPictureFinder: # Default AbstractDocumentFactory is the public one. RZ\Roadiz\Documents\AbstractDocumentFactory: diff --git a/lib/RoadizCoreBundle/migrations/Version20201203004857.php b/lib/RoadizCoreBundle/migrations/Version20201203004857.php index 48ccc417..57294c19 100644 --- a/lib/RoadizCoreBundle/migrations/Version20201203004857.php +++ b/lib/RoadizCoreBundle/migrations/Version20201203004857.php @@ -1,4 +1,5 @@ skipIf($schema->hasTable('nodes'), 'Database has been initialized before Doctrine Migration tool.'); - if ($this->connection->getDatabasePlatform()->getName() === 'mysql') { + if ('mysql' === $this->connection->getDatabasePlatform()->getName()) { $this->mysqlUp(); - } elseif ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + } elseif ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->postgresUp(); } } @@ -480,15 +479,14 @@ private function postgresUp(): void $this->addSql('ALTER TABLE users_groups ADD CONSTRAINT FK_FF8AB7E0FE54D947 FOREIGN KEY (group_id) REFERENCES usergroups (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { $this->throwIrreversibleMigrationException(); } /** - * Temporary workaround + * Temporary workaround. * - * @return bool * @see https://github.com/doctrine/migrations/issues/1104 */ public function isTransactional(): bool diff --git a/lib/RoadizCoreBundle/migrations/Version20201214232628.php b/lib/RoadizCoreBundle/migrations/Version20201214232628.php index 3ec778c3..0f7a852c 100644 --- a/lib/RoadizCoreBundle/migrations/Version20201214232628.php +++ b/lib/RoadizCoreBundle/migrations/Version20201214232628.php @@ -1,4 +1,5 @@ skipIf( - $this->connection->getDatabasePlatform()->getName() !== 'mysql', + 'mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.' ); $this->skipIf($schema->hasTable('usergroups'), 'Table `usergroups` already exists.'); @@ -33,10 +34,10 @@ public function up(Schema $schema) : void // $this->addSql('ALTER TABLE `usergroups` RENAME INDEX uniq_f06d39705e237e06 TO UNIQ_98972EB45E237E06'); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { $this->skipIf( - $this->connection->getDatabasePlatform()->getName() !== 'mysql', + 'mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.' ); $this->skipIf($schema->hasTable('groups'), 'Table `groups` already exists.'); @@ -54,9 +55,8 @@ public function down(Schema $schema) : void } /** - * Temporary workaround + * Temporary workaround. * - * @return bool * @see https://github.com/doctrine/migrations/issues/1104 */ public function isTransactional(): bool diff --git a/lib/RoadizCoreBundle/migrations/Version20201225181256.php b/lib/RoadizCoreBundle/migrations/Version20201225181256.php index 3e099267..91e16547 100644 --- a/lib/RoadizCoreBundle/migrations/Version20201225181256.php +++ b/lib/RoadizCoreBundle/migrations/Version20201225181256.php @@ -1,4 +1,5 @@ write('Nothing to do with RZ\Roadiz\Migrations\Version20201225181256.'); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { $this->throwIrreversibleMigrationException(); } /** - * Temporary workaround + * Temporary workaround. * - * @return bool * @see https://github.com/doctrine/migrations/issues/1104 */ public function isTransactional(): bool diff --git a/lib/RoadizCoreBundle/migrations/Version20210423072744.php b/lib/RoadizCoreBundle/migrations/Version20210423072744.php index 2a92eff7..c463eaca 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210423072744.php +++ b/lib/RoadizCoreBundle/migrations/Version20210423072744.php @@ -7,22 +7,19 @@ use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; -/** - * @package RZ\Roadiz\Migrations - */ final class Version20210423072744 extends AbstractMigration { - public function getDescription() : string + public function getDescription(): string { return 'Added Documents duration field.'; } - public function up(Schema $schema) : void + public function up(Schema $schema): void { $this->addSql('ALTER TABLE documents ADD duration INT DEFAULT 0 NOT NULL'); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { $this->addSql('ALTER TABLE documents DROP duration'); } diff --git a/lib/RoadizCoreBundle/migrations/Version20210423161606.php b/lib/RoadizCoreBundle/migrations/Version20210423161606.php index 56ae3af1..707e52e2 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210423161606.php +++ b/lib/RoadizCoreBundle/migrations/Version20210423161606.php @@ -12,12 +12,12 @@ */ final class Version20210423161606 extends AbstractMigration { - public function getDescription() : string + public function getDescription(): string { return 'Additional table indexes on documents, folders, logs and tags'; } - public function up(Schema $schema) : void + public function up(Schema $schema): void { $this->addSql('CREATE INDEX document_created_at ON documents (created_at)'); $this->addSql('CREATE INDEX document_updated_at ON documents (updated_at)'); @@ -33,9 +33,9 @@ public function up(Schema $schema) : void $this->addSql('CREATE INDEX tag_parent_position ON tags (parent_tag_id, position)'); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('DROP INDEX IF EXISTS document_created_at'); $this->addSql('DROP INDEX IF EXISTS document_updated_at'); $this->addSql('DROP INDEX IF EXISTS document_raw_created_at'); diff --git a/lib/RoadizCoreBundle/migrations/Version20210423164248.php b/lib/RoadizCoreBundle/migrations/Version20210423164248.php index 74af5a4a..044e1cfc 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210423164248.php +++ b/lib/RoadizCoreBundle/migrations/Version20210423164248.php @@ -9,12 +9,12 @@ final class Version20210423164248 extends AbstractMigration { - public function getDescription() : string + public function getDescription(): string { return 'Additional table indexes and renaming important performance indexes'; } - public function up(Schema $schema) : void + public function up(Schema $schema): void { $this->addSql('CREATE INDEX answer_customform_submitted_at ON custom_form_answers (custom_form_id, submitted_at)'); $this->addSql('CREATE INDEX cffattribute_answer_field ON custom_form_field_attributes (custom_form_answer_id, custom_form_field_id)'); @@ -23,7 +23,7 @@ public function up(Schema $schema) : void $this->addSql('CREATE INDEX customform_node_position ON nodes_custom_forms (node_id, position)'); $this->addSql('CREATE INDEX customform_node_field_position ON nodes_custom_forms (node_id, node_type_field_id, position)'); - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('DROP INDEX IF EXISTS IDX_7C7DED6DE0D4FDE19CAA2B25'); $this->addSql('DROP INDEX IF EXISTS IDX_7C7DED6DE0D4FDE14AD260649CAA2B25'); $this->addSql('DROP INDEX IF EXISTS IDX_7C7DED6D2B36786BE0D4FDE19CAA2B25'); @@ -38,7 +38,7 @@ public function up(Schema $schema) : void $this->addSql('CREATE INDEX ns_discr_translation_published ON nodes_sources (discr, translation_id, published_at)'); $this->addSql('CREATE INDEX ns_title_translation_published ON nodes_sources (title, translation_id, published_at)'); - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER INDEX IF EXISTS ns_node_translation_discr RENAME TO ns_node_discr_translation'); $this->addSql('ALTER INDEX IF EXISTS idx_7c7ded6d460d9fd79caa2b25e0d4fde1 RENAME TO ns_node_translation_published'); $this->addSql('ALTER INDEX IF EXISTS idx_7c7ded6d4ad260649caa2b25 RENAME TO ns_discr_translation'); @@ -65,9 +65,9 @@ public function up(Schema $schema) : void } } - public function down(Schema $schema) : void + public function down(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('DROP INDEX IF EXISTS answer_customform_submitted_at'); $this->addSql('DROP INDEX IF EXISTS cffattribute_answer_field'); $this->addSql('DROP INDEX IF EXISTS cfield_customform_positio'); @@ -95,7 +95,7 @@ public function down(Schema $schema) : void $this->addSql('CREATE INDEX IDX_7C7DED6DE0D4FDE14AD260649CAA2B25 ON nodes_sources (published_at, discr, translation_id)'); $this->addSql('CREATE INDEX IDX_7C7DED6D2B36786BE0D4FDE19CAA2B25 ON nodes_sources (title, published_at, translation_id)'); - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER INDEX IF EXISTS ns_title_published RENAME TO IDX_7C7DED6D2B36786BE0D4FDE1'); $this->addSql('ALTER INDEX IF EXISTS ns_node_discr_translation RENAME TO ns_node_translation_discr'); $this->addSql('ALTER INDEX IF EXISTS ns_discr_translation RENAME TO IDX_7C7DED6D4AD260649CAA2B25'); diff --git a/lib/RoadizCoreBundle/migrations/Version20210506085247.php b/lib/RoadizCoreBundle/migrations/Version20210506085247.php index d1801bc4..11f2f7c3 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210506085247.php +++ b/lib/RoadizCoreBundle/migrations/Version20210506085247.php @@ -25,7 +25,7 @@ public function up(Schema $schema): void $this->addSql('CREATE INDEX node_visible_parent_position ON nodes (visible, parent_node_id, position)'); $this->addSql('CREATE INDEX node_status_visible_parent_position ON nodes (status, visible, parent_node_id, position)'); - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER INDEX IF EXISTS idx_1d3d05fc7ab0e8597b00651c3445eb91 RENAME TO node_visible_status_parent'); $this->addSql('ALTER INDEX IF EXISTS idx_1d3d05fc7ab0e8593445eb91 RENAME TO node_visible_parent'); } else { @@ -36,7 +36,7 @@ public function up(Schema $schema): void $this->addSql('CREATE INDEX tag_visible_position ON tags (visible, position)'); $this->addSql('CREATE INDEX tag_parent_visible_position ON tags (parent_tag_id, visible, position)'); - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER INDEX IF EXISTS idx_6fbc9426f5c1a0d77ab0e859 RENAME TO tag_parent_visible'); } else { $this->addSql('ALTER TABLE tags RENAME INDEX idx_6fbc9426f5c1a0d77ab0e859 TO tag_parent_visible'); @@ -45,7 +45,7 @@ public function up(Schema $schema): void public function down(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('DROP INDEX node_status_parent'); $this->addSql('DROP INDEX node_nodetype_status_parent'); $this->addSql('DROP INDEX node_nodetype_status_parent_position'); diff --git a/lib/RoadizCoreBundle/migrations/Version20210520092543.php b/lib/RoadizCoreBundle/migrations/Version20210520092543.php index d20d9cc3..1b38b5ba 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210520092543.php +++ b/lib/RoadizCoreBundle/migrations/Version20210520092543.php @@ -19,14 +19,14 @@ public function getDescription(): string public function up(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'mysql') { + if ('mysql' === $this->connection->getDatabasePlatform()->getName()) { /* * MYSQL */ $this->addSql('ALTER TABLE node_type_fields ADD serialization_exclusion_expression LONGTEXT DEFAULT NULL, ADD serialization_groups JSON DEFAULT NULL, ADD serialization_max_depth INT DEFAULT NULL, ADD excluded_from_serialization TINYINT(1) DEFAULT \'0\' NOT NULL'); $this->addSql('ALTER TABLE node_types ADD searchable TINYINT(1) DEFAULT \'1\' NOT NULL'); $this->addSql('CREATE INDEX nt_searchable ON node_types (searchable)'); - } elseif ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + } elseif ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { /* * POSTGRES */ @@ -42,11 +42,11 @@ public function up(Schema $schema): void public function down(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'mysql') { + if ('mysql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER TABLE node_type_fields DROP serialization_exclusion_expression, DROP serialization_groups, DROP serialization_max_depth, DROP excluded_from_serialization'); $this->addSql('DROP INDEX nt_searchable ON node_types'); $this->addSql('ALTER TABLE node_types DROP searchable'); - } elseif ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + } elseif ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { /* * POSTGRES */ diff --git a/lib/RoadizCoreBundle/migrations/Version20210527131435.php b/lib/RoadizCoreBundle/migrations/Version20210527131435.php index 44edb4ff..081ec0ae 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210527131435.php +++ b/lib/RoadizCoreBundle/migrations/Version20210527131435.php @@ -16,7 +16,7 @@ public function getDescription(): string public function up(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER TABLE redirections ALTER redirecturi TYPE TEXT'); $this->addSql('ALTER TABLE redirections ALTER redirecturi DROP DEFAULT'); $this->addSql('ALTER TABLE redirections ALTER redirecturi TYPE TEXT'); @@ -27,7 +27,7 @@ public function up(Schema $schema): void public function down(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER TABLE redirections ALTER redirecturi TYPE VARCHAR(255)'); $this->addSql('ALTER TABLE redirections ALTER redirecturi DROP DEFAULT'); $this->addSql('ALTER TABLE redirections ALTER redirecturi TYPE VARCHAR(255)'); diff --git a/lib/RoadizCoreBundle/migrations/Version20210701151713.php b/lib/RoadizCoreBundle/migrations/Version20210701151713.php index 00a6a06e..c0e65fd7 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210701151713.php +++ b/lib/RoadizCoreBundle/migrations/Version20210701151713.php @@ -16,7 +16,7 @@ public function getDescription(): string public function up(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('CREATE TABLE webhooks (id VARCHAR(36) NOT NULL, message_type VARCHAR(255) DEFAULT NULL, uri TEXT DEFAULT NULL, payload JSON DEFAULT NULL, throttleSeconds INT NOT NULL, last_triggered_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL, automatic BOOLEAN DEFAULT \'false\' NOT NULL, created_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL, updated_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL, PRIMARY KEY(id))'); $this->addSql('CREATE INDEX webhook_message_type ON webhooks (message_type)'); $this->addSql('CREATE INDEX webhook_created_at ON webhooks (created_at)'); diff --git a/lib/RoadizCoreBundle/migrations/Version20210715120118.php b/lib/RoadizCoreBundle/migrations/Version20210715120118.php index 9e28c5b6..9a577148 100644 --- a/lib/RoadizCoreBundle/migrations/Version20210715120118.php +++ b/lib/RoadizCoreBundle/migrations/Version20210715120118.php @@ -19,7 +19,7 @@ public function getDescription(): string public function up(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER TABLE webhooks ADD root_node INT DEFAULT NULL'); $this->addSql('ALTER TABLE webhooks ADD CONSTRAINT FK_998C4FDDC2A25172 FOREIGN KEY (root_node) REFERENCES nodes (id) ON DELETE SET NULL NOT DEFERRABLE INITIALLY IMMEDIATE'); } else { @@ -31,7 +31,7 @@ public function up(Schema $schema): void public function down(Schema $schema): void { - if ($this->connection->getDatabasePlatform()->getName() === 'postgresql') { + if ('postgresql' === $this->connection->getDatabasePlatform()->getName()) { $this->addSql('ALTER TABLE webhooks DROP CONSTRAINT FK_998C4FDDC2A25172'); $this->addSql('DROP INDEX webhook_root_node'); } else { diff --git a/lib/RoadizCoreBundle/src/Api/Breadcrumbs/Breadcrumbs.php b/lib/RoadizCoreBundle/src/Api/Breadcrumbs/Breadcrumbs.php index 6d0fb068..1c23e4e0 100644 --- a/lib/RoadizCoreBundle/src/Api/Breadcrumbs/Breadcrumbs.php +++ b/lib/RoadizCoreBundle/src/Api/Breadcrumbs/Breadcrumbs.php @@ -13,9 +13,9 @@ final class Breadcrumbs implements BreadcrumbsInterface * @param PersistableInterface[] $items */ public function __construct( - #[Serializer\Groups(["breadcrumbs", "web_response"])] + #[Serializer\Groups(['breadcrumbs', 'web_response'])] #[Serializer\MaxDepth(1)] - private readonly array $items + private readonly array $items, ) { } diff --git a/lib/RoadizCoreBundle/src/Api/Breadcrumbs/NodesSourcesBreadcrumbsFactory.php b/lib/RoadizCoreBundle/src/Api/Breadcrumbs/NodesSourcesBreadcrumbsFactory.php index 93cb2ee1..8779fb19 100644 --- a/lib/RoadizCoreBundle/src/Api/Breadcrumbs/NodesSourcesBreadcrumbsFactory.php +++ b/lib/RoadizCoreBundle/src/Api/Breadcrumbs/NodesSourcesBreadcrumbsFactory.php @@ -9,10 +9,6 @@ final class NodesSourcesBreadcrumbsFactory implements BreadcrumbsFactoryInterface { - /** - * @param PersistableInterface|null $entity - * @return BreadcrumbsInterface|null - */ public function create(?PersistableInterface $entity): ?BreadcrumbsInterface { if (!$entity instanceof NodesSources) { @@ -27,8 +23,8 @@ public function create(?PersistableInterface $entity): ?BreadcrumbsInterface while (null !== $entity = $entity->getParent()) { if ( - null !== $entity->getNode() && - $entity->getNode()->isVisible() + null !== $entity->getNode() + && $entity->getNode()->isVisible() ) { $parents[] = $entity; } diff --git a/lib/RoadizCoreBundle/src/Api/Controller/GetWebResponseByPathController.php b/lib/RoadizCoreBundle/src/Api/Controller/GetWebResponseByPathController.php index 57d514b6..3542e1df 100644 --- a/lib/RoadizCoreBundle/src/Api/Controller/GetWebResponseByPathController.php +++ b/lib/RoadizCoreBundle/src/Api/Controller/GetWebResponseByPathController.php @@ -4,10 +4,10 @@ namespace RZ\Roadiz\CoreBundle\Api\Controller; -use ApiPlatform\Metadata\IriConverterInterface; use ApiPlatform\Metadata\Exception\InvalidArgumentException; -use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException; use ApiPlatform\Metadata\Exception\OperationNotFoundException; +use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException; +use ApiPlatform\Metadata\IriConverterInterface; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use Psr\Log\LoggerInterface; use RZ\Roadiz\Core\AbstractEntities\PersistableInterface; @@ -32,7 +32,7 @@ public function __construct( private readonly IriConverterInterface $iriConverter, private readonly PreviewResolverInterface $previewResolver, private readonly ApiResourceOperationNameGenerator $apiResourceOperationNameGenerator, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } @@ -40,8 +40,8 @@ public function __invoke(?Request $request): ?WebResponseInterface { try { if ( - null === $request || - empty($request->query->get('path')) + null === $request + || empty($request->query->get('path')) ) { throw new InvalidArgumentException('path query parameter is mandatory'); } @@ -88,7 +88,7 @@ public function __invoke(?Request $request): ?WebResponseInterface $request->attributes->set('data', $data); return $data; - } catch (ResourceNotFoundException | ResourceClassNotFoundException $exception) { + } catch (ResourceNotFoundException|ResourceClassNotFoundException $exception) { throw $this->createNotFoundException($exception->getMessage(), $exception); } } @@ -121,8 +121,8 @@ protected function normalizeResourcePath(?Request $request, string $path): Persi } $resource = $nodeSource; } elseif ( - null !== $resource->getRedirectUri() && - (new UnicodeString($resource->getRedirectUri()))->startsWith('/') + null !== $resource->getRedirectUri() + && (new UnicodeString($resource->getRedirectUri()))->startsWith('/') ) { /* * Recursive call to normalize path coming from Redirection if redirected path @@ -153,7 +153,7 @@ protected function addResourceToCacheTags(?Request $request, PersistableInterfac { if (null !== $request) { $iri = $this->iriConverter->getIriFromResource($resource); - $request->attributes->set('_resources', $request->attributes->get('_resources', []) + [ $iri => $iri ]); + $request->attributes->set('_resources', $request->attributes->get('_resources', []) + [$iri => $iri]); } } } diff --git a/lib/RoadizCoreBundle/src/Api/Controller/NodesSourcesSearchController.php b/lib/RoadizCoreBundle/src/Api/Controller/NodesSourcesSearchController.php index ad76db3d..e9d4ebab 100644 --- a/lib/RoadizCoreBundle/src/Api/Controller/NodesSourcesSearchController.php +++ b/lib/RoadizCoreBundle/src/Api/Controller/NodesSourcesSearchController.php @@ -28,7 +28,7 @@ public function __construct( ManagerRegistry $managerRegistry, PreviewResolverInterface $previewResolver, ?NodeSourceSearchHandlerInterface $nodeSourceSearchHandler, - int $highlightingFragmentSize = 200 + int $highlightingFragmentSize = 200, ) { $this->nodeSourceSearchHandler = $nodeSourceSearchHandler; $this->highlightingFragmentSize = $highlightingFragmentSize; @@ -46,9 +46,6 @@ protected function getPreviewResolver(): PreviewResolverInterface return $this->previewResolver; } - /** - * @return SearchHandlerInterface - */ protected function getSearchHandler(): SearchHandlerInterface { if (null === $this->nodeSourceSearchHandler) { @@ -58,6 +55,7 @@ protected function getSearchHandler(): SearchHandlerInterface if ($this->highlightingFragmentSize > 0) { $this->nodeSourceSearchHandler->setHighlightingFragmentSize($this->highlightingFragmentSize); } + return $this->nodeSourceSearchHandler; } @@ -65,7 +63,7 @@ protected function getCriteria(Request $request): array { return [ 'publishedAt' => ['<=', new \DateTime()], - 'translation' => $this->getTranslation($request) + 'translation' => $this->getTranslation($request), ]; } @@ -77,6 +75,7 @@ public function __invoke(Request $request): SolrPaginator $this->getCriteria($request), true ); + return new SolrPaginator($entityListManager); } } diff --git a/lib/RoadizCoreBundle/src/Api/Controller/TranslationAwareControllerTrait.php b/lib/RoadizCoreBundle/src/Api/Controller/TranslationAwareControllerTrait.php index 47533414..465fb5d6 100644 --- a/lib/RoadizCoreBundle/src/Api/Controller/TranslationAwareControllerTrait.php +++ b/lib/RoadizCoreBundle/src/Api/Controller/TranslationAwareControllerTrait.php @@ -15,6 +15,7 @@ trait TranslationAwareControllerTrait { abstract protected function getManagerRegistry(): ManagerRegistry; + abstract protected function getPreviewResolver(): PreviewResolverInterface; /** @@ -30,7 +31,7 @@ protected function getTranslation(Request $request): TranslationInterface /** @var TranslationRepository $repository */ $repository = $this->getManagerRegistry()->getRepository(TranslationInterface::class); - if (!\is_string($locale) || $locale === '') { + if (!\is_string($locale) || '' === $locale) { return $repository->findDefault(); } diff --git a/lib/RoadizCoreBundle/src/Api/DataTransformer/BlocksAwareWebResponseOutputDataTransformerTrait.php b/lib/RoadizCoreBundle/src/Api/DataTransformer/BlocksAwareWebResponseOutputDataTransformerTrait.php index 2e89b12e..db62eb8c 100644 --- a/lib/RoadizCoreBundle/src/Api/DataTransformer/BlocksAwareWebResponseOutputDataTransformerTrait.php +++ b/lib/RoadizCoreBundle/src/Api/DataTransformer/BlocksAwareWebResponseOutputDataTransformerTrait.php @@ -16,8 +16,11 @@ trait BlocksAwareWebResponseOutputDataTransformerTrait { abstract protected function getWalkerContext(): WalkerContextInterface; + abstract protected function getCacheItemPool(): CacheItemPoolInterface; + abstract protected function getTreeWalkerGenerator(): TreeWalkerGenerator; + abstract protected function getChildrenNodeSourceWalkerMaxLevel(): int; /** diff --git a/lib/RoadizCoreBundle/src/Api/DataTransformer/RealmsAwareWebResponseOutputDataTransformerTrait.php b/lib/RoadizCoreBundle/src/Api/DataTransformer/RealmsAwareWebResponseOutputDataTransformerTrait.php index 5645704e..b34a8cd5 100644 --- a/lib/RoadizCoreBundle/src/Api/DataTransformer/RealmsAwareWebResponseOutputDataTransformerTrait.php +++ b/lib/RoadizCoreBundle/src/Api/DataTransformer/RealmsAwareWebResponseOutputDataTransformerTrait.php @@ -16,9 +16,6 @@ trait RealmsAwareWebResponseOutputDataTransformerTrait abstract protected function getRealmResolver(): RealmResolverInterface; /** - * @param RealmsAwareWebResponseInterface $output - * @param NodesSources $data - * @return WebResponseInterface * @throws UnauthorizedHttpException */ protected function injectRealms(RealmsAwareWebResponseInterface $output, NodesSources $data): WebResponseInterface @@ -27,14 +24,14 @@ protected function injectRealms(RealmsAwareWebResponseInterface $output, NodesSo $output->setHidingBlocks(false); $denyingRealms = array_filter($output->getRealms(), function (RealmInterface $realm) { - return $realm->getBehaviour() === RealmInterface::BEHAVIOUR_DENY; + return RealmInterface::BEHAVIOUR_DENY === $realm->getBehaviour(); }); foreach ($denyingRealms as $denyingRealm) { $this->getRealmResolver()->denyUnlessGranted($denyingRealm); } $blockHidingRealms = array_filter($output->getRealms(), function (RealmInterface $realm) { - return $realm->getBehaviour() === RealmInterface::BEHAVIOUR_HIDE_BLOCKS; + return RealmInterface::BEHAVIOUR_HIDE_BLOCKS === $realm->getBehaviour(); }); foreach ($blockHidingRealms as $blockHidingRealm) { if (!$this->getRealmResolver()->isGranted($blockHidingRealm)) { diff --git a/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseDataTransformerInterface.php b/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseDataTransformerInterface.php index 424d02a3..c493e29c 100644 --- a/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseDataTransformerInterface.php +++ b/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseDataTransformerInterface.php @@ -11,9 +11,9 @@ interface WebResponseDataTransformerInterface { /** * @template T of PersistableInterface + * * @param T $object - * @param string $to - * @param array $context + * * @return WebResponseInterface|null */ public function transform(PersistableInterface $object, string $to, array $context = []): ?WebResponseInterface; diff --git a/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseOutputDataTransformer.php b/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseOutputDataTransformer.php index 7cd9a1e1..409ad4fe 100644 --- a/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseOutputDataTransformer.php +++ b/lib/RoadizCoreBundle/src/Api/DataTransformer/WebResponseOutputDataTransformer.php @@ -27,13 +27,6 @@ class WebResponseOutputDataTransformer implements WebResponseDataTransformerInte use RealmsAwareWebResponseOutputDataTransformerTrait; /** - * @param NodesSourcesHeadFactoryInterface $nodesSourcesHeadFactory - * @param BreadcrumbsFactoryInterface $breadcrumbsFactory - * @param WalkerContextInterface $walkerContext - * @param CacheItemPoolInterface $cacheItemPool - * @param UrlGeneratorInterface $urlGenerator - * @param RealmResolverInterface $realmResolver - * @param TreeWalkerGenerator $treeWalkerGenerator * @param class-string $webResponseClass */ public function __construct( @@ -44,7 +37,7 @@ public function __construct( protected readonly UrlGeneratorInterface $urlGenerator, protected readonly RealmResolverInterface $realmResolver, protected readonly TreeWalkerGenerator $treeWalkerGenerator, - private readonly string $webResponseClass + private readonly string $webResponseClass, ) { } @@ -99,7 +92,7 @@ public function transform(PersistableInterface $object, string $to, array $conte } $output->setPath($this->urlGenerator->generate(RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ - RouteObjectInterface::ROUTE_OBJECT => $object + RouteObjectInterface::ROUTE_OBJECT => $object, ], UrlGeneratorInterface::ABSOLUTE_PATH)); $output->setHead($this->nodesSourcesHeadFactory->createForNodeSource($object)); $output->setBreadcrumbs($this->breadcrumbsFactory->create($object)); @@ -108,6 +101,7 @@ public function transform(PersistableInterface $object, string $to, array $conte if ($object instanceof TranslationInterface) { $output->setHead($this->nodesSourcesHeadFactory->createForTranslation($object)); } + return $output; } } diff --git a/lib/RoadizCoreBundle/src/Api/Dto/Archive.php b/lib/RoadizCoreBundle/src/Api/Dto/Archive.php index d6204a70..9f410105 100644 --- a/lib/RoadizCoreBundle/src/Api/Dto/Archive.php +++ b/lib/RoadizCoreBundle/src/Api/Dto/Archive.php @@ -8,9 +8,9 @@ final class Archive { - #[Groups(["archives"])] + #[Groups(['archives'])] public int $year; - #[Groups(["archives"])] + #[Groups(['archives'])] public array $months; } diff --git a/lib/RoadizCoreBundle/src/Api/Extension/ArchiveExtension.php b/lib/RoadizCoreBundle/src/Api/Extension/ArchiveExtension.php index 14c615c6..7cf3dccd 100644 --- a/lib/RoadizCoreBundle/src/Api/Extension/ArchiveExtension.php +++ b/lib/RoadizCoreBundle/src/Api/Extension/ArchiveExtension.php @@ -19,7 +19,7 @@ * pagination_client_enabled: false * archive_enabled: true * archive_publication_field_name: publishedAt - * ``` + * ```. * * ``` * "hydra:member": [ @@ -45,7 +45,7 @@ final class ArchiveExtension implements QueryResultCollectionExtensionInterface { public function __construct( private readonly RequestStack $requestStack, - private readonly string $defaultPublicationFieldName = 'publishedAt' + private readonly string $defaultPublicationFieldName = 'publishedAt', ) { } @@ -54,7 +54,7 @@ public function applyToCollection( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { if (!$this->supportsResult($resourceClass, $operation)) { return; @@ -65,7 +65,7 @@ public function applyToCollection( $aliases = $queryBuilder->getRootAliases(); $alias = reset($aliases); $publicationFieldName = $this->getPublicationFieldName($operation); - $publicationField = $alias . '.' . $publicationFieldName; + $publicationField = $alias.'.'.$publicationFieldName; $queryBuilder->select($publicationField) ->addGroupBy($publicationField) @@ -85,7 +85,7 @@ public function getResult( QueryBuilder $queryBuilder, ?string $resourceClass = null, ?Operation $operation = null, - array $context = [] + array $context = [], ): iterable { $entities = []; $dates = []; @@ -123,13 +123,13 @@ public function getResult( } private function isArchiveEnabled( - ?Operation $operation = null + ?Operation $operation = null, ): bool { return $operation->getExtraProperties()['archive_enabled'] ?? false; } private function getPublicationFieldName( - ?Operation $operation = null + ?Operation $operation = null, ): string { return $operation->getExtraProperties()['archive_publication_field_name'] ?? $this->defaultPublicationFieldName; } diff --git a/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueQueryExtension.php b/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueQueryExtension.php index 889d8ef4..94dffeb2 100644 --- a/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueQueryExtension.php +++ b/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueQueryExtension.php @@ -17,7 +17,7 @@ final class AttributeValueQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface { public function __construct( - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } @@ -27,7 +27,7 @@ public function applyToItem( string $resourceClass, array $identifiers, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { $this->apply($queryBuilder, $resourceClass); } @@ -37,17 +37,17 @@ public function applyToCollection( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { $this->apply($queryBuilder, $resourceClass); } private function apply( QueryBuilder $queryBuilder, - string $resourceClass + string $resourceClass, ): void { if ( - $resourceClass !== AttributeValue::class + AttributeValue::class !== $resourceClass ) { return; } @@ -60,7 +60,7 @@ private function apply( */ $existingNodeJoin = QueryBuilderHelper::getExistingJoin($queryBuilder, 'o', 'node'); if (null === $existingNodeJoin || !$existingNodeJoin->getAlias()) { - $queryBuilder->leftJoin($rootAlias . '.node', 'node'); + $queryBuilder->leftJoin($rootAlias.'.node', 'node'); $joinAlias = 'node'; } else { $joinAlias = $existingNodeJoin->getAlias(); @@ -68,14 +68,16 @@ private function apply( if ($this->previewResolver->isPreview()) { $queryBuilder - ->andWhere($queryBuilder->expr()->lte($joinAlias . '.status', ':status')) + ->andWhere($queryBuilder->expr()->lte($joinAlias.'.status', ':status')) ->setParameter(':status', Node::PUBLISHED); + return; } $queryBuilder - ->andWhere($queryBuilder->expr()->eq($joinAlias . '.status', ':status')) + ->andWhere($queryBuilder->expr()->eq($joinAlias.'.status', ':status')) ->setParameter(':status', Node::PUBLISHED); + return; } } diff --git a/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueRealmExtension.php b/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueRealmExtension.php index d14b3437..4838fcfc 100644 --- a/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueRealmExtension.php +++ b/lib/RoadizCoreBundle/src/Api/Extension/AttributeValueRealmExtension.php @@ -18,23 +18,23 @@ final class AttributeValueRealmExtension implements QueryCollectionExtensionInte { public function __construct( private readonly Security $security, - private readonly RealmResolverInterface $realmResolver + private readonly RealmResolverInterface $realmResolver, ) { } - public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void + public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void { $this->addWhere($queryBuilder, $resourceClass); } - public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void + public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, ?Operation $operation = null, array $context = []): void { $this->addWhere($queryBuilder, $resourceClass); } private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void { - if ($resourceClass !== AttributeValue::class || $this->security->isGranted('ROLE_ACCESS_NODE_ATTRIBUTES')) { + if (AttributeValue::class !== $resourceClass || $this->security->isGranted('ROLE_ACCESS_NODE_ATTRIBUTES')) { return; } @@ -44,6 +44,7 @@ private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): vo $rootAlias = $queryBuilder->getRootAliases()[0]; if ($this->security->isGranted('IS_ANONYMOUS')) { $queryBuilder->andWhere($queryBuilder->expr()->isNull(sprintf('%s.realm', $rootAlias))); + return; } diff --git a/lib/RoadizCoreBundle/src/Api/Extension/DocumentQueryExtension.php b/lib/RoadizCoreBundle/src/Api/Extension/DocumentQueryExtension.php index 7d3894da..36daa36d 100644 --- a/lib/RoadizCoreBundle/src/Api/Extension/DocumentQueryExtension.php +++ b/lib/RoadizCoreBundle/src/Api/Extension/DocumentQueryExtension.php @@ -16,9 +16,9 @@ final class DocumentQueryExtension implements QueryItemExtensionInterface, Query private function apply( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, - string $resourceClass + string $resourceClass, ): void { - if ($resourceClass !== Document::class) { + if (Document::class !== $resourceClass) { return; } @@ -32,8 +32,8 @@ public function applyToItem( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, - Operation $operation = null, - array $context = [] + ?Operation $operation = null, + array $context = [], ): void { $this->apply($queryBuilder, $queryNameGenerator, $resourceClass); } @@ -42,8 +42,8 @@ public function applyToCollection( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, - Operation $operation = null, - array $context = [] + ?Operation $operation = null, + array $context = [], ): void { $this->apply($queryBuilder, $queryNameGenerator, $resourceClass); } diff --git a/lib/RoadizCoreBundle/src/Api/Extension/NodeQueryExtension.php b/lib/RoadizCoreBundle/src/Api/Extension/NodeQueryExtension.php index 9a4ee6c6..2a09dac9 100644 --- a/lib/RoadizCoreBundle/src/Api/Extension/NodeQueryExtension.php +++ b/lib/RoadizCoreBundle/src/Api/Extension/NodeQueryExtension.php @@ -17,7 +17,7 @@ final class NodeQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface { public function __construct( - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } @@ -26,8 +26,8 @@ public function applyToItem( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, - Operation $operation = null, - array $context = [] + ?Operation $operation = null, + array $context = [], ): void { $this->apply($queryBuilder, $queryNameGenerator, $resourceClass); } @@ -35,9 +35,9 @@ public function applyToItem( private function apply( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, - string $resourceClass + string $resourceClass, ): void { - if ($resourceClass !== Node::class) { + if (Node::class !== $resourceClass) { return; } @@ -45,6 +45,7 @@ private function apply( $queryBuilder ->andWhere($queryBuilder->expr()->lte('o.status', ':status')) ->setParameter(':status', Node::PUBLISHED); + return; } @@ -56,10 +57,11 @@ private function apply( Join::INNER_JOIN ); $queryBuilder - ->andWhere($queryBuilder->expr()->lte($alias . '.publishedAt', ':lte_published_at')) + ->andWhere($queryBuilder->expr()->lte($alias.'.publishedAt', ':lte_published_at')) ->andWhere($queryBuilder->expr()->eq('o.status', ':status')) ->setParameter(':lte_published_at', new \DateTime()) ->setParameter(':status', Node::PUBLISHED); + return; } @@ -67,8 +69,8 @@ public function applyToCollection( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, - Operation $operation = null, - array $context = [] + ?Operation $operation = null, + array $context = [], ): void { $this->apply($queryBuilder, $queryNameGenerator, $resourceClass); } diff --git a/lib/RoadizCoreBundle/src/Api/Extension/NodesSourcesQueryExtension.php b/lib/RoadizCoreBundle/src/Api/Extension/NodesSourcesQueryExtension.php index aca8ba43..60f82de9 100644 --- a/lib/RoadizCoreBundle/src/Api/Extension/NodesSourcesQueryExtension.php +++ b/lib/RoadizCoreBundle/src/Api/Extension/NodesSourcesQueryExtension.php @@ -19,7 +19,7 @@ final class NodesSourcesQueryExtension implements QueryItemExtensionInterface, Q { public function __construct( private readonly PreviewResolverInterface $previewResolver, - private readonly string $generatedEntityNamespacePattern = '#^App\\\GeneratedEntity\\\NS(?:[a-zA-Z]+)$#' + private readonly string $generatedEntityNamespacePattern = '#^App\\\GeneratedEntity\\\NS(?:[a-zA-Z]+)$#', ) { } @@ -29,7 +29,7 @@ public function applyToItem( string $resourceClass, array $identifiers, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { $this->apply($queryBuilder, $queryNameGenerator, $resourceClass); } @@ -39,7 +39,7 @@ public function applyToCollection( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { $this->apply($queryBuilder, $queryNameGenerator, $resourceClass); } @@ -47,11 +47,11 @@ public function applyToCollection( private function apply( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, - string $resourceClass + string $resourceClass, ): void { if ( - $resourceClass !== NodesSources::class && - preg_match($this->generatedEntityNamespacePattern, $resourceClass) === 0 + NodesSources::class !== $resourceClass + && 0 === preg_match($this->generatedEntityNamespacePattern, $resourceClass) ) { return; } @@ -70,8 +70,9 @@ private function apply( Join::INNER_JOIN ); $queryBuilder - ->andWhere($queryBuilder->expr()->lte($alias . '.status', ':status')) + ->andWhere($queryBuilder->expr()->lte($alias.'.status', ':status')) ->setParameter(':status', Node::PUBLISHED); + return; } @@ -84,9 +85,10 @@ private function apply( ); $queryBuilder ->andWhere($queryBuilder->expr()->lte('o.publishedAt', ':lte_published_at')) - ->andWhere($queryBuilder->expr()->eq($alias . '.status', ':status')) + ->andWhere($queryBuilder->expr()->eq($alias.'.status', ':status')) ->setParameter(':lte_published_at', new \DateTime()) ->setParameter(':status', Node::PUBLISHED); + return; } } diff --git a/lib/RoadizCoreBundle/src/Api/Extension/NodesTagsQueryExtension.php b/lib/RoadizCoreBundle/src/Api/Extension/NodesTagsQueryExtension.php index 37afa629..b166c880 100644 --- a/lib/RoadizCoreBundle/src/Api/Extension/NodesTagsQueryExtension.php +++ b/lib/RoadizCoreBundle/src/Api/Extension/NodesTagsQueryExtension.php @@ -17,7 +17,7 @@ final class NodesTagsQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface { public function __construct( - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } @@ -27,7 +27,7 @@ public function applyToItem( string $resourceClass, array $identifiers, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { $this->apply($queryBuilder, $resourceClass); } @@ -37,17 +37,17 @@ public function applyToCollection( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { $this->apply($queryBuilder, $resourceClass); } private function apply( QueryBuilder $queryBuilder, - string $resourceClass + string $resourceClass, ): void { if ( - $resourceClass !== Tag::class + Tag::class !== $resourceClass ) { return; } @@ -73,14 +73,16 @@ private function apply( if ($this->previewResolver->isPreview()) { $queryBuilder - ->andWhere($queryBuilder->expr()->lte($existingNodeJoin->getAlias() . '.status', ':status')) + ->andWhere($queryBuilder->expr()->lte($existingNodeJoin->getAlias().'.status', ':status')) ->setParameter(':status', Node::PUBLISHED); + return; } $queryBuilder - ->andWhere($queryBuilder->expr()->eq($existingNodeJoin->getAlias() . '.status', ':status')) + ->andWhere($queryBuilder->expr()->eq($existingNodeJoin->getAlias().'.status', ':status')) ->setParameter(':status', Node::PUBLISHED); + return; } } diff --git a/lib/RoadizCoreBundle/src/Api/Filter/ArchiveFilter.php b/lib/RoadizCoreBundle/src/Api/Filter/ArchiveFilter.php index 7b58e2f5..a7e5b6dc 100644 --- a/lib/RoadizCoreBundle/src/Api/Filter/ArchiveFilter.php +++ b/lib/RoadizCoreBundle/src/Api/Filter/ArchiveFilter.php @@ -31,12 +31,10 @@ protected function isDateField(string $property, string $resourceClass): bool if (\is_string($type)) { return \in_array($type, \array_keys(DateFilter::DOCTRINE_DATE_TYPES), true); } - return $type->getName() === 'datetime' || $type->getName() === 'date'; + + return 'datetime' === $type->getName() || 'date' === $type->getName(); } - /** - * {@inheritdoc} - */ protected function filterProperty( string $property, mixed $value, @@ -44,14 +42,14 @@ protected function filterProperty( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { // Expect $values to be an array having the period as keys and the date value as values if ( - !$this->isPropertyEnabled($property, $resourceClass) || - !$this->isPropertyMapped($property, $resourceClass) || - !$this->isDateField($property, $resourceClass) || - !isset($value[self::PARAMETER_ARCHIVE]) + !$this->isPropertyEnabled($property, $resourceClass) + || !$this->isPropertyMapped($property, $resourceClass) + || !$this->isDateField($property, $resourceClass) + || !isset($value[self::PARAMETER_ARCHIVE]) ) { return; } @@ -71,15 +69,12 @@ protected function filterProperty( } if (!is_string($value[self::PARAMETER_ARCHIVE])) { - throw new FilterValidationException([sprintf( - '“%s” filter must be only used with a string value.', - self::PARAMETER_ARCHIVE - )]); + throw new FilterValidationException([sprintf('“%s” filter must be only used with a string value.', self::PARAMETER_ARCHIVE)]); } $range = $this->normalizeFilteringDates($value[self::PARAMETER_ARCHIVE]); - if (null === $range || count($range) !== 2) { + if (null === $range || 2 !== count($range)) { return; } @@ -87,18 +82,18 @@ protected function filterProperty( $queryBuilder->andWhere($queryBuilder->expr()->isNotNull(sprintf('%s.%s', $alias, $field))) ->andWhere($queryBuilder->expr()->between( sprintf('%s.%s', $alias, $field), - ':' . $valueParameter . 'Start', - ':' . $valueParameter . 'End' + ':'.$valueParameter.'Start', + ':'.$valueParameter.'End' )) - ->setParameter($valueParameter . 'Start', $range[0]) - ->setParameter($valueParameter . 'End', $range[1]); + ->setParameter($valueParameter.'Start', $range[0]) + ->setParameter($valueParameter.'End', $range[1]); } /** * Support archive parameter with year or year-month. * - * @param string $value * @return \DateTime[]|null + * * @throws \Exception */ protected function normalizeFilteringDates(string $value): ?array @@ -107,24 +102,25 @@ protected function normalizeFilteringDates(string $value): ?array * Support archive parameter with year or year-month */ if (preg_match('#[0-9]{4}\-[0-9]{2}\-[0-9]{2}#', $value) > 0) { - $startDate = new \DateTime($value . ' 00:00:00'); + $startDate = new \DateTime($value.' 00:00:00'); $endDate = clone $startDate; $endDate->add(new \DateInterval('P1D')); return [$startDate, $this->limitEndDate($endDate)]; } elseif (preg_match('#[0-9]{4}\-[0-9]{2}#', $value) > 0) { - $startDate = new \DateTime($value . '-01 00:00:00'); + $startDate = new \DateTime($value.'-01 00:00:00'); $endDate = clone $startDate; $endDate->add(new \DateInterval('P1M')); return [$startDate, $this->limitEndDate($endDate)]; } elseif (preg_match('#[0-9]{4}#', $value) > 0) { - $startDate = new \DateTime($value . '-01-01 00:00:00'); + $startDate = new \DateTime($value.'-01-01 00:00:00'); $endDate = clone $startDate; $endDate->add(new \DateInterval('P1Y')); return [$startDate, $this->limitEndDate($endDate)]; } + return null; } @@ -134,6 +130,7 @@ protected function limitEndDate(\DateTime $endDate): \DateTime if ($endDate > $now) { return $now; } + return $endDate->sub(new \DateInterval('PT1S')); } diff --git a/lib/RoadizCoreBundle/src/Api/Filter/CopyrightValidFilter.php b/lib/RoadizCoreBundle/src/Api/Filter/CopyrightValidFilter.php index ea8f56f2..d20026a9 100644 --- a/lib/RoadizCoreBundle/src/Api/Filter/CopyrightValidFilter.php +++ b/lib/RoadizCoreBundle/src/Api/Filter/CopyrightValidFilter.php @@ -23,12 +23,12 @@ protected function filterProperty( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { - if ($property !== self::PARAMETER) { + if (self::PARAMETER !== $property) { return; } - if ($resourceClass !== Document::class) { + if (Document::class !== $resourceClass) { return; } @@ -41,12 +41,13 @@ protected function filterProperty( if (in_array($value, self::TRUE_VALUES)) { // Copyright MUST be valid $queryBuilder->andWhere($queryBuilder->expr()->orX( - $queryBuilder->expr()->isNull($alias . '.copyrightValidSince'), - $queryBuilder->expr()->lte($alias . '.copyrightValidSince', ':now') + $queryBuilder->expr()->isNull($alias.'.copyrightValidSince'), + $queryBuilder->expr()->lte($alias.'.copyrightValidSince', ':now') ))->andWhere($queryBuilder->expr()->orX( - $queryBuilder->expr()->isNull($alias . '.copyrightValidUntil'), - $queryBuilder->expr()->gte($alias . '.copyrightValidUntil', ':now') + $queryBuilder->expr()->isNull($alias.'.copyrightValidUntil'), + $queryBuilder->expr()->gte($alias.'.copyrightValidUntil', ':now') ))->setParameter(':now', new \DateTime()); + return; } @@ -54,10 +55,11 @@ protected function filterProperty( // Copyright MUST NOT be valid $queryBuilder->andWhere( $queryBuilder->expr()->orX( - $queryBuilder->expr()->gt($alias . '.copyrightValidSince', ':now'), - $queryBuilder->expr()->lt($alias . '.copyrightValidUntil', ':now') + $queryBuilder->expr()->gt($alias.'.copyrightValidSince', ':now'), + $queryBuilder->expr()->lt($alias.'.copyrightValidUntil', ':now') ) )->setParameter(':now', new \DateTime()); + return; } } @@ -71,9 +73,9 @@ public function getDescription(string $resourceClass): array 'required' => false, 'description' => 'Filter items for which copyright dates are valid.', 'openapi' => [ - 'description' => 'Filter items for which copyright dates are valid.' - ] - ] + 'description' => 'Filter items for which copyright dates are valid.', + ], + ], ]; } } diff --git a/lib/RoadizCoreBundle/src/Api/Filter/GeneratedEntityFilter.php b/lib/RoadizCoreBundle/src/Api/Filter/GeneratedEntityFilter.php index 255be66d..3b39c6a7 100644 --- a/lib/RoadizCoreBundle/src/Api/Filter/GeneratedEntityFilter.php +++ b/lib/RoadizCoreBundle/src/Api/Filter/GeneratedEntityFilter.php @@ -13,18 +13,11 @@ abstract class GeneratedEntityFilter extends AbstractFilter { private string $generatedEntityNamespacePattern; - /** - * @param ManagerRegistry $managerRegistry - * @param LoggerInterface|null $logger - * @param array|null $properties - * @param NameConverterInterface|null $nameConverter - * @param string $generatedEntityNamespacePattern - */ public function __construct( ManagerRegistry $managerRegistry, - LoggerInterface $logger = null, - array $properties = null, - NameConverterInterface $nameConverter = null, + ?LoggerInterface $logger = null, + ?array $properties = null, + ?NameConverterInterface $nameConverter = null, string $generatedEntityNamespacePattern = '#^App\\\GeneratedEntity\\\NS(?:[a-zA-Z]+)$#', ) { parent::__construct($managerRegistry, $logger, $properties, $nameConverter); @@ -32,17 +25,11 @@ public function __construct( $this->generatedEntityNamespacePattern = $generatedEntityNamespacePattern; } - /** - * @return string - */ public function getGeneratedEntityNamespacePattern(): string { return $this->generatedEntityNamespacePattern; } - /** - * @inheritDoc - */ public function getDescription(string $resourceClass): array { return []; diff --git a/lib/RoadizCoreBundle/src/Api/Filter/IntersectionFilter.php b/lib/RoadizCoreBundle/src/Api/Filter/IntersectionFilter.php index 699e1edc..bd380435 100644 --- a/lib/RoadizCoreBundle/src/Api/Filter/IntersectionFilter.php +++ b/lib/RoadizCoreBundle/src/Api/Filter/IntersectionFilter.php @@ -4,8 +4,8 @@ namespace RZ\Roadiz\CoreBundle\Api\Filter; -use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter; +use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; use ApiPlatform\Exception\FilterValidationException; use ApiPlatform\Metadata\Operation; use Doctrine\ORM\Query\Expr\Join; @@ -18,9 +18,6 @@ final class IntersectionFilter extends AbstractFilter { public const PARAMETER = 'intersect'; - /** - * @inheritDoc - */ protected function filterProperty( string $property, mixed $value, @@ -28,9 +25,9 @@ protected function filterProperty( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { - if ($property !== IntersectionFilter::PARAMETER || !is_array($value)) { + if (IntersectionFilter::PARAMETER !== $property || !is_array($value)) { return; } @@ -52,7 +49,7 @@ protected function filterProperty( $resourceClass, Join::INNER_JOIN // Join type must be inner to filter out empty result sets ); - $placeholder = ':' . $alias . $splitFieldName; + $placeholder = ':'.$alias.$splitFieldName; $queryBuilder->andWhere($queryBuilder->expr()->eq(sprintf('%s.%s', $alias, $splitFieldName), $placeholder)); $queryBuilder->setParameter($placeholder, $singleValue); } @@ -60,9 +57,6 @@ protected function filterProperty( } } - /** - * @inheritDoc - */ public function getDescription(string $resourceClass): array { $properties = $this->properties; @@ -80,8 +74,8 @@ function ($carry, $property) { 'required' => false, 'description' => 'Discriminate an existing filter with additional filtering value using a new inner join.', 'openapi' => [ - 'description' => 'Discriminate an existing filter with additional filtering value using a new inner join.' - ] + 'description' => 'Discriminate an existing filter with additional filtering value using a new inner join.', + ], ]; $carry[sprintf('%s[%s][]', IntersectionFilter::PARAMETER, $property)] = [ 'property' => $property, @@ -89,9 +83,10 @@ function ($carry, $property) { 'required' => false, 'description' => 'Discriminate an existing filter with additional filtering value using a new inner join.', 'openapi' => [ - 'description' => 'Discriminate an existing filter with additional filtering value using a new inner join.' - ] + 'description' => 'Discriminate an existing filter with additional filtering value using a new inner join.', + ], ]; + return $carry; }, [] @@ -104,7 +99,7 @@ protected function addDuplicatedJoinsForNestedProperty( QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, - string $joinType + string $joinType, ): array { $propertyParts = $this->splitPropertyParts($property, $resourceClass); $parentAlias = $rootAlias; @@ -130,9 +125,9 @@ public static function addDuplicatedJoin( QueryNameGeneratorInterface $queryNameGenerator, string $alias, string $association, - string $joinType = null + ?string $joinType = null, ): string { - $associationAlias = $queryNameGenerator->generateJoinAlias($association) . uniqid(); + $associationAlias = $queryNameGenerator->generateJoinAlias($association).uniqid(); $query = "$alias.$association"; if (Join::LEFT_JOIN === $joinType) { diff --git a/lib/RoadizCoreBundle/src/Api/Filter/LocaleFilter.php b/lib/RoadizCoreBundle/src/Api/Filter/LocaleFilter.php index aaefd4a5..54e7f74b 100644 --- a/lib/RoadizCoreBundle/src/Api/Filter/LocaleFilter.php +++ b/lib/RoadizCoreBundle/src/Api/Filter/LocaleFilter.php @@ -22,10 +22,10 @@ final class LocaleFilter extends GeneratedEntityFilter public function __construct( private readonly PreviewResolverInterface $previewResolver, ManagerRegistry $managerRegistry, - LoggerInterface $logger = null, - array $properties = null, - NameConverterInterface $nameConverter = null, - string $generatedEntityNamespacePattern = '#^App\\\GeneratedEntity\\\NS(?:[a-zA-Z]+)$#' + ?LoggerInterface $logger = null, + ?array $properties = null, + ?NameConverterInterface $nameConverter = null, + string $generatedEntityNamespacePattern = '#^App\\\GeneratedEntity\\\NS(?:[a-zA-Z]+)$#', ) { parent::__construct($managerRegistry, $logger, $properties, $nameConverter, $generatedEntityNamespacePattern); } @@ -37,9 +37,9 @@ protected function filterProperty( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { - if ($property !== self::PROPERTY) { + if (self::PROPERTY !== $property) { return; } @@ -53,28 +53,20 @@ protected function filterProperty( ->getAvailableLocales(); } - if (count($supportedLocales) === 0) { - throw new FilterValidationException( - ['Locale filter is not available because no translation exist.'] - ); + if (0 === count($supportedLocales)) { + throw new FilterValidationException(['Locale filter is not available because no translation exist.']); } if (!in_array($value, $supportedLocales)) { - throw new FilterValidationException( - [sprintf( - 'Locale filter value "%s" not supported. Supported values are %s', - $value, - implode(', ', $supportedLocales) - )] - ); + throw new FilterValidationException([sprintf('Locale filter value "%s" not supported. Supported values are %s', $value, implode(', ', $supportedLocales))]); } /* * Apply translation filter only for NodesSources */ if ( - $resourceClass === NodesSources::class || - preg_match($this->getGeneratedEntityNamespacePattern(), $resourceClass) > 0 + NodesSources::class === $resourceClass + || preg_match($this->getGeneratedEntityNamespacePattern(), $resourceClass) > 0 ) { if ($this->previewResolver->isPreview()) { $translation = $this->managerRegistry @@ -87,7 +79,7 @@ protected function filterProperty( } if (null === $translation) { - throw new FilterValidationException(['No translation exist for locale: ' . $value]); + throw new FilterValidationException(['No translation exist for locale: '.$value]); } $queryBuilder @@ -106,23 +98,20 @@ protected function filterProperty( * - strategy: the used strategy * - swagger (optional): additional parameters for the path operation, e.g. 'swagger' => ['description' => 'My Description'] * The description can contain additional data specific to a filter. - * - * @param string $resourceClass - * - * @return array */ public function getDescription(string $resourceClass): array { $supportedLocales = $this->managerRegistry->getRepository(Translation::class)->getAvailableLocales(); - return [ - self::PROPERTY => [ + + return [ + self::PROPERTY => [ 'property' => self::PROPERTY, 'type' => 'string', 'required' => false, 'openapi' => [ - 'description' => 'Filter items with translation locale (' . implode(', ', $supportedLocales) . ').' - ] - ] + 'description' => 'Filter items with translation locale ('.implode(', ', $supportedLocales).').', + ], + ], ]; } } diff --git a/lib/RoadizCoreBundle/src/Api/Filter/NotFilter.php b/lib/RoadizCoreBundle/src/Api/Filter/NotFilter.php index b1677bd0..de2f0682 100644 --- a/lib/RoadizCoreBundle/src/Api/Filter/NotFilter.php +++ b/lib/RoadizCoreBundle/src/Api/Filter/NotFilter.php @@ -4,8 +4,8 @@ namespace RZ\Roadiz\CoreBundle\Api\Filter; -use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter; +use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; use ApiPlatform\Metadata\Operation; use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\QueryBuilder; @@ -22,9 +22,9 @@ protected function filterProperty( QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, - array $context = [] + array $context = [], ): void { - if ($property !== self::PARAMETER || !\is_array($value)) { + if (self::PARAMETER !== $property || !\is_array($value)) { return; } @@ -43,7 +43,7 @@ protected function filterProperty( ); } - $placeholder = ':' . (new AsciiSlugger())->slug($alias . '_' . $field, '_')->toString(); + $placeholder = ':'.(new AsciiSlugger())->slug($alias.'_'.$field, '_')->toString(); if (\is_array($notValue)) { $queryBuilder->andWhere( $queryBuilder->expr()->notIn(sprintf('%s.%s', $alias, $field), $placeholder) @@ -67,10 +67,6 @@ protected function filterProperty( * - strategy: the used strategy * - swagger (optional): additional parameters for the path operation, e.g. 'swagger' => ['description' => 'My Description'] * The description can contain additional data specific to a filter. - * - * @param string $resourceClass - * - * @return array */ public function getDescription(string $resourceClass): array { @@ -89,8 +85,8 @@ function ($carry, $property) { 'required' => false, 'description' => 'Filter items that are not equal.', 'openapi' => [ - 'description' => 'Filter items that are not equal.' - ] + 'description' => 'Filter items that are not equal.', + ], ]; $carry[sprintf('%s[%s][]', self::PARAMETER, $property)] = [ 'property' => $property, @@ -98,9 +94,10 @@ function ($carry, $property) { 'required' => false, 'description' => 'Filter items that are not equal.', 'openapi' => [ - 'description' => 'Filter items that are not equal.' - ] + 'description' => 'Filter items that are not equal.', + ], ]; + return $carry; }, [] diff --git a/lib/RoadizCoreBundle/src/Api/ListManager/SolrPaginator.php b/lib/RoadizCoreBundle/src/Api/ListManager/SolrPaginator.php index 7ff11677..5056d140 100644 --- a/lib/RoadizCoreBundle/src/Api/ListManager/SolrPaginator.php +++ b/lib/RoadizCoreBundle/src/Api/ListManager/SolrPaginator.php @@ -27,6 +27,7 @@ protected function handleOnce(): void public function count(): int { $this->handleOnce(); + return $this->listManager->getItemCount(); } @@ -34,24 +35,28 @@ public function getLastPage(): float { $this->handleOnce(); $lastPage = $this->listManager->getPageCount(); + return max($lastPage, 1); } public function getTotalItems(): float { $this->handleOnce(); + return $this->listManager->getItemCount(); } public function getCurrentPage(): float { $this->handleOnce(); + return $this->listManager->getAssignation()['currentPage']; } public function getItemsPerPage(): float { $this->handleOnce(); + return $this->listManager->getAssignation()['itemPerPage']; } @@ -59,6 +64,7 @@ public function getIterator(): \Traversable { $this->handleOnce(); $entities = $this->listManager->getEntities(); + return new \ArrayIterator($entities); } } diff --git a/lib/RoadizCoreBundle/src/Api/ListManager/SolrSearchListManager.php b/lib/RoadizCoreBundle/src/Api/ListManager/SolrSearchListManager.php index edacc39f..d14e89fb 100644 --- a/lib/RoadizCoreBundle/src/Api/ListManager/SolrSearchListManager.php +++ b/lib/RoadizCoreBundle/src/Api/ListManager/SolrSearchListManager.php @@ -20,14 +20,14 @@ public function __construct( ?Request $request, private readonly SearchHandlerInterface $searchHandler, private readonly array $criteria = [], - private readonly bool $searchInTags = true + private readonly bool $searchInTags = true, ) { parent::__construct($request); } public function handle(bool $disabled = false): void { - if ($this->request === null) { + if (null === $this->request) { throw new \InvalidArgumentException('Cannot handle a NULL request.'); } @@ -42,18 +42,18 @@ public function handle(bool $disabled = false): void */ if (\mb_strlen($this->query) > 3) { $this->searchResults = $this->searchHandler->searchWithHighlight( - $this->query, # Use ?q query parameter to search with - $this->criteria, # a simple criteria array to filter search results - $this->getItemPerPage(), # result count - $this->searchInTags, # Search in tags too, + $this->query, // Use ?q query parameter to search with + $this->criteria, // a simple criteria array to filter search results + $this->getItemPerPage(), // result count + $this->searchInTags, // Search in tags too, $this->getPage() ); } else { $this->searchResults = $this->searchHandler->search( - $this->query, # Use ?q query parameter to search with - $this->criteria, # a simple criteria array to filter search results - $this->getItemPerPage(), # result count - $this->searchInTags, # Search in tags too, + $this->query, // Use ?q query parameter to search with + $this->criteria, // a simple criteria array to filter search results + $this->getItemPerPage(), // result count + $this->searchInTags, // Search in tags too, $this->getPage() ); } @@ -65,9 +65,6 @@ protected function handleSearchParam(string $search): void $this->query = trim($search); } - /** - * @inheritDoc - */ public function getItemCount(): int { if (null !== $this->searchResults) { @@ -76,9 +73,6 @@ public function getItemCount(): int throw new \InvalidArgumentException('Call EntityListManagerInterface::handle before counting entities.'); } - /** - * @inheritDoc - */ public function getEntities(): array { if (null !== $this->searchResults) { diff --git a/lib/RoadizCoreBundle/src/Api/Model/BlocksAwareWebResponseInterface.php b/lib/RoadizCoreBundle/src/Api/Model/BlocksAwareWebResponseInterface.php index bdf356fe..0dc8a927 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/BlocksAwareWebResponseInterface.php +++ b/lib/RoadizCoreBundle/src/Api/Model/BlocksAwareWebResponseInterface.php @@ -16,6 +16,7 @@ public function getBlocks(): ?array; /** * @param Collection|null $blocks + * * @return $this */ public function setBlocks(?Collection $blocks): self; diff --git a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHead.php b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHead.php index c0f52e2b..56fcfda1 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHead.php +++ b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHead.php @@ -38,21 +38,13 @@ class NodesSourcesHead implements NodesSourcesHeadInterface #[Serializer\Ignore] protected TranslationInterface $defaultTranslation; - /** - * @param NodesSources|null $nodesSource - * @param Settings $settingsBag - * @param UrlGeneratorInterface $urlGenerator - * @param NodeSourceApi $nodeSourceApi - * @param HandlerFactoryInterface $handlerFactory - * @param TranslationInterface $defaultTranslation - */ public function __construct( ?NodesSources $nodesSource, Settings $settingsBag, UrlGeneratorInterface $urlGenerator, NodeSourceApi $nodeSourceApi, HandlerFactoryInterface $handlerFactory, - TranslationInterface $defaultTranslation + TranslationInterface $defaultTranslation, ) { $this->nodesSource = $nodesSource; $this->settingsBag = $settingsBag; @@ -62,63 +54,42 @@ public function __construct( $this->handlerFactory = $handlerFactory; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getGoogleAnalytics(): ?string { return $this->settingsBag->get('universal_analytics_id', null) ?? null; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getGoogleTagManager(): ?string { return $this->settingsBag->get('google_tag_manager_id', null) ?? null; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getMatomoTagManager(): ?string { return $this->settingsBag->get('matomo_tag_manager_id', null) ?? null; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getMatomoUrl(): ?string { return $this->settingsBag->get('matomo_url', null) ?? null; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getMatomoSiteId(): ?string { return $this->settingsBag->get('matomo_site_id', null) ?? null; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getSiteName(): ?string { return $this->settingsBag->get('site_name', null) ?? null; } - /** - * @return array - */ #[Serializer\Ignore] protected function getDefaultSeo(): array { @@ -128,16 +99,14 @@ protected function getDefaultSeo(): array return $nodesSourcesHandler->getSEO(); } } + return [ 'title' => $this->settingsBag->get('site_name'), 'description' => $this->settingsBag->get('seo_description'), ]; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getMetaTitle(): ?string { if (null === $this->seo) { @@ -147,10 +116,7 @@ public function getMetaTitle(): ?string return $this->seo['title']; } - /** - * @return string|null - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getMetaDescription(): ?string { if (null === $this->seo) { @@ -160,124 +126,125 @@ public function getMetaDescription(): ?string return $this->seo['description']; } - /** - * @return bool - */ - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function isNoIndex(): bool { if (null !== $this->nodesSource) { return $this->nodesSource->isNoIndex(); } + return false; } - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getPolicyUrl(): ?string { $translation = $this->getTranslation(); $policyNodeSource = $this->nodeSourceApi->getOneBy([ 'node.nodeName' => 'privacy', - 'translation' => $translation + 'translation' => $translation, ]); if (null === $policyNodeSource) { $policyNodeSource = $this->nodeSourceApi->getOneBy([ 'node.nodeName' => 'legal', - 'translation' => $translation + 'translation' => $translation, ]); } if (null !== $policyNodeSource) { return $this->urlGenerator->generate(RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ - RouteObjectInterface::ROUTE_OBJECT => $policyNodeSource + RouteObjectInterface::ROUTE_OBJECT => $policyNodeSource, ]); } + return null; } - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getMainColor(): ?string { return $this->settingsBag->get('main_color', null) ?? null; } - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getFacebookUrl(): ?string { return $this->settingsBag->get('facebook_url', null) ?? null; } - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getInstagramUrl(): ?string { return $this->settingsBag->get('instagram_url', null) ?? null; } - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getTwitterUrl(): ?string { return $this->settingsBag->get('twitter_url', null) ?? null; } - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getYoutubeUrl(): ?string { return $this->settingsBag->get('youtube_url', null) ?? null; } - #[Serializer\Groups(["nodes_sources_single", "walker"])] + #[Serializer\Groups(['nodes_sources_single', 'walker'])] public function getLinkedinUrl(): ?string { return $this->settingsBag->get('linkedin_url', null) ?? null; } - #[Serializer\Groups(["nodes_sources_single", "walker"])] + #[Serializer\Groups(['nodes_sources_single', 'walker'])] public function getSpotifyUrl(): ?string { return $this->settingsBag->get('spotify_url', null) ?? null; } - #[Serializer\Groups(["nodes_sources_single", "walker"])] + #[Serializer\Groups(['nodes_sources_single', 'walker'])] public function getSoundcloudUrl(): ?string { return $this->settingsBag->get('soundcloud_url', null) ?? null; } - #[Serializer\Groups(["nodes_sources_single", "walker"])] + #[Serializer\Groups(['nodes_sources_single', 'walker'])] public function getTikTokUrl(): ?string { return $this->settingsBag->get('tiktok_url', null) ?? null; } - #[Serializer\Groups(["web_response", "nodes_sources_single", "walker"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single', 'walker'])] public function getHomePageUrl(): ?string { $homePage = $this->getHomePage(); if (null !== $homePage) { return $this->urlGenerator->generate(RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ - RouteObjectInterface::ROUTE_OBJECT => $homePage + RouteObjectInterface::ROUTE_OBJECT => $homePage, ]); } + return null; } - #[Serializer\Groups(["web_response", "nodes_sources_single"])] + #[Serializer\Groups(['web_response', 'nodes_sources_single'])] public function getShareImage(): ?DocumentInterface { if ( - null !== $this->nodesSource && - method_exists($this->nodesSource, 'getHeaderImage') && - isset($this->nodesSource->getHeaderImage()[0]) + null !== $this->nodesSource + && method_exists($this->nodesSource, 'getHeaderImage') + && isset($this->nodesSource->getHeaderImage()[0]) ) { return $this->nodesSource->getHeaderImage()[0]; } if ( - null !== $this->nodesSource && - method_exists($this->nodesSource, 'getImage') && - isset($this->nodesSource->getImage()[0]) + null !== $this->nodesSource + && method_exists($this->nodesSource, 'getImage') + && isset($this->nodesSource->getImage()[0]) ) { return $this->nodesSource->getImage()[0]; } + return $this->settingsBag->getDocument('share_image') ?? null; } @@ -287,6 +254,7 @@ public function getTranslation(): TranslationInterface if (null !== $this->nodesSource) { return $this->nodesSource->getTranslation(); } + return $this->defaultTranslation; } @@ -295,7 +263,7 @@ public function getHomePage(): ?NodesSources { return $this->nodeSourceApi->getOneBy([ 'node.home' => true, - 'translation' => $this->getTranslation() + 'translation' => $this->getTranslation(), ]); } } diff --git a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactory.php b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactory.php index 9cae9098..f2d6e210 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactory.php +++ b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactory.php @@ -17,7 +17,7 @@ public function __construct( private readonly Settings $settingsBag, private readonly UrlGeneratorInterface $urlGenerator, private readonly NodeSourceApi $nodeSourceApi, - private readonly HandlerFactoryInterface $handlerFactory + private readonly HandlerFactoryInterface $handlerFactory, ) { } diff --git a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactoryInterface.php b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactoryInterface.php index 51295929..b13f85f2 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactoryInterface.php +++ b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadFactoryInterface.php @@ -10,5 +10,6 @@ interface NodesSourcesHeadFactoryInterface { public function createForTranslation(TranslationInterface $translation): NodesSourcesHeadInterface; + public function createForNodeSource(NodesSources $nodesSources): NodesSourcesHeadInterface; } diff --git a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadInterface.php b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadInterface.php index 36e0fd92..3413ee1f 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadInterface.php +++ b/lib/RoadizCoreBundle/src/Api/Model/NodesSourcesHeadInterface.php @@ -11,12 +11,20 @@ interface NodesSourcesHeadInterface { public function getSiteName(): ?string; + public function getMetaTitle(): ?string; + public function getMetaDescription(): ?string; + public function getPolicyUrl(): ?string; + public function getHomePageUrl(): ?string; + public function isNoIndex(): bool; + public function getHomePage(): ?NodesSources; + public function getShareImage(): ?DocumentInterface; + public function getTranslation(): TranslationInterface; } diff --git a/lib/RoadizCoreBundle/src/Api/Model/RealmsAwareWebResponseInterface.php b/lib/RoadizCoreBundle/src/Api/Model/RealmsAwareWebResponseInterface.php index 3962bfe0..adeded2b 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/RealmsAwareWebResponseInterface.php +++ b/lib/RoadizCoreBundle/src/Api/Model/RealmsAwareWebResponseInterface.php @@ -15,17 +15,14 @@ public function getRealms(): ?array; /** * @param RealmInterface[]|null $realms + * * @return $this */ public function setRealms(?array $realms): self; - /** - * @return bool - */ public function isHidingBlocks(): bool; /** - * @param bool $hidingBlocks * @return $this */ public function setHidingBlocks(bool $hidingBlocks): self; diff --git a/lib/RoadizCoreBundle/src/Api/Model/WebResponseInterface.php b/lib/RoadizCoreBundle/src/Api/Model/WebResponseInterface.php index 61ff1727..6b8f73ae 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/WebResponseInterface.php +++ b/lib/RoadizCoreBundle/src/Api/Model/WebResponseInterface.php @@ -13,18 +13,22 @@ interface WebResponseInterface { public function setHead(?NodesSourcesHeadInterface $head): self; + public function setBreadcrumbs(?BreadcrumbsInterface $breadcrumbs): self; /** * @param T|null $item - * @return self */ public function setItem(?PersistableInterface $item): self; + public function setPath(?string $path): self; + /** * @return T|null */ public function getItem(): ?PersistableInterface; + public function getMaxAge(): ?int; + public function setMaxAge(?int $maxAge): self; } diff --git a/lib/RoadizCoreBundle/src/Api/Model/WebResponseTrait.php b/lib/RoadizCoreBundle/src/Api/Model/WebResponseTrait.php index 8acf455f..ed1718fa 100644 --- a/lib/RoadizCoreBundle/src/Api/Model/WebResponseTrait.php +++ b/lib/RoadizCoreBundle/src/Api/Model/WebResponseTrait.php @@ -15,39 +15,39 @@ trait WebResponseTrait { #[ApiProperty( - description: "The path of the current WebResponse.", + description: 'The path of the current WebResponse.', readable: true, writable: false, identifier: true )] public ?string $path = null; - #[Serializer\Groups(["web_response"])] + #[Serializer\Groups(['web_response'])] public ?PersistableInterface $item = null; - #[Serializer\Groups(["web_response"])] + #[Serializer\Groups(['web_response'])] public ?BreadcrumbsInterface $breadcrumbs = null; - #[Serializer\Groups(["web_response"])] + #[Serializer\Groups(['web_response'])] public ?NodesSourcesHeadInterface $head = null; /** * @var Collection|null */ - #[Serializer\Groups(["web_response"])] + #[Serializer\Groups(['web_response'])] private ?Collection $blocks = null; /** * @var array|null */ - #[Serializer\Groups(["web_response"])] + #[Serializer\Groups(['web_response'])] private ?array $realms = null; - #[Serializer\Groups(["web_response"])] + #[Serializer\Groups(['web_response'])] private bool $hidingBlocks = false; /** * @var int|null WebResponse item maximum age in seconds */ - #[Serializer\Groups(["web_response"])] + #[Serializer\Groups(['web_response'])] private ?int $maxAge = null; public function getMaxAge(): ?int @@ -58,24 +58,24 @@ public function getMaxAge(): ?int public function setMaxAge(?int $maxAge): self { $this->maxAge = $maxAge; + return $this; } public function setPath(?string $path): self { $this->path = $path; + return $this; } public function setItem(?PersistableInterface $item): self { $this->item = $item; + return $this; } - /** - * @return PersistableInterface|null - */ public function getItem(): ?PersistableInterface { return $this->item; @@ -91,11 +91,13 @@ public function getBlocks(): ?array /** * @param Collection|null $blocks + * * @return $this */ public function setBlocks(?Collection $blocks): self { $this->blocks = $blocks; + return $this; } @@ -109,41 +111,42 @@ public function getRealms(): ?array /** * @param RealmInterface[]|null $realms + * * @return $this */ public function setRealms(?array $realms): self { $this->realms = $realms; + return $this; } - /** - * @return bool - */ public function isHidingBlocks(): bool { return $this->hidingBlocks; } /** - * @param bool $hidingBlocks * @return $this */ public function setHidingBlocks(bool $hidingBlocks): self { $this->hidingBlocks = $hidingBlocks; + return $this; } public function setBreadcrumbs(?BreadcrumbsInterface $breadcrumbs): self { $this->breadcrumbs = $breadcrumbs; + return $this; } public function setHead(?NodesSourcesHeadInterface $head): self { $this->head = $head; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Api/OpenApi/JwtDecorator.php b/lib/RoadizCoreBundle/src/Api/OpenApi/JwtDecorator.php index cb41dee7..65cb1f12 100644 --- a/lib/RoadizCoreBundle/src/Api/OpenApi/JwtDecorator.php +++ b/lib/RoadizCoreBundle/src/Api/OpenApi/JwtDecorator.php @@ -5,13 +5,13 @@ namespace RZ\Roadiz\CoreBundle\Api\OpenApi; use ApiPlatform\OpenApi\Factory\OpenApiFactoryInterface; -use ApiPlatform\OpenApi\OpenApi; use ApiPlatform\OpenApi\Model; +use ApiPlatform\OpenApi\OpenApi; final class JwtDecorator implements OpenApiFactoryInterface { public function __construct( - private readonly OpenApiFactoryInterface $decorated + private readonly OpenApiFactoryInterface $decorated, ) { } diff --git a/lib/RoadizCoreBundle/src/Api/OpenApi/PreviewDecorator.php b/lib/RoadizCoreBundle/src/Api/OpenApi/PreviewDecorator.php index 7dcecaae..e575d75a 100644 --- a/lib/RoadizCoreBundle/src/Api/OpenApi/PreviewDecorator.php +++ b/lib/RoadizCoreBundle/src/Api/OpenApi/PreviewDecorator.php @@ -12,7 +12,7 @@ final class PreviewDecorator implements OpenApiFactoryInterface { public function __construct( - private readonly OpenApiFactoryInterface $decorated + private readonly OpenApiFactoryInterface $decorated, ) { } @@ -37,10 +37,10 @@ public function __invoke(array $context = []): OpenApi 'query', 'Enables preview mode (requires a valid bearer JWT token)', false - ))->withSchema(['type' => 'boolean'])->withExample('1') + ))->withSchema(['type' => 'boolean'])->withExample('1'), ])->withSecurity([ ...$operation->getSecurity() ?? [], - ['JWT' => []] + ['JWT' => []], ])->withResponses($responses); $openApi->getPaths()->addPath($path, $pathItem->withGet($newOperation)); } diff --git a/lib/RoadizCoreBundle/src/Api/OpenApi/WebResponseDecorator.php b/lib/RoadizCoreBundle/src/Api/OpenApi/WebResponseDecorator.php index e76a1947..0c09dc08 100644 --- a/lib/RoadizCoreBundle/src/Api/OpenApi/WebResponseDecorator.php +++ b/lib/RoadizCoreBundle/src/Api/OpenApi/WebResponseDecorator.php @@ -11,7 +11,7 @@ final class WebResponseDecorator implements OpenApiFactoryInterface { public function __construct( - private readonly OpenApiFactoryInterface $decorated + private readonly OpenApiFactoryInterface $decorated, ) { } @@ -39,7 +39,7 @@ public function __invoke(array $context = []): OpenApi 'query', 'Enables preview mode (requires a valid bearer JWT token)', false - ))->withSchema(['type' => 'boolean'])->withExample('1') + ))->withSchema(['type' => 'boolean'])->withExample('1'), ]) )); diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/AutoChildrenNodeSourceWalker.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/AutoChildrenNodeSourceWalker.php index 96ea462d..3d0c9a27 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/AutoChildrenNodeSourceWalker.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/AutoChildrenNodeSourceWalker.php @@ -42,18 +42,13 @@ protected function initializeAdditionalDefinitions(): void } /** - * @param NodeTypeInterface $nodeType - * @return callable * @throws InvalidArgumentException */ protected function createDefinitionForNodeType(NodeTypeInterface $nodeType): callable { $context = $this->getContext(); if (!$context instanceof NodeSourceWalkerContext) { - throw new \InvalidArgumentException( - 'TreeWalker context must be instance of ' . - NodeSourceWalkerContext::class - ); + throw new \InvalidArgumentException('TreeWalker context must be instance of '.NodeSourceWalkerContext::class); } $childrenNodeTypes = $context->getNodeTypeResolver()->getChildrenNodeTypeList($nodeType); if (count($childrenNodeTypes) > 0) { diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/DefinitionFactoryConfiguration.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/DefinitionFactoryConfiguration.php index a4326a3e..3b227a1c 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/DefinitionFactoryConfiguration.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/DefinitionFactoryConfiguration.php @@ -8,13 +8,11 @@ final class DefinitionFactoryConfiguration { /** * @param class-string $classname - * @param DefinitionFactoryInterface $definitionFactory - * @param bool $onlyVisible */ public function __construct( public readonly string $classname, public readonly DefinitionFactoryInterface $definitionFactory, - public readonly bool $onlyVisible + public readonly bool $onlyVisible, ) { } } diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php index aa3d441f..fd0c85fa 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php @@ -15,25 +15,22 @@ final class MultiTypeChildrenDefinition use ContextualDefinitionTrait; /** - * @param WalkerContextInterface $context * @param array $types - * @param bool $onlyVisible */ public function __construct( private readonly WalkerContextInterface $context, private readonly array $types, - private readonly bool $onlyVisible = true + private readonly bool $onlyVisible = true, ) { } /** - * @param NodesSources $source * @return array */ public function __invoke(NodesSources $source): array { if (!($this->context instanceof NodeSourceWalkerContext)) { - throw new \InvalidArgumentException('Context should be instance of ' . NodeSourceWalkerContext::class); + throw new \InvalidArgumentException('Context should be instance of '.NodeSourceWalkerContext::class); } $this->context->getStopwatch()->start(self::class); @@ -50,7 +47,7 @@ public function __invoke(NodesSources $source): array if ($this->onlyVisible) { $criteria['node.visible'] = true; } - if (count($nodeTypes) === 1) { + if (1 === count($nodeTypes)) { $entityName = $nodeTypes[0]->getSourceEntityFullQualifiedClassName(); } else { $entityName = NodesSources::class; diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php index 26a5a482..91da32fc 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\CoreBundle\Api\TreeWalker\Definition; -use Exception; use RZ\Roadiz\CoreBundle\Api\TreeWalker\NodeSourceWalkerContext; use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\TreeWalker\Definition\ContextualDefinitionTrait; @@ -16,17 +15,17 @@ final class NonReachableNodeSourceBlockDefinition public function __construct( private readonly WalkerContextInterface $context, - private readonly bool $onlyVisible = true + private readonly bool $onlyVisible = true, ) { } /** - * @throws Exception + * @throws \Exception */ public function __invoke(NodesSources $source): array { if (!($this->context instanceof NodeSourceWalkerContext)) { - throw new \InvalidArgumentException('Context should be instance of ' . NodeSourceWalkerContext::class); + throw new \InvalidArgumentException('Context should be instance of '.NodeSourceWalkerContext::class); } $this->context->getStopwatch()->start(self::class); diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php index 0d193896..f50e947f 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\CoreBundle\Api\TreeWalker\Definition; -use Exception; use RZ\Roadiz\CoreBundle\Api\TreeWalker\NodeSourceWalkerContext; use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\TreeWalker\Definition\ContextualDefinitionTrait; @@ -16,17 +15,17 @@ final class ReachableNodeSourceDefinition public function __construct( private readonly WalkerContextInterface $context, - private readonly bool $onlyVisible = true + private readonly bool $onlyVisible = true, ) { } /** - * @throws Exception + * @throws \Exception */ public function __invoke(NodesSources $source): array { if (!($this->context instanceof NodeSourceWalkerContext)) { - throw new \InvalidArgumentException('Context should be instance of ' . NodeSourceWalkerContext::class); + throw new \InvalidArgumentException('Context should be instance of '.NodeSourceWalkerContext::class); } $this->context->getStopwatch()->start(self::class); diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContext.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContext.php index 928d0241..ba0d5f85 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContext.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContext.php @@ -28,28 +28,21 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly CacheItemPoolInterface $cacheAdapter, private readonly NodeTypeResolver $nodeTypeResolver, - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } - /** - * @return Stopwatch - */ public function getStopwatch(): Stopwatch { return $this->stopwatch; } - /** - * @return NodeTypes - */ public function getNodeTypesBag(): NodeTypes { return $this->nodeTypesBag; } /** - * @return NodeSourceApi * @deprecated Use getManagerRegistry */ public function getNodeSourceApi(): NodeSourceApi @@ -57,16 +50,12 @@ public function getNodeSourceApi(): NodeSourceApi return $this->nodeSourceApi; } - /** - * @return RequestStack - */ public function getRequestStack(): RequestStack { return $this->requestStack; } /** - * @return Request|null * @deprecated Use getMainRequest */ public function getMasterRequest(): ?Request @@ -74,49 +63,31 @@ public function getMasterRequest(): ?Request return $this->requestStack->getMainRequest(); } - /** - * @return Request|null - */ public function getMainRequest(): ?Request { return $this->requestStack->getMainRequest(); } - /** - * @return ManagerRegistry - */ public function getManagerRegistry(): ManagerRegistry { return $this->managerRegistry; } - /** - * @return ObjectManager - */ public function getEntityManager(): ObjectManager { return $this->getManagerRegistry()->getManager(); } - /** - * @return CacheItemPoolInterface - */ public function getCacheAdapter(): CacheItemPoolInterface { return $this->cacheAdapter; } - /** - * @return NodeTypeResolver - */ public function getNodeTypeResolver(): NodeTypeResolver { return $this->nodeTypeResolver; } - /** - * @return PreviewResolverInterface - */ public function getPreviewResolver(): PreviewResolverInterface { return $this->previewResolver; diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php index 2c5099c6..3b79a0e7 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php @@ -24,7 +24,7 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly CacheItemPoolInterface $cacheAdapter, private readonly NodeTypeResolver $nodeTypeResolver, - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } diff --git a/lib/RoadizCoreBundle/src/Api/TreeWalker/TreeWalkerGenerator.php b/lib/RoadizCoreBundle/src/Api/TreeWalker/TreeWalkerGenerator.php index b456f2db..6d995b16 100644 --- a/lib/RoadizCoreBundle/src/Api/TreeWalker/TreeWalkerGenerator.php +++ b/lib/RoadizCoreBundle/src/Api/TreeWalker/TreeWalkerGenerator.php @@ -27,22 +27,20 @@ public function __construct( private readonly NodeSourceApi $nodeSourceApi, private readonly NodeTypes $nodeTypesBag, private readonly WalkerContextInterface $walkerContext, - private readonly CacheItemPoolInterface $cacheItemPool + private readonly CacheItemPoolInterface $cacheItemPool, ) { } /** - * @param string $nodeType * @param class-string $walkerClass - * @param TranslationInterface $translation - * @param int $maxLevel + * * @return array */ public function getTreeWalkersForTypeAtRoot( string $nodeType, string $walkerClass, TranslationInterface $translation, - int $maxLevel = 3 + int $maxLevel = 3, ): array { $walkers = []; /** @var NodesSources[] $roots */ @@ -53,7 +51,7 @@ public function getTreeWalkersForTypeAtRoot( ]); foreach ($roots as $root) { - $walkerName = (new UnicodeString($root->getNode()->getNodeName() . ' walker')) + $walkerName = (new UnicodeString($root->getNode()->getNodeName().' walker')) ->trim() ->camel() ->toString(); @@ -71,19 +69,14 @@ public function getTreeWalkersForTypeAtRoot( } /** - * @param object $root * @param class-string $walkerClass - * @param WalkerContextInterface $walkerContext - * @param int $maxLevel - * @param CacheItemPoolInterface $cacheItemPool - * @return WalkerInterface */ public function buildForRoot( object $root, string $walkerClass, WalkerContextInterface $walkerContext, int $maxLevel, - CacheItemPoolInterface $cacheItemPool + CacheItemPoolInterface $cacheItemPool, ): WalkerInterface { /** @var callable $callable */ $callable = [$walkerClass, 'build']; @@ -104,6 +97,7 @@ public function buildForRoot( ) ); } + return $walker; } @@ -112,14 +106,11 @@ public function buildForRoot( * using `roadiz_core.tree_walker_definition_factory` tag. * * @param class-string $classname - * @param DefinitionFactoryInterface $definitionFactory - * @param bool $onlyVisible - * @return void */ public function addDefinitionFactoryConfiguration( string $classname, DefinitionFactoryInterface $definitionFactory, - bool $onlyVisible + bool $onlyVisible, ): void { $this->walkerDefinitionFactories[$classname] = new DefinitionFactoryConfiguration( $classname, diff --git a/lib/RoadizCoreBundle/src/Bag/NodeTypes.php b/lib/RoadizCoreBundle/src/Bag/NodeTypes.php index fbaf9dd5..410a5db3 100644 --- a/lib/RoadizCoreBundle/src/Bag/NodeTypes.php +++ b/lib/RoadizCoreBundle/src/Bag/NodeTypes.php @@ -24,6 +24,7 @@ public function getRepository(): NodeTypeRepository if (null === $this->repository) { $this->repository = $this->managerRegistry->getRepository(NodeType::class); } + return $this->repository; } diff --git a/lib/RoadizCoreBundle/src/Bag/Roles.php b/lib/RoadizCoreBundle/src/Bag/Roles.php index e98d7e14..b2b25044 100644 --- a/lib/RoadizCoreBundle/src/Bag/Roles.php +++ b/lib/RoadizCoreBundle/src/Bag/Roles.php @@ -23,6 +23,7 @@ public function getRepository(): RoleRepository if (null === $this->repository) { $this->repository = $this->managerRegistry->getRepository(Role::class); } + return $this->repository; } @@ -44,10 +45,7 @@ protected function populateParameters(): void /** * Get role by name or create it if non-existent. * - * @param string $key - * @param null $default - * - * @return Role + * @param null $default */ public function get(string $key, $default = null): Role { diff --git a/lib/RoadizCoreBundle/src/Bag/Settings.php b/lib/RoadizCoreBundle/src/Bag/Settings.php index 4760721b..3599c596 100644 --- a/lib/RoadizCoreBundle/src/Bag/Settings.php +++ b/lib/RoadizCoreBundle/src/Bag/Settings.php @@ -17,7 +17,7 @@ class Settings extends LazyParameterBag public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly Stopwatch $stopwatch + private readonly Stopwatch $stopwatch, ) { parent::__construct(); } @@ -27,6 +27,7 @@ public function getRepository(): SettingRepository if (null === $this->repository) { $this->repository = $this->managerRegistry->getRepository(Setting::class); } + return $this->repository; } @@ -47,11 +48,6 @@ protected function populateParameters(): void $this->stopwatch->stop('settings'); } - /** - * @param string $key - * @param mixed $default - * @return mixed - */ public function get(string $key, $default = false): mixed { return parent::get($key, $default); @@ -59,14 +55,12 @@ public function get(string $key, $default = false): mixed /** * Get a document from its setting name. - * - * @param string $key - * @return Document|null */ public function getDocument(string $key): ?Document { try { $id = $this->getInt($key); + return $this->managerRegistry ->getRepository(Document::class) ->findOneById($id); diff --git a/lib/RoadizCoreBundle/src/Cache/Clearer/ClearerInterface.php b/lib/RoadizCoreBundle/src/Cache/Clearer/ClearerInterface.php index 3b76c801..d4dd9615 100644 --- a/lib/RoadizCoreBundle/src/Cache/Clearer/ClearerInterface.php +++ b/lib/RoadizCoreBundle/src/Cache/Clearer/ClearerInterface.php @@ -6,18 +6,12 @@ interface ClearerInterface { - /** - * @return bool - */ public function clear(): bool; - /** - * @return string - */ + public function getOutput(): string; + /** * Get global cache directory. - * - * @return string */ public function getCacheDir(): string; } diff --git a/lib/RoadizCoreBundle/src/Cache/Clearer/FileClearer.php b/lib/RoadizCoreBundle/src/Cache/Clearer/FileClearer.php index 955e348f..c1a5e037 100644 --- a/lib/RoadizCoreBundle/src/Cache/Clearer/FileClearer.php +++ b/lib/RoadizCoreBundle/src/Cache/Clearer/FileClearer.php @@ -24,8 +24,6 @@ public function getOutput(): string /** * Get global cache directory. - * - * @return string */ public function getCacheDir(): string { diff --git a/lib/RoadizCoreBundle/src/Cache/Clearer/NodesSourcesUrlsCacheClearer.php b/lib/RoadizCoreBundle/src/Cache/Clearer/NodesSourcesUrlsCacheClearer.php index a7018fe0..8cd5d7a2 100644 --- a/lib/RoadizCoreBundle/src/Cache/Clearer/NodesSourcesUrlsCacheClearer.php +++ b/lib/RoadizCoreBundle/src/Cache/Clearer/NodesSourcesUrlsCacheClearer.php @@ -19,8 +19,10 @@ public function clear(): bool if ($this->cacheProvider->clear()) { $this->output .= 'cleared'; + return true; } + return false; } } diff --git a/lib/RoadizCoreBundle/src/Cache/Clearer/OPCacheClearer.php b/lib/RoadizCoreBundle/src/Cache/Clearer/OPCacheClearer.php index 9d165804..c9a8cadd 100644 --- a/lib/RoadizCoreBundle/src/Cache/Clearer/OPCacheClearer.php +++ b/lib/RoadizCoreBundle/src/Cache/Clearer/OPCacheClearer.php @@ -16,10 +16,11 @@ public function clear(): bool \apcu_clear_cache(); } if ( - \function_exists('opcache_reset') && - true === \opcache_reset() + \function_exists('opcache_reset') + && true === \opcache_reset() ) { $this->output = 'PHP OPCache has been reset.'; + return true; } else { $this->output = 'PHP OPCache is disabled.'; diff --git a/lib/RoadizCoreBundle/src/Cache/CloudflareProxyCache.php b/lib/RoadizCoreBundle/src/Cache/CloudflareProxyCache.php index 93485e54..33cec455 100644 --- a/lib/RoadizCoreBundle/src/Cache/CloudflareProxyCache.php +++ b/lib/RoadizCoreBundle/src/Cache/CloudflareProxyCache.php @@ -13,61 +13,40 @@ public function __construct( private readonly string $bearer, private readonly string $email, private readonly string $key, - private readonly int $timeout + private readonly int $timeout, ) { } - /** - * @return string - */ public function getName(): string { return $this->name; } - /** - * @return string - */ public function getZone(): string { return $this->zone; } - /** - * @return string - */ public function getVersion(): string { return $this->version; } - /** - * @return string - */ public function getBearer(): string { return $this->bearer; } - /** - * @return string - */ public function getEmail(): string { return $this->email; } - /** - * @return string - */ public function getKey(): string { return $this->key; } - /** - * @return int - */ public function getTimeout(): int { return $this->timeout; diff --git a/lib/RoadizCoreBundle/src/Cache/ReverseProxyCache.php b/lib/RoadizCoreBundle/src/Cache/ReverseProxyCache.php index 8aa36611..07c0b882 100644 --- a/lib/RoadizCoreBundle/src/Cache/ReverseProxyCache.php +++ b/lib/RoadizCoreBundle/src/Cache/ReverseProxyCache.php @@ -10,29 +10,20 @@ public function __construct( private readonly string $name, private readonly string $host, private readonly string $domainName, - private readonly int $timeout + private readonly int $timeout, ) { } - /** - * @return string - */ public function getName(): string { return $this->name; } - /** - * @return string - */ public function getHost(): string { return $this->host; } - /** - * @return string - */ public function getDomainName(): string { return $this->domainName; diff --git a/lib/RoadizCoreBundle/src/Cache/ReverseProxyCacheLocator.php b/lib/RoadizCoreBundle/src/Cache/ReverseProxyCacheLocator.php index b3f4b963..62f6fcb4 100644 --- a/lib/RoadizCoreBundle/src/Cache/ReverseProxyCacheLocator.php +++ b/lib/RoadizCoreBundle/src/Cache/ReverseProxyCacheLocator.php @@ -8,11 +8,10 @@ final class ReverseProxyCacheLocator { /** * @param ReverseProxyCache[] $frontends - * @param CloudflareProxyCache|null $cloudflareProxyCache */ public function __construct( private readonly array $frontends, - private readonly ?CloudflareProxyCache $cloudflareProxyCache = null + private readonly ?CloudflareProxyCache $cloudflareProxyCache = null, ) { } @@ -24,9 +23,6 @@ public function getFrontends(): array return $this->frontends; } - /** - * @return CloudflareProxyCache|null - */ public function getCloudflareProxyCache(): ?CloudflareProxyCache { return $this->cloudflareProxyCache; diff --git a/lib/RoadizCoreBundle/src/Configuration/CollectionFieldConfiguration.php b/lib/RoadizCoreBundle/src/Configuration/CollectionFieldConfiguration.php index faf08a15..1208b608 100644 --- a/lib/RoadizCoreBundle/src/Configuration/CollectionFieldConfiguration.php +++ b/lib/RoadizCoreBundle/src/Configuration/CollectionFieldConfiguration.php @@ -9,9 +9,6 @@ class CollectionFieldConfiguration implements ConfigurationInterface { - /** - * @return TreeBuilder - */ public function getConfigTreeBuilder(): TreeBuilder { $builder = new TreeBuilder('collection'); diff --git a/lib/RoadizCoreBundle/src/Configuration/JoinNodeTypeFieldConfiguration.php b/lib/RoadizCoreBundle/src/Configuration/JoinNodeTypeFieldConfiguration.php index 952c6447..9a68111e 100644 --- a/lib/RoadizCoreBundle/src/Configuration/JoinNodeTypeFieldConfiguration.php +++ b/lib/RoadizCoreBundle/src/Configuration/JoinNodeTypeFieldConfiguration.php @@ -9,9 +9,6 @@ class JoinNodeTypeFieldConfiguration implements ConfigurationInterface { - /** - * @return TreeBuilder - */ public function getConfigTreeBuilder(): TreeBuilder { $builder = new TreeBuilder('join'); diff --git a/lib/RoadizCoreBundle/src/Configuration/ProviderFieldConfiguration.php b/lib/RoadizCoreBundle/src/Configuration/ProviderFieldConfiguration.php index c9a5d00f..8da8645d 100644 --- a/lib/RoadizCoreBundle/src/Configuration/ProviderFieldConfiguration.php +++ b/lib/RoadizCoreBundle/src/Configuration/ProviderFieldConfiguration.php @@ -9,9 +9,6 @@ class ProviderFieldConfiguration implements ConfigurationInterface { - /** - * @return TreeBuilder - */ public function getConfigTreeBuilder(): TreeBuilder { $builder = new TreeBuilder('provider'); diff --git a/lib/RoadizCoreBundle/src/Console/AppInstallCommand.php b/lib/RoadizCoreBundle/src/Console/AppInstallCommand.php index 06599c29..d47ebdd2 100644 --- a/lib/RoadizCoreBundle/src/Console/AppInstallCommand.php +++ b/lib/RoadizCoreBundle/src/Console/AppInstallCommand.php @@ -37,7 +37,7 @@ public function __construct( private readonly RolesImporter $rolesImporter, private readonly GroupsImporter $groupsImporter, private readonly AttributeImporter $attributeImporter, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -64,17 +64,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int /* * Test if Classname is not a valid yaml file before using Theme */ - $configPath = $this->projectDir . '/src/Resources/config.yml'; + $configPath = $this->projectDir.'/src/Resources/config.yml'; $realConfigPath = realpath($configPath); if (false !== $realConfigPath && file_exists($realConfigPath)) { - $this->io->note('Install assets directly from file: ' . $realConfigPath); + $this->io->note('Install assets directly from file: '.$realConfigPath); $themeConfigPath = $realConfigPath; } else { - $this->io->error($configPath . ' configuration file is not readable.'); + $this->io->error($configPath.' configuration file is not readable.'); + return 1; } $this->importAppData($themeConfigPath); + return 0; } @@ -82,96 +84,92 @@ protected function importAppData(string $themeConfigPath): void { $data = $this->getAppConfig($themeConfigPath); - if (!isset($data["importFiles"]) || !is_array($data["importFiles"])) { - $this->io->warning('Config file "' . $themeConfigPath . '" has no data to import.'); + if (!isset($data['importFiles']) || !is_array($data['importFiles'])) { + $this->io->warning('Config file "'.$themeConfigPath.'" has no data to import.'); + return; } - if (isset($data["importFiles"]['groups'])) { - foreach ($data["importFiles"]['groups'] as $filename) { + if (isset($data['importFiles']['groups'])) { + foreach ($data['importFiles']['groups'] as $filename) { $this->importFile($filename, $this->groupsImporter); } } - if (isset($data["importFiles"]['roles'])) { - foreach ($data["importFiles"]['roles'] as $filename) { + if (isset($data['importFiles']['roles'])) { + foreach ($data['importFiles']['roles'] as $filename) { $this->importFile($filename, $this->rolesImporter); } } - if (isset($data["importFiles"]['settings'])) { - foreach ($data["importFiles"]['settings'] as $filename) { + if (isset($data['importFiles']['settings'])) { + foreach ($data['importFiles']['settings'] as $filename) { $this->importFile($filename, $this->settingsImporter); } } - if (isset($data["importFiles"]['nodetypes'])) { - foreach ($data["importFiles"]['nodetypes'] as $filename) { + if (isset($data['importFiles']['nodetypes'])) { + foreach ($data['importFiles']['nodetypes'] as $filename) { $this->importFile($filename, $this->nodeTypesImporter); } } - if (isset($data["importFiles"]['tags'])) { - foreach ($data["importFiles"]['tags'] as $filename) { + if (isset($data['importFiles']['tags'])) { + foreach ($data['importFiles']['tags'] as $filename) { $this->importFile($filename, $this->tagsImporter); } } - if (isset($data["importFiles"]['attributes'])) { - foreach ($data["importFiles"]['attributes'] as $filename) { + if (isset($data['importFiles']['attributes'])) { + foreach ($data['importFiles']['attributes'] as $filename) { $this->importFile($filename, $this->attributeImporter); } } } - /** - * @param string $filename - * @param EntityImporterInterface $importer - */ protected function importFile(string $filename, EntityImporterInterface $importer): void { if (false !== $realFilename = realpath($filename)) { $file = new File($realFilename); } else { - throw new \RuntimeException($filename . ' is not a valid file'); + throw new \RuntimeException($filename.' is not a valid file'); } if ($this->dryRun) { $this->io->writeln( - '* ' . $file->getPathname() . ' file would be imported.' + '* '.$file->getPathname().' file would be imported.' ); + return; } try { if (false === $fileContent = file_get_contents($file->getPathname())) { - throw new \RuntimeException($file->getPathname() . ' file is not readable'); + throw new \RuntimeException($file->getPathname().' file is not readable'); } $importer->import($fileContent); $this->managerRegistry->getManager()->flush(); $this->io->writeln( - '* ' . $file->getPathname() . ' file has been imported.' + '* '.$file->getPathname().' file has been imported.' ); + return; } catch (EntityAlreadyExistsException $e) { $this->io->writeln( - '* ' . $file->getPathname() . '' . - ' has NOT been imported (' . $e->getMessage() . ').' + '* '.$file->getPathname().''. + ' has NOT been imported ('.$e->getMessage().').' ); } $this->io->writeln( - '* ' . $file->getPathname() . ' file has been imported.' + '* '.$file->getPathname().' file has been imported.' ); } - /** - * @param string $appConfigPath - * @return array - */ protected function getAppConfig(string $appConfigPath): array { if (false === $fileContent = file_get_contents($appConfigPath)) { - throw new \RuntimeException($appConfigPath . ' file is not readable'); + throw new \RuntimeException($appConfigPath.' file is not readable'); } $data = Yaml::parse($fileContent); if (!\is_array($data)) { - throw new \RuntimeException($appConfigPath . ' file is not a valid YAML file'); + throw new \RuntimeException($appConfigPath.' file is not a valid YAML file'); } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Console/AppMigrateCommand.php b/lib/RoadizCoreBundle/src/Console/AppMigrateCommand.php index 08bcb012..08b25b29 100644 --- a/lib/RoadizCoreBundle/src/Console/AppMigrateCommand.php +++ b/lib/RoadizCoreBundle/src/Console/AppMigrateCommand.php @@ -21,7 +21,7 @@ public function __construct( private readonly SchemaUpdater $schemaUpdater, #[Autowire('%kernel.project_dir%')] private readonly string $projectDir, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -51,8 +51,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'Are you sure to migrate against app config.yml file? This will generate new Doctrine Migrations and execute them. If you just want to import node-types run `bin/console app:install` instead', !$input->isInteractive() ); - if ($io->askQuestion($question) === false) { + if (false === $io->askQuestion($question)) { $io->note('Nothing was done…'); + return 0; } @@ -65,21 +66,21 @@ protected function execute(InputInterface $input, OutputInterface $output): int $output->isQuiet(), ); } else { - $this->runCommand( + 0 === $this->runCommand( 'app:install', '', null, $input->isInteractive(), $output->isQuiet() - ) === 0 ? $io->success('app:install') : $io->error('app:install'); + ) ? $io->success('app:install') : $io->error('app:install'); - $this->runCommand( + 0 === $this->runCommand( 'generate:nsentities', '', null, $input->isInteractive(), $output->isQuiet() - ) === 0 ? $io->success('generate:nsentities') : $io->error('generate:nsentities'); + ) ? $io->success('generate:nsentities') : $io->error('generate:nsentities'); $this->schemaUpdater->updateNodeTypesSchema(); $this->schemaUpdater->updateSchema(); @@ -87,6 +88,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->clearCaches($io); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/CustomFormAnswerPurgeCommand.php b/lib/RoadizCoreBundle/src/Console/CustomFormAnswerPurgeCommand.php index 2045e9af..a84d5cc3 100644 --- a/lib/RoadizCoreBundle/src/Console/CustomFormAnswerPurgeCommand.php +++ b/lib/RoadizCoreBundle/src/Console/CustomFormAnswerPurgeCommand.php @@ -23,7 +23,7 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly EventDispatcherInterface $eventDispatcher, private readonly LoggerInterface $logger, - string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -90,8 +90,8 @@ protected function purgeCustomFormAnswers(CustomForm $customForm, InputInterface )); if ( - !$input->getOption('dry-run') && - (!$input->isInteractive() || $io->confirm(\sprintf( + !$input->getOption('dry-run') + && (!$input->isInteractive() || $io->confirm(\sprintf( 'Are you sure you want to delete %d custom-form answer(s) and %d document(s) from “%s” before %s', $count, $documentsCount, diff --git a/lib/RoadizCoreBundle/src/Console/FilesCommandTrait.php b/lib/RoadizCoreBundle/src/Console/FilesCommandTrait.php index 15d73514..b745da54 100644 --- a/lib/RoadizCoreBundle/src/Console/FilesCommandTrait.php +++ b/lib/RoadizCoreBundle/src/Console/FilesCommandTrait.php @@ -6,25 +6,16 @@ trait FilesCommandTrait { - /** - * @return string - */ protected function getPublicFolderName(): string { return '/exported_public'; } - /** - * @return string - */ protected function getPrivateFolderName(): string { return '/exported_private'; } - /** - * @return string - */ protected function getFontsFolderName(): string { return '/exported_fonts'; diff --git a/lib/RoadizCoreBundle/src/Console/FilesExportCommand.php b/lib/RoadizCoreBundle/src/Console/FilesExportCommand.php index db8d1d3e..49c4267e 100644 --- a/lib/RoadizCoreBundle/src/Console/FilesExportCommand.php +++ b/lib/RoadizCoreBundle/src/Console/FilesExportCommand.php @@ -12,7 +12,6 @@ use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; use Symfony\Component\String\Slugger\AsciiSlugger; -use ZipArchive; final class FilesExportCommand extends Command { @@ -22,7 +21,7 @@ public function __construct( private readonly FileAwareInterface $fileAware, private readonly string $exportDir, private readonly string $appNamespace, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -34,20 +33,11 @@ protected function configure(): void ->setDescription('Export public files, private files and fonts into a single ZIP archive at root dir.'); } - /** - * @param string $appName - * @return string - */ - protected function getArchiveFileName(string $appName = "files_export"): string + protected function getArchiveFileName(string $appName = 'files_export'): string { - return $appName . '_' . date('Y-m-d') . '.zip'; + return $appName.'_'.date('Y-m-d').'.zip'; } - /** - * @param InputInterface $input - * @param OutputInterface $output - * @return int - */ protected function execute(InputInterface $input, OutputInterface $output): int { $fs = new Filesystem(); @@ -57,14 +47,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int $fontFileFolder = $this->fileAware->getFontsFilesPath(); $archiveName = $this->getArchiveFileName((new AsciiSlugger())->slug($this->appNamespace, '_')->toString()); - $archivePath = $this->exportDir . DIRECTORY_SEPARATOR . $archiveName; + $archivePath = $this->exportDir.DIRECTORY_SEPARATOR.$archiveName; if (!$fs->exists($this->exportDir)) { - throw new \RuntimeException($archivePath . ': directory does not exist or is not writable'); + throw new \RuntimeException($archivePath.': directory does not exist or is not writable'); } - $zip = new ZipArchive(); - $zip->open($archivePath, ZipArchive::CREATE | ZipArchive::OVERWRITE); + $zip = new \ZipArchive(); + $zip->open($archivePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE); if ($fs->exists($publicFileFolder)) { $this->zipFolder($zip, $publicFileFolder, $this->getPublicFolderName()); @@ -78,16 +68,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int // Zip archive will be created only after closing object $zip->close(); + return 0; } - - /** - * @param ZipArchive $zip - * @param string $folder - * @param string $prefix - */ - protected function zipFolder(ZipArchive $zip, string $folder, string $prefix = "/public"): void + protected function zipFolder(\ZipArchive $zip, string $folder, string $prefix = '/public'): void { $finder = new Finder(); $files = $finder->files() @@ -108,7 +93,7 @@ protected function zipFolder(ZipArchive $zip, string $folder, string $prefix = " $relativePath = \mb_substr($filePath, \mb_strlen($folder) + 1); // Add current file to archive - $zip->addFile($filePath, $prefix . '/' . $relativePath); + $zip->addFile($filePath, $prefix.'/'.$relativePath); } } } diff --git a/lib/RoadizCoreBundle/src/Console/FilesImportCommand.php b/lib/RoadizCoreBundle/src/Console/FilesImportCommand.php index 4e92136c..67783b6e 100644 --- a/lib/RoadizCoreBundle/src/Console/FilesImportCommand.php +++ b/lib/RoadizCoreBundle/src/Console/FilesImportCommand.php @@ -13,7 +13,6 @@ use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\String\Slugger\AsciiSlugger; -use ZipArchive; final class FilesImportCommand extends Command { @@ -22,7 +21,7 @@ final class FilesImportCommand extends Command public function __construct( private readonly FileAwareInterface $fileAware, private readonly string $appNamespace, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -37,11 +36,6 @@ protected function configure(): void ]); } - /** - * @param InputInterface $input - * @param OutputInterface $output - * @return int - */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); @@ -52,7 +46,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int ); $appNamespace = (new AsciiSlugger())->slug($this->appNamespace, '_'); - $tempDir = tempnam(sys_get_temp_dir(), $appNamespace . '_files'); + $tempDir = tempnam(sys_get_temp_dir(), $appNamespace.'_files'); if (false === $tempDir) { throw new \RuntimeException('Cannot create temporary directory.'); } @@ -62,9 +56,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int mkdir($tempDir); $zipArchivePath = $input->getArgument('input'); - $zip = new ZipArchive(); + $zip = new \ZipArchive(); if (true !== $zip->open($zipArchivePath)) { $io->error('Zip archive does not exist or is invalid.'); + return 1; } @@ -75,20 +70,21 @@ protected function execute(InputInterface $input, OutputInterface $output): int $zip->extractTo($tempDir); $fs = new Filesystem(); - if ($fs->exists($tempDir . $this->getPublicFolderName())) { - $fs->mirror($tempDir . $this->getPublicFolderName(), $this->fileAware->getPublicFilesPath()); + if ($fs->exists($tempDir.$this->getPublicFolderName())) { + $fs->mirror($tempDir.$this->getPublicFolderName(), $this->fileAware->getPublicFilesPath()); $io->success('Public files have been imported.'); } - if ($fs->exists($tempDir . $this->getPrivateFolderName())) { - $fs->mirror($tempDir . $this->getPrivateFolderName(), $this->fileAware->getPrivateFilesPath()); + if ($fs->exists($tempDir.$this->getPrivateFolderName())) { + $fs->mirror($tempDir.$this->getPrivateFolderName(), $this->fileAware->getPrivateFilesPath()); $io->success('Private files have been imported.'); } - if ($fs->exists($tempDir . $this->getFontsFolderName())) { - $fs->mirror($tempDir . $this->getFontsFolderName(), $this->fileAware->getFontsFilesPath()); + if ($fs->exists($tempDir.$this->getFontsFolderName())) { + $fs->mirror($tempDir.$this->getFontsFolderName(), $this->fileAware->getFontsFilesPath()); $io->success('Font files have been imported.'); } $fs->remove($tempDir); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/GenerateApiResourceCommand.php b/lib/RoadizCoreBundle/src/Console/GenerateApiResourceCommand.php index f9e78104..d1b68475 100644 --- a/lib/RoadizCoreBundle/src/Console/GenerateApiResourceCommand.php +++ b/lib/RoadizCoreBundle/src/Console/GenerateApiResourceCommand.php @@ -17,7 +17,7 @@ final class GenerateApiResourceCommand extends Command public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly ApiResourceGenerator $apiResourceGenerator, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -38,17 +38,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(NodeType::class) ->findAll(); - if (count($nodeTypes) === 0) { + if (0 === count($nodeTypes)) { $io->error('No available node-types…'); + return 1; } foreach ($nodeTypes as $nt) { $resourcePath = $this->apiResourceGenerator->generate($nt); if (null !== $resourcePath) { - $io->writeln("* API resource " . $resourcePath . " has been generated."); + $io->writeln('* API resource '.$resourcePath.' has been generated.'); } } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/GenerateNodeSourceEntitiesCommand.php b/lib/RoadizCoreBundle/src/Console/GenerateNodeSourceEntitiesCommand.php index 98e0dcf8..22192299 100644 --- a/lib/RoadizCoreBundle/src/Console/GenerateNodeSourceEntitiesCommand.php +++ b/lib/RoadizCoreBundle/src/Console/GenerateNodeSourceEntitiesCommand.php @@ -20,7 +20,7 @@ final class GenerateNodeSourceEntitiesCommand extends Command public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly HandlerFactory $handlerFactory, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -43,8 +43,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(NodeType::class) ->findAll(); - if (count($nodeTypes) === 0) { + if (0 === count($nodeTypes)) { $io->error('No available node-types…'); + return 1; } @@ -54,12 +55,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $handler = $this->handlerFactory->getHandler($nt); $handler->removeSourceEntityClass(); $handler->generateSourceEntityClass(); - $io->writeln("* Source class " . $nt->getSourceEntityClassName() . " has been generated."); + $io->writeln('* Source class '.$nt->getSourceEntityClassName().' has been generated.'); if ($output->isVeryVerbose()) { - $io->writeln("\t" . $handler->getSourceClassPath() . ""); + $io->writeln("\t".$handler->getSourceClassPath().''); } } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/GetCronLastExecDateCommand.php b/lib/RoadizCoreBundle/src/Console/GetCronLastExecDateCommand.php index e090c16d..9cc65f30 100644 --- a/lib/RoadizCoreBundle/src/Console/GetCronLastExecDateCommand.php +++ b/lib/RoadizCoreBundle/src/Console/GetCronLastExecDateCommand.php @@ -1,5 +1,7 @@ settingRepository->findOneByName('cron_last_exec_date'); if (!($setting instanceof Setting)) { $io->warning('Last execution date of cron job has not been persisted yet.'); + return Command::FAILURE; } diff --git a/lib/RoadizCoreBundle/src/Console/InstallCommand.php b/lib/RoadizCoreBundle/src/Console/InstallCommand.php index d4dd1f9f..a79e84ce 100644 --- a/lib/RoadizCoreBundle/src/Console/InstallCommand.php +++ b/lib/RoadizCoreBundle/src/Console/InstallCommand.php @@ -28,7 +28,7 @@ public function __construct( private readonly SettingsImporter $settingsImporter, #[Autowire('%kernel.project_dir%')] private readonly string $projectDir, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -55,61 +55,65 @@ protected function execute(InputInterface $input, OutputInterface $output): int ); if ( - $input->getOption('no-interaction') || - $io->askQuestion($question) + $input->getOption('no-interaction') + || $io->askQuestion($question) ) { - $this->runCommand( + 0 === $this->runCommand( 'doctrine:migrations:migrate', '', null, false, true - ) === 0 ? $io->success('doctrine:migrations:migrate') : $io->error('doctrine:migrations:migrate'); + ) ? $io->success('doctrine:migrations:migrate') : $io->error('doctrine:migrations:migrate'); - $fixturesRoot = dirname(__DIR__) . '/../config'; - $fixtureFile = file_get_contents($fixturesRoot . "/fixtures.yaml"); + $fixturesRoot = dirname(__DIR__).'/../config'; + $fixtureFile = file_get_contents($fixturesRoot.'/fixtures.yaml'); if (false === $fixtureFile) { - $io->error('No fixtures.yaml file found in ' . $fixturesRoot); + $io->error('No fixtures.yaml file found in '.$fixturesRoot); + return 1; } $data = Yaml::parse($fixtureFile); - if (isset($data["importFiles"]['roles'])) { - foreach ($data["importFiles"]['roles'] as $filename) { - $filePath = $fixturesRoot . "/" . $filename; + if (isset($data['importFiles']['roles'])) { + foreach ($data['importFiles']['roles'] as $filename) { + $filePath = $fixturesRoot.'/'.$filename; $fileContents = file_get_contents($filePath); if (false === $fileContents) { - $io->error('No file found in ' . $filePath); + $io->error('No file found in '.$filePath); + return 1; } $this->rolesImporter->import($fileContents); - $io->success('Theme file “' . $filePath . '” has been imported.'); + $io->success('Theme file “'.$filePath.'” has been imported.'); } } - if (isset($data["importFiles"]['groups'])) { - foreach ($data["importFiles"]['groups'] as $filename) { - $filePath = $fixturesRoot . "/" . $filename; + if (isset($data['importFiles']['groups'])) { + foreach ($data['importFiles']['groups'] as $filename) { + $filePath = $fixturesRoot.'/'.$filename; $fileContents = file_get_contents($filePath); if (false === $fileContents) { - $io->error('No file found in ' . $filePath); + $io->error('No file found in '.$filePath); + return 1; } $this->groupsImporter->import($fileContents); - $io->success('Theme file “' . $filePath . '” has been imported.'); + $io->success('Theme file “'.$filePath.'” has been imported.'); } } - if (isset($data["importFiles"]['settings'])) { - foreach ($data["importFiles"]['settings'] as $filename) { - $filePath = $fixturesRoot . "/" . $filename; + if (isset($data['importFiles']['settings'])) { + foreach ($data['importFiles']['settings'] as $filename) { + $filePath = $fixturesRoot.'/'.$filename; $fileContents = file_get_contents($filePath); if (false === $fileContents) { - $io->error('No file found in ' . $filePath); + $io->error('No file found in '.$filePath); + return 1; } $this->settingsImporter->import($fileContents); - $io->success('Theme files “' . $filePath . '” has been imported.'); + $io->success('Theme files “'.$filePath.'” has been imported.'); } } $manager = $this->managerRegistry->getManagerForClass(Translation::class); @@ -120,8 +124,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int $defaultTrans = new Translation(); $defaultTrans ->setDefaultTranslation(true) - ->setLocale("en") - ->setName("Default translation"); + ->setLocale('en') + ->setName('Default translation'); $manager->persist($defaultTrans); @@ -133,13 +137,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->clearCaches($io); } + return 0; } /** * Tell if there is any translation. - * - * @return bool */ public function hasDefaultTranslation(): bool { diff --git a/lib/RoadizCoreBundle/src/Console/LogsCleanupCommand.php b/lib/RoadizCoreBundle/src/Console/LogsCleanupCommand.php index 56fd662a..66517c82 100644 --- a/lib/RoadizCoreBundle/src/Console/LogsCleanupCommand.php +++ b/lib/RoadizCoreBundle/src/Console/LogsCleanupCommand.php @@ -19,7 +19,7 @@ final class LogsCleanupCommand extends Command { public function __construct( private readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -34,15 +34,12 @@ protected function configure(): void ; } - /** - * @inheritDoc - */ protected function execute(InputInterface $input, OutputInterface $output): int { $now = new \DateTime('now'); $since = '-3 months'; if (\is_string($input->getOption('since'))) { - $since = '-' . $input->getOption('since'); + $since = '-'.$input->getOption('since'); } $interval = \DateInterval::createFromDateString($since); if (false === $interval) { @@ -65,7 +62,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $logs = 0; } - $io->note($logs . ' log entries found before ' . $now->format('Y-m-d H:i:s') . '.'); + $io->note($logs.' log entries found before '.$now->format('Y-m-d H:i:s').'.'); if ($input->getOption('erase') && $logs > 0) { $qb2 = $logRepository->createQueryBuilder('l'); @@ -75,11 +72,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ; try { $numDeleted = $qb2->getQuery()->execute(); - $io->success($numDeleted . ' log entries were deleted.'); + $io->success($numDeleted.' log entries were deleted.'); } catch (NoResultException $e) { $io->writeln('No log entries were deleted.'); } } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/MailerTestCommand.php b/lib/RoadizCoreBundle/src/Console/MailerTestCommand.php index 5a5d4eec..0269ee96 100644 --- a/lib/RoadizCoreBundle/src/Console/MailerTestCommand.php +++ b/lib/RoadizCoreBundle/src/Console/MailerTestCommand.php @@ -17,7 +17,7 @@ final class MailerTestCommand extends Command { public function __construct( private readonly EmailManagerFactory $emailManagerFactory, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -46,11 +46,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->setEmailTemplate('@RoadizCore/email/base_email.html.twig') ->setAssignation([ 'title' => $title, - 'content' => 'This is a test email send to *' . $to->getAddress() . '* from `mailer:send:test` CLI command.', - 'mailContact' => $from->getAddress() + 'content' => 'This is a test email send to *'.$to->getAddress().'* from `mailer:send:test` CLI command.', + 'mailContact' => $from->getAddress(), ]) ->send(); (new SymfonyStyle($input, $output))->success('Email sent.'); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodeApplyUniversalFieldsCommand.php b/lib/RoadizCoreBundle/src/Console/NodeApplyUniversalFieldsCommand.php index 942e2541..645fb4d3 100644 --- a/lib/RoadizCoreBundle/src/Console/NodeApplyUniversalFieldsCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodeApplyUniversalFieldsCommand.php @@ -20,7 +20,7 @@ final class NodeApplyUniversalFieldsCommand extends Command public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly UniversalDataDuplicator $universalDataDuplicator, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -39,7 +39,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $manager = $this->managerRegistry->getManagerForClass(NodesSources::class); if (null === $manager) { - throw new \RuntimeException('No manager found for ' . NodesSources::class); + throw new \RuntimeException('No manager found for '.NodesSources::class); } $qb = $manager->createQueryBuilder(); @@ -54,7 +54,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->setParameter(':translation', $translation); try { $sources = $qb->getQuery()->getResult(); - $io->note(count($sources) . ' node(s) with universal fields were found.'); + $io->note(count($sources).' node(s) with universal fields were found.'); $question = new ConfirmationQuestion( 'Are you sure to force every universal fields?', @@ -78,6 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } catch (NoResultException $e) { $io->warning('No node with universal fields were found.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodeClearTagCommand.php b/lib/RoadizCoreBundle/src/Console/NodeClearTagCommand.php index e7e775f7..9a0db025 100644 --- a/lib/RoadizCoreBundle/src/Console/NodeClearTagCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodeClearTagCommand.php @@ -19,7 +19,7 @@ final class NodeClearTagCommand extends Command { public function __construct( private readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -35,6 +35,7 @@ protected function configure(): void protected function getNodeQueryBuilder(Tag $tag): QueryBuilder { $qb = $this->managerRegistry->getRepository(Node::class)->createQueryBuilder('n'); + return $qb->innerJoin('n.nodesTags', 'ntg') ->andWhere($qb->expr()->eq('ntg.tag', ':tagId')) ->setParameter(':tagId', $tag); @@ -51,7 +52,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } /** @var Tag|null $tag */ $tag = $em->find(Tag::class, $tagId); - if ($tag === null) { + if (null === $tag) { throw new \InvalidArgumentException(sprintf('Tag #%d does not exist.', $tagId)); } @@ -65,6 +66,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($count <= 0) { $io->warning('No nodes were found linked with this tag.'); + return 0; } diff --git a/lib/RoadizCoreBundle/src/Console/NodeTypesAddFieldCommand.php b/lib/RoadizCoreBundle/src/Console/NodeTypesAddFieldCommand.php index 554f5e0d..f5643271 100644 --- a/lib/RoadizCoreBundle/src/Console/NodeTypesAddFieldCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodeTypesAddFieldCommand.php @@ -38,8 +38,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(NodeType::class) ->findOneBy(['name' => $name]); - if ($nodeType === null) { - $io->error('Node-type "' . $name . '" does not exist.'); + if (null === $nodeType) { + $io->error('Node-type "'.$name.'" does not exist.'); + return 1; } @@ -54,7 +55,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int $handler->regenerateEntityClass(); $this->schemaUpdater->updateNodeTypesSchema(); - $io->success('Node type ' . $nodeType->getName() . ' has been updated.'); + $io->success('Node type '.$nodeType->getName().' has been updated.'); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodeTypesCommand.php b/lib/RoadizCoreBundle/src/Console/NodeTypesCommand.php index 6be399c2..b5275ab5 100644 --- a/lib/RoadizCoreBundle/src/Console/NodeTypesCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodeTypesCommand.php @@ -17,7 +17,7 @@ final class NodeTypesCommand extends Command { public function __construct( private readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -43,8 +43,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(NodeType::class) ->findOneByName($name); - if ($nodetype === null) { - $io->note($name . ' node type does not exist.'); + if (null === $nodetype) { + $io->note($name.' node type does not exist.'); + return 0; } /** @var array $fields */ @@ -60,8 +61,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int $field->getLabel(), $field->getName(), str_replace('.type', '', $field->getTypeName()), - ($field->isVisible() ? 'X' : ''), - ($field->isIndexed() ? 'X' : ''), + $field->isVisible() ? 'X' : '', + $field->isIndexed() ? 'X' : '', ]; } $io->table(['Id', 'Label', 'Name', 'Type', 'Visible', 'Index'], $tableContent); @@ -71,7 +72,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(NodeType::class) ->findBy([], ['name' => 'ASC']); - if (count($nodetypes) === 0) { + if (0 === count($nodetypes)) { $io->note('No available node-types…'); } @@ -81,12 +82,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $tableContent[] = [ $nt->getId(), $nt->getName(), - ($nt->isVisible() ? 'X' : ''), + $nt->isVisible() ? 'X' : '', ]; } $io->table(['Id', 'Title', 'Visible'], $tableContent); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodeTypesCreationCommand.php b/lib/RoadizCoreBundle/src/Console/NodeTypesCreationCommand.php index 25788fec..af1577ef 100644 --- a/lib/RoadizCoreBundle/src/Console/NodeTypesCreationCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodeTypesCreationCommand.php @@ -27,7 +27,7 @@ public function __construct( protected readonly ManagerRegistry $managerRegistry, protected readonly HandlerFactory $handlerFactory, protected readonly SchemaUpdater $schemaUpdater, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -57,12 +57,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(NodeType::class) ->findOneBy(['name' => $name]); - if ($nodeType !== null) { - $io->error('Node-type "' . $name . '" already exists.'); + if (null !== $nodeType) { + $io->error('Node-type "'.$name.'" already exists.'); + return 1; } else { $this->executeCreation($input, $output); } + return 0; } @@ -73,7 +75,7 @@ private function executeCreation(InputInterface $input, OutputInterface $output) $nt = new NodeType(); $nt->setName($name); - $io->note('OK! Let’s create that "' . $nt->getName() . '" node-type together!'); + $io->note('OK! Let’s create that "'.$nt->getName().'" node-type together!'); $question0 = new Question('Enter your node-type display name', ucwords($name)); $displayName = $io->askQuestion($question0); @@ -94,7 +96,7 @@ private function executeCreation(InputInterface $input, OutputInterface $output) $handler->regenerateEntityClass(); $this->schemaUpdater->updateNodeTypesSchema(); - $io->success('Node type ' . $nt->getName() . ' has been created.'); + $io->success('Node type '.$nt->getName().' has been created.'); } protected function addNodeTypeField(NodeType $nodeType, int|float|string $position, SymfonyStyle $io): void @@ -103,15 +105,15 @@ protected function addNodeTypeField(NodeType $nodeType, int|float|string $positi $position = floatval($position); $field->setPosition($position); - $questionfName = new Question('[Field ' . $position . '] Enter field name', 'content'); + $questionfName = new Question('[Field '.$position.'] Enter field name', 'content'); $fName = $io->askQuestion($questionfName); $field->setName($fName); - $questionfLabel = new Question('[Field ' . $position . '] Enter field label', 'Your content'); + $questionfLabel = new Question('[Field '.$position.'] Enter field label', 'Your content'); $fLabel = $io->askQuestion($questionfLabel); $field->setLabel($fLabel); - $questionfType = new Question('[Field ' . $position . '] Enter field type', 'STRING_T'); + $questionfType = new Question('[Field '.$position.'] Enter field type', 'STRING_T'); $questionfType->setAutocompleterValues([ 'STRING_T', 'DATETIME_T', @@ -136,10 +138,10 @@ protected function addNodeTypeField(NodeType $nodeType, int|float|string $positi ]); $fType = $io->askQuestion($questionfType); - $fType = constant(NodeTypeField::class . '::' . $fType); + $fType = constant(NodeTypeField::class.'::'.$fType); $field->setType($fType); - $questionIndexed = new ConfirmationQuestion('[Field ' . $position . '] Must this field be indexed?', false); + $questionIndexed = new ConfirmationQuestion('[Field '.$position.'] Must this field be indexed?', false); if ($io->askQuestion($questionIndexed)) { $field->setIndexed(true); } diff --git a/lib/RoadizCoreBundle/src/Console/NodeTypesDefaultValuesCommand.php b/lib/RoadizCoreBundle/src/Console/NodeTypesDefaultValuesCommand.php index 2c4c3ec7..5fdc67d1 100644 --- a/lib/RoadizCoreBundle/src/Console/NodeTypesDefaultValuesCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodeTypesDefaultValuesCommand.php @@ -19,7 +19,7 @@ final class NodeTypesDefaultValuesCommand extends Command public function __construct( private readonly DefaultValuesResolverInterface $defaultValuesResolver, private readonly ManagerRegistry $managerRegistry, - string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -57,7 +57,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int throw new \InvalidArgumentException('Field name must be a valid field name.'); } if (!$oneField->isEnum()) { - throw new \InvalidArgumentException('Field name must be an enum field. Valid fields names are: ' . implode(', ', $enumFieldsNames)); + throw new \InvalidArgumentException('Field name must be an enum field. Valid fields names are: '.implode(', ', $enumFieldsNames)); } $defaultValues = $this->defaultValuesResolver->getDefaultValuesAmongAllFields($oneField); @@ -70,9 +70,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int $oneField->getLabel(), $oneField->getDescription(), implode(', ', array_unique($defaultValues)), - $maxDefaultValuesLength + $maxDefaultValuesLength, ], ]); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodeTypesDeleteCommand.php b/lib/RoadizCoreBundle/src/Console/NodeTypesDeleteCommand.php index 795c829e..f312ecc0 100644 --- a/lib/RoadizCoreBundle/src/Console/NodeTypesDeleteCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodeTypesDeleteCommand.php @@ -25,7 +25,7 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly HandlerFactory $handlerFactory, private readonly SchemaUpdater $schemaUpdater, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -55,18 +55,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(NodeType::class) ->findOneByName($name); - if ($nodeType === null) { - $io->error('"' . $name . '" node type does not exist'); + if (null === $nodeType) { + $io->error('"'.$name.'" node type does not exist'); + return 1; } - $io->note('///////////////////////////////' . PHP_EOL . - '/////////// WARNING ///////////' . PHP_EOL . - '///////////////////////////////' . PHP_EOL . - 'This operation cannot be undone.' . PHP_EOL . + $io->note('///////////////////////////////'.PHP_EOL. + '/////////// WARNING ///////////'.PHP_EOL. + '///////////////////////////////'.PHP_EOL. + 'This operation cannot be undone.'.PHP_EOL. 'Deleting a node-type, you will automatically delete every nodes of this type.'); $question = new ConfirmationQuestion( - 'Are you sure to delete ' . $nodeType->getName() . ' node-type?', + 'Are you sure to delete '.$nodeType->getName().' node-type?', false ); if ( @@ -82,6 +83,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->schemaUpdater->updateNodeTypesSchema(); $io->success('Node-type deleted.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodesCleanNamesCommand.php b/lib/RoadizCoreBundle/src/Console/NodesCleanNamesCommand.php index 4a420a16..4f60243d 100644 --- a/lib/RoadizCoreBundle/src/Console/NodesCleanNamesCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodesCleanNamesCommand.php @@ -20,7 +20,7 @@ final class NodesCleanNamesCommand extends Command public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly NodeNamePolicyInterface $nodeNamePolicy, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -65,25 +65,26 @@ protected function execute(InputInterface $input, OutputInterface $output): int ]); $io->note( - 'This command will rename EVERY nodes (except for locked and not dynamic ones) names according to their node-source for current default translation.' . PHP_EOL . - count($nodes) . ' nodes might be affected.' + 'This command will rename EVERY nodes (except for locked and not dynamic ones) names according to their node-source for current default translation.'.PHP_EOL. + count($nodes).' nodes might be affected.' ); $question1 = new ConfirmationQuestion('Are you sure to proceed? This could break many page URLs!', false); if (!$io->askQuestion($question1)) { $io->warning('Renaming cancelled…'); + return 1; } - $io->note('Renaming ' . count($nodes) . ' nodes…'); + $io->note('Renaming '.count($nodes).' nodes…'); $renameCount = 0; $names = []; /** @var Node $node */ foreach ($nodes as $node) { $nodeSource = $node->getNodeSources()->first() ?: null; - if ($nodeSource === null) { + if (null === $nodeSource) { continue; } @@ -93,21 +94,21 @@ protected function execute(InputInterface $input, OutputInterface $output): int * node-name AND if it is not ALREADY suffixed with a unique ID. */ if ( - $prefixNameSlug != $node->getNodeName() && - $this->nodeNamePolicy->isNodeNameValid($prefixNameSlug) && - !$this->nodeNamePolicy->isNodeNameWithUniqId($prefixNameSlug, $nodeSource->getNode()->getNodeName()) + $prefixNameSlug != $node->getNodeName() + && $this->nodeNamePolicy->isNodeNameValid($prefixNameSlug) + && !$this->nodeNamePolicy->isNodeNameWithUniqId($prefixNameSlug, $nodeSource->getNode()->getNodeName()) ) { $alreadyUsed = $this->nodeNamePolicy->isNodeNameAlreadyUsed($prefixNameSlug); if (!$alreadyUsed) { $names[] = [ $node->getNodeName(), - $prefixNameSlug + $prefixNameSlug, ]; $node->setNodeName($prefixNameSlug); } else { if ( - $input->getOption('use-date') && - null !== $nodeSource->getPublishedAt() + $input->getOption('use-date') + && null !== $nodeSource->getPublishedAt() ) { $suffixedNameSlug = $this->nodeNamePolicy->getDatestampedNodeName($nodeSource); } else { @@ -116,14 +117,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (!$this->nodeNamePolicy->isNodeNameAlreadyUsed($suffixedNameSlug)) { $names[] = [ $node->getNodeName(), - $suffixedNameSlug + $suffixedNameSlug, ]; $node->setNodeName($suffixedNameSlug); } else { $suffixedNameSlug = $this->nodeNamePolicy->getSafeNodeName($nodeSource); $names[] = [ $node->getNodeName(), - $suffixedNameSlug + $suffixedNameSlug, ]; $node->setNodeName($suffixedNameSlug); } @@ -131,16 +132,16 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (!$input->getOption('dry-run')) { $entityManager->flush(); } - $renameCount++; + ++$renameCount; } } $io->table(['Old name', 'New name'], $names); if (!$input->getOption('dry-run')) { - $io->success('Renaming done! ' . $renameCount . ' nodes have been affected. Do not forget to reindex your Solr documents if you are using it.'); + $io->success('Renaming done! '.$renameCount.' nodes have been affected. Do not forget to reindex your Solr documents if you are using it.'); } else { - $io->success($renameCount . ' nodes would have been affected. Nothing was saved to database.'); + $io->success($renameCount.' nodes would have been affected. Nothing was saved to database.'); } } diff --git a/lib/RoadizCoreBundle/src/Console/NodesCommand.php b/lib/RoadizCoreBundle/src/Console/NodesCommand.php index cd5e56a0..f3210b5e 100644 --- a/lib/RoadizCoreBundle/src/Console/NodesCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodesCommand.php @@ -17,7 +17,7 @@ final class NodesCommand extends Command { public function __construct( private readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -63,12 +63,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $node->getId(), $node->getNodeName(), $node->getNodeType()->getName(), - (!$node->isVisible() ? 'X' : ''), - ($node->isPublished() ? 'X' : ''), + !$node->isVisible() ? 'X' : '', + $node->isPublished() ? 'X' : '', ]; } $io->table(['Id', 'Name', 'Type', 'Hidden', 'Published'], $tableContent); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodesDetailsCommand.php b/lib/RoadizCoreBundle/src/Console/NodesDetailsCommand.php index 53515526..e2dc827a 100644 --- a/lib/RoadizCoreBundle/src/Console/NodesDetailsCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodesDetailsCommand.php @@ -18,7 +18,7 @@ final class NodesDetailsCommand extends Command { public function __construct( private readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -41,6 +41,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int /** * @var NodesSources|null $source + * * @phpstan-ignore-next-line */ $source = $this->managerRegistry->getRepository(NodesSources::class) @@ -78,8 +79,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int } } else { $io->error('No node found.'); + return 1; } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/NodesEmptyTrashCommand.php b/lib/RoadizCoreBundle/src/Console/NodesEmptyTrashCommand.php index 9beea3c6..031b6f9b 100644 --- a/lib/RoadizCoreBundle/src/Console/NodesEmptyTrashCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodesEmptyTrashCommand.php @@ -20,7 +20,7 @@ final class NodesEmptyTrashCommand extends Command public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly HandlerFactory $handlerFactory, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -43,8 +43,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->andWhere($countQb->expr()->eq('n.status', Node::DELETED)) ->getQuery(); $emptiedCount = $countQuery->getSingleScalarResult(); - if ($emptiedCount == 0) { + if (0 == $emptiedCount) { $io->success('Nodes trashcan is already empty.'); + return 0; } diff --git a/lib/RoadizCoreBundle/src/Console/NodesOrphansCommand.php b/lib/RoadizCoreBundle/src/Console/NodesOrphansCommand.php index 2be332d9..bdfb3f41 100644 --- a/lib/RoadizCoreBundle/src/Console/NodesOrphansCommand.php +++ b/lib/RoadizCoreBundle/src/Console/NodesOrphansCommand.php @@ -17,7 +17,7 @@ final class NodesOrphansCommand extends Command { public function __construct( private readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -35,10 +35,6 @@ protected function configure(): void } /** - * @param InputInterface $input - * @param OutputInterface $output - * - * @return int * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException */ @@ -59,8 +55,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int } catch (NoResultException $e) { } - if (count($orphans) === 0) { + if (0 === count($orphans)) { $io->success('That’s OK, you don’t have any orphan node.'); + return 0; } @@ -73,8 +70,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int $node->getId(), $node->getNodeName(), null !== $node->getNodeType() ? $node->getNodeType()->getName() : '', - (!$node->isVisible() ? 'X' : ''), - ($node->isPublished() ? 'X' : ''), + !$node->isVisible() ? 'X' : '', + $node->isPublished() ? 'X' : '', ]; } @@ -91,6 +88,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } else { $io->note('Use --delete option to actually remove these nodes.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/RegisterCronLastExecDateCommand.php b/lib/RoadizCoreBundle/src/Console/RegisterCronLastExecDateCommand.php index 20bed441..8ebf77f1 100644 --- a/lib/RoadizCoreBundle/src/Console/RegisterCronLastExecDateCommand.php +++ b/lib/RoadizCoreBundle/src/Console/RegisterCronLastExecDateCommand.php @@ -1,5 +1,7 @@ setWorkingDirectory($this->getProjectDir()); $process->setTty($interactive); $process->run(); + return $process->wait(); } protected function clearCaches(SymfonyStyle $io): void { - $this->runCommand( + 0 === $this->runCommand( 'doctrine:cache:clear-metadata', '', null, false, true - ) === 0 ? $io->success('doctrine:cache:clear-metadata') : $io->error('doctrine:cache:clear-metadata'); + ) ? $io->success('doctrine:cache:clear-metadata') : $io->error('doctrine:cache:clear-metadata'); - $this->runCommand( + 0 === $this->runCommand( 'cache:clear', '', null, false, true - ) === 0 ? $io->success('cache:clear') : $io->error('cache:clear'); + ) ? $io->success('cache:clear') : $io->error('cache:clear'); - $this->runCommand( + 0 === $this->runCommand( 'cache:pool:clear', 'cache.global_clearer', null, false, true - ) === 0 ? $io->success('cache:pool:clear') : $io->error('cache:pool:clear'); + ) ? $io->success('cache:pool:clear') : $io->error('cache:pool:clear'); } } diff --git a/lib/RoadizCoreBundle/src/Console/SolrCommand.php b/lib/RoadizCoreBundle/src/Console/SolrCommand.php index 55977a44..0372582e 100644 --- a/lib/RoadizCoreBundle/src/Console/SolrCommand.php +++ b/lib/RoadizCoreBundle/src/Console/SolrCommand.php @@ -17,7 +17,7 @@ class SolrCommand extends Command public function __construct( protected readonly ClientRegistry $clientRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -34,12 +34,14 @@ protected function validateSolrState(SymfonyStyle $io): ?Client if (null === $client) { $this->displayBasicConfig(); + return null; } if (true !== $this->clientRegistry->isClientReady($client)) { $io->error('Solr search engine server does not respond…'); $io->note('See your `config/packages/roadiz_core.yaml` file to correct your Solr connection settings.'); + return null; } @@ -54,6 +56,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $this->io->success('Solr search engine server is running.'); + return 0; } diff --git a/lib/RoadizCoreBundle/src/Console/SolrOptimizeCommand.php b/lib/RoadizCoreBundle/src/Console/SolrOptimizeCommand.php index 9c9e9b89..edc9032e 100644 --- a/lib/RoadizCoreBundle/src/Console/SolrOptimizeCommand.php +++ b/lib/RoadizCoreBundle/src/Console/SolrOptimizeCommand.php @@ -17,7 +17,7 @@ final class SolrOptimizeCommand extends SolrCommand public function __construct( protected readonly IndexerFactoryInterface $indexerFactory, ClientRegistry $clientRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($clientRegistry, $name); } @@ -42,6 +42,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $documentIndexer->optimizeSolr(); $this->io->success('Solr core has been optimized.'); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/SolrReindexCommand.php b/lib/RoadizCoreBundle/src/Console/SolrReindexCommand.php index 5576c0ab..cbfef2a6 100644 --- a/lib/RoadizCoreBundle/src/Console/SolrReindexCommand.php +++ b/lib/RoadizCoreBundle/src/Console/SolrReindexCommand.php @@ -23,7 +23,7 @@ class SolrReindexCommand extends SolrCommand implements ThemeAwareCommandInterfa public function __construct( protected readonly IndexerFactoryInterface $indexerFactory, ClientRegistry $clientRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($clientRegistry, $name); } @@ -65,6 +65,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->executeForAll($stopwatch); } } + return 0; } @@ -109,7 +110,7 @@ protected function executeForNodes(Stopwatch $stopwatch, int $batchCount, int $b $nodesSourcesIndexer->setIo($this->io); } // Empty first ONLY if one batch or first batch. - if ($batchNumber === 0) { + if (0 === $batchNumber) { $nodesSourcesIndexer->emptySolr(SolariumNodeSource::DOCUMENT_TYPE); } diff --git a/lib/RoadizCoreBundle/src/Console/SolrResetCommand.php b/lib/RoadizCoreBundle/src/Console/SolrResetCommand.php index ba0b94b4..2789e2bc 100644 --- a/lib/RoadizCoreBundle/src/Console/SolrResetCommand.php +++ b/lib/RoadizCoreBundle/src/Console/SolrResetCommand.php @@ -18,7 +18,7 @@ final class SolrResetCommand extends SolrCommand public function __construct( private readonly IndexerFactoryInterface $indexerFactory, ClientRegistry $clientRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($clientRegistry, $name); } @@ -41,13 +41,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int false ); if ($this->io->askQuestion($confirmation)) { - $indexer = $this->indexerFactory->getIndexerFor(NodesSources::class); + $indexer = $this->indexerFactory->getIndexerFor(NodesSources::class); if ($indexer instanceof CliAwareIndexer) { $indexer->setIo($this->io); } $indexer->emptySolr(); $this->io->success('Solr index resetted.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/TranslationsCommand.php b/lib/RoadizCoreBundle/src/Console/TranslationsCommand.php index 5f557c74..61fd990e 100644 --- a/lib/RoadizCoreBundle/src/Console/TranslationsCommand.php +++ b/lib/RoadizCoreBundle/src/Console/TranslationsCommand.php @@ -15,7 +15,7 @@ class TranslationsCommand extends Command { public function __construct( protected readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -33,8 +33,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(Translation::class) ->findAll(); - if (count($translations) === 0) { + if (0 === count($translations)) { $io->error('No available translations.'); + return 1; } @@ -45,11 +46,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int $trans->getId(), $trans->getName(), $trans->getLocale(), - (!$trans->isAvailable() ? 'X' : ''), - ($trans->isDefaultTranslation() ? 'X' : ''), + !$trans->isAvailable() ? 'X' : '', + $trans->isDefaultTranslation() ? 'X' : '', ]; } $io->table(['Id', 'Name', 'Locale', 'Disabled', 'Default'], $tableContent); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/TranslationsCreationCommand.php b/lib/RoadizCoreBundle/src/Console/TranslationsCreationCommand.php index 387801e0..52f5b679 100644 --- a/lib/RoadizCoreBundle/src/Console/TranslationsCreationCommand.php +++ b/lib/RoadizCoreBundle/src/Console/TranslationsCreationCommand.php @@ -12,7 +12,7 @@ use Symfony\Component\Console\Style\SymfonyStyle; /** - * Command line utils for managing translations + * Command line utils for managing translations. */ final class TranslationsCreationCommand extends TranslationsCommand { @@ -50,15 +50,17 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->findOneByLocale($locale); $confirmation = new ConfirmationQuestion( - 'Are you sure to create ' . $name . ' (' . $locale . ') translation?', + 'Are you sure to create '.$name.' ('.$locale.') translation?', false ); if (null !== $translationByName) { - $io->error('Translation ' . $name . ' already exists.'); + $io->error('Translation '.$name.' already exists.'); + return 1; } elseif (null !== $translationByLocale) { - $io->error('Translation locale ' . $locale . ' is already used.'); + $io->error('Translation locale '.$locale.' is already used.'); + return 1; } @@ -74,8 +76,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->managerRegistry->getManagerForClass(Translation::class)->persist($newTrans); $this->managerRegistry->getManagerForClass(Translation::class)->flush(); - $io->success('New ' . $newTrans->getName() . ' translation for ' . $newTrans->getLocale() . ' locale.'); + $io->success('New '.$newTrans->getName().' translation for '.$newTrans->getLocale().' locale.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/TranslationsDeleteCommand.php b/lib/RoadizCoreBundle/src/Console/TranslationsDeleteCommand.php index 50498511..a12097c3 100644 --- a/lib/RoadizCoreBundle/src/Console/TranslationsDeleteCommand.php +++ b/lib/RoadizCoreBundle/src/Console/TranslationsDeleteCommand.php @@ -41,21 +41,23 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($translationCount < 2) { $io->error('You cannot delete the only one available translation!'); + return 1; } - if ($translation === null) { - $io->error('Translation for locale ' . $locale . ' does not exist.'); + if (null === $translation) { + $io->error('Translation for locale '.$locale.' does not exist.'); + return 1; } - $io->note('///////////////////////////////' . PHP_EOL . - '/////////// WARNING ///////////' . PHP_EOL . - '///////////////////////////////' . PHP_EOL . - 'This operation cannot be undone.' . PHP_EOL . + $io->note('///////////////////////////////'.PHP_EOL. + '/////////// WARNING ///////////'.PHP_EOL. + '///////////////////////////////'.PHP_EOL. + 'This operation cannot be undone.'.PHP_EOL. 'Deleting a translation, you will automatically delete every translated tags, node-sources, url-aliases and documents.'); $confirmation = new ConfirmationQuestion( - 'Are you sure to delete ' . $translation->getName() . ' (' . $translation->getLocale() . ') translation?', + 'Are you sure to delete '.$translation->getName().' ('.$translation->getLocale().') translation?', false ); if ( @@ -67,6 +69,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->managerRegistry->getManagerForClass(Translation::class)->flush(); $io->success('Translation deleted.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/TranslationsDisableCommand.php b/lib/RoadizCoreBundle/src/Console/TranslationsDisableCommand.php index 4407fb5b..124039e4 100644 --- a/lib/RoadizCoreBundle/src/Console/TranslationsDisableCommand.php +++ b/lib/RoadizCoreBundle/src/Console/TranslationsDisableCommand.php @@ -36,13 +36,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(Translation::class) ->findOneByLocale($locale); - if ($translation === null) { - $io->error('Translation for locale ' . $locale . ' does not exist.'); + if (null === $translation) { + $io->error('Translation for locale '.$locale.' does not exist.'); + return 1; } $confirmation = new ConfirmationQuestion( - 'Are you sure to disable ' . $translation->getName() . ' (' . $translation->getLocale() . ') translation?', + 'Are you sure to disable '.$translation->getName().' ('.$translation->getLocale().') translation?', false ); if ( @@ -54,6 +55,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->managerRegistry->getManagerForClass(Translation::class)->flush(); $io->success('Translation disabled.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/TranslationsEnableCommand.php b/lib/RoadizCoreBundle/src/Console/TranslationsEnableCommand.php index 5c4121f4..c196b97a 100644 --- a/lib/RoadizCoreBundle/src/Console/TranslationsEnableCommand.php +++ b/lib/RoadizCoreBundle/src/Console/TranslationsEnableCommand.php @@ -36,13 +36,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(Translation::class) ->findOneByLocale($locale); - if ($translation === null) { - $io->error('Translation for locale ' . $locale . ' does not exist.'); + if (null === $translation) { + $io->error('Translation for locale '.$locale.' does not exist.'); + return 1; } $confirmation = new ConfirmationQuestion( - 'Are you sure to enable ' . $translation->getName() . ' (' . $translation->getLocale() . ') translation?', + 'Are you sure to enable '.$translation->getName().' ('.$translation->getLocale().') translation?', false ); if ( @@ -54,6 +55,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->managerRegistry->getManagerForClass(Translation::class)->flush(); $io->success('Translation enabled.'); } + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersCommand.php b/lib/RoadizCoreBundle/src/Console/UsersCommand.php index 2309ff8d..36de8d56 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersCommand.php @@ -18,7 +18,7 @@ class UsersCommand extends Command { public function __construct( protected readonly ManagerRegistry $managerRegistry, - string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -58,8 +58,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->getRepository(User::class) ->findOneBy(['username' => $name]); - if ($user === null) { - $io->error('User “' . $name . '” does not exist… use users:create to add a new user.'); + if (null === $user) { + $io->error('User “'.$name.'” does not exist… use users:create to add a new user.'); } else { $tableContent = [ $this->getUserTableRow($user), @@ -88,6 +88,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $io->warning('No available users.'); } } + return 0; } @@ -105,7 +106,7 @@ protected function getUserForInput(InputInterface $input): User ->findOneBy(['username' => $name]); if (!($user instanceof User)) { - throw new InvalidArgumentException('User “' . $name . '” does not exist.'); + throw new InvalidArgumentException('User “'.$name.'” does not exist.'); } return $user; @@ -113,9 +114,6 @@ protected function getUserForInput(InputInterface $input): User /** * Get role by name, and create it if it does not exist. - * - * @param string $roleName - * @return Role */ public function getRole(string $roleName = Role::ROLE_SUPERADMIN): Role { @@ -123,7 +121,7 @@ public function getRole(string $roleName = Role::ROLE_SUPERADMIN): Role ->getRepository(Role::class) ->findOneBy(['name' => $roleName]); - if ($role === null) { + if (null === $role) { $role = new Role($roleName); $this->managerRegistry->getManagerForClass(Role::class)->persist($role); $this->managerRegistry->getManagerForClass(Role::class)->flush(); diff --git a/lib/RoadizCoreBundle/src/Console/UsersCreationCommand.php b/lib/RoadizCoreBundle/src/Console/UsersCreationCommand.php index 2373093e..9d3723e5 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersCreationCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersCreationCommand.php @@ -48,7 +48,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->findOneBy(['username' => $name]); if ($user instanceof User) { - $io->warning('User “' . $name . '” already exists.'); + $io->warning('User “'.$name.'” already exists.'); + return 1; } @@ -60,20 +61,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'username' => $user->getUsername(), ]; $passwordInput = new ArrayInput($arguments); + return $command->run($passwordInput, $output); } - /** - * @param string $username - * @param InputInterface $input - * @param OutputInterface $output - * - * @return User - */ private function executeUserCreation( string $username, InputInterface $input, - OutputInterface $output + OutputInterface $output, ): User { $user = new User(); $io = new SymfonyStyle($input, $output); @@ -94,8 +89,8 @@ private function executeUserCreation( $questionEmail ); } while ( - !filter_var($email, FILTER_VALIDATE_EMAIL) || - $this->managerRegistry->getRepository(User::class)->emailExists($email) + !filter_var($email, FILTER_VALIDATE_EMAIL) + || $this->managerRegistry->getRepository(User::class)->emailExists($email) ); } else { /* @@ -124,7 +119,7 @@ private function executeUserCreation( ) { $user->addRoleEntity($this->getRole(Role::ROLE_BACKEND_USER)); } - } elseif ($input->getOption('back-end') === true) { + } elseif (true === $input->getOption('back-end')) { $user->addRoleEntity($this->getRole(Role::ROLE_BACKEND_USER)); } @@ -140,7 +135,7 @@ private function executeUserCreation( ) { $user->addRoleEntity($this->getRole(Role::ROLE_SUPERADMIN)); } - } elseif ($input->getOption('super-admin') === true) { + } elseif (true === $input->getOption('super-admin')) { $user->addRoleEntity($this->getRole(Role::ROLE_SUPERADMIN)); } @@ -155,7 +150,8 @@ private function executeUserCreation( $this->managerRegistry->getManagerForClass(User::class)->persist($user); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $username . '”<' . $email . '> created no password.'); + $io->success('User “'.$username.'”<'.$email.'> created no password.'); + return $user; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersDeleteCommand.php b/lib/RoadizCoreBundle/src/Console/UsersDeleteCommand.php index 2e8c3062..0f2007fa 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersDeleteCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersDeleteCommand.php @@ -31,7 +31,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $user = $this->getUserForInput($input); $confirmation = new ConfirmationQuestion( - 'Do you really want to delete user “' . $user->getUsername() . '”?', + 'Do you really want to delete user “'.$user->getUsername().'”?', false ); if ( @@ -41,10 +41,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $this->managerRegistry->getManagerForClass(User::class)->remove($user); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $name . '” deleted.'); + $io->success('User “'.$name.'” deleted.'); + return 0; } else { - $io->warning('User “' . $name . '” was not deleted.'); + $io->warning('User “'.$name.'” was not deleted.'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersDisableCommand.php b/lib/RoadizCoreBundle/src/Console/UsersDisableCommand.php index 97b0062a..587e8ecf 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersDisableCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersDisableCommand.php @@ -31,7 +31,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $user = $this->getUserForInput($input); $confirmation = new ConfirmationQuestion( - 'Do you really want to disable user “' . $user->getUsername() . '”?', + 'Do you really want to disable user “'.$user->getUsername().'”?', false ); if ( @@ -41,10 +41,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $user->setEnabled(false); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $name . '” disabled.'); + $io->success('User “'.$name.'” disabled.'); + return 0; } else { - $io->warning('User “' . $name . '” was not disabled.'); + $io->warning('User “'.$name.'” was not disabled.'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersEnableCommand.php b/lib/RoadizCoreBundle/src/Console/UsersEnableCommand.php index b9092656..11488c5e 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersEnableCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersEnableCommand.php @@ -31,7 +31,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $user = $this->getUserForInput($input); $confirmation = new ConfirmationQuestion( - 'Do you really want to enable user “' . $user->getUsername() . '”?', + 'Do you really want to enable user “'.$user->getUsername().'”?', false ); if ( @@ -41,10 +41,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $user->setEnabled(true); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $name . '” was enabled.'); + $io->success('User “'.$name.'” was enabled.'); + return 0; } else { - $io->warning('User “' . $name . '” was not enabled'); + $io->warning('User “'.$name.'” was not enabled'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersExpireCommand.php b/lib/RoadizCoreBundle/src/Console/UsersExpireCommand.php index f8aafd30..c9d865e5 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersExpireCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersExpireCommand.php @@ -49,10 +49,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $user->setExpiresAt($expirationDate); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $name . '” expiration date was set on ' . $expirationDate->format('c') . '.'); + $io->success('User “'.$name.'” expiration date was set on '.$expirationDate->format('c').'.'); + return 0; } else { - $io->warning('User “' . $name . '” was not updated.'); + $io->warning('User “'.$name.'” was not updated.'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersInactiveCommand.php b/lib/RoadizCoreBundle/src/Console/UsersInactiveCommand.php index f456b99a..37e0f086 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersInactiveCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersInactiveCommand.php @@ -14,7 +14,7 @@ final class UsersInactiveCommand extends Command { - public function __construct(private readonly ManagerRegistry $managerRegistry, string $name = null) + public function __construct(private readonly ManagerRegistry $managerRegistry, ?string $name = null) { parent::__construct($name); } @@ -61,6 +61,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $daysCount = $input->getOption('days'); if (!\is_numeric($daysCount) || $daysCount < 1) { $io->error('Days option must be a positive number.'); + return 1; } @@ -108,7 +109,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $purge = $input->getOption('purge'); - if (!$purge || count($inactiveUsers) === 0) { + if (!$purge || 0 === count($inactiveUsers)) { return 0; } @@ -117,11 +118,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'You cannot purge inactive users since %s without filtering them by a ROLE name.', $sinceDate->format('Y-m-d') )); + return 1; } if ($input->isInteractive() && !$io->confirm('Do you want to delete these users?')) { $io->comment('No user has been deleted.'); + return 0; } @@ -133,6 +136,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int '%d inactive users have been deleted.', count($inactiveUsers) )); + return 0; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersLockCommand.php b/lib/RoadizCoreBundle/src/Console/UsersLockCommand.php index 03e9b9dc..7df7055d 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersLockCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersLockCommand.php @@ -31,7 +31,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $user = $this->getUserForInput($input); $confirmation = new ConfirmationQuestion( - 'Do you really want to lock user “' . $user->getUsername() . '”?', + 'Do you really want to lock user “'.$user->getUsername().'”?', false ); if ( @@ -41,10 +41,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $user->setLocked(true); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $name . '” locked.'); + $io->success('User “'.$name.'” locked.'); + return 0; } else { - $io->warning('User “' . $name . '” was not locked.'); + $io->warning('User “'.$name.'” was not locked.'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersPasswordCommand.php b/lib/RoadizCoreBundle/src/Console/UsersPasswordCommand.php index 9d265e1f..379328ba 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersPasswordCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersPasswordCommand.php @@ -18,7 +18,7 @@ final class UsersPasswordCommand extends UsersCommand public function __construct( private readonly PasswordGenerator $passwordGenerator, ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($managerRegistry, $name); } @@ -41,7 +41,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $user = $this->getUserForInput($input); $confirmation = new ConfirmationQuestion( - 'Do you really want to regenerate user “' . $user->getUsername() . '” password?', + 'Do you really want to regenerate user “'.$user->getUsername().'” password?', false ); if ( @@ -51,10 +51,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $user->setPlainPassword($this->passwordGenerator->generatePassword(12)); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('A new password was regenerated for ' . $name . ': ' . $user->getPlainPassword()); + $io->success('A new password was regenerated for '.$name.': '.$user->getPlainPassword()); + return 0; } else { $io->warning('User password was not changed.'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersRolesCommand.php b/lib/RoadizCoreBundle/src/Console/UsersRolesCommand.php index 047a2d5b..304998db 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersRolesCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersRolesCommand.php @@ -23,7 +23,7 @@ final class UsersRolesCommand extends UsersCommand public function __construct( private readonly Roles $rolesBag, ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($managerRegistry, $name); } @@ -68,12 +68,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int do { $role = $io->askQuestion($question); - if ($role != "") { + if ('' != $role) { $user->addRoleEntity($this->rolesBag->get($role)); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('Role: ' . $role . ' added.'); + $io->success('Role: '.$role.' added.'); } - } while ($role != ""); + } while ('' != $role); } elseif ($input->getOption('remove')) { do { $roles = $user->getRoles(); @@ -86,9 +86,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (in_array($role, $roles)) { $user->removeRoleEntity($this->rolesBag->get($role)); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('Role: ' . $role . ' removed.'); + $io->success('Role: '.$role.' removed.'); } - } while ($role != ""); + } while ('' != $role); } return 0; diff --git a/lib/RoadizCoreBundle/src/Console/UsersUnexpireCommand.php b/lib/RoadizCoreBundle/src/Console/UsersUnexpireCommand.php index 0430a728..a3dd5055 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersUnexpireCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersUnexpireCommand.php @@ -31,7 +31,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $user = $this->getUserForInput($input); $confirmation = new ConfirmationQuestion( - 'Do you really want to remove user “' . $user->getUsername() . '” expiration date?', + 'Do you really want to remove user “'.$user->getUsername().'” expiration date?', false ); if ( @@ -41,10 +41,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $user->setExpiresAt(null); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $name . '” unexpired.'); + $io->success('User “'.$name.'” unexpired.'); + return 0; } else { - $io->warning('User “' . $name . '” was not updated.'); + $io->warning('User “'.$name.'” was not updated.'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/UsersUnlockCommand.php b/lib/RoadizCoreBundle/src/Console/UsersUnlockCommand.php index 0fd4be6a..bd4684cb 100644 --- a/lib/RoadizCoreBundle/src/Console/UsersUnlockCommand.php +++ b/lib/RoadizCoreBundle/src/Console/UsersUnlockCommand.php @@ -31,7 +31,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $user = $this->getUserForInput($input); $confirmation = new ConfirmationQuestion( - 'Do you really want to unlock user “' . $user->getUsername() . '”?', + 'Do you really want to unlock user “'.$user->getUsername().'”?', false ); if ( @@ -41,10 +41,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int ) { $user->setLocked(false); $this->managerRegistry->getManagerForClass(User::class)->flush(); - $io->success('User “' . $name . '” unlocked.'); + $io->success('User “'.$name.'” unlocked.'); + return 0; } else { - $io->warning('User “' . $name . '” was not unlocked.'); + $io->warning('User “'.$name.'” was not unlocked.'); + return 1; } } diff --git a/lib/RoadizCoreBundle/src/Console/VersionsPurgeCommand.php b/lib/RoadizCoreBundle/src/Console/VersionsPurgeCommand.php index 1c89935c..d7531d84 100644 --- a/lib/RoadizCoreBundle/src/Console/VersionsPurgeCommand.php +++ b/lib/RoadizCoreBundle/src/Console/VersionsPurgeCommand.php @@ -20,7 +20,7 @@ final class VersionsPurgeCommand extends Command { public function __construct( private readonly ManagerRegistry $managerRegistry, - ?string $name = null + ?string $name = null, ) { parent::__construct($name); } @@ -54,7 +54,7 @@ protected function configure(): void protected function execute(InputInterface $input, OutputInterface $output): int { - if ($input->hasOption('before') && $input->getOption('before') != '') { + if ($input->hasOption('before') && '' != $input->getOption('before')) { $this->purgeByDate($input, $output); } elseif ($input->hasOption('count')) { if ((int) $input->getOption('count') < 2) { @@ -64,6 +64,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } else { throw new \InvalidArgumentException('Choose an option between --before or --count'); } + return 0; } diff --git a/lib/RoadizCoreBundle/src/Controller/CustomFormController.php b/lib/RoadizCoreBundle/src/Controller/CustomFormController.php index c201a49c..f878a43d 100644 --- a/lib/RoadizCoreBundle/src/Controller/CustomFormController.php +++ b/lib/RoadizCoreBundle/src/Controller/CustomFormController.php @@ -5,7 +5,6 @@ namespace RZ\Roadiz\CoreBundle\Controller; use Doctrine\Persistence\ManagerRegistry; -use Exception; use League\Flysystem\FilesystemException; use Limenius\Liform\LiformInterface; use Psr\Log\LoggerInterface; @@ -56,11 +55,6 @@ private function validateCustomForm(?CustomForm $customForm): void } } - /** - * @param Request $request - * @param int $id - * @return JsonResponse - */ public function definitionAction(Request $request, int $id): JsonResponse { /** @var CustomForm|null $customForm */ @@ -79,10 +73,7 @@ public function definitionAction(Request $request, int $id): JsonResponse } /** - * @param Request $request - * @param int $id - * @return Response - * @throws Exception|FilesystemException + * @throws \Exception|FilesystemException */ public function postAction(Request $request, int $id): Response { @@ -114,6 +105,7 @@ public function postAction(Request $request, int $id): Response if ($mixed instanceof Response) { $mixed->prepare($request); + return $mixed; } @@ -121,8 +113,9 @@ public function postAction(Request $request, int $id): Response if ($mixed['formObject']->isSubmitted()) { $errorPayload = [ 'status' => Response::HTTP_BAD_REQUEST, - 'errorsPerForm' => $this->formErrorSerializer->getErrorsAsArray($mixed['formObject']) + 'errorsPerForm' => $this->formErrorSerializer->getErrorsAsArray($mixed['formObject']), ]; + return new JsonResponse( $this->serializer->serialize($errorPayload, 'json'), Response::HTTP_BAD_REQUEST, @@ -136,9 +129,6 @@ public function postAction(Request $request, int $id): Response } /** - * @param Request $request - * @param int $customFormId - * @return Response * @throws FilesystemException */ public function addAction(Request $request, int $customFormId): Response @@ -153,7 +143,7 @@ public function addAction(Request $request, int $customFormId): Response new RedirectResponse( $this->generateUrl( 'customFormSentAction', - ["customFormId" => $customFormId] + ['customFormId' => $customFormId] ) ) ); @@ -165,11 +155,6 @@ public function addAction(Request $request, int $customFormId): Response } } - /** - * @param Request $request - * @param int $customFormId - * @return Response - */ public function sentAction(Request $request, int $customFormId): Response { $assignation = []; @@ -178,6 +163,7 @@ public function sentAction(Request $request, int $customFormId): Response $this->validateCustomForm($customForm); $assignation['customForm'] = $customForm; + return $this->render('@RoadizCore/customForm/customFormSent.html.twig', $assignation); } @@ -190,13 +176,8 @@ public function sentAction(Request $request, int $customFormId): Response * * form * * If form is validated, **RedirectResponse** will be returned. * - * @param Request $request - * @param CustomForm $customFormsEntity - * @param Response $response - * @param bool $forceExpanded - * @param string|null $emailSender - * @param bool $prefix * @return array|Response + * * @throws FilesystemException */ private function prepareAndHandleCustomFormAssignation( @@ -205,14 +186,14 @@ private function prepareAndHandleCustomFormAssignation( Response $response, bool $forceExpanded = false, ?string $emailSender = null, - bool $prefix = true + bool $prefix = true, ) { $assignation = [ 'customForm' => $customFormsEntity, 'fields' => $customFormsEntity->getFields(), 'head' => [ 'siteTitle' => $this->settingsBag->get('site_name'), - ] + ], ]; $helper = $this->customFormHelperFactory->createHelper($customFormsEntity); $form = $helper->getForm( @@ -266,6 +247,7 @@ private function prepareAndHandleCustomFormAssignation( $assignation['form'] = $form->createView(); $assignation['formObject'] = $form; + return $assignation; } } diff --git a/lib/RoadizCoreBundle/src/Controller/DefaultNodeSourceController.php b/lib/RoadizCoreBundle/src/Controller/DefaultNodeSourceController.php index 02529958..007ae0ad 100644 --- a/lib/RoadizCoreBundle/src/Controller/DefaultNodeSourceController.php +++ b/lib/RoadizCoreBundle/src/Controller/DefaultNodeSourceController.php @@ -13,7 +13,7 @@ final class DefaultNodeSourceController extends AbstractController public function indexAction(NodesSources $nodeSource): Response { return $this->render('@RoadizCore/nodeSource/default.html.twig', [ - 'nodeSource' => $nodeSource + 'nodeSource' => $nodeSource, ]); } } diff --git a/lib/RoadizCoreBundle/src/Controller/HealthCheckController.php b/lib/RoadizCoreBundle/src/Controller/HealthCheckController.php index 952f17f1..422a1fe3 100644 --- a/lib/RoadizCoreBundle/src/Controller/HealthCheckController.php +++ b/lib/RoadizCoreBundle/src/Controller/HealthCheckController.php @@ -15,15 +15,15 @@ public function __construct( private readonly ?string $healthCheckToken, private readonly ?string $appVersion, private readonly ?string $cmsVersion, - private readonly ?string $cmsVersionPrefix + private readonly ?string $cmsVersionPrefix, ) { } public function __invoke(Request $request): JsonResponse { if ( - !empty($this->healthCheckToken) && - $request->headers->get('x-health-check') !== $this->healthCheckToken + !empty($this->healthCheckToken) + && $request->headers->get('x-health-check') !== $this->healthCheckToken ) { throw new NotFoundHttpException(); } @@ -34,10 +34,10 @@ public function __invoke(Request $request): JsonResponse 'notes' => [ 'roadiz_version' => $this->cmsVersion ?? '', 'roadiz_channel' => $this->cmsVersionPrefix ?? '', - ] + ], ], Response::HTTP_OK, [ 'Content-type' => 'application/health+json', - 'Cache-Control' => 'public, max-age=10' + 'Cache-Control' => 'public, max-age=10', ]); } } diff --git a/lib/RoadizCoreBundle/src/Controller/RedirectionController.php b/lib/RoadizCoreBundle/src/Controller/RedirectionController.php index 6ede96a6..caf3ed14 100644 --- a/lib/RoadizCoreBundle/src/Controller/RedirectionController.php +++ b/lib/RoadizCoreBundle/src/Controller/RedirectionController.php @@ -31,8 +31,8 @@ public function redirectAction(Request $request, Redirection $redirection): Redi } if ( - null !== $redirection->getRedirectUri() && - \mb_strlen($redirection->getRedirectUri()) > 0 + null !== $redirection->getRedirectUri() + && \mb_strlen($redirection->getRedirectUri()) > 0 ) { return new RedirectResponse($redirection->getRedirectUri(), $redirection->getType()); } @@ -62,7 +62,7 @@ public function redirectToRouteAction( Request $request, string $route, bool $permanent = false, - $ignoreAttributes = false + $ignoreAttributes = false, ): RedirectResponse { if ('' == $route) { throw new HttpException($permanent ? 410 : 404); @@ -75,6 +75,7 @@ public function redirectToRouteAction( $attributes = array_diff_key($attributes, array_flip($ignoreAttributes)); } } + return new RedirectResponse( $this->urlGenerator->generate( $route, diff --git a/lib/RoadizCoreBundle/src/CustomForm/CustomFormAnswerSerializer.php b/lib/RoadizCoreBundle/src/CustomForm/CustomFormAnswerSerializer.php index 6259d353..5753bc58 100644 --- a/lib/RoadizCoreBundle/src/CustomForm/CustomFormAnswerSerializer.php +++ b/lib/RoadizCoreBundle/src/CustomForm/CustomFormAnswerSerializer.php @@ -22,7 +22,7 @@ public function toSimpleArray(CustomFormAnswer $answer): array { $answers = [ 'ip' => $answer->getIp(), - 'submitted.date' => $answer->getSubmittedAt() + 'submitted.date' => $answer->getSubmittedAt(), ]; /** @var CustomFormFieldAttribute $answerAttr */ foreach ($answer->getAnswerFields() as $answerAttr) { @@ -30,13 +30,14 @@ public function toSimpleArray(CustomFormAnswer $answer): array if ($field->isDocuments()) { $answers[$field->getLabel()] = implode(PHP_EOL, $answerAttr->getDocuments()->map(function (Document $document) { return $this->urlGenerator->generate('documentsDownloadPage', [ - 'documentId' => $document->getId() + 'documentId' => $document->getId(), ], UrlGeneratorInterface::ABSOLUTE_URL); })->toArray()); } else { $answers[$field->getLabel()] = $answerAttr->getValue(); } } + return $answers; } } diff --git a/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelper.php b/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelper.php index 2e57ed4d..9c84c496 100644 --- a/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelper.php +++ b/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelper.php @@ -28,25 +28,20 @@ final class CustomFormHelper { public const ARRAY_SEPARATOR = ', '; + public function __construct( private readonly ObjectManager $em, private readonly CustomForm $customForm, private readonly AbstractDocumentFactory $documentFactory, private readonly FormFactoryInterface $formFactory, - private readonly EventDispatcherInterface $eventDispatcher + private readonly EventDispatcherInterface $eventDispatcher, ) { } - /** - * @param Request $request - * @param boolean $forceExpanded - * @param bool $prefix - * @return FormInterface - */ public function getForm( Request $request, bool $forceExpanded = false, - bool $prefix = true + bool $prefix = true, ): FormInterface { $defaults = $request->query->all(); if ($prefix) { @@ -54,6 +49,7 @@ public function getForm( } else { $name = ''; } + return $this->formFactory->createNamed($name, CustomFormsType::class, $defaults, [ 'customForm' => $this->customForm, 'forceExpanded' => $forceExpanded, @@ -64,16 +60,12 @@ public function getForm( * Create or update custom-form answer and its attributes from * a submitted form data. * - * @param FormInterface $form - * @param CustomFormAnswer|null $answer - * @param string $ipAddress - * @return CustomFormAnswer * @throws FilesystemException */ public function parseAnswerFormData( FormInterface $form, - CustomFormAnswer $answer = null, - string $ipAddress = "" + ?CustomFormAnswer $answer = null, + string $ipAddress = '', ): CustomFormAnswer { if (!$form->isSubmitted()) { throw new \InvalidArgumentException('Form must be submitted before begin parsing.'); @@ -102,7 +94,7 @@ public function parseAnswerFormData( /* * Get data in form groups */ - if ($customFormField->getGroupName() != '') { + if ('' != $customFormField->getGroupName()) { $groupCanonical = StringHandler::slugify($customFormField->getGroupName()); $formGroup = $form->get($groupCanonical); if ($formGroup->has($customFormField->getName())) { @@ -156,23 +148,21 @@ public function parseAnswerFormData( } /** - * @param UploadedFile $file - * @param CustomFormFieldAttribute $fieldAttr - * @return DocumentInterface|null * @throws FilesystemException * @throws \Exception */ protected function handleUploadedFile( UploadedFile $file, - CustomFormFieldAttribute $fieldAttr + CustomFormFieldAttribute $fieldAttr, ): ?DocumentInterface { $this->documentFactory->setFile($file); $this->documentFactory->setFolder($this->getDocumentFolderForCustomForm()); $document = $this->documentFactory->getDocument(); if (null !== $document) { $fieldAttr->getDocuments()->add($document); - $fieldAttr->setValue($fieldAttr->getValue() . ', ' . $file->getPathname()); + $fieldAttr->setValue($fieldAttr->getValue().', '.$file->getPathname()); } + return $document; } @@ -180,8 +170,8 @@ protected function getDocumentFolderForCustomForm(): ?Folder { return $this->em->getRepository(Folder::class) ->findOrCreateByPath( - 'custom_forms/' . - $this->customForm->getCreatedAt()->format('Ymd') . '_' . + 'custom_forms/'. + $this->customForm->getCreatedAt()->format('Ymd').'_'. \mb_substr($this->customForm->getDisplayName(), 0, 30) ); } @@ -194,17 +184,13 @@ private function formValueToString(mixed $rawValue): string $values = $rawValue; $values = array_map('trim', $values); $values = array_map('strip_tags', $values); + return implode(static::ARRAY_SEPARATOR, $values); } else { return strip_tags((string) $rawValue); } } - /** - * @param CustomFormAnswer $answer - * @param CustomFormField $field - * @return CustomFormFieldAttribute|null - */ private function getAttribute(CustomFormAnswer $answer, CustomFormField $field): ?CustomFormFieldAttribute { return $this->em->getRepository(CustomFormFieldAttribute::class)->findOneBy([ diff --git a/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelperFactory.php b/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelperFactory.php index 0de6b420..6d031703 100644 --- a/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelperFactory.php +++ b/lib/RoadizCoreBundle/src/CustomForm/CustomFormHelperFactory.php @@ -16,7 +16,7 @@ public function __construct( private readonly PrivateDocumentFactory $privateDocumentFactory, private readonly ObjectManager $em, private readonly FormFactoryInterface $formFactory, - private readonly EventDispatcherInterface $eventDispatcher + private readonly EventDispatcherInterface $eventDispatcher, ) { } diff --git a/lib/RoadizCoreBundle/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php b/lib/RoadizCoreBundle/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php index ce56e283..fd65e172 100644 --- a/lib/RoadizCoreBundle/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php +++ b/lib/RoadizCoreBundle/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php @@ -12,7 +12,7 @@ public function __construct( private readonly int $customFormAnswerId, private readonly string $title, private readonly string $senderAddress, - private readonly string $locale + private readonly string $locale, ) { } diff --git a/lib/RoadizCoreBundle/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php b/lib/RoadizCoreBundle/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php index 2e03ac0f..7a72f1df 100644 --- a/lib/RoadizCoreBundle/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php +++ b/lib/RoadizCoreBundle/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php @@ -44,8 +44,8 @@ public function __invoke(CustomFormAnswerNotifyMessage $message): void } $emailFields = [ - ["name" => "ip.address", "value" => $answer->getIp()], - ["name" => "submittedAt", "value" => $answer->getSubmittedAt()->format('Y-m-d H:i:s')], + ['name' => 'ip.address', 'value' => $answer->getIp()], + ['name' => 'submittedAt', 'value' => $answer->getSubmittedAt()->format('Y-m-d H:i:s')], ]; $emailFields = array_merge( $emailFields, @@ -72,6 +72,7 @@ private function getCustomFormReceivers(CustomFormAnswer $answer): array $receiver = array_filter( array_map('trim', explode(',', $answer->getCustomForm()->getEmail() ?? '')) ); + return array_map(function (string $email) { return new Address($email); }, $receiver); @@ -80,8 +81,6 @@ private function getCustomFormReceivers(CustomFormAnswer $answer): array /** * Send an answer form by Email. * - * @param CustomFormAnswer $answer - * @param array $assignation * @throws TransportExceptionInterface * @throws LoaderError * @throws RuntimeError @@ -89,7 +88,7 @@ private function getCustomFormReceivers(CustomFormAnswer $answer): array */ private function sendAnswer( CustomFormAnswer $answer, - array $assignation + array $assignation, ): void { $defaultSender = $this->settingsBag->get('email_sender'); $defaultSender = filter_var($defaultSender, FILTER_VALIDATE_EMAIL) ? $defaultSender : 'sender@roadiz.io'; @@ -121,7 +120,7 @@ private function sendAnswer( } } catch (FilesystemException $exception) { $this->messengerLogger->error($exception->getMessage(), [ - 'entity' => $answer + 'entity' => $answer, ]); } diff --git a/lib/RoadizCoreBundle/src/DataCollector/RequestDataCollector.php b/lib/RoadizCoreBundle/src/DataCollector/RequestDataCollector.php index aee3b26b..28a170f5 100644 --- a/lib/RoadizCoreBundle/src/DataCollector/RequestDataCollector.php +++ b/lib/RoadizCoreBundle/src/DataCollector/RequestDataCollector.php @@ -12,7 +12,7 @@ #[AutoconfigureTag('data_collector', [ 'template' => '@RoadizCore/DataCollector/request.html.twig', - # must match the value returned by the getName() method + // must match the value returned by the getName() method 'id' => 'roadiz.data_collector.request', 'priority' => 400, ])] @@ -22,17 +22,14 @@ public function __construct( #[Autowire('%roadiz_core.cms_version%')] private readonly string $cmsVersion, #[Autowire('%roadiz_core.cms_version_prefix%')] - private readonly string $cmsVersionPrefix + private readonly string $cmsVersionPrefix, ) { } - /** - * {@inheritdoc} - */ - public function collect(Request $request, Response $response, \Throwable $exception = null): void + public function collect(Request $request, Response $response, ?\Throwable $exception = null): void { $this->data = [ - 'version' => implode(' - ', [$this->cmsVersionPrefix, $this->cmsVersion]) + 'version' => implode(' - ', [$this->cmsVersionPrefix, $this->cmsVersion]), ]; } @@ -41,9 +38,6 @@ public function getVersion(): string return $this->data['version'] ?? ''; } - /** - * {@inheritdoc} - */ public function getName(): string { return 'roadiz.data_collector.request'; diff --git a/lib/RoadizCoreBundle/src/DataCollector/SolariumLogger.php b/lib/RoadizCoreBundle/src/DataCollector/SolariumLogger.php index 8de222d6..555396e7 100644 --- a/lib/RoadizCoreBundle/src/DataCollector/SolariumLogger.php +++ b/lib/RoadizCoreBundle/src/DataCollector/SolariumLogger.php @@ -25,7 +25,7 @@ */ #[AutoconfigureTag('data_collector', [ 'template' => '@RoadizCore/DataCollector/solarium.html.twig', - # must match the value returned by the getName() method + // must match the value returned by the getName() method 'id' => 'solarium', ])] #[AutoconfigureTag('monolog.logger', [ @@ -41,7 +41,7 @@ final class SolariumLogger extends SolariumPlugin implements DataCollectorInterf public function __construct( private readonly LoggerInterface $searchEngineLogger, - private readonly Stopwatch $stopwatch + private readonly Stopwatch $stopwatch, ) { parent::__construct(); } @@ -58,17 +58,17 @@ public function log( SolariumRequest $request, ?SolariumResponse $response, SolariumEndpoint $endpoint, - float $duration + float $duration, ): void { - $this->queries[] = array( + $this->queries[] = [ 'request' => $request, 'response' => $response, 'duration' => $duration, 'base_uri' => $this->getEndpointBaseUrl($endpoint), - ); + ]; } - public function collect(HttpRequest $request, HttpResponse $response, \Throwable $exception = null): void + public function collect(HttpRequest $request, HttpResponse $response, ?\Throwable $exception = null): void { if (isset($this->currentRequest)) { $this->failCurrentRequest(); @@ -78,10 +78,10 @@ public function collect(HttpRequest $request, HttpResponse $response, \Throwable foreach ($this->queries as $queryStruct) { $time += $queryStruct['duration']; } - $this->data = array( - 'queries' => $this->queries, - 'total_time' => $time, - ); + $this->data = [ + 'queries' => $this->queries, + 'total_time' => $time, + ]; } public function getName(): string @@ -114,7 +114,7 @@ public function preExecuteRequest(SolariumPreExecuteRequestEvent $event): void $this->currentRequest = $event->getRequest(); $this->currentEndpoint = $event->getEndpoint(); - $this->searchEngineLogger->debug($this->getEndpointBaseUrl($this->currentEndpoint) . $this->currentRequest->getUri()); + $this->searchEngineLogger->debug($this->getEndpointBaseUrl($this->currentEndpoint).$this->currentRequest->getUri()); $this->currentStartTime = microtime(true); } diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/CommonMarkCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/CommonMarkCompilerPass.php index fc540e8c..7c24a3d2 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/CommonMarkCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/CommonMarkCompilerPass.php @@ -10,9 +10,6 @@ class CommonMarkCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->has('roadiz_core.markdown.environments.text_converter')) { @@ -40,7 +37,7 @@ public function process(ContainerBuilder $container): void foreach ($taggedServices as $id => $tags) { $definition->addMethodCall( 'addExtension', - array(new Reference($id)) + [new Reference($id)] ); } } @@ -55,7 +52,7 @@ public function process(ContainerBuilder $container): void foreach ($taggedServices as $id => $tags) { $definition->addMethodCall( 'addExtension', - array(new Reference($id)) + [new Reference($id)] ); } } diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php index 4a4a5a29..7609a4ee 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php @@ -4,15 +4,11 @@ namespace RZ\Roadiz\CoreBundle\DependencyInjection\Compiler; -use RuntimeException; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class DoctrineMigrationCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->hasDefinition('doctrine.migrations.configuration')) { @@ -27,11 +23,12 @@ public function process(ContainerBuilder $container): void private function checkIfBundleRelativePath(string $path, ContainerBuilder $container): string { - if (isset($path[0]) && $path[0] === '@') { - $pathParts = explode('/', $path); + if (isset($path[0]) && '@' === $path[0]) { + $pathParts = explode('/', $path); $bundleName = \mb_substr($pathParts[0], 1); $bundlePath = $this->getBundlePath($bundleName, $container); - return $bundlePath . \mb_substr($path, \mb_strlen('@' . $bundleName)); + + return $bundlePath.\mb_substr($path, \mb_strlen('@'.$bundleName)); } return $path; @@ -42,12 +39,8 @@ private function getBundlePath(string $bundleName, ContainerBuilder $container): $bundleMetadata = $container->getParameter('kernel.bundles_metadata'); assert(is_array($bundleMetadata)); - if (! isset($bundleMetadata[$bundleName])) { - throw new RuntimeException(sprintf( - 'The bundle "%s" has not been registered, available bundles: %s', - $bundleName, - implode(', ', array_keys($bundleMetadata)) - )); + if (!isset($bundleMetadata[$bundleName])) { + throw new \RuntimeException(sprintf('The bundle "%s" has not been registered, available bundles: %s', $bundleName, implode(', ', array_keys($bundleMetadata)))); } return $bundleMetadata[$bundleName]['path']; diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DocumentRendererCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DocumentRendererCompilerPass.php index 80542056..ecf0ac81 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DocumentRendererCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/DocumentRendererCompilerPass.php @@ -13,9 +13,6 @@ class DocumentRendererCompilerPass implements CompilerPassInterface { use PriorityTaggedServiceTrait; - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->has(ChainRenderer::class)) { diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/FlysystemStorageCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/FlysystemStorageCompilerPass.php index b4f53aae..7e833e8f 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/FlysystemStorageCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/FlysystemStorageCompilerPass.php @@ -19,11 +19,11 @@ protected function getStorageReference( ContainerBuilder $container, string $storageName, array $storageConfig, - ?string $publicUrl = null + ?string $publicUrl = null, ): Reference { if (!$container->hasDefinition($storageName)) { $definitionFactory = new AdapterDefinitionFactory(); - $adapterName = 'flysystem.adapter.' . $storageName; + $adapterName = 'flysystem.adapter.'.$storageName; if ($adapter = $definitionFactory->createDefinition('local', $storageConfig['options'])) { $container->setDefinition($adapterName, $adapter)->setPublic(false); $container->setDefinition( @@ -32,6 +32,7 @@ protected function getStorageReference( ); } } + return new Reference($storageName); } @@ -54,9 +55,6 @@ protected function getDocumentPrivateStorage(ContainerBuilder $container): Refer ); } - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { $container->setDefinition( diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/ImporterCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/ImporterCompilerPass.php index b2de17cc..08fed012 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/ImporterCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/ImporterCompilerPass.php @@ -11,9 +11,6 @@ class ImporterCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->has(ChainImporter::class)) { diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/MediaFinderCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/MediaFinderCompilerPass.php index ee69f857..38344fb6 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/MediaFinderCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/MediaFinderCompilerPass.php @@ -9,9 +9,6 @@ class MediaFinderCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->hasParameter('roadiz_core.medias.supported_platforms')) { diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/NodesSourcesEntitiesPathCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/NodesSourcesEntitiesPathCompilerPass.php index 037afe46..849facef 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/NodesSourcesEntitiesPathCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/NodesSourcesEntitiesPathCompilerPass.php @@ -9,17 +9,14 @@ class NodesSourcesEntitiesPathCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { $projectDir = $container->getParameter('kernel.project_dir'); if (!\is_string($projectDir)) { throw new \RuntimeException('kernel.project_dir parameter must be a string.'); } - $container->setParameter('roadiz_core.generated_entities_dir', $projectDir . '/src/GeneratedEntity'); - $container->setParameter('roadiz_core.serialized_node_types_dir', $projectDir . '/src/Resources/node-types'); - $container->setParameter('roadiz_core.import_files_config_path', $projectDir . '/src/Resources/config.yml'); + $container->setParameter('roadiz_core.generated_entities_dir', $projectDir.'/src/GeneratedEntity'); + $container->setParameter('roadiz_core.serialized_node_types_dir', $projectDir.'/src/Resources/node-types'); + $container->setParameter('roadiz_core.import_files_config_path', $projectDir.'/src/Resources/config.yml'); } } diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/PathResolverCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/PathResolverCompilerPass.php index aff479f2..d94474cd 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/PathResolverCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/PathResolverCompilerPass.php @@ -6,16 +6,13 @@ use RZ\Roadiz\CoreBundle\Routing\ChainResourcePathResolver; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait; +use Symfony\Component\DependencyInjection\ContainerBuilder; class PathResolverCompilerPass implements CompilerPassInterface { use PriorityTaggedServiceTrait; - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->has(ChainResourcePathResolver::class)) { diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/RateLimitersCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/RateLimitersCompilerPass.php index d619971c..bdd67acb 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/RateLimitersCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/RateLimitersCompilerPass.php @@ -26,14 +26,14 @@ public function process(ContainerBuilder $container): void 'cache_pool' => 'cache.rate_limiter', 'policy' => 'token_bucket', 'limit' => 1, - 'rate' => [ 'interval' => '10 seconds'], + 'rate' => ['interval' => '10 seconds'], ]; $limiter = $container->setDefinition( - $limiterId = 'limiter.' . $name, + $limiterId = 'limiter.'.$name, new ChildDefinition('limiter') ); $container->register( - $storageId = 'limiter.storage.' . $name, + $storageId = 'limiter.storage.'.$name, CacheStorage::class )->addArgument(new Reference($limiterConfig['cache_pool'])); @@ -41,6 +41,6 @@ public function process(ContainerBuilder $container): void unset($limiterConfig['cache_pool']); $limiterConfig['id'] = $name; $limiter->replaceArgument(0, $limiterConfig); - $container->registerAliasForArgument($limiterId, RateLimiterFactory::class, $name . '.limiter'); + $container->registerAliasForArgument($limiterId, RateLimiterFactory::class, $name.'.limiter'); } } diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TreeWalkerDefinitionFactoryCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TreeWalkerDefinitionFactoryCompilerPass.php index b8c0d188..1a142ee7 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TreeWalkerDefinitionFactoryCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TreeWalkerDefinitionFactoryCompilerPass.php @@ -11,9 +11,6 @@ class TreeWalkerDefinitionFactoryCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->has(TreeWalkerGenerator::class)) { @@ -32,7 +29,7 @@ public function process(ContainerBuilder $container): void [ $tag['classname'], new Reference($serviceId), - $tag['onlyVisible'] ?? true + $tag['onlyVisible'] ?? true, ] ); } diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TwigLoaderCompilerPass.php b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TwigLoaderCompilerPass.php index a59480e1..ab0b250f 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TwigLoaderCompilerPass.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Compiler/TwigLoaderCompilerPass.php @@ -12,16 +12,13 @@ class TwigLoaderCompilerPass implements CompilerPassInterface { use PriorityTaggedServiceTrait; - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->has('twig.loader.native_filesystem')) { $definition = $container->findDefinition('twig.loader.native_filesystem'); $definition->addMethodCall( 'prependPath', - [ realpath(dirname(__DIR__) . '/../../templates/ApiPlatformBundle'), 'ApiPlatform' ] + [realpath(dirname(__DIR__).'/../../templates/ApiPlatformBundle'), 'ApiPlatform'] ); } } diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/Configuration.php b/lib/RoadizCoreBundle/src/DependencyInjection/Configuration.php index 7f5e8948..1cbf4f65 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/Configuration.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/Configuration.php @@ -81,6 +81,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->append($this->addReverseProxyCacheNode()) ->append($this->addMediasNode()) ; + return $builder; } @@ -105,12 +106,13 @@ classes table(s). BE CAREFUL, if you change this ->validate() ->ifNotInArray([ static::INHERITANCE_TYPE_JOINED, - static::INHERITANCE_TYPE_SINGLE_TABLE + static::INHERITANCE_TYPE_SINGLE_TABLE, ]) ->thenInvalid('The %s inheritance type is not supported ("joined", "single_table" are accepted).') ->end() ->end() ; + return $node; } diff --git a/lib/RoadizCoreBundle/src/DependencyInjection/RoadizCoreExtension.php b/lib/RoadizCoreBundle/src/DependencyInjection/RoadizCoreExtension.php index 2aeab2b7..71959864 100644 --- a/lib/RoadizCoreBundle/src/DependencyInjection/RoadizCoreExtension.php +++ b/lib/RoadizCoreBundle/src/DependencyInjection/RoadizCoreExtension.php @@ -44,12 +44,9 @@ public function getAlias(): string return 'roadiz_core'; } - /** - * @inheritDoc - */ public function load(array $configs, ContainerBuilder $container): void { - $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__) . '/../config')); + $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__).'/../config')); $loader->load('services.yaml'); $configuration = new Configuration(); @@ -84,7 +81,7 @@ public function load(array $configs, ContainerBuilder $container): void $projectDir = $container->getParameter('kernel.project_dir'); $container->setParameter( 'roadiz_core.documents_lib_dir', - $projectDir . DIRECTORY_SEPARATOR . trim($config['documentsLibDir'], "/ \t\n\r\0\x0B") + $projectDir.DIRECTORY_SEPARATOR.trim($config['documentsLibDir'], "/ \t\n\r\0\x0B") ); /* * Media config @@ -132,7 +129,7 @@ private function registerReverseProxyCache(array $config, ContainerBuilder $cont $reverseProxyCacheFrontendsReferences = []; if (isset($config['reverseProxyCache'])) { foreach ($config['reverseProxyCache']['frontend'] as $name => $frontend) { - $definitionName = 'roadiz_core.reverse_proxy_cache.frontends.' . $name; + $definitionName = 'roadiz_core.reverse_proxy_cache.frontends.'.$name; $container->setDefinition( $definitionName, (new Definition()) @@ -149,8 +146,8 @@ private function registerReverseProxyCache(array $config, ContainerBuilder $cont } if ( - isset($config['reverseProxyCache']['cloudflare']) && - isset($config['reverseProxyCache']['cloudflare']['bearer']) + isset($config['reverseProxyCache']['cloudflare']) + && isset($config['reverseProxyCache']['cloudflare']['bearer']) ) { $container->setDefinition( 'roadiz_core.reverse_proxy_cache.cloudflare', @@ -180,7 +177,7 @@ private function registerReverseProxyCache(array $config, ContainerBuilder $cont new Reference( 'roadiz_core.reverse_proxy_cache.cloudflare', ContainerInterface::NULL_ON_INVALID_REFERENCE - ) + ), ]) ); } @@ -217,16 +214,16 @@ private function registerSolr(array $config, ContainerBuilder $container): void if (isset($config['solr'])) { foreach ($config['solr']['endpoints'] as $name => $endpoint) { $container->setDefinition( - 'roadiz_core.solr.endpoints.' . $name, + 'roadiz_core.solr.endpoints.'.$name, (new Definition()) ->setClass(Endpoint::class) ->setPublic(true) ->setArguments([ - $endpoint + $endpoint, ]) ->addMethodCall('setKey', [$name]) ); - $solrEndpoints[] = 'roadiz_core.solr.endpoints.' . $name; + $solrEndpoints[] = 'roadiz_core.solr.endpoints.'.$name; } } if (count($solrEndpoints) > 0) { @@ -240,7 +237,7 @@ private function registerSolr(array $config, ContainerBuilder $container): void ->setShared(true) ->setArguments([ new Reference('roadiz_core.solr.adapter'), - new Reference(EventDispatcherInterface::class) + new Reference(EventDispatcherInterface::class), ]) ->addMethodCall('registerPlugin', ['roadiz_core.solr.client.logger', $logger]) ->addMethodCall('setEndpoints', [array_map(function (string $endpointId) { @@ -258,26 +255,26 @@ private function registerMarkdown(array $config, ContainerBuilder $container): v 'open_in_new_window' => true, 'noopener' => 'external', 'noreferrer' => 'external', - ] + ], ]); /** @var array $defaultConfig */ $defaultConfig = $container->getParameter('roadiz_core.markdown_config_default'); $container->setParameter( 'roadiz_core.markdown_config_text_converter', array_merge($defaultConfig, [ - 'html_input' => 'allow' + 'html_input' => 'allow', ]) ); $container->setParameter( 'roadiz_core.markdown_config_text_extra_converter', array_merge($defaultConfig, [ - 'html_input' => 'allow' + 'html_input' => 'allow', ]) ); $container->setParameter( 'roadiz_core.markdown_config_line_converter', array_merge($defaultConfig, [ - 'html_input' => 'escape' + 'html_input' => 'escape', ]) ); @@ -299,7 +296,7 @@ private function registerMarkdown(array $config, ContainerBuilder $container): v ->setShared(true) ->setPublic(true) ->setArguments([ - new Reference('roadiz_core.markdown.environments.text_converter') + new Reference('roadiz_core.markdown.environments.text_converter'), ]) ); @@ -321,7 +318,7 @@ private function registerMarkdown(array $config, ContainerBuilder $container): v ->setShared(true) ->setPublic(true) ->setArguments([ - new Reference('roadiz_core.markdown.environments.text_extra_converter') + new Reference('roadiz_core.markdown.environments.text_extra_converter'), ]) ); @@ -343,7 +340,7 @@ private function registerMarkdown(array $config, ContainerBuilder $container): v ->setShared(true) ->setPublic(true) ->setArguments([ - new Reference('roadiz_core.markdown.environments.line_converter') + new Reference('roadiz_core.markdown.environments.line_converter'), ]) ); diff --git a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterNodesSourcesQueryBuilderCriteriaEvent.php b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterNodesSourcesQueryBuilderCriteriaEvent.php index ee8da9b0..5337a9d1 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterNodesSourcesQueryBuilderCriteriaEvent.php +++ b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterNodesSourcesQueryBuilderCriteriaEvent.php @@ -5,28 +5,26 @@ namespace RZ\Roadiz\CoreBundle\Doctrine\Event; use Doctrine\ORM\QueryBuilder; -use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderBuildEvent; +use RZ\Roadiz\CoreBundle\Entity\NodesSources; -/** - * @package RZ\Roadiz\CoreBundle\Doctrine\Event - */ abstract class FilterNodesSourcesQueryBuilderCriteriaEvent extends QueryBuilderBuildEvent { /** - * @inheritDoc + * @param class-string $actualEntityName */ - public function __construct(QueryBuilder $queryBuilder, $property, $value, $actualEntityName) - { + public function __construct( + QueryBuilder $queryBuilder, + string $property, + mixed $value, + string $actualEntityName, + ) { parent::__construct($queryBuilder, NodesSources::class, $property, $value, $actualEntityName); } - /** - * @inheritDoc - */ public function supports(): bool { - if ($this->actualEntityName === NodesSources::class) { + if (NodesSources::class === $this->actualEntityName) { return true; } diff --git a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderCriteriaEvent.php b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderCriteriaEvent.php index 974ff248..3e056d90 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderCriteriaEvent.php +++ b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderCriteriaEvent.php @@ -7,88 +7,49 @@ use Doctrine\ORM\QueryBuilder; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Doctrine\Event - */ abstract class FilterQueryBuilderCriteriaEvent extends Event { - protected string $property; /** - * @var mixed - */ - protected $value; - protected QueryBuilder $queryBuilder; - /** - * @var class-string - */ - protected string $entityClass; - /** - * @var class-string - */ - protected string $actualEntityName; - - /** - * @param QueryBuilder $queryBuilder * @param class-string $entityClass - * @param string $property - * @param mixed $value * @param class-string $actualEntityName */ - public function __construct(QueryBuilder $queryBuilder, string $entityClass, string $property, $value, string $actualEntityName) - { - $this->queryBuilder = $queryBuilder; - $this->entityClass = $entityClass; - $this->property = $property; - $this->value = $value; - $this->actualEntityName = $actualEntityName; + public function __construct( + protected QueryBuilder $queryBuilder, + protected string $entityClass, + protected string $property, + protected mixed $value, + protected string $actualEntityName, + ) { } - /** - * @return QueryBuilder - */ public function getQueryBuilder(): QueryBuilder { return $this->queryBuilder; } - /** - * @param QueryBuilder $queryBuilder - * @return FilterQueryBuilderCriteriaEvent - */ public function setQueryBuilder(QueryBuilder $queryBuilder): self { $this->queryBuilder = $queryBuilder; + return $this; } - /** - * @return string - */ - public function getProperty() + public function supports(): bool { - return $this->property; + return $this->entityClass === $this->actualEntityName; } - /** - * @return mixed - */ - public function getValue() + public function getProperty(): string { - return $this->value; + return $this->property; } - /** - * @return bool - */ - public function supports(): bool + public function getValue(): mixed { - return $this->entityClass === $this->actualEntityName; + return $this->value; } - /** - * @return string - */ - public function getActualEntityName() + public function getActualEntityName(): string { return $this->actualEntityName; } diff --git a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderEvent.php b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderEvent.php index 202811ca..a3aa4c20 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderEvent.php +++ b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryBuilderEvent.php @@ -7,52 +7,32 @@ use Doctrine\ORM\QueryBuilder; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Doctrine\Event - */ abstract class FilterQueryBuilderEvent extends Event { /** - * @var QueryBuilder - */ - private QueryBuilder $queryBuilder; - /** - * @var class-string - */ - private string $entityClass; - - /** - * @param QueryBuilder $queryBuilder * @param class-string $entityClass */ - public function __construct(QueryBuilder $queryBuilder, string $entityClass) + public function __construct(private QueryBuilder $queryBuilder, private readonly string $entityClass) { - $this->queryBuilder = $queryBuilder; - $this->entityClass = $entityClass; } - /** - * @return QueryBuilder - */ public function getQueryBuilder(): QueryBuilder { return $this->queryBuilder; } /** - * @param QueryBuilder $queryBuilder * @return FilterQueryBuilderEvent */ public function setQueryBuilder(QueryBuilder $queryBuilder) { $this->queryBuilder = $queryBuilder; + return $this; } - /** * @param class-string $entityClass - * @return bool */ public function supports(string $entityClass): bool { diff --git a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryCriteriaEvent.php b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryCriteriaEvent.php index baa4f5c5..23b761e4 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryCriteriaEvent.php +++ b/lib/RoadizCoreBundle/src/Doctrine/Event/FilterQueryCriteriaEvent.php @@ -10,78 +10,46 @@ abstract class FilterQueryCriteriaEvent extends Event { /** - * @var string - */ - protected string $property; - /** - * @var mixed - */ - protected $value; - /** - * @var class-string - */ - protected string $entityClass; - /** - * @var Query - */ - protected Query $query; - - /** - * @param Query $query * @param class-string $entityClass - * @param string $property - * @param mixed $value */ - public function __construct(Query $query, string $entityClass, string $property, $value) + public function __construct(protected Query $query, protected string $entityClass, protected string $property, protected mixed $value) { - $this->entityClass = $entityClass; - $this->property = $property; - $this->value = $value; - $this->query = $query; } - /** - * @return Query - */ public function getQuery(): Query { return $this->query; } /** - * @param Query $query - * - * @return FilterQueryCriteriaEvent + * @return $this */ - public function setQuery(Query $query) + public function setQuery(Query $query): self { $this->query = $query; return $this; } - /** - * @return string - */ - public function getProperty() + public function getEntityClass(): string + { + return $this->entityClass; + } + + public function getProperty(): string { return $this->property; } - /** - * @return mixed - */ - public function getValue() + public function getValue(): mixed { return $this->value; } - /** - * @param string $entityClass - * @return bool + * @param class-string $entityClass */ - public function supports($entityClass): bool + public function supports(string $entityClass): bool { return $this->entityClass === $entityClass; } diff --git a/lib/RoadizCoreBundle/src/Doctrine/Event/QueryEvent.php b/lib/RoadizCoreBundle/src/Doctrine/Event/QueryEvent.php index dc85f161..ce966683 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/Event/QueryEvent.php +++ b/lib/RoadizCoreBundle/src/Doctrine/Event/QueryEvent.php @@ -9,26 +9,13 @@ class QueryEvent extends Event { - protected Query $query; - - /** - * @var class-string - */ - protected string $entityClass; - /** - * @param Query $query * @param class-string $entityClass */ - public function __construct(Query $query, string $entityClass) + public function __construct(protected Query $query, protected string $entityClass) { - $this->query = $query; - $this->entityClass = $entityClass; } - /** - * @return Query - */ public function getQuery(): Query { return $this->query; diff --git a/lib/RoadizCoreBundle/src/Doctrine/Event/QueryNodesSourcesEvent.php b/lib/RoadizCoreBundle/src/Doctrine/Event/QueryNodesSourcesEvent.php index 07999c22..8ec8187f 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/Event/QueryNodesSourcesEvent.php +++ b/lib/RoadizCoreBundle/src/Doctrine/Event/QueryNodesSourcesEvent.php @@ -10,7 +10,6 @@ final class QueryNodesSourcesEvent extends QueryEvent { /** - * @param Query $query * @param class-string $actualEntityName */ public function __construct(Query $query, private readonly string $actualEntityName) @@ -27,12 +26,11 @@ public function getActualEntityName(): string } /** - * @return bool * @throws \ReflectionException */ public function supports(): bool { - if ($this->actualEntityName === NodesSources::class) { + if (NodesSources::class === $this->actualEntityName) { return true; } diff --git a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php index 9061b4cf..96c1fdd2 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php +++ b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\CoreBundle\Doctrine\EventSubscriber; -use ArrayIterator; use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener; use Doctrine\ORM\Event\OnFlushEventArgs; use Doctrine\Persistence\Event\LifecycleEventArgs; @@ -15,16 +14,13 @@ #[AsDoctrineListener('onFlush')] final class AttributeValueLifeCycleSubscriber { - /** - * @param LifecycleEventArgs $event - */ public function prePersist(LifecycleEventArgs $event): void { $entity = $event->getObject(); if ($entity instanceof AttributeValueInterface) { if ( - null !== $entity->getAttribute() && - null !== $entity->getAttribute()->getDefaultRealm() + null !== $entity->getAttribute() + && null !== $entity->getAttribute()->getDefaultRealm() ) { $entity->setRealm($entity->getAttribute()->getDefaultRealm()); } @@ -32,7 +28,7 @@ public function prePersist(LifecycleEventArgs $event): void /* * Automatically set position only if not manually set before. */ - if ($entity->getPosition() === 0.0) { + if (0.0 === $entity->getPosition()) { /* * Get the last index after last node in parent */ @@ -40,7 +36,7 @@ public function prePersist(LifecycleEventArgs $event): void $lastPosition = 1; foreach ($nodeAttributes as $nodeAttribute) { $nodeAttribute->setPosition($lastPosition); - $lastPosition++; + ++$lastPosition; } $entity->setPosition($lastPosition); @@ -49,8 +45,6 @@ public function prePersist(LifecycleEventArgs $event): void } /** - * @param OnFlushEventArgs $eventArgs - * * @throws \Exception */ public function onFlush(OnFlushEventArgs $eventArgs): void @@ -62,13 +56,13 @@ public function onFlush(OnFlushEventArgs $eventArgs): void if ($entity instanceof AttributeValueInterface) { $classMetadata = $em->getClassMetadata(AttributeValue::class); foreach ($uow->getEntityChangeSet($entity) as $keyField => $field) { - if ($keyField === 'position') { + if ('position' === $keyField) { $nodeAttributes = $entity->getAttributable()->getAttributeValues(); /* * Need to resort collection based on updated position. */ $iterator = $nodeAttributes->getIterator(); - if ($iterator instanceof ArrayIterator) { + if ($iterator instanceof \ArrayIterator) { // define ordering closure, using preferred comparison method/field $iterator->uasort(function (AttributeValueInterface $first, AttributeValueInterface $second) { return $first->getPosition() > $second->getPosition() ? 1 : -1; @@ -80,7 +74,7 @@ public function onFlush(OnFlushEventArgs $eventArgs): void foreach ($iterator as $nodeAttribute) { $nodeAttribute->setPosition($lastPosition); $uow->computeChangeSet($classMetadata, $nodeAttribute); - $lastPosition++; + ++$lastPosition; } } } diff --git a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php index 07729514..15c56304 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php +++ b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php @@ -16,9 +16,6 @@ public function __construct(private readonly CustomFormFieldHandler $customFormF { } - /** - * @param LifecycleEventArgs $event - */ public function prePersist(LifecycleEventArgs $event): void { $field = $event->getObject(); @@ -26,7 +23,7 @@ public function prePersist(LifecycleEventArgs $event): void /* * Automatically set position only if not manually set before. */ - if ($field->getPosition() === 0.0) { + if (0.0 === $field->getPosition()) { /* * Get the last index after last node in parent */ diff --git a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php index 6f4d28cd..d5256b85 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php +++ b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php @@ -25,7 +25,7 @@ public function __construct( private readonly NodeTypes $nodeTypes, private readonly string $inheritanceType, private readonly LoggerInterface $logger, - private readonly Stopwatch $stopwatch + private readonly Stopwatch $stopwatch, ) { } @@ -46,7 +46,7 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void // obtained from the $metadata $class = $metadata->getReflectionClass(); - if ($class->getName() === NodesSources::class) { + if (NodesSources::class === $class->getName()) { $this->stopwatch->start('NodesSources loadClassMetadata'); try { /** @var NodeType[] $nodeTypes */ @@ -85,13 +85,13 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void 'ns_title_translation_published' => ['columns' => ['title', 'translation_id', 'published_at']], ], 'uniqueConstraints' => [ - ['columns' => ["node_id", "translation_id"]] - ] + ['columns' => ['node_id', 'translation_id']], + ], ]; - if ($this->inheritanceType === Configuration::INHERITANCE_TYPE_JOINED) { + if (Configuration::INHERITANCE_TYPE_JOINED === $this->inheritanceType) { $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_JOINED); - } elseif ($this->inheritanceType === Configuration::INHERITANCE_TYPE_SINGLE_TABLE) { + } elseif (Configuration::INHERITANCE_TYPE_SINGLE_TABLE === $this->inheritanceType) { $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE); /* * If inheritance type is single table, we need to set indexes on parent class: NodesSources @@ -102,13 +102,13 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void }); /** @var NodeTypeFieldInterface $indexedField */ foreach ($indexedFields as $indexedField) { - $nodeSourceTableAnnotation['indexes']['nsapp_' . $indexedField->getName()] = [ + $nodeSourceTableAnnotation['indexes']['nsapp_'.$indexedField->getName()] = [ 'columns' => [$indexedField->getName()], ]; } } } else { - throw new \RuntimeException('Inheritance type not supported: ' . $this->inheritanceType); + throw new \RuntimeException('Inheritance type not supported: '.$this->inheritanceType); } $metadata->setPrimaryTable($nodeSourceTableAnnotation); } catch (\Exception $e) { diff --git a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php index 1d8dd0c7..7b1dcb55 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php +++ b/lib/RoadizCoreBundle/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php @@ -27,20 +27,19 @@ #[AsDoctrineListener(event: Events::postPersist)] #[AsDoctrineListener(event: Events::postUpdate)] #[AsDoctrineListener(event: Events::postRemove)] -final class UserLifeCycleSubscriber +final readonly class UserLifeCycleSubscriber { public function __construct( - private readonly UserViewer $userViewer, - private readonly EventDispatcherInterface $dispatcher, - private readonly PasswordHasherFactoryInterface $passwordHasherFactory, - private readonly LoggerInterface $logger, - private readonly bool $useGravatar + private UserViewer $userViewer, + private EventDispatcherInterface $dispatcher, + private PasswordHasherFactoryInterface $passwordHasherFactory, + private FacebookPictureFinder $facebookPictureFinder, + private LoggerInterface $logger, + private bool $useGravatar, ) { } /** - * @param PreUpdateEventArgs $event - * @return void * @throws \GuzzleHttp\Exception\GuzzleException */ public function preUpdate(PreUpdateEventArgs $event): void @@ -48,16 +47,16 @@ public function preUpdate(PreUpdateEventArgs $event): void $user = $event->getObject(); if ($user instanceof User) { if ( - $event->hasChangedField('enabled') && - true === $event->getNewValue('enabled') + $event->hasChangedField('enabled') + && true === $event->getNewValue('enabled') ) { $userEvent = new UserEnabledEvent($user); $this->dispatcher->dispatch($userEvent); } if ( - $event->hasChangedField('enabled') && - false === $event->getNewValue('enabled') + $event->hasChangedField('enabled') + && false === $event->getNewValue('enabled') ) { $userEvent = new UserDisabledEvent($user); $this->dispatcher->dispatch($userEvent); @@ -66,8 +65,7 @@ public function preUpdate(PreUpdateEventArgs $event): void if ($event->hasChangedField('facebookName')) { if ('' != $event->getNewValue('facebookName')) { try { - $facebook = new FacebookPictureFinder($user->getFacebookName()); - $url = $facebook->getPictureUrl(); + $url = $this->facebookPictureFinder->getPictureUrl($user->getFacebookName()); $user->setPictureUrl($url); } catch (\Exception $e) { $user->setFacebookName(''); @@ -83,9 +81,9 @@ public function preUpdate(PreUpdateEventArgs $event): void * Encode user password */ if ( - $event->hasChangedField('password') && - null !== $user->getPlainPassword() && - '' !== $user->getPlainPassword() + $event->hasChangedField('password') + && null !== $user->getPlainPassword() + && '' !== $user->getPlainPassword() ) { $this->setPassword($user, $user->getPlainPassword()); $userEvent = new UserPasswordChangedEvent($user); @@ -94,10 +92,6 @@ public function preUpdate(PreUpdateEventArgs $event): void } } - /** - * @param User $user - * @param string|null $plainPassword - */ protected function setPassword(User $user, ?string $plainPassword): void { if (null !== $plainPassword) { @@ -107,9 +101,6 @@ protected function setPassword(User $user, ?string $plainPassword): void } } - /** - * @param LifecycleEventArgs $event - */ public function postUpdate(LifecycleEventArgs $event): void { $user = $event->getObject(); @@ -119,9 +110,6 @@ public function postUpdate(LifecycleEventArgs $event): void } } - /** - * @param LifecycleEventArgs $event - */ public function postRemove(LifecycleEventArgs $event): void { $user = $event->getObject(); @@ -132,8 +120,6 @@ public function postRemove(LifecycleEventArgs $event): void } /** - * @param LifecycleEventArgs $event - * * @throws \Exception */ public function postPersist(LifecycleEventArgs $event): void @@ -146,7 +132,6 @@ public function postPersist(LifecycleEventArgs $event): void } /** - * @param LifecycleEventArgs $event * @throws \Throwable */ public function prePersist(LifecycleEventArgs $event): void @@ -154,9 +139,9 @@ public function prePersist(LifecycleEventArgs $event): void $user = $event->getObject(); if ($user instanceof User) { if ( - $user->willSendCreationConfirmationEmail() && - (null === $user->getPlainPassword() || - $user->getPlainPassword() === '') + $user->willSendCreationConfirmationEmail() + && (null === $user->getPlainPassword() + || '' === $user->getPlainPassword()) ) { /* * Do not generate password for new users diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/ANodesFilter.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/ANodesFilter.php index ebfcb49e..5e654e85 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/ANodesFilter.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/ANodesFilter.php @@ -4,50 +4,38 @@ namespace RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter; -use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderBuildEvent; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderNodesSourcesBuildEvent; -use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use RZ\Roadiz\CoreBundle\Doctrine\ORM\SimpleQueryBuilder; +use RZ\Roadiz\CoreBundle\Entity\Node; +use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -/** - * @package RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter - */ class ANodesFilter implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ QueryBuilderNodesSourcesBuildEvent::class => [['onNodesSourcesQueryBuilderBuild', 40]], - QueryBuilderBuildEvent::class => [['onNodeQueryBuilderBuild', 30]] + QueryBuilderBuildEvent::class => [['onNodeQueryBuilderBuild', 30]], ]; } - /** - * @return string - */ protected function getProperty(): string { return 'aNodes'; } - /** - * @return string - */ protected function getNodeJoinAlias(): string { return 'a_n'; } - /** - * @param QueryBuilderBuildEvent $event - */ public function onNodeQueryBuilderBuild(QueryBuilderBuildEvent $event): void { - if ($event->supports() && $event->getActualEntityName() === Node::class) { + if ($event->supports() && Node::class === $event->getActualEntityName()) { $simpleQB = new SimpleQueryBuilder($event->getQueryBuilder()); - if (str_contains($event->getProperty(), $this->getProperty() . '.')) { + if (str_contains($event->getProperty(), $this->getProperty().'.')) { // Prevent other query builder filters to execute $event->stopPropagation(); $qb = $event->getQueryBuilder(); @@ -60,27 +48,24 @@ public function onNodeQueryBuilderBuild(QueryBuilderBuildEvent $event): void ) ) { $qb->innerJoin( - $simpleQB->getRootAlias() . '.' . $this->getProperty(), + $simpleQB->getRootAlias().'.'.$this->getProperty(), $this->getNodeJoinAlias() ); } - $prefix = $this->getNodeJoinAlias() . '.'; - $key = str_replace($this->getProperty() . '.', '', $event->getProperty()); + $prefix = $this->getNodeJoinAlias().'.'; + $key = str_replace($this->getProperty().'.', '', $event->getProperty()); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($event->getValue(), $prefix, $key, $baseKey)); } } } - /** - * @param QueryBuilderNodesSourcesBuildEvent $event - */ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEvent $event): void { if ($event->supports()) { $simpleQB = new SimpleQueryBuilder($event->getQueryBuilder()); - if (str_contains($event->getProperty(), 'node.' . $this->getProperty() . '.')) { + if (str_contains($event->getProperty(), 'node.'.$this->getProperty().'.')) { // Prevent other query builder filters to execute $event->stopPropagation(); $qb = $event->getQueryBuilder(); @@ -93,7 +78,7 @@ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEve ) ) { $qb->innerJoin( - $simpleQB->getRootAlias() . '.node', + $simpleQB->getRootAlias().'.node', EntityRepository::NODE_ALIAS ); } @@ -105,13 +90,13 @@ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEve ) ) { $qb->innerJoin( - EntityRepository::NODE_ALIAS . '.' . $this->getProperty(), + EntityRepository::NODE_ALIAS.'.'.$this->getProperty(), $this->getNodeJoinAlias() ); } - $prefix = $this->getNodeJoinAlias() . '.'; - $key = str_replace('node.' . $this->getProperty() . '.', '', $event->getProperty()); + $prefix = $this->getNodeJoinAlias().'.'; + $key = str_replace('node.'.$this->getProperty().'.', '', $event->getProperty()); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($event->getValue(), $prefix, $key, $baseKey)); } diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/BNodesFilter.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/BNodesFilter.php index 8cb6f894..4b15cb47 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/BNodesFilter.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/BNodesFilter.php @@ -7,30 +7,21 @@ use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderBuildEvent; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderNodesSourcesBuildEvent; -/** - * @package RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter - */ class BNodesFilter extends ANodesFilter { public static function getSubscribedEvents(): array { return [ QueryBuilderNodesSourcesBuildEvent::class => [['onNodesSourcesQueryBuilderBuild', 40]], - QueryBuilderBuildEvent::class => [['onNodeQueryBuilderBuild', 30]] + QueryBuilderBuildEvent::class => [['onNodeQueryBuilderBuild', 30]], ]; } - /** - * @return string - */ protected function getProperty(): string { return 'bNodes'; } - /** - * @return string - */ protected function getNodeJoinAlias(): string { return 'b_n'; diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTranslationFilter.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTranslationFilter.php index 5f86e660..d7d22312 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTranslationFilter.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTranslationFilter.php @@ -4,16 +4,14 @@ namespace RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter; -use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderBuildEvent; -use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use RZ\Roadiz\CoreBundle\Doctrine\ORM\SimpleQueryBuilder; +use RZ\Roadiz\CoreBundle\Entity\Node; +use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Filter on translation fields when criteria contains translation. prefix. - * - * @package RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter */ class NodeTranslationFilter implements EventSubscriberInterface { @@ -24,25 +22,17 @@ public static function getSubscribedEvents(): array // This event must be the last to perform ['onTranslationPrefixFilter', 0], ['onTranslationFilter', -10], - ] + ], ]; } - /** - * @param QueryBuilderBuildEvent $event - * - * @return bool - */ protected function supports(QueryBuilderBuildEvent $event): bool { - return $event->supports() && - $event->getActualEntityName() === Node::class && - str_contains($event->getProperty(), 'translation'); + return $event->supports() + && Node::class === $event->getActualEntityName() + && str_contains($event->getProperty(), 'translation'); } - /** - * @param QueryBuilderBuildEvent $event - */ public function onTranslationPrefixFilter(QueryBuilderBuildEvent $event): void { if ($this->supports($event)) { @@ -60,7 +50,7 @@ public function onTranslationPrefixFilter(QueryBuilderBuildEvent $event): void ) ) { $qb->innerJoin( - $simpleQB->getRootAlias() . '.nodeSources', + $simpleQB->getRootAlias().'.nodeSources', EntityRepository::NODESSOURCES_ALIAS ); } @@ -72,26 +62,23 @@ public function onTranslationPrefixFilter(QueryBuilderBuildEvent $event): void ) ) { $qb->innerJoin( - EntityRepository::NODESSOURCES_ALIAS . '.translation', + EntityRepository::NODESSOURCES_ALIAS.'.translation', EntityRepository::TRANSLATION_ALIAS ); } - $prefix = EntityRepository::TRANSLATION_ALIAS . '.'; + $prefix = EntityRepository::TRANSLATION_ALIAS.'.'; $key = str_replace('translation.', '', $event->getProperty()); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($event->getValue(), $prefix, $key, $baseKey)); } } } - /** - * @param QueryBuilderBuildEvent $event - */ public function onTranslationFilter(QueryBuilderBuildEvent $event): void { if ($this->supports($event)) { $simpleQB = new SimpleQueryBuilder($event->getQueryBuilder()); - if ($event->getProperty() === 'translation') { + if ('translation' === $event->getProperty()) { // Prevent other query builder filters to execute $event->stopPropagation(); $qb = $event->getQueryBuilder(); @@ -104,12 +91,12 @@ public function onTranslationFilter(QueryBuilderBuildEvent $event): void ) ) { $qb->innerJoin( - $simpleQB->getRootAlias() . '.nodeSources', + $simpleQB->getRootAlias().'.nodeSources', EntityRepository::NODESSOURCES_ALIAS ); } - $prefix = EntityRepository::NODESSOURCES_ALIAS . '.'; + $prefix = EntityRepository::NODESSOURCES_ALIAS.'.'; $key = $event->getProperty(); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($event->getValue(), $prefix, $key, $baseKey)); } diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTypeFilter.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTypeFilter.php index 561797e7..3da315da 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTypeFilter.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodeTypeFilter.php @@ -6,14 +6,12 @@ use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderBuildEvent; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderNodesSourcesBuildEvent; -use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use RZ\Roadiz\CoreBundle\Doctrine\ORM\SimpleQueryBuilder; +use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Filter on nodeType fields when criteria contains nodeType. prefix. - * - * @package RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter */ class NodeTypeFilter implements EventSubscriberInterface { @@ -23,7 +21,7 @@ public static function getSubscribedEvents(): array QueryBuilderNodesSourcesBuildEvent::class => [['onNodesSourcesQueryBuilderBuild', 40]], QueryBuilderBuildEvent::class => [ ['onNodeQueryBuilderBuild', 30], - ] + ], ]; } @@ -32,9 +30,6 @@ protected function supports(QueryBuilderBuildEvent $event): bool return $event->supports() && str_contains($event->getProperty(), 'nodeType.'); } - /** - * @param QueryBuilderBuildEvent $event - */ public function onNodeQueryBuilderBuild(QueryBuilderBuildEvent $event): void { if ($this->supports($event)) { @@ -52,20 +47,17 @@ public function onNodeQueryBuilderBuild(QueryBuilderBuildEvent $event): void ) { $qb->addSelect(EntityRepository::NODETYPE_ALIAS); $qb->innerJoin( - $simpleQB->getRootAlias() . '.nodeType', + $simpleQB->getRootAlias().'.nodeType', EntityRepository::NODETYPE_ALIAS ); } - $prefix = EntityRepository::NODETYPE_ALIAS . '.'; + $prefix = EntityRepository::NODETYPE_ALIAS.'.'; $key = str_replace('nodeType.', '', $event->getProperty()); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($event->getValue(), $prefix, $key, $baseKey)); } } - /** - * @param QueryBuilderNodesSourcesBuildEvent $event - */ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEvent $event): void { if ($this->supports($event)) { @@ -83,7 +75,7 @@ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEve ) ) { $qb->innerJoin( - $simpleQB->getRootAlias() . '.node', + $simpleQB->getRootAlias().'.node', EntityRepository::NODE_ALIAS ); } @@ -95,12 +87,12 @@ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEve ) { $qb->addSelect(EntityRepository::NODETYPE_ALIAS); $qb->innerJoin( - EntityRepository::NODE_ALIAS . '.nodeType', + EntityRepository::NODE_ALIAS.'.nodeType', EntityRepository::NODETYPE_ALIAS ); } - $prefix = EntityRepository::NODETYPE_ALIAS . '.'; + $prefix = EntityRepository::NODETYPE_ALIAS.'.'; $key = str_replace('node.nodeType.', '', $event->getProperty()); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($event->getValue(), $prefix, $key, $baseKey)); } diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeFilter.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeFilter.php index 3a4f3310..18ffc69f 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeFilter.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeFilter.php @@ -5,14 +5,12 @@ namespace RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderNodesSourcesBuildEvent; -use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use RZ\Roadiz\CoreBundle\Doctrine\ORM\SimpleQueryBuilder; +use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Filter on nodeType fields when criteria contains nodeType. prefix. - * - * @package RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter */ class NodesSourcesNodeFilter implements EventSubscriberInterface { @@ -23,19 +21,11 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param QueryBuilderNodesSourcesBuildEvent $event - * - * @return bool - */ protected function supports(QueryBuilderNodesSourcesBuildEvent $event): bool { return $event->supports() && str_contains($event->getProperty(), 'node.'); } - /** - * @param QueryBuilderNodesSourcesBuildEvent $event - */ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEvent $event): void { if ($this->supports($event)) { @@ -52,12 +42,12 @@ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEve ) ) { $qb->innerJoin( - $simpleQB->getRootAlias() . '.node', + $simpleQB->getRootAlias().'.node', EntityRepository::NODE_ALIAS ); } - $prefix = EntityRepository::NODE_ALIAS . '.'; + $prefix = EntityRepository::NODE_ALIAS.'.'; $key = str_replace('node.', '', $event->getProperty()); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($event->getValue(), $prefix, $key, $baseKey)); } diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeTypeFilter.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeTypeFilter.php index 62d943e5..974709ff 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeTypeFilter.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesNodeTypeFilter.php @@ -4,16 +4,13 @@ namespace RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter; -use RZ\Roadiz\CoreBundle\Entity\NodeType; use RZ\Roadiz\CoreBundle\Doctrine\Event\FilterNodesSourcesQueryBuilderCriteriaEvent; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderNodesSourcesApplyEvent; use RZ\Roadiz\CoreBundle\Doctrine\Event\QueryBuilder\QueryBuilderNodesSourcesBuildEvent; use RZ\Roadiz\CoreBundle\Doctrine\ORM\SimpleQueryBuilder; +use RZ\Roadiz\CoreBundle\Entity\NodeType; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -/** - * @package RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter - */ final class NodesSourcesNodeTypeFilter implements EventSubscriberInterface { public static function getSubscribedEvents(): array @@ -24,26 +21,18 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param FilterNodesSourcesQueryBuilderCriteriaEvent $event - * - * @return bool - */ protected function supports(FilterNodesSourcesQueryBuilderCriteriaEvent $event): bool { - return $event->supports() && - $event->getProperty() === 'node.nodeType' && - ( - $event->getValue() instanceof NodeType || - (is_array($event->getValue()) && - count($event->getValue()) > 0 && - $event->getValue()[0] instanceof NodeType) + return $event->supports() + && 'node.nodeType' === $event->getProperty() + && ( + $event->getValue() instanceof NodeType + || (is_array($event->getValue()) + && count($event->getValue()) > 0 + && $event->getValue()[0] instanceof NodeType) ); } - /** - * @param QueryBuilderNodesSourcesBuildEvent $event - */ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEvent $event): void { if ($this->supports($event)) { diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesReachableFilter.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesReachableFilter.php index 6f524f5c..9a038091 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesReachableFilter.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/Filter/NodesSourcesReachableFilter.php @@ -13,14 +13,11 @@ use RZ\Roadiz\CoreBundle\Entity\NodeType; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -/** - * @package RZ\Roadiz\CoreBundle\Doctrine\ORM\Filter - */ final class NodesSourcesReachableFilter implements EventSubscriberInterface { public const PARAMETER = [ 'node.nodeType.reachable', - 'reachable' + 'reachable', ]; public function __construct(private readonly NodeTypes $nodeTypesBag) @@ -36,21 +33,13 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param FilterNodesSourcesQueryBuilderCriteriaEvent $event - * - * @return bool - */ protected function supports(FilterNodesSourcesQueryBuilderCriteriaEvent $event): bool { - return $event->supports() && - in_array($event->getProperty(), self::PARAMETER) && - is_bool($event->getValue()); + return $event->supports() + && in_array($event->getProperty(), self::PARAMETER) + && is_bool($event->getValue()); } - /** - * @param QueryBuilderNodesSourcesBuildEvent $event - */ public function onNodesSourcesQueryBuilderBuild(QueryBuilderNodesSourcesBuildEvent $event): void { if ($this->supports($event)) { diff --git a/lib/RoadizCoreBundle/src/Doctrine/ORM/SimpleQueryBuilder.php b/lib/RoadizCoreBundle/src/Doctrine/ORM/SimpleQueryBuilder.php index 90c7713b..38d54ce4 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/ORM/SimpleQueryBuilder.php +++ b/lib/RoadizCoreBundle/src/Doctrine/ORM/SimpleQueryBuilder.php @@ -5,59 +5,37 @@ namespace RZ\Roadiz\CoreBundle\Doctrine\ORM; use Doctrine\ORM\Query\Expr\Comparison; -use Doctrine\ORM\Query\Expr\Func; use Doctrine\ORM\Query\Expr\From; +use Doctrine\ORM\Query\Expr\Func; use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\QueryBuilder; use RZ\Roadiz\Core\AbstractEntities\PersistableInterface; use Scienta\DoctrineJsonFunctions\Query\AST\Functions\Mysql\JsonContains; -class SimpleQueryBuilder +final readonly class SimpleQueryBuilder { - protected QueryBuilder $queryBuilder; - - /** - * @param QueryBuilder $queryBuilder - */ - public function __construct(QueryBuilder $queryBuilder) + public function __construct(private QueryBuilder $queryBuilder) { - $this->queryBuilder = $queryBuilder; } - /** - * @param string $key - * - * @return string - */ public function getParameterKey(string $key): string { return \mb_strtolower(str_replace('.', '_', $key)); } /** - * @param mixed $value * @param string $prefix Property prefix including DOT - * @param string $key - * - * @return QueryBuilder */ - public function buildExpressionWithBinding($value, string $prefix, string $key): QueryBuilder + public function buildExpressionWithBinding(mixed $value, string $prefix, string $key): QueryBuilder { $this->buildExpressionWithoutBinding($value, $prefix, $key); + return $this->bindValue($key, $value); } - /** - * @param mixed $value - * @param string $prefix - * @param string $key - * @param string|null $baseKey - * - * @return Comparison|Func|string - */ - public function buildExpressionWithoutBinding(mixed $value, string $prefix, string $key, string $baseKey = null) + public function buildExpressionWithoutBinding(mixed $value, string $prefix, string $key, ?string $baseKey = null): Comparison|Func|string { - if (\mb_strlen($prefix) > 0 && \mb_substr($prefix, -\mb_strlen('.')) !== '.') { + if (\mb_strlen($prefix) > 0 && '.' !== \mb_substr($prefix, -\mb_strlen('.'))) { $prefix .= '.'; } @@ -65,10 +43,10 @@ public function buildExpressionWithoutBinding(mixed $value, string $prefix, stri $baseKey = $this->getParameterKey($key); } if (is_bool($value)) { - return $this->queryBuilder->expr()->eq($prefix . $key, ':' . $baseKey); + return $this->queryBuilder->expr()->eq($prefix.$key, ':'.$baseKey); } if ('NOT NULL' === $value) { - return $this->queryBuilder->expr()->isNotNull($prefix . $key); + return $this->queryBuilder->expr()->isNotNull($prefix.$key); } if (is_array($value)) { /* @@ -87,64 +65,60 @@ public function buildExpressionWithoutBinding(mixed $value, string $prefix, stri if (count($value) > 1) { switch ($value[0]) { case '!=': - # neq - return $this->queryBuilder->expr()->neq($prefix . $key, ':' . $baseKey); + // neq + return $this->queryBuilder->expr()->neq($prefix.$key, ':'.$baseKey); case '<=': - # lte - return $this->queryBuilder->expr()->lte($prefix . $key, ':' . $baseKey); + // lte + return $this->queryBuilder->expr()->lte($prefix.$key, ':'.$baseKey); case '<': - # lt - return $this->queryBuilder->expr()->lt($prefix . $key, ':' . $baseKey); + // lt + return $this->queryBuilder->expr()->lt($prefix.$key, ':'.$baseKey); case '>=': - # gte - return $this->queryBuilder->expr()->gte($prefix . $key, ':' . $baseKey); + // gte + return $this->queryBuilder->expr()->gte($prefix.$key, ':'.$baseKey); case '>': - # gt - return $this->queryBuilder->expr()->gt($prefix . $key, ':' . $baseKey); + // gt + return $this->queryBuilder->expr()->gt($prefix.$key, ':'.$baseKey); case 'BETWEEN': return $this->queryBuilder->expr()->between( - $prefix . $key, - ':' . $baseKey . '_1', - ':' . $baseKey . '_2' + $prefix.$key, + ':'.$baseKey.'_1', + ':'.$baseKey.'_2' ); case 'LIKE': - $fullKey = sprintf('LOWER(%s)', $prefix . $key); + $fullKey = sprintf('LOWER(%s)', $prefix.$key); + return $this->queryBuilder->expr()->like( $fullKey, $this->queryBuilder->expr()->literal(\mb_strtolower($value[1] ?? '')) ); case 'NOT IN': - return $this->queryBuilder->expr()->notIn($prefix . $key, ':' . $baseKey); + return $this->queryBuilder->expr()->notIn($prefix.$key, ':'.$baseKey); case JsonContains::FUNCTION_NAME: // Json flat array/object contains a given value - return JsonContains::FUNCTION_NAME . '(' . $prefix . $key . ', :' . $baseKey . ', \'$\') = 1'; + return JsonContains::FUNCTION_NAME.'('.$prefix.$key.', :'.$baseKey.', \'$\') = 1'; case 'INSTANCE OF': - return $this->queryBuilder->expr()->isInstanceOf($prefix . $key, ':' . $baseKey); + return $this->queryBuilder->expr()->isInstanceOf($prefix.$key, ':'.$baseKey); } } - return $this->queryBuilder->expr()->in($prefix . $key, ':' . $baseKey); + + return $this->queryBuilder->expr()->in($prefix.$key, ':'.$baseKey); } if ($value instanceof PersistableInterface) { - return $this->queryBuilder->expr()->eq($prefix . $key, ':' . $baseKey); + return $this->queryBuilder->expr()->eq($prefix.$key, ':'.$baseKey); } if (null === $value) { - return $this->queryBuilder->expr()->isNull($prefix . $key); + return $this->queryBuilder->expr()->isNull($prefix.$key); } - return $this->queryBuilder->expr()->eq($prefix . $key, ':' . $baseKey); + return $this->queryBuilder->expr()->eq($prefix.$key, ':'.$baseKey); } - /** - * @param string $key - * @param mixed $value - * - * @return QueryBuilder - */ - public function bindValue(string $key, $value): QueryBuilder + public function bindValue(string $key, mixed $value): QueryBuilder { $key = $this->getParameterKey($key); - if (is_bool($value) || $value === 0) { + if (is_bool($value) || 0 === $value) { return $this->queryBuilder->setParameter($key, $value); } if ('NOT NULL' == $value) { @@ -163,16 +137,17 @@ public function bindValue(string $key, $value): QueryBuilder case 'NOT IN': return $this->queryBuilder->setParameter($key, $value[1]); case 'BETWEEN': - return $this->queryBuilder->setParameter($key . '_1', $value[1]) - ->setParameter($key . '_2', $value[2]); + return $this->queryBuilder->setParameter($key.'_1', $value[1]) + ->setParameter($key.'_2', $value[2]); case JsonContains::FUNCTION_NAME: // Need to quote Json value - return $this->queryBuilder->setParameter($key, '"' . $value[1] . '"'); + return $this->queryBuilder->setParameter($key, '"'.$value[1].'"'); case 'LIKE': // param is set in filterBy return $this->queryBuilder; } } + return $this->queryBuilder->setParameter($key, $value); } if ($value instanceof PersistableInterface) { @@ -185,20 +160,13 @@ public function bindValue(string $key, $value): QueryBuilder return $this->queryBuilder->setParameter($key, $value); } - /** - * @param string $rootAlias - * @param string $joinAlias - * - * @return bool - */ public function joinExists(string $rootAlias, string $joinAlias): bool { if (isset($this->queryBuilder->getDQLPart('join')[$rootAlias])) { foreach ($this->queryBuilder->getDQLPart('join')[$rootAlias] as $join) { if ( - null !== $join && - $join instanceof Join && - $join->getAlias() === $joinAlias + $join instanceof Join + && $join->getAlias() === $joinAlias ) { return true; } @@ -208,17 +176,11 @@ public function joinExists(string $rootAlias, string $joinAlias): bool return false; } - /** - * @return QueryBuilder - */ public function getQueryBuilder(): QueryBuilder { return $this->queryBuilder; } - /** - * @return string|null - */ public function getRootAlias(): ?string { $fromArray = $this->getQueryBuilder()->getDQLPart('from'); diff --git a/lib/RoadizCoreBundle/src/Doctrine/SchemaUpdater.php b/lib/RoadizCoreBundle/src/Doctrine/SchemaUpdater.php index bd1ccdeb..e00257f1 100644 --- a/lib/RoadizCoreBundle/src/Doctrine/SchemaUpdater.php +++ b/lib/RoadizCoreBundle/src/Doctrine/SchemaUpdater.php @@ -15,7 +15,7 @@ public function __construct( private readonly CacheClearerInterface $cacheClearer, private readonly OPCacheClearer $opCacheClearer, private readonly LoggerInterface $logger, - private readonly string $projectDir + private readonly string $projectDir, ) { } @@ -29,10 +29,10 @@ public function clearMetadata(): void ); $process->run(); - if ($process->wait() === 0) { + if (0 === $process->wait()) { $this->logger->info('Cleared Doctrine metadata cache.'); } else { - throw new \RuntimeException('Cannot clear Doctrine metadata cache. ' . $process->getErrorOutput()); + throw new \RuntimeException('Cannot clear Doctrine metadata cache. '.$process->getErrorOutput()); } $process = $this->runCommand( @@ -40,10 +40,10 @@ public function clearMetadata(): void ); $process->run(); - if ($process->wait() === 0) { + if (0 === $process->wait()) { $this->logger->info('Stop any running messenger worker to force them to restart'); } else { - throw new \RuntimeException('Cannot stop messenger workers. ' . $process->getErrorOutput()); + throw new \RuntimeException('Cannot stop messenger workers. '.$process->getErrorOutput()); } } @@ -56,10 +56,10 @@ public function clearAllCaches(): void ); $process->run(); - if ($process->wait() === 0) { + if (0 === $process->wait()) { $this->logger->info('Cleared all caches.'); } else { - throw new \RuntimeException('Cannot clear cache. ' . $process->getErrorOutput()); + throw new \RuntimeException('Cannot clear cache. '.$process->getErrorOutput()); } } @@ -77,10 +77,10 @@ public function updateSchema(): void ); $process->run(); - if ($process->wait() === 0) { + if (0 === $process->wait()) { $this->logger->info('Executed pending migrations.'); } else { - throw new \RuntimeException('Migrations failed. ' . $process->getErrorOutput()); + throw new \RuntimeException('Migrations failed. '.$process->getErrorOutput()); } } @@ -95,26 +95,27 @@ public function updateNodeTypesSchema(): void '--namespace=DoctrineMigrations --quiet --allow-empty-diff', ); $process->run(); - if ($process->wait() === 0) { + if (0 === $process->wait()) { $this->logger->info('New migration has been generated.'); $this->updateSchema(); } else { - throw new \RuntimeException('DB schema update failed. ' . $process->getErrorOutput()); + throw new \RuntimeException('DB schema update failed. '.$process->getErrorOutput()); } } private function runCommand( string $command, - string $args = '' + string $args = '', ): Process { $args .= ' --no-interaction'; $args .= ' --quiet'; $process = Process::fromShellCommandline( - 'php bin/console ' . $command . ' ' . $args + 'php bin/console '.$command.' '.$args ); $process->setWorkingDirectory($this->projectDir); $process->setTty(false); + return $process; } } diff --git a/lib/RoadizCoreBundle/src/Document/DocumentFactory.php b/lib/RoadizCoreBundle/src/Document/DocumentFactory.php index 91f6f612..7ff20cb1 100644 --- a/lib/RoadizCoreBundle/src/Document/DocumentFactory.php +++ b/lib/RoadizCoreBundle/src/Document/DocumentFactory.php @@ -23,7 +23,7 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, FilesystemOperator $documentsStorage, DocumentFinderInterface $documentFinder, - ?LoggerInterface $logger = null + ?LoggerInterface $logger = null, ) { parent::__construct($documentsStorage, $documentFinder, $logger); } @@ -33,9 +33,6 @@ protected function persistDocument(DocumentInterface $document): void $this->managerRegistry->getManagerForClass(Document::class)->persist($document); } - /** - * @inheritDoc - */ protected function createDocument(): DocumentInterface { return new Document(); diff --git a/lib/RoadizCoreBundle/src/Document/DocumentFinder.php b/lib/RoadizCoreBundle/src/Document/DocumentFinder.php index 7de00596..cb542b1d 100644 --- a/lib/RoadizCoreBundle/src/Document/DocumentFinder.php +++ b/lib/RoadizCoreBundle/src/Document/DocumentFinder.php @@ -16,42 +16,30 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) { } - /** - * @inheritDoc - */ public function findAllByFilenames(array $fileNames): iterable { return $this->getRepository()->findBy([ - "filename" => $fileNames, - "raw" => false, + 'filename' => $fileNames, + 'raw' => false, ]); } - /** - * @inheritDoc - */ public function findOneByFilenames(array $fileNames): ?DocumentInterface { return $this->getRepository()->findOneBy([ - "filename" => $fileNames, - "raw" => false, + 'filename' => $fileNames, + 'raw' => false, ]); } - /** - * @inheritDoc - */ public function findOneByHashAndAlgorithm(string $hash, string $algorithm): ?DocumentInterface { return $this->getRepository()->findOneBy([ - "fileHash" => $hash, - "fileHashAlgorithm" => $algorithm, + 'fileHash' => $hash, + 'fileHashAlgorithm' => $algorithm, ]); } - /** - * @return DocumentRepository - */ protected function getRepository(): DocumentRepository { return $this->managerRegistry->getRepository(Document::class); diff --git a/lib/RoadizCoreBundle/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php b/lib/RoadizCoreBundle/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php index cf6a6844..bfb8bd6b 100644 --- a/lib/RoadizCoreBundle/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php +++ b/lib/RoadizCoreBundle/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php @@ -26,15 +26,12 @@ public function __construct(private readonly MessageBusInterface $bus) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ // Only dispatch async message when document files are updated or created - DocumentCreatedEvent::class => ['onFilterDocumentEvent', 0], - DocumentFileUpdatedEvent::class => ['onFilterDocumentEvent', 0], + DocumentCreatedEvent::class => ['onFilterDocumentEvent', 0], + DocumentFileUpdatedEvent::class => ['onFilterDocumentEvent', 0], ]; } @@ -42,10 +39,10 @@ public function onFilterDocumentEvent(FilterDocumentEvent $event): void { $document = $event->getDocument(); if ( - $document instanceof Document && - \is_numeric($document->getId()) && - $document->isLocal() && - null !== $document->getRelativePath() + $document instanceof Document + && \is_numeric($document->getId()) + && $document->isLocal() + && null !== $document->getRelativePath() ) { $id = (int) $document->getId(); $this->bus->dispatch(new Envelope(new DocumentRawMessage($id))); diff --git a/lib/RoadizCoreBundle/src/Document/MediaFinder/EmbedFinderTrait.php b/lib/RoadizCoreBundle/src/Document/MediaFinder/EmbedFinderTrait.php index 66dfee7b..bd5b5787 100644 --- a/lib/RoadizCoreBundle/src/Document/MediaFinder/EmbedFinderTrait.php +++ b/lib/RoadizCoreBundle/src/Document/MediaFinder/EmbedFinderTrait.php @@ -14,10 +14,7 @@ trait EmbedFinderTrait { - /** - * @inheritDoc - */ - protected function documentExists(ObjectManager $objectManager, $embedId, $embedPlatform): bool + protected function documentExists(ObjectManager $objectManager, string $embedId, ?string $embedPlatform): bool { $existingDocument = $objectManager->getRepository(Document::class) ->findOneBy([ @@ -28,9 +25,6 @@ protected function documentExists(ObjectManager $objectManager, $embedId, $embed return null !== $existingDocument; } - /** - * @inheritDoc - */ protected function injectMetaInDocument(ObjectManager $objectManager, DocumentInterface $document): DocumentInterface { $translations = $objectManager->getRepository(Translation::class)->findAll(); @@ -58,7 +52,7 @@ protected function injectMetaInDocument(ObjectManager $objectManager, DocumentIn } catch (APINeedsAuthentificationException $exception) { // do no prevent from creating document if credentials are not provided. } catch (ClientException $exception) { - // do no prevent from creating document if platform has errors, such as + // do not prevent from creating document if platform has errors, such as // too much API usage. } diff --git a/lib/RoadizCoreBundle/src/Document/MediaFinder/PodcastFinder.php b/lib/RoadizCoreBundle/src/Document/MediaFinder/PodcastFinder.php index bc10601d..95090585 100644 --- a/lib/RoadizCoreBundle/src/Document/MediaFinder/PodcastFinder.php +++ b/lib/RoadizCoreBundle/src/Document/MediaFinder/PodcastFinder.php @@ -18,7 +18,7 @@ class PodcastFinder extends AbstractPodcastFinder protected function injectMetaFromPodcastItem( ObjectManager $objectManager, DocumentInterface $document, - \SimpleXMLElement $item + \SimpleXMLElement $item, ): void { $translations = $objectManager->getRepository(Translation::class)->findAll(); diff --git a/lib/RoadizCoreBundle/src/Document/Message/AbstractDocumentMessage.php b/lib/RoadizCoreBundle/src/Document/Message/AbstractDocumentMessage.php index bce65ca5..8e464990 100644 --- a/lib/RoadizCoreBundle/src/Document/Message/AbstractDocumentMessage.php +++ b/lib/RoadizCoreBundle/src/Document/Message/AbstractDocumentMessage.php @@ -10,17 +10,11 @@ abstract class AbstractDocumentMessage implements AsyncMessage { private int $documentId; - /** - * @param int $documentId - */ public function __construct(int $documentId) { $this->documentId = $documentId; } - /** - * @return int - */ public function getDocumentId(): int { return $this->documentId; diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractDocumentMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractDocumentMessageHandler.php index 23b21023..311b6358 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractDocumentMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractDocumentMessageHandler.php @@ -19,7 +19,7 @@ abstract class AbstractDocumentMessageHandler public function __construct( protected readonly ManagerRegistry $managerRegistry, protected readonly LoggerInterface $messengerLogger, - protected readonly FilesystemOperator $documentsStorage + protected readonly FilesystemOperator $documentsStorage, ) { } diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractLockingDocumentMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractLockingDocumentMessageHandler.php index e15c6139..1a78fba5 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractLockingDocumentMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/AbstractLockingDocumentMessageHandler.php @@ -30,10 +30,7 @@ public function __invoke(AbstractDocumentMessage $message): void $this->managerRegistry->getManager()->flush(); @\flock($resource, \LOCK_UN); } else { - throw new RecoverableMessageHandlingException(sprintf( - '%s file is currently locked', - $documentPath - )); + throw new RecoverableMessageHandlingException(sprintf('%s file is currently locked', $documentPath)); } } else { $this->processMessage($message, $document); @@ -48,7 +45,7 @@ public function __invoke(AbstractDocumentMessage $message): void protected function isFileLocal(DocumentInterface $document): bool { return - $document->isPrivate() || - str_starts_with($this->documentsStorage->publicUrl($document->getMountPath()), '/'); + $document->isPrivate() + || str_starts_with($this->documentsStorage->publicUrl($document->getMountPath()), '/'); } } diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php index 2959d4ae..0b841c53 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php @@ -36,23 +36,19 @@ public function __construct( private readonly ?string $ffmpegPath, ManagerRegistry $managerRegistry, LoggerInterface $messengerLogger, - FilesystemOperator $documentsStorage + FilesystemOperator $documentsStorage, ) { parent::__construct($managerRegistry, $messengerLogger, $documentsStorage); } - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { /* * If none of AV tool are available, do not stream media for nothing. */ - return $document->isLocal() && - ($document->isVideo() || $document->isAudio()) && - (\class_exists('getID3') || is_string($this->ffmpegPath)); + return $document->isLocal() + && ($document->isVideo() || $document->isAudio()) + && (\class_exists('getID3') || is_string($this->ffmpegPath)); } protected function processMessage(AbstractDocumentMessage $message, DocumentInterface $document): void @@ -136,13 +132,7 @@ protected function extractMediaThumbnail(DocumentInterface $document, string $lo $this->eventDispatcher->dispatch(new DocumentCreatedEvent($thumbnailDocument)); } } catch (ProcessFailedException $exception) { - throw new UnrecoverableMessageHandlingException( - sprintf( - 'Cannot extract thumbnail from %s video file : %s', - $localMediaPath, - $exception->getMessage() - ), - ); + throw new UnrecoverableMessageHandlingException(sprintf('Cannot extract thumbnail from %s video file : %s', $localMediaPath, $exception->getMessage())); } } } diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php index 18278757..e2e9c8b7 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php @@ -25,19 +25,12 @@ public function __construct( parent::__construct($managerRegistry, $messengerLogger, $documentsStorage); } - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { return $document->isLocal() && $document->isProcessable(); } /** - * @param AbstractDocumentMessage $message - * @param DocumentInterface $document - * @return void * @throws \League\Flysystem\FilesystemException */ protected function processMessage(AbstractDocumentMessage $message, DocumentInterface $document): void @@ -54,7 +47,7 @@ protected function processMessage(AbstractDocumentMessage $message, DocumentInte 'Document file is not a readable image.', [ 'path' => $document->getMountPath(), - 'message' => $exception->getMessage() + 'message' => $exception->getMessage(), ] ); } diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentExifMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentExifMessageHandler.php index 5983a7b3..94b38602 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentExifMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentExifMessageHandler.php @@ -12,21 +12,17 @@ final class DocumentExifMessageHandler extends AbstractLockingDocumentMessageHandler { - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { if (!$document->isLocal()) { return false; } - if ($document->getEmbedPlatform() !== "") { + if ('' !== $document->getEmbedPlatform()) { return false; } - if ($document->getMimeType() == 'image/jpeg' || $document->getMimeType() == 'image/tiff') { + if ('image/jpeg' == $document->getMimeType() || 'image/tiff' == $document->getMimeType()) { return true; } @@ -39,8 +35,8 @@ protected function processMessage(AbstractDocumentMessage $message, DocumentInte return; } if ( - function_exists('exif_read_data') && - $document->getDocumentTranslations()->count() === 0 + function_exists('exif_read_data') + && 0 === $document->getDocumentTranslations()->count() ) { $fileStream = $this->documentsStorage->readStream($document->getMountPath()); $exif = @\exif_read_data($fileStream, 'FILE,COMPUTED,ANY_TAG,EXIF,COMMENT'); @@ -53,7 +49,7 @@ function_exists('exif_read_data') && $this->messengerLogger->debug( 'EXIF information available for document.', [ - 'document' => (string)$document + 'document' => (string) $document, ] ); $manager = $this->managerRegistry->getManagerForClass(DocumentTranslation::class); @@ -73,16 +69,12 @@ function_exists('exif_read_data') && } } - /** - * @param array $exif - * @return string|null - */ private function getCopyright(array $exif): ?string { foreach ($exif as $key => $section) { if (is_array($section)) { foreach ($section as $skey => $value) { - if (\mb_strtolower($skey) === 'copyright') { + if ('copyright' === \mb_strtolower($skey)) { return $value; } } @@ -92,25 +84,22 @@ private function getCopyright(array $exif): ?string return null; } - /** - * @param array $exif - * @return string|null - */ private function getDescription(array $exif): ?string { foreach ($exif as $key => $section) { - if (is_string($section) && \mb_strtolower($key) === 'imagedescription') { + if (is_string($section) && 'imagedescription' === \mb_strtolower($key)) { return $section; } elseif (is_array($section)) { - if (\mb_strtolower($key) == 'comment') { + if ('comment' == \mb_strtolower($key)) { $comment = ''; foreach ($section as $value) { - $comment .= $value . PHP_EOL; + $comment .= $value.PHP_EOL; } + return $comment; } else { foreach ($section as $skey => $value) { - if (\mb_strtolower($skey) == 'comment') { + if ('comment' == \mb_strtolower($skey)) { return $value; } } diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentFilesizeMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentFilesizeMessageHandler.php index 14600d04..5a5a96a5 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentFilesizeMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentFilesizeMessageHandler.php @@ -11,10 +11,6 @@ final class DocumentFilesizeMessageHandler extends AbstractLockingDocumentMessageHandler { - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { return $document->isLocal() && null !== $document->getRelativePath(); diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentPdfMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentPdfMessageHandler.php index 2a6453ff..54ade391 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentPdfMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentPdfMessageHandler.php @@ -23,21 +23,17 @@ public function __construct( private readonly EventDispatcherInterface $eventDispatcher, ManagerRegistry $managerRegistry, LoggerInterface $messengerLogger, - FilesystemOperator $documentsStorage + FilesystemOperator $documentsStorage, ) { parent::__construct($managerRegistry, $messengerLogger, $documentsStorage); } - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { - return $document->isLocal() && - $document->isPdf() && - \class_exists('\Imagick') && - \class_exists('\ImagickException'); + return $document->isLocal() + && $document->isPdf() + && \class_exists('\Imagick') + && \class_exists('\ImagickException'); } protected function processMessage(AbstractDocumentMessage $message, DocumentInterface $document): void @@ -79,13 +75,13 @@ protected function extractPdfThumbnail(DocumentInterface $document, string $loca if (false === $thumbnailPath) { throw new UnrecoverableMessageHandlingException('Cannot create temporary file for PDF thumbnail.'); } - \rename($thumbnailPath, $thumbnailPath .= $document->getFilename() . '.jpg'); + \rename($thumbnailPath, $thumbnailPath .= $document->getFilename().'.jpg'); try { $im = new \Imagick(); $im->setResolution(144, 144); // Use [0] to get first page of PDF. - if ($im->readImage($localPdfPath . '[0]')) { + if ($im->readImage($localPdfPath.'[0]')) { $im->writeImages($thumbnailPath, false); $thumbnailDocument = $this->documentFactory diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentRawMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentRawMessageHandler.php index ef15d44b..fcb658db 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentRawMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentRawMessageHandler.php @@ -17,15 +17,11 @@ public function __construct( private readonly DownscaleImageManager $downscaleImageManager, ManagerRegistry $managerRegistry, LoggerInterface $messengerLogger, - FilesystemOperator $documentsStorage + FilesystemOperator $documentsStorage, ) { parent::__construct($managerRegistry, $messengerLogger, $documentsStorage); } - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { return $document->isLocal() && null !== $document->getRelativePath() && $document->isProcessable(); diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSizeMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSizeMessageHandler.php index 6c6fe07a..ab917f95 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSizeMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSizeMessageHandler.php @@ -24,10 +24,6 @@ public function __construct( parent::__construct($managerRegistry, $messengerLogger, $documentsStorage); } - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { return $document->isLocal() && $document->isImage(); @@ -47,7 +43,7 @@ protected function processMessage(AbstractDocumentMessage $message, DocumentInte 'Document file is not a readable image.', [ 'path' => $document->getMountPath(), - 'message' => $exception->getMessage() + 'message' => $exception->getMessage(), ] ); } diff --git a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSvgMessageHandler.php b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSvgMessageHandler.php index b833a3d3..240f389c 100644 --- a/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSvgMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Document/MessageHandler/DocumentSvgMessageHandler.php @@ -12,10 +12,6 @@ final class DocumentSvgMessageHandler extends AbstractLockingDocumentMessageHandler { - /** - * @param DocumentInterface $document - * @return bool - */ protected function supports(DocumentInterface $document): bool { return $document->isLocal() && null !== $document->getRelativePath() && $document->isSvg(); diff --git a/lib/RoadizCoreBundle/src/Document/PrivateDocumentFactory.php b/lib/RoadizCoreBundle/src/Document/PrivateDocumentFactory.php index 68713ac9..e29f9454 100644 --- a/lib/RoadizCoreBundle/src/Document/PrivateDocumentFactory.php +++ b/lib/RoadizCoreBundle/src/Document/PrivateDocumentFactory.php @@ -25,7 +25,7 @@ public function __construct( ManagerRegistry $managerRegistry, FilesystemOperator $documentsStorage, DocumentFinderInterface $documentFinder, - ?LoggerInterface $logger = null + ?LoggerInterface $logger = null, ) { parent::__construct($documentsStorage, $documentFinder, $logger); $this->managerRegistry = $managerRegistry; @@ -36,13 +36,11 @@ protected function persistDocument(DocumentInterface $document): void $this->managerRegistry->getManagerForClass(Document::class)->persist($document); } - /** - * @inheritDoc - */ protected function createDocument(): DocumentInterface { $document = new Document(); $document->setPrivate(true); + return $document; } } diff --git a/lib/RoadizCoreBundle/src/Entity/AbstractDateTimedPositioned.php b/lib/RoadizCoreBundle/src/Entity/AbstractDateTimedPositioned.php index 9f33830a..5151807a 100644 --- a/lib/RoadizCoreBundle/src/Entity/AbstractDateTimedPositioned.php +++ b/lib/RoadizCoreBundle/src/Entity/AbstractDateTimedPositioned.php @@ -22,19 +22,19 @@ ORM\MappedSuperclass, ORM\HasLifecycleCallbacks, ORM\Table, - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["created_at"]), - ORM\Index(columns: ["updated_at"]) + ORM\Index(columns: ['position']), + ORM\Index(columns: ['created_at']), + ORM\Index(columns: ['updated_at']) ] abstract class AbstractDateTimedPositioned extends AbstractDateTimed implements PositionedInterface, Comparable { use PositionedTrait; #[ - ORM\Column(type: "float"), - Serializer\Groups(["position"]), - Serializer\Type("float"), - SymfonySerializer\Groups(["position"]), + ORM\Column(type: 'float'), + Serializer\Groups(['position']), + Serializer\Type('float'), + SymfonySerializer\Groups(['position']), ApiFilter(RangeFilter::class), ApiFilter(NumericFilter::class) ] diff --git a/lib/RoadizCoreBundle/src/Entity/Attribute.php b/lib/RoadizCoreBundle/src/Entity/Attribute.php index 04657460..7edc8776 100644 --- a/lib/RoadizCoreBundle/src/Entity/Attribute.php +++ b/lib/RoadizCoreBundle/src/Entity/Attribute.php @@ -20,20 +20,17 @@ use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\Range; -/** - * @package RZ\Roadiz\CoreBundle\Entity - */ #[ ORM\Entity(repositoryClass: AttributeRepository::class), - ORM\Table(name: "attributes"), - ORM\Index(columns: ["code"]), - ORM\Index(columns: ["type"]), - ORM\Index(columns: ["searchable"]), - ORM\Index(columns: ["weight"]), - ORM\Index(columns: ["color"]), - ORM\Index(columns: ["group_id"]), + ORM\Table(name: 'attributes'), + ORM\Index(columns: ['code']), + ORM\Index(columns: ['type']), + ORM\Index(columns: ['searchable']), + ORM\Index(columns: ['weight']), + ORM\Index(columns: ['color']), + ORM\Index(columns: ['group_id']), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["code"]), + UniqueEntity(fields: ['code']), ] class Attribute extends AbstractEntity implements AttributeInterface { @@ -44,12 +41,12 @@ class Attribute extends AbstractEntity implements AttributeInterface */ #[ ORM\OneToMany( - mappedBy: "attribute", + mappedBy: 'attribute', targetEntity: AttributeDocuments::class, - cascade: ["persist", "merge"], + cascade: ['persist', 'merge'], orphanRemoval: true ), - ORM\OrderBy(["position" => "ASC"]), + ORM\OrderBy(['position' => 'ASC']), Serializer\Exclude, Serializer\Type("ArrayCollection"), SymfonySerializer\Ignore @@ -69,13 +66,13 @@ class Attribute extends AbstractEntity implements AttributeInterface private ?RealmInterface $defaultRealm = null; /** - * @var int Absolute weight for sorting attributes in filtered lists. + * @var int absolute weight for sorting attributes in filtered lists */ #[ - ORM\Column(type: "integer", nullable: false, options: ["default" => 0]), - Serializer\Type("integer"), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - SymfonySerializer\Groups(["attribute", "node", "nodes_sources"]), + ORM\Column(type: 'integer', nullable: false, options: ['default' => 0]), + Serializer\Type('integer'), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + SymfonySerializer\Groups(['attribute', 'node', 'nodes_sources']), ApiFilter(OrderFilter::class), Range(min: 0, max: 9999), NotNull, @@ -97,11 +94,6 @@ public function getAttributeDocuments(): Collection return $this->attributeDocuments; } - /** - * @param Collection $attributeDocuments - * - * @return Attribute - */ public function setAttributeDocuments(Collection $attributeDocuments): Attribute { $this->attributeDocuments = $attributeDocuments; @@ -117,6 +109,7 @@ public function getDefaultRealm(): ?RealmInterface public function setDefaultRealm(?RealmInterface $defaultRealm): Attribute { $this->defaultRealm = $defaultRealm; + return $this; } @@ -128,6 +121,7 @@ public function getWeight(): int public function setWeight(?int $weight): Attribute { $this->weight = $weight ?? 0; + return $this; } @@ -136,8 +130,8 @@ public function setWeight(?int $weight): Attribute */ #[ Serializer\VirtualProperty(), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - SymfonySerializer\Groups(["attribute", "node", "nodes_sources"]), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + SymfonySerializer\Groups(['attribute', 'node', 'nodes_sources']), ] public function getDocuments(): Collection { @@ -147,6 +141,7 @@ public function getDocuments(): Collection })->filter(function (?Document $document) { return null !== $document; }); + return $values; // phpstan does not understand filtering null values } } diff --git a/lib/RoadizCoreBundle/src/Entity/AttributeDocuments.php b/lib/RoadizCoreBundle/src/Entity/AttributeDocuments.php index 596a3947..fad0ebce 100644 --- a/lib/RoadizCoreBundle/src/Entity/AttributeDocuments.php +++ b/lib/RoadizCoreBundle/src/Entity/AttributeDocuments.php @@ -5,8 +5,8 @@ namespace RZ\Roadiz\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use RZ\Roadiz\Core\AbstractEntities\AbstractPositioned; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\AbstractPositioned; use RZ\Roadiz\CoreBundle\Repository\AttributeDocumentsRepository; use Symfony\Component\Serializer\Annotation as SymfonySerializer; @@ -16,24 +16,24 @@ */ #[ ORM\Entity(repositoryClass: AttributeDocumentsRepository::class), - ORM\Table(name: "attributes_documents"), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["attribute_id", "position"]) + ORM\Table(name: 'attributes_documents'), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['attribute_id', 'position']) ] class AttributeDocuments extends AbstractPositioned { #[ ORM\ManyToOne( targetEntity: Attribute::class, - cascade: ["persist", "merge"], - fetch: "EAGER", - inversedBy: "attributeDocuments" + cascade: ['persist', 'merge'], + fetch: 'EAGER', + inversedBy: 'attributeDocuments' ), ORM\JoinColumn( - name: "attribute_id", - referencedColumnName: "id", + name: 'attribute_id', + referencedColumnName: 'id', nullable: false, - onDelete: "CASCADE" + onDelete: 'CASCADE' ), Serializer\Exclude(), SymfonySerializer\Ignore() @@ -43,18 +43,18 @@ class AttributeDocuments extends AbstractPositioned #[ ORM\ManyToOne( targetEntity: Document::class, - cascade: ["persist", "merge"], - fetch: "EAGER", - inversedBy: "attributeDocuments" + cascade: ['persist', 'merge'], + fetch: 'EAGER', + inversedBy: 'attributeDocuments' ), ORM\JoinColumn( - name: "document_id", - referencedColumnName: "id", + name: 'document_id', + referencedColumnName: 'id', nullable: false, - onDelete: "CASCADE" + onDelete: 'CASCADE' ), - Serializer\Groups(["attribute"]), - SymfonySerializer\Groups(["attribute"]), + Serializer\Groups(['attribute']), + SymfonySerializer\Groups(['attribute']), Serializer\Type(Document::class) ] protected Document $document; @@ -80,6 +80,7 @@ public function getDocument(): Document public function setDocument(Document $document): AttributeDocuments { $this->document = $document; + return $this; } @@ -91,6 +92,7 @@ public function getAttribute(): Attribute public function setAttribute(Attribute $attribute): AttributeDocuments { $this->attribute = $attribute; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/AttributeGroup.php b/lib/RoadizCoreBundle/src/Entity/AttributeGroup.php index a0601959..cd56cac5 100644 --- a/lib/RoadizCoreBundle/src/Entity/AttributeGroup.php +++ b/lib/RoadizCoreBundle/src/Entity/AttributeGroup.php @@ -6,19 +6,19 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Model\AttributeGroupInterface; use RZ\Roadiz\CoreBundle\Model\AttributeGroupTrait; use RZ\Roadiz\CoreBundle\Model\AttributeGroupTranslationInterface; -use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Repository\AttributeGroupRepository; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; #[ ORM\Entity(repositoryClass: AttributeGroupRepository::class), - ORM\Table(name: "attribute_groups"), - ORM\Index(columns: ["canonical_name"]), + ORM\Table(name: 'attribute_groups'), + ORM\Index(columns: ['canonical_name']), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["canonicalName"]) + UniqueEntity(fields: ['canonicalName']) ] class AttributeGroup extends AbstractEntity implements AttributeGroupInterface { diff --git a/lib/RoadizCoreBundle/src/Entity/AttributeGroupTranslation.php b/lib/RoadizCoreBundle/src/Entity/AttributeGroupTranslation.php index 502e2ea7..299e70d7 100644 --- a/lib/RoadizCoreBundle/src/Entity/AttributeGroupTranslation.php +++ b/lib/RoadizCoreBundle/src/Entity/AttributeGroupTranslation.php @@ -5,21 +5,21 @@ namespace RZ\Roadiz\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use RZ\Roadiz\CoreBundle\Model\AttributeGroupTranslationInterface; use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; +use RZ\Roadiz\CoreBundle\Model\AttributeGroupTranslationInterface; use RZ\Roadiz\CoreBundle\Model\AttributeGroupTranslationTrait; use RZ\Roadiz\CoreBundle\Repository\AttributeGroupTranslationRepository; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; #[ ORM\Entity(repositoryClass: AttributeGroupTranslationRepository::class), - ORM\Table(name: "attribute_group_translations"), - ORM\Index(columns: ["name"]), - ORM\UniqueConstraint(columns: ["attribute_group_id", "translation_id"]), - ORM\UniqueConstraint(columns: ["name", "translation_id"]), + ORM\Table(name: 'attribute_group_translations'), + ORM\Index(columns: ['name']), + ORM\UniqueConstraint(columns: ['attribute_group_id', 'translation_id']), + ORM\UniqueConstraint(columns: ['name', 'translation_id']), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["attributeGroup", "translation"]), - UniqueEntity(fields: ["name", "translation"]) + UniqueEntity(fields: ['attributeGroup', 'translation']), + UniqueEntity(fields: ['name', 'translation']) ] class AttributeGroupTranslation extends AbstractEntity implements AttributeGroupTranslationInterface { diff --git a/lib/RoadizCoreBundle/src/Entity/AttributeTranslation.php b/lib/RoadizCoreBundle/src/Entity/AttributeTranslation.php index ef55c991..780ed7fd 100644 --- a/lib/RoadizCoreBundle/src/Entity/AttributeTranslation.php +++ b/lib/RoadizCoreBundle/src/Entity/AttributeTranslation.php @@ -5,19 +5,19 @@ namespace RZ\Roadiz\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; +use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Model\AttributeTranslationInterface; use RZ\Roadiz\CoreBundle\Model\AttributeTranslationTrait; -use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Repository\AttributeTranslationRepository; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; #[ ORM\Entity(repositoryClass: AttributeTranslationRepository::class), - ORM\Table(name: "attribute_translations"), - ORM\Index(columns: ["label"]), - ORM\UniqueConstraint(columns: ["attribute_id", "translation_id"]), + ORM\Table(name: 'attribute_translations'), + ORM\Index(columns: ['label']), + ORM\UniqueConstraint(columns: ['attribute_id', 'translation_id']), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["attribute", "translation"], errorPath: "translation") + UniqueEntity(fields: ['attribute', 'translation'], errorPath: 'translation') ] class AttributeTranslation extends AbstractEntity implements AttributeTranslationInterface { diff --git a/lib/RoadizCoreBundle/src/Entity/AttributeValue.php b/lib/RoadizCoreBundle/src/Entity/AttributeValue.php index f5df8d02..1bc3488d 100644 --- a/lib/RoadizCoreBundle/src/Entity/AttributeValue.php +++ b/lib/RoadizCoreBundle/src/Entity/AttributeValue.php @@ -21,14 +21,14 @@ #[ ORM\Entity(repositoryClass: AttributeValueRepository::class), - ORM\Table(name: "attribute_values"), - ORM\Index(columns: ["attribute_id", "node_id"]), - ORM\Index(columns: ["node_id", "position"], name: "idx_attribute_value_node_position"), - ORM\Index(columns: ["position"], name: "idx_attribute_value_position"), + ORM\Table(name: 'attribute_values'), + ORM\Index(columns: ['attribute_id', 'node_id']), + ORM\Index(columns: ['node_id', 'position'], name: 'idx_attribute_value_node_position'), + ORM\Index(columns: ['position'], name: 'idx_attribute_value_position'), ORM\HasLifecycleCallbacks, ApiFilter(PropertyFilter::class), ApiFilter(BaseFilter\OrderFilter::class, properties: [ - "position", + 'position', ]), ] class AttributeValue extends AbstractPositioned implements AttributeValueInterface @@ -36,20 +36,20 @@ class AttributeValue extends AbstractPositioned implements AttributeValueInterfa use AttributeValueTrait; #[ - ORM\ManyToOne(targetEntity: Node::class, inversedBy: "attributeValues"), - ORM\JoinColumn(name: "node_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), - Serializer\Groups(["attribute_node"]), - SymfonySerializer\Groups(["attribute_node"]), + ORM\ManyToOne(targetEntity: Node::class, inversedBy: 'attributeValues'), + ORM\JoinColumn(name: 'node_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), + Serializer\Groups(['attribute_node']), + SymfonySerializer\Groups(['attribute_node']), SymfonySerializer\MaxDepth(1), ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "node" => "exact", - "node.id" => "exact", - "node.nodeName" => "exact", - "node.nodeType" => "exact", - "node.nodeType.name" => "exact" + 'node' => 'exact', + 'node.id' => 'exact', + 'node.nodeName' => 'exact', + 'node.nodeType' => 'exact', + 'node.nodeType.name' => 'exact', ]), ApiFilter(BaseFilter\BooleanFilter::class, properties: [ - "node.visible" + 'node.visible', ]) ] protected Node $node; @@ -88,12 +88,13 @@ public function getAttributable(): Node } /** - * @inheritDoc + * @return $this */ - public function setAttributable(?AttributableInterface $attributable) + public function setAttributable(?AttributableInterface $attributable): self { if ($attributable instanceof Node) { $this->node = $attributable; + return $this; } throw new \InvalidArgumentException('Attributable have to be an instance of Node.'); @@ -119,6 +120,7 @@ public function getRealm(): ?RealmInterface public function setRealm(?RealmInterface $realm): AttributeValue { $this->realm = $realm; + return $this; } diff --git a/lib/RoadizCoreBundle/src/Entity/AttributeValueTranslation.php b/lib/RoadizCoreBundle/src/Entity/AttributeValueTranslation.php index 83ed9f1d..180144d7 100644 --- a/lib/RoadizCoreBundle/src/Entity/AttributeValueTranslation.php +++ b/lib/RoadizCoreBundle/src/Entity/AttributeValueTranslation.php @@ -5,16 +5,16 @@ namespace RZ\Roadiz\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; +use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Model\AttributeValueTranslationInterface; use RZ\Roadiz\CoreBundle\Model\AttributeValueTranslationTrait; -use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Repository\AttributeValueTranslationRepository; #[ ORM\Entity(repositoryClass: AttributeValueTranslationRepository::class), - ORM\Table(name: "attribute_value_translations"), - ORM\Index(columns: ["value"]), - ORM\Index(columns: ["translation_id", "attribute_value"]), + ORM\Table(name: 'attribute_value_translations'), + ORM\Index(columns: ['value']), + ORM\Index(columns: ['translation_id', 'attribute_value']), ORM\HasLifecycleCallbacks ] class AttributeValueTranslation extends AbstractEntity implements AttributeValueTranslationInterface diff --git a/lib/RoadizCoreBundle/src/Entity/CustomForm.php b/lib/RoadizCoreBundle/src/Entity/CustomForm.php index b4f9be4e..6fd474c0 100644 --- a/lib/RoadizCoreBundle/src/Entity/CustomForm.php +++ b/lib/RoadizCoreBundle/src/Entity/CustomForm.php @@ -5,17 +5,16 @@ namespace RZ\Roadiz\CoreBundle\Entity; use ApiPlatform\Metadata\ApiFilter; -use DateTime; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\AbstractDateTimed; +use RZ\Roadiz\CoreBundle\Api\Filter as RoadizFilter; use RZ\Roadiz\CoreBundle\Repository\CustomFormRepository; +use RZ\Roadiz\Utils\StringHandler; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Serializer\Annotation as SymfonySerializer; -use RZ\Roadiz\Core\AbstractEntities\AbstractDateTimed; -use RZ\Roadiz\Utils\StringHandler; -use RZ\Roadiz\CoreBundle\Api\Filter as RoadizFilter; use Symfony\Component\Validator\Constraints as Assert; /** @@ -24,26 +23,26 @@ */ #[ ORM\Entity(repositoryClass: CustomFormRepository::class), - ORM\Table(name: "custom_forms"), + ORM\Table(name: 'custom_forms'), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["name"]), - ORM\Index(columns: ["created_at"], name: "custom_form_created_at"), - ORM\Index(columns: ["updated_at"], name: "custom_form_updated_at"), + UniqueEntity(fields: ['name']), + ORM\Index(columns: ['created_at'], name: 'custom_form_created_at'), + ORM\Index(columns: ['updated_at'], name: 'custom_form_updated_at'), ] class CustomForm extends AbstractDateTimed { #[ - ORM\Column(name: "color", type: "string", length: 7, unique: false, nullable: true), - Serializer\Groups(["custom_form", "nodes_sources"]), + ORM\Column(name: 'color', type: 'string', length: 7, unique: false, nullable: true), + Serializer\Groups(['custom_form', 'nodes_sources']), Assert\Length(max: 7), SymfonySerializer\Ignore() ] protected ?string $color = '#000000'; #[ - ORM\Column(type: "string", length: 250, unique: true), - Serializer\Groups(["custom_form", "nodes_sources"]), - SymfonySerializer\Groups(["custom_form", "nodes_sources"]), + ORM\Column(type: 'string', length: 250, unique: true), + Serializer\Groups(['custom_form', 'nodes_sources']), + SymfonySerializer\Groups(['custom_form', 'nodes_sources']), Assert\NotNull(), Assert\NotBlank(), Assert\Length(max: 250), @@ -52,9 +51,9 @@ class CustomForm extends AbstractDateTimed private string $name = 'Untitled'; #[ - ORM\Column(name: "display_name", type: "string", length: 250), - Serializer\Groups(["custom_form", "nodes_sources"]), - SymfonySerializer\Groups(["custom_form", "nodes_sources"]), + ORM\Column(name: 'display_name', type: 'string', length: 250), + Serializer\Groups(['custom_form', 'nodes_sources']), + SymfonySerializer\Groups(['custom_form', 'nodes_sources']), Assert\NotNull(), Assert\NotBlank(), Assert\Length(max: 250), @@ -63,60 +62,60 @@ class CustomForm extends AbstractDateTimed private string $displayName = 'Untitled'; #[ - ORM\Column(type: "text", nullable: true), - Serializer\Groups(["custom_form", "nodes_sources"]), - SymfonySerializer\Groups(["custom_form", "nodes_sources"]), + ORM\Column(type: 'text', nullable: true), + Serializer\Groups(['custom_form', 'nodes_sources']), + SymfonySerializer\Groups(['custom_form', 'nodes_sources']), SymfonySerializer\Ignore() ] private ?string $description = null; #[ - ORM\Column(type: "text", nullable: true), - Serializer\Groups(["custom_form"]), - SymfonySerializer\Groups(["custom_form"]), + ORM\Column(type: 'text', nullable: true), + Serializer\Groups(['custom_form']), + SymfonySerializer\Groups(['custom_form']), SymfonySerializer\Ignore() ] private ?string $email = null; #[ - ORM\Column(type: "string", length: 15, nullable: true), - Serializer\Groups(["custom_form"]), - SymfonySerializer\Groups(["custom_form"]), + ORM\Column(type: 'string', length: 15, nullable: true), + Serializer\Groups(['custom_form']), + SymfonySerializer\Groups(['custom_form']), Assert\Length(max: 15), SymfonySerializer\Ignore() ] private ?string $retentionTime = null; #[ - ORM\Column(type: "boolean", nullable: false, options: ["default" => true]), - Serializer\Groups(["custom_form", "nodes_sources"]), - SymfonySerializer\Groups(["custom_form", "nodes_sources"]), + ORM\Column(type: 'boolean', nullable: false, options: ['default' => true]), + Serializer\Groups(['custom_form', 'nodes_sources']), + SymfonySerializer\Groups(['custom_form', 'nodes_sources']), SymfonySerializer\Ignore() ] private bool $open = true; #[ ApiFilter(RoadizFilter\ArchiveFilter::class), - ORM\Column(name: "close_date", type: "datetime", nullable: true), - Serializer\Groups(["custom_form", "nodes_sources"]), - SymfonySerializer\Groups(["custom_form", "nodes_sources"]), + ORM\Column(name: 'close_date', type: 'datetime', nullable: true), + Serializer\Groups(['custom_form', 'nodes_sources']), + SymfonySerializer\Groups(['custom_form', 'nodes_sources']), SymfonySerializer\Ignore() ] - private ?DateTime $closeDate = null; + private ?\DateTime $closeDate = null; /** * @var Collection */ #[ ORM\OneToMany( - mappedBy: "customForm", + mappedBy: 'customForm', targetEntity: CustomFormField::class, - cascade: ["ALL"], + cascade: ['ALL'], orphanRemoval: true ), - ORM\OrderBy(["position" => "ASC"]), - Serializer\Groups(["custom_form"]), - SymfonySerializer\Groups(["custom_form"]), + ORM\OrderBy(['position' => 'ASC']), + Serializer\Groups(['custom_form']), + SymfonySerializer\Groups(['custom_form']), SymfonySerializer\Ignore() ] private Collection $fields; @@ -126,9 +125,9 @@ class CustomForm extends AbstractDateTimed */ #[ ORM\OneToMany( - mappedBy: "customForm", + mappedBy: 'customForm', targetEntity: CustomFormAnswer::class, - cascade: ["ALL"], + cascade: ['ALL'], orphanRemoval: true ), Serializer\Exclude, @@ -140,7 +139,7 @@ class CustomForm extends AbstractDateTimed * @var Collection */ #[ - ORM\OneToMany(mappedBy: "customForm", targetEntity: NodesCustomForms::class, fetch: "EXTRA_LAZY"), + ORM\OneToMany(mappedBy: 'customForm', targetEntity: NodesCustomForms::class, fetch: 'EXTRA_LAZY'), Serializer\Exclude, SymfonySerializer\Ignore ] @@ -154,16 +153,12 @@ public function __construct() $this->initAbstractDateTimed(); } - /** - * @return string - */ public function getDisplayName(): string { return $this->displayName; } /** - * @param string|null $displayName * @return $this */ public function setDisplayName(?string $displayName): CustomForm @@ -174,94 +169,78 @@ public function setDisplayName(?string $displayName): CustomForm return $this; } - /** - * @return string|null - */ public function getDescription(): ?string { return $this->description; } /** - * @param string $description * @return $this */ public function setDescription(string $description): CustomForm { $this->description = $description; + return $this; } - /** - * @return string|null - */ public function getEmail(): ?string { return $this->email; } /** - * @param string|null $email - * * @return $this */ public function setEmail(?string $email): CustomForm { $this->email = $email; + return $this; } /** - * @param bool $open - * * @return $this */ public function setOpen(bool $open): CustomForm { $this->open = $open; + return $this; } - /** - * @return \DateTime|null - */ public function getCloseDate(): ?\DateTime { return $this->closeDate; } /** - * @param \DateTime|null $closeDate - * * @return $this */ public function setCloseDate(?\DateTime $closeDate): CustomForm { $this->closeDate = $closeDate; + return $this; } /** * Combine open flag and closeDate to determine * if current form is still available. - * - * @return bool */ #[ - Serializer\Groups(["custom_form", "nodes_sources"]), + Serializer\Groups(['custom_form', 'nodes_sources']), Serializer\VirtualProperty, SymfonySerializer\Ignore ] public function isFormStillOpen(): bool { - return (null === $this->getCloseDate() || $this->getCloseDate() >= (new \DateTime('now'))) && - $this->open === true; + return (null === $this->getCloseDate() || $this->getCloseDate() >= (new \DateTime('now'))) + && true === $this->open; } /** * Gets the value of color. - * - * @return string */ public function getColor(): string { @@ -271,21 +250,18 @@ public function getColor(): string /** * Sets the value of color. * - * @param string $color - * * @return $this */ public function setColor(string $color): CustomForm { $this->color = $color; + return $this; } /** * Get every node-type fields names in * a simple array. - * - * @return array */ public function getFieldsNames(): array { @@ -298,9 +274,6 @@ public function getFieldsNames(): array return $namesArray; } - /** - * @return Collection - */ public function getFields(): Collection { return $this->fields; @@ -309,8 +282,6 @@ public function getFields(): Collection /** * Get every node-type fields names in * a simple array. - * - * @return array */ public function getFieldsLabels(): array { @@ -323,10 +294,6 @@ public function getFieldsLabels(): array return $namesArray; } - /** - * @param CustomFormField $field - * @return CustomForm - */ public function addField(CustomFormField $field): CustomForm { if (!$this->getFields()->contains($field)) { @@ -337,10 +304,6 @@ public function addField(CustomFormField $field): CustomForm return $this; } - /** - * @param CustomFormField $field - * @return CustomForm - */ public function removeField(CustomFormField $field): CustomForm { if ($this->getFields()->contains($field)) { @@ -358,45 +321,32 @@ public function getCustomFormAnswers(): Collection return $this->customFormAnswers; } - /** - * @return string - */ public function getOneLineSummary(): string { - return $this->getId() . " — " . $this->getName() . - " — Open : " . ($this->isOpen() ? 'true' : 'false') . PHP_EOL; + return $this->getId().' — '.$this->getName(). + ' — Open : '.($this->isOpen() ? 'true' : 'false').PHP_EOL; } - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string $name - * * @return $this */ public function setName(string $name): CustomForm { $this->name = StringHandler::slugify($name); + return $this; } - /** - * @return bool - */ public function isOpen(): bool { return $this->open; } - /** - * @return string|null - */ public function getRetentionTime(): ?string { return $this->retentionTime; @@ -411,13 +361,10 @@ public function getRetentionTimeInterval(): ?\DateInterval } } - /** - * @param string|null $retentionTime - * @return CustomForm - */ public function setRetentionTime(?string $retentionTime): CustomForm { $this->retentionTime = $retentionTime; + return $this; } @@ -426,17 +373,14 @@ public function setRetentionTime(?string $retentionTime): CustomForm */ public function getFieldsSummary(): string { - $text = "|" . PHP_EOL; + $text = '|'.PHP_EOL; foreach ($this->getFields() as $field) { - $text .= "|--- " . $field->getOneLineSummary(); + $text .= '|--- '.$field->getOneLineSummary(); } return $text; } - /** - * @return Collection - */ public function getNodes(): Collection { return $this->nodes; @@ -446,7 +390,7 @@ public function __clone() { if ($this->id) { $this->id = null; - $suffix = "-" . uniqid(); + $suffix = '-'.uniqid(); $this->name .= $suffix; $this->displayName .= $suffix; $this->customFormAnswers = new ArrayCollection(); diff --git a/lib/RoadizCoreBundle/src/Entity/CustomFormAnswer.php b/lib/RoadizCoreBundle/src/Entity/CustomFormAnswer.php index 3199d4d1..0ba86fcb 100644 --- a/lib/RoadizCoreBundle/src/Entity/CustomFormAnswer.php +++ b/lib/RoadizCoreBundle/src/Entity/CustomFormAnswer.php @@ -4,36 +4,36 @@ namespace RZ\Roadiz\CoreBundle\Entity; -use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Repository\CustomFormAnswerRepository; use Symfony\Component\Serializer\Annotation as SymfonySerializer; -use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use Symfony\Component\Validator\Constraints as Assert; #[ ORM\Entity(repositoryClass: CustomFormAnswerRepository::class), - ORM\Table(name: "custom_form_answers"), - ORM\Index(columns: ["ip"]), - ORM\Index(columns: ["submitted_at"]), - ORM\Index(columns: ["custom_form_id", "submitted_at"], name: "answer_customform_submitted_at") + ORM\Table(name: 'custom_form_answers'), + ORM\Index(columns: ['ip']), + ORM\Index(columns: ['submitted_at']), + ORM\Index(columns: ['custom_form_id', 'submitted_at'], name: 'answer_customform_submitted_at') ] class CustomFormAnswer extends AbstractEntity { #[ - ORM\Column(name: "ip", type: "string", length: 46, nullable: false), - Serializer\Groups(["custom_form_answer"]), - SymfonySerializer\Groups(["custom_form_answer"]), + ORM\Column(name: 'ip', type: 'string', length: 46, nullable: false), + Serializer\Groups(['custom_form_answer']), + SymfonySerializer\Groups(['custom_form_answer']), Assert\Length(max: 46) ] private string $ip = ''; #[ - ORM\Column(name: "submitted_at", type: "datetime", nullable: false), - Serializer\Groups(["custom_form_answer"]), - SymfonySerializer\Groups(["custom_form_answer"]) + ORM\Column(name: 'submitted_at', type: 'datetime', nullable: false), + Serializer\Groups(['custom_form_answer']), + SymfonySerializer\Groups(['custom_form_answer']) ] private \DateTime $submittedAt; @@ -42,22 +42,22 @@ class CustomFormAnswer extends AbstractEntity */ #[ ORM\OneToMany( - mappedBy: "customFormAnswer", + mappedBy: 'customFormAnswer', targetEntity: CustomFormFieldAttribute::class, - cascade: ["ALL"], + cascade: ['ALL'], orphanRemoval: true ), - Serializer\Groups(["custom_form_answer"]), - SymfonySerializer\Groups(["custom_form_answer"]) + Serializer\Groups(['custom_form_answer']), + SymfonySerializer\Groups(['custom_form_answer']) ] private Collection $answerFields; #[ ORM\ManyToOne( targetEntity: CustomForm::class, - inversedBy: "customFormAnswers" + inversedBy: 'customFormAnswers' ), - ORM\JoinColumn(name: "custom_form_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), + ORM\JoinColumn(name: 'custom_form_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), Serializer\Exclude, SymfonySerializer\Ignore ] @@ -70,7 +70,6 @@ public function __construct() } /** - * @param CustomFormFieldAttribute $field * @return $this */ public function addAnswerField(CustomFormFieldAttribute $field): CustomFormAnswer @@ -91,8 +90,6 @@ public function getAnswerFields(): Collection } /** - * @param CustomFormFieldAttribute $field - * * @return $this */ public function removeAnswerField(CustomFormFieldAttribute $field): CustomFormAnswer @@ -104,84 +101,68 @@ public function removeAnswerField(CustomFormFieldAttribute $field): CustomFormAn return $this; } - /** - * @return CustomForm - */ public function getCustomForm(): CustomForm { return $this->customForm; } /** - * @param CustomForm $customForm * @return $this */ public function setCustomForm(CustomForm $customForm): CustomFormAnswer { $this->customForm = $customForm; + return $this; } - /** - * @return string - */ public function __toString(): string { return (string) $this->getId(); } - /** - * @return string - */ public function getIp(): string { return $this->ip; } /** - * @param string $ip - * * @return $this */ public function setIp(string $ip): CustomFormAnswer { $this->ip = $ip; + return $this; } - /** - * @return \DateTime|null - */ public function getSubmittedAt(): ?\DateTime { return $this->submittedAt; } /** - * @param \DateTime $submittedAt - * * @return $this */ public function setSubmittedAt(\DateTime $submittedAt): CustomFormAnswer { $this->submittedAt = $submittedAt; + return $this; } - /** - * @return string|null - */ public function getEmail(): ?string { $attribute = $this->getAnswerFields()->filter(function (CustomFormFieldAttribute $attribute) { return $attribute->getCustomFormField()->isEmail(); })->first(); + return $attribute ? (string) $attribute->getValue() : null; } /** * @param bool $namesAsKeys Use fields name as key. Default: true - * @return array + * * @throws \Exception */ public function toArray(bool $namesAsKeys = true): array @@ -201,6 +182,7 @@ public function toArray(bool $namesAsKeys = true): array ]; } } + return $answers; } } diff --git a/lib/RoadizCoreBundle/src/Entity/CustomFormField.php b/lib/RoadizCoreBundle/src/Entity/CustomFormField.php index b58a6f29..f2048c53 100644 --- a/lib/RoadizCoreBundle/src/Entity/CustomFormField.php +++ b/lib/RoadizCoreBundle/src/Entity/CustomFormField.php @@ -8,10 +8,10 @@ use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\AbstractField; use RZ\Roadiz\CoreBundle\Repository\CustomFormFieldRepository; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Serializer\Annotation as SymfonySerializer; -use RZ\Roadiz\Core\AbstractEntities\AbstractField; use Symfony\Component\Validator\Constraints\Choice; /** @@ -20,20 +20,17 @@ */ #[ ORM\Entity(repositoryClass: CustomFormFieldRepository::class), - ORM\Table(name: "custom_form_fields"), - ORM\UniqueConstraint(columns: ["name", "custom_form_id"]), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["group_name"]), - ORM\Index(columns: ["type"]), - ORM\Index(columns: ["custom_form_id", "position"], name: "cfield_customform_position"), + ORM\Table(name: 'custom_form_fields'), + ORM\UniqueConstraint(columns: ['name', 'custom_form_id']), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['group_name']), + ORM\Index(columns: ['type']), + ORM\Index(columns: ['custom_form_id', 'position'], name: 'cfield_customform_position'), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["label", "customForm"]) + UniqueEntity(fields: ['label', 'customForm']) ] class CustomFormField extends AbstractField { - /** - * @inheritdoc - */ public static array $typeToHuman = [ AbstractField::STRING_T => 'string.type', AbstractField::DATETIME_T => 'date-time.type', @@ -51,8 +48,8 @@ class CustomFormField extends AbstractField ]; #[ - ORM\ManyToOne(targetEntity: CustomForm::class, inversedBy: "fields"), - ORM\JoinColumn(name: "custom_form_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), + ORM\ManyToOne(targetEntity: CustomForm::class, inversedBy: 'fields'), + ORM\JoinColumn(name: 'custom_form_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), Serializer\Exclude, SymfonySerializer\Ignore ] @@ -62,16 +59,16 @@ class CustomFormField extends AbstractField * @var Collection */ #[ - ORM\OneToMany(mappedBy: "customFormField", targetEntity: CustomFormFieldAttribute::class), + ORM\OneToMany(mappedBy: 'customFormField', targetEntity: CustomFormFieldAttribute::class), Serializer\Exclude, SymfonySerializer\Ignore ] private Collection $customFormFieldAttributes; #[ - ORM\Column(name: "field_required", type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["custom_form"]), - SymfonySerializer\Groups(["custom_form"]) + ORM\Column(name: 'field_required', type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['custom_form']), + SymfonySerializer\Groups(['custom_form']) ] private bool $required = false; @@ -79,9 +76,9 @@ class CustomFormField extends AbstractField * @var string|null https://developer.mozilla.org/fr/docs/Web/HTML/Attributes/autocomplete */ #[ - ORM\Column(name: "autocomplete", type: 'string', length:18, nullable: true), - Serializer\Groups(["custom_form"]), - SymfonySerializer\Groups(["custom_form"]), + ORM\Column(name: 'autocomplete', type: 'string', length: 18, nullable: true), + Serializer\Groups(['custom_form']), + SymfonySerializer\Groups(['custom_form']), Choice([ 'off', 'name', @@ -144,9 +141,6 @@ public function setCustomForm(CustomForm $customForm): CustomFormField return $this; } - /** - * @return Collection - */ public function getCustomFormFieldAttribute(): Collection { return $this->customFormFieldAttributes; @@ -161,13 +155,12 @@ public function isRequired(): bool } /** - * @param bool $required - * * @return $this */ public function setRequired(bool $required): CustomFormField { $this->required = $required; + return $this; } @@ -179,20 +172,15 @@ public function getAutocomplete(): ?string public function setAutocomplete(?string $autocomplete): CustomFormField { $this->autocomplete = $autocomplete; + return $this; } - /** - * @return string - */ public function getOneLineSummary(): string { - return $this->getId() . " — " . $this->getName() . " — " . $this->getLabel() . PHP_EOL; + return $this->getId().' — '.$this->getName().' — '.$this->getLabel().PHP_EOL; } - /** - * @return string - */ public function __toString(): string { return (string) $this->getId(); diff --git a/lib/RoadizCoreBundle/src/Entity/CustomFormFieldAttribute.php b/lib/RoadizCoreBundle/src/Entity/CustomFormFieldAttribute.php index b8452226..188a0d91 100644 --- a/lib/RoadizCoreBundle/src/Entity/CustomFormFieldAttribute.php +++ b/lib/RoadizCoreBundle/src/Entity/CustomFormFieldAttribute.php @@ -16,21 +16,21 @@ */ #[ ORM\Entity(repositoryClass: CustomFormFieldAttributeRepository::class), - ORM\Table(name: "custom_form_field_attributes"), - ORM\Index(columns: ["custom_form_answer_id", "custom_form_field_id"], name: "cffattribute_answer_field"), + ORM\Table(name: 'custom_form_field_attributes'), + ORM\Index(columns: ['custom_form_answer_id', 'custom_form_field_id'], name: 'cffattribute_answer_field'), ORM\HasLifecycleCallbacks ] class CustomFormFieldAttribute extends AbstractEntity { #[ - ORM\ManyToOne(targetEntity: CustomFormAnswer::class, inversedBy: "answerFields"), - ORM\JoinColumn(name: "custom_form_answer_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE") + ORM\ManyToOne(targetEntity: CustomFormAnswer::class, inversedBy: 'answerFields'), + ORM\JoinColumn(name: 'custom_form_answer_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected CustomFormAnswer $customFormAnswer; #[ - ORM\ManyToOne(targetEntity: CustomFormField::class, inversedBy: "customFormFieldAttributes"), - ORM\JoinColumn(name: "custom_form_field_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE") + ORM\ManyToOne(targetEntity: CustomFormField::class, inversedBy: 'customFormFieldAttributes'), + ORM\JoinColumn(name: 'custom_form_field_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE') ] protected CustomFormField $customFormField; @@ -38,14 +38,14 @@ class CustomFormFieldAttribute extends AbstractEntity * @var Collection */ #[ - ORM\ManyToMany(targetEntity: Document::class, inversedBy: "customFormFieldAttributes"), - ORM\JoinTable(name: "custom_form_answers_documents"), - ORM\JoinColumn(name: "customformfieldattribute_id", onDelete: "CASCADE"), - ORM\InverseJoinColumn(name: "document_id", onDelete: "CASCADE") + ORM\ManyToMany(targetEntity: Document::class, inversedBy: 'customFormFieldAttributes'), + ORM\JoinTable(name: 'custom_form_answers_documents'), + ORM\JoinColumn(name: 'customformfieldattribute_id', onDelete: 'CASCADE'), + ORM\InverseJoinColumn(name: 'document_id', onDelete: 'CASCADE') ] protected Collection $documents; - #[ORM\Column(type: "text", nullable: true)] + #[ORM\Column(type: 'text', nullable: true)] protected ?string $value = null; public function __construct() @@ -55,6 +55,7 @@ public function __construct() /** * @return string|null $value + * * @throws \Exception */ public function getValue(): ?string @@ -70,16 +71,17 @@ public function getValue(): ?string if ($this->getCustomFormField()->isDateTime()) { return (new \DateTime($this->value))->format('Y-m-d H:i:s'); } + return $this->value; } /** - * @param string|null $value * @return $this */ public function setValue(?string $value): CustomFormFieldAttribute { $this->value = $value; + return $this; } @@ -96,7 +98,6 @@ public function setCustomFormAnswer(CustomFormAnswer $customFormAnswer): CustomF } /** - * @return string * @throws \Exception */ public function __toString(): string @@ -116,22 +117,15 @@ public function setCustomFormField(CustomFormField $customFormField): CustomForm return $this; } - /** - * @return Collection - */ public function getDocuments(): Collection { return $this->documents; } - /** - * @param Collection $documents - * - * @return CustomFormFieldAttribute - */ public function setDocuments(Collection $documents): CustomFormFieldAttribute { $this->documents = $documents; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Document.php b/lib/RoadizCoreBundle/src/Entity/Document.php index e81e5633..d7d7039f 100644 --- a/lib/RoadizCoreBundle/src/Entity/Document.php +++ b/lib/RoadizCoreBundle/src/Entity/Document.php @@ -34,39 +34,39 @@ */ #[ ORM\Entity(repositoryClass: DocumentRepository::class), - ORM\Table(name: "documents"), - ORM\Index(columns: ["created_at"], name: "document_created_at"), - ORM\Index(columns: ["updated_at"], name: "document_updated_at"), - ORM\Index(columns: ["raw"]), - ORM\Index(columns: ["raw", "created_at"], name: "document_raw_created_at"), - ORM\Index(columns: ["private"]), - ORM\Index(columns: ["filename"], name: "document_filename"), - ORM\Index(columns: ["file_hash"], name: "document_file_hash"), - ORM\Index(columns: ["file_hash_algorithm"], name: "document_hash_algorithm"), - ORM\Index(columns: ["file_hash", "file_hash_algorithm"], name: "document_file_hash_algorithm"), - ORM\Index(columns: ["embedId"], name: "document_embed_id"), - ORM\Index(columns: ["embedId", "embedPlatform"], name: "document_embed_platform_id"), - ORM\Index(columns: ["embedPlatform"], name: "document_embed_platform"), - ORM\Index(columns: ["raw", "private"]), - ORM\Index(columns: ["duration"], name: "document_duration"), - ORM\Index(columns: ["filesize"], name: "document_filesize"), - ORM\Index(columns: ["imageWidth"], name: "document_image_width"), - ORM\Index(columns: ["imageHeight"], name: "document_image_height"), - ORM\Index(columns: ["mime_type"]), - Serializer\ExclusionPolicy("all"), + ORM\Table(name: 'documents'), + ORM\Index(columns: ['created_at'], name: 'document_created_at'), + ORM\Index(columns: ['updated_at'], name: 'document_updated_at'), + ORM\Index(columns: ['raw']), + ORM\Index(columns: ['raw', 'created_at'], name: 'document_raw_created_at'), + ORM\Index(columns: ['private']), + ORM\Index(columns: ['filename'], name: 'document_filename'), + ORM\Index(columns: ['file_hash'], name: 'document_file_hash'), + ORM\Index(columns: ['file_hash_algorithm'], name: 'document_hash_algorithm'), + ORM\Index(columns: ['file_hash', 'file_hash_algorithm'], name: 'document_file_hash_algorithm'), + ORM\Index(columns: ['embedId'], name: 'document_embed_id'), + ORM\Index(columns: ['embedId', 'embedPlatform'], name: 'document_embed_platform_id'), + ORM\Index(columns: ['embedPlatform'], name: 'document_embed_platform'), + ORM\Index(columns: ['raw', 'private']), + ORM\Index(columns: ['duration'], name: 'document_duration'), + ORM\Index(columns: ['filesize'], name: 'document_filesize'), + ORM\Index(columns: ['imageWidth'], name: 'document_image_width'), + ORM\Index(columns: ['imageHeight'], name: 'document_image_height'), + ORM\Index(columns: ['mime_type']), + Serializer\ExclusionPolicy('all'), ApiFilter(PropertyFilter::class), ApiFilter(BaseFilter\OrderFilter::class, properties: [ - "createdAt", - "updatedAt", - "copyrightValidSince", - "copyrightValidUntil", - "filesize" + 'createdAt', + 'updatedAt', + 'copyrightValidSince', + 'copyrightValidUntil', + 'filesize', ]), ApiFilter(BaseFilter\DateFilter::class, properties: [ - "createdAt", - "updatedAt", - "copyrightValidSince" => "include_null_before", - "copyrightValidUntil" => "include_null_after" + 'createdAt', + 'updatedAt', + 'copyrightValidSince' => 'include_null_before', + 'copyrightValidUntil' => 'include_null_after', ]), ApiFilter(CopyrightValidFilter::class) ] @@ -123,7 +123,7 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H 'right', 'bottom-left', 'bottom', - 'bottom-right' + 'bottom-right', ])] protected ?string $imageCropAlignment = null; @@ -140,8 +140,8 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H #[ SymfonySerializer\Ignore, - Serializer\Groups(["document"]), - Serializer\Type("bool"), + Serializer\Groups(['document']), + Serializer\Type('bool'), ORM\Column(name: 'raw', type: 'boolean', nullable: false, options: ['default' => false]) ] protected bool $raw = false; @@ -149,7 +149,7 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H #[ORM\Column(name: 'embedId', type: 'string', length: 250, unique: false, nullable: true)] #[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] - #[Serializer\Type("string")] + #[Serializer\Type('string')] #[ApiProperty( description: 'Embed ID on external platforms', example: 'FORSwsjtQSE', @@ -171,7 +171,7 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H #[Assert\Length(max: 15)] protected ?string $fileHashAlgorithm = null; - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "exact")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'exact')] #[ApiFilter(RoadizFilter\NotFilter::class)] #[ORM\Column(name: 'embedPlatform', type: 'string', length: 100, unique: false, nullable: true)] #[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] @@ -230,20 +230,14 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H #[Serializer\Groups(['document', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Type('ArrayCollection')] protected Collection $documentTranslations; - /** - * @var string|null - */ - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "partial")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'partial')] #[ORM\Column(name: 'filename', type: 'string', length: 250, nullable: true)] #[SymfonySerializer\Ignore] #[Serializer\Groups(['document', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Type('string')] #[Assert\Length(max: 250)] private ?string $filename = null; - /** - * @var string|null - */ - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "exact")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'exact')] #[ApiFilter(RoadizFilter\NotFilter::class)] #[ORM\Column(name: 'mime_type', type: 'string', length: 255, nullable: true)] #[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] @@ -262,26 +256,17 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H #[SymfonySerializer\Ignore] #[Serializer\Exclude] private Collection $downscaledDocuments; - /** - * @var string - */ #[ORM\Column(type: 'string', length: 100)] #[SymfonySerializer\Ignore] #[Assert\Length(max: 100)] #[Serializer\Groups(['document', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Type('string')] private string $folder = ''; - /** - * @var bool - */ #[ORM\Column(type: 'boolean', nullable: false, options: ['default' => false])] #[SymfonySerializer\Ignore] #[Serializer\Groups(['document', 'document_private', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Type('bool')] private bool $private = false; - /** - * @var integer - */ #[ORM\Column(name: 'imageWidth', type: 'integer', nullable: false, options: ['default' => 0])] #[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] @@ -291,9 +276,6 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H example: '1280', )] private int $imageWidth = 0; - /** - * @var integer - */ #[ORM\Column(name: 'imageHeight', type: 'integer', nullable: false, options: ['default' => 0])] #[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] @@ -303,9 +285,6 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H example: '800', )] private int $imageHeight = 0; - /** - * @var integer - */ #[ORM\Column(name: 'duration', type: 'integer', nullable: false, options: ['default' => 0])] #[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] @@ -315,9 +294,6 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H example: '300', )] private int $mediaDuration = 0; - /** - * @var string|null - */ #[ORM\Column(name: 'average_color', type: 'string', length: 7, unique: false, nullable: true)] #[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] #[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])] @@ -329,7 +305,7 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H )] private ?string $imageAverageColor = null; /** - * @var int|null The filesize in bytes. + * @var int|null the filesize in bytes */ #[ORM\Column(name: 'filesize', type: 'integer', unique: false, nullable: true)] #[SymfonySerializer\Groups(['document_filesize'])] @@ -346,9 +322,6 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H #[Serializer\Type('ArrayCollection')] private Collection $thumbnails; - /** - * @var HasThumbnailInterface|null - */ #[ORM\ManyToOne(targetEntity: Document::class, fetch: 'EXTRA_LAZY', inversedBy: 'thumbnails')] #[ORM\JoinColumn(name: 'original', nullable: true, onDelete: 'SET NULL')] #[SymfonySerializer\Groups(['document_original'])] @@ -373,9 +346,6 @@ public function __construct() $this->thumbnails = new ArrayCollection(); } - /** - * @return string|null - */ public function getMimeType(): ?string { return $this->mimeType; @@ -384,12 +354,10 @@ public function getMimeType(): ?string public function setMimeType(?string $mimeType): static { $this->mimeType = $mimeType; + return $this; } - /** - * @return string - */ public function getFolder(): string { return $this->folder; @@ -398,6 +366,7 @@ public function getFolder(): string public function setFolder(string $folder): static { $this->folder = $folder; + return $this; } @@ -422,11 +391,12 @@ public function getRawDocument(): ?DocumentInterface return $this->rawDocument; } - public function setRawDocument(DocumentInterface $rawDocument = null): static + public function setRawDocument(?DocumentInterface $rawDocument = null): static { if (null === $rawDocument || $rawDocument instanceof Document) { $this->rawDocument = $rawDocument; } + return $this; } @@ -494,7 +464,6 @@ public function removeFolder(FolderInterface $folder): static } /** - * @param TranslationInterface $translation * @return Collection */ #[SymfonySerializer\Ignore] @@ -515,7 +484,6 @@ public function getDocumentTranslationsByDefaultTranslation(): ?DocumentTranslat } /** - * @param DocumentTranslation $documentTranslation * @return $this */ public function addDocumentTranslation(DocumentTranslation $documentTranslation): static @@ -535,9 +503,6 @@ public function getDocumentTranslations(): Collection return $this->documentTranslations; } - /** - * @return bool - */ #[SymfonySerializer\Ignore] public function hasTranslations(): bool { @@ -546,8 +511,6 @@ public function hasTranslations(): bool /** * Is document a raw one. - * - * @return bool */ public function isRaw(): bool { @@ -557,13 +520,12 @@ public function isRaw(): bool public function setRaw(bool $raw): static { $this->raw = $raw; + return $this; } /** * Gets the downscaledDocument. - * - * @return DocumentInterface|null */ #[SymfonySerializer\Ignore] public function getDownscaledDocument(): ?DocumentInterface @@ -571,21 +533,16 @@ public function getDownscaledDocument(): ?DocumentInterface return $this->downscaledDocuments->first() ?: null; } - /** - * @return float|null - */ #[SymfonySerializer\Ignore] public function getImageRatio(): ?float { if ($this->getImageWidth() > 0 && $this->getImageHeight() > 0) { return $this->getImageWidth() / $this->getImageHeight(); } + return null; } - /** - * @return int - */ public function getImageWidth(): int { return $this->imageWidth; @@ -598,9 +555,6 @@ public function setImageWidth(int $imageWidth): static return $this; } - /** - * @return int - */ public function getImageHeight(): int { return $this->imageHeight; @@ -613,9 +567,6 @@ public function setImageHeight(int $imageHeight): static return $this; } - /** - * @return int - */ public function getMediaDuration(): int { return $this->mediaDuration; @@ -624,12 +575,10 @@ public function getMediaDuration(): int public function setMediaDuration(int $duration): static { $this->mediaDuration = $duration; + return $this; } - /** - * @return string|null - */ public function getImageAverageColor(): ?string { return $this->imageAverageColor; @@ -638,12 +587,10 @@ public function getImageAverageColor(): ?string public function setImageAverageColor(?string $imageAverageColor): static { $this->imageAverageColor = $imageAverageColor; + return $this; } - /** - * @return int|null - */ public function getFilesize(): ?int { return $this->filesize; @@ -652,16 +599,17 @@ public function getFilesize(): ?int public function setFilesize(?int $filesize): static { $this->filesize = $filesize; + return $this; } #[ - Serializer\Groups(["document", "document_display", "nodes_sources", "tag", "attribute"]), - Serializer\Type("string"), + Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute']), + Serializer\Type('string'), Serializer\VirtualProperty, - Serializer\SerializedName("alt"), - SymfonySerializer\Groups(["document", "document_display", "nodes_sources", "tag", "attribute"]), - SymfonySerializer\SerializedName("alt"), + Serializer\SerializedName('alt'), + SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute']), + SymfonySerializer\SerializedName('alt'), ApiProperty( description: 'Document alternative text, for img HTML tag.', writable: false, @@ -670,6 +618,7 @@ public function setFilesize(?int $filesize): static public function getAlternativeText(): string { $documentTranslation = $this->getDocumentTranslations()->first(); + return $documentTranslation && !empty($documentTranslation->getName()) ? $documentTranslation->getName() : $this->getFilename(); @@ -683,20 +632,14 @@ public function __clone() } } - /** - * @return bool - */ #[SymfonySerializer\Groups(['document'])] #[Serializer\Groups(['document'])] #[Serializer\VirtualProperty] public function isThumbnail(): bool { - return $this->getOriginal() !== null; + return null !== $this->getOriginal(); } - /** - * @return HasThumbnailInterface|null - */ #[SymfonySerializer\Ignore] public function getOriginal(): ?HasThumbnailInterface { @@ -712,9 +655,6 @@ public function setOriginal(?HasThumbnailInterface $original): static return $this; } - /** - * @return bool - */ #[SymfonySerializer\Groups(['document'])] #[Serializer\Groups(['document'])] #[Serializer\VirtualProperty] @@ -723,9 +663,6 @@ public function hasThumbnails(): bool return $this->getThumbnails()->count() > 0; } - /** - * @return Collection - */ public function getThumbnails(): Collection { // Filter private thumbnails @@ -755,9 +692,6 @@ public function setThumbnails(Collection $thumbnails): static return $this; } - /** - * @return DocumentInterface|null - */ #[SymfonySerializer\Groups(['document_thumbnails'])] #[SymfonySerializer\SerializedName('thumbnail')] #[SymfonySerializer\MaxDepth(1)] @@ -767,20 +701,15 @@ public function getFirstThumbnail(): ?DocumentInterface if ($this->isEmbed() || !$this->isImage()) { return $this->getThumbnails()->first() ?: null; } + return null; } - /** - * @return bool - */ public function needsThumbnail(): bool { return !$this->isProcessable(); } - /** - * @return string|null - */ public function getFileHash(): ?string { return $this->fileHash; @@ -789,12 +718,10 @@ public function getFileHash(): ?string public function setFileHash(?string $hash): static { $this->fileHash = $hash; + return $this; } - /** - * @return string|null - */ public function getFileHashAlgorithm(): ?string { return $this->fileHashAlgorithm; @@ -803,12 +730,10 @@ public function getFileHashAlgorithm(): ?string public function setFileHashAlgorithm(?string $algorithm): static { $this->fileHashAlgorithm = $algorithm; + return $this; } - /** - * @return \DateTime|null - */ public function getCopyrightValidSince(): ?\DateTime { return $this->copyrightValidSince; @@ -817,12 +742,10 @@ public function getCopyrightValidSince(): ?\DateTime public function setCopyrightValidSince(?\DateTime $copyrightValidSince): static { $this->copyrightValidSince = $copyrightValidSince; + return $this; } - /** - * @return \DateTime|null - */ public function getCopyrightValidUntil(): ?\DateTime { return $this->copyrightValidUntil; @@ -831,12 +754,10 @@ public function getCopyrightValidUntil(): ?\DateTime public function setCopyrightValidUntil(?\DateTime $copyrightValidUntil): static { $this->copyrightValidUntil = $copyrightValidUntil; + return $this; } - /** - * @return string - */ public function __toString(): string { if (!empty($this->getFilename())) { @@ -847,14 +768,12 @@ public function __toString(): string return $translation->getName(); } if (!empty($this->getEmbedPlatform())) { - return $this->getEmbedPlatform() . ' (' . $this->getEmbedId() . ')'; + return $this->getEmbedPlatform().' ('.$this->getEmbedId().')'; } + return (string) $this->getId(); } - /** - * @return string - */ public function getFilename(): string { return $this->filename ?? ''; @@ -867,7 +786,6 @@ public function setFilename(string $filename): static return $this; } - public function getEmbedPlatform(): ?string { return $this->embedPlatform; @@ -876,6 +794,7 @@ public function getEmbedPlatform(): ?string public function setEmbedPlatform(?string $embedPlatform): static { $this->embedPlatform = $embedPlatform; + return $this; } @@ -887,6 +806,7 @@ public function getEmbedId(): ?string public function setEmbedId(?string $embedId): static { $this->embedId = $embedId; + return $this; } @@ -898,6 +818,7 @@ public function getImageCropAlignment(): ?string public function setImageCropAlignment(?string $imageCropAlignment): Document { $this->imageCropAlignment = $imageCropAlignment; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/DocumentTranslation.php b/lib/RoadizCoreBundle/src/Entity/DocumentTranslation.php index e7ac1609..db4872b3 100644 --- a/lib/RoadizCoreBundle/src/Entity/DocumentTranslation.php +++ b/lib/RoadizCoreBundle/src/Entity/DocumentTranslation.php @@ -17,8 +17,8 @@ #[ ORM\Entity(repositoryClass: DocumentTranslationRepository::class), - ORM\Table(name: "documents_translations"), - ORM\UniqueConstraint(columns: ["document_id", "translation_id"]), + ORM\Table(name: 'documents_translations'), + ORM\UniqueConstraint(columns: ['document_id', 'translation_id']), Gedmo\Loggable(logEntryClass: UserLogEntry::class) ] class DocumentTranslation extends AbstractEntity implements Loggable @@ -60,22 +60,18 @@ class DocumentTranslation extends AbstractEntity implements Loggable #[Gedmo\Versioned] private ?string $copyright = null; - /** - * @return string|null - */ public function getName(): ?string { return $this->name; } /** - * @param string|null $name - * * @return $this */ public function setName(?string $name): DocumentTranslation { $this->name = $name; + return $this; } @@ -87,20 +83,16 @@ public function getDescription(): ?string public function setDescription(?string $description): DocumentTranslation { $this->description = $description; + return $this; } - /** - * @return string|null - */ public function getCopyright(): ?string { return $this->copyright; } /** - * @param string|null $copyright - * * @return $this */ public function setCopyright(?string $copyright): DocumentTranslation @@ -110,34 +102,24 @@ public function setCopyright(?string $copyright): DocumentTranslation return $this; } - /** - * @return string|null - */ public function getExternalUrl(): ?string { return $this->externalUrl; } - /** - * @param string|null $externalUrl - * @return DocumentTranslation - */ public function setExternalUrl(?string $externalUrl): DocumentTranslation { $this->externalUrl = $externalUrl; + return $this; } - /** - * @return TranslationInterface - */ public function getTranslation(): TranslationInterface { return $this->translation; } /** - * @param TranslationInterface $translation * @return $this */ public function setTranslation(TranslationInterface $translation): DocumentTranslation @@ -147,21 +129,18 @@ public function setTranslation(TranslationInterface $translation): DocumentTrans return $this; } - /** - * @return DocumentInterface - */ public function getDocument(): DocumentInterface { return $this->document; } /** - * @param DocumentInterface $document * @return $this */ public function setDocument(DocumentInterface $document): DocumentTranslation { $this->document = $document; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/FieldAwareEntityTrait.php b/lib/RoadizCoreBundle/src/Entity/FieldAwareEntityTrait.php index be0611eb..db01735e 100644 --- a/lib/RoadizCoreBundle/src/Entity/FieldAwareEntityTrait.php +++ b/lib/RoadizCoreBundle/src/Entity/FieldAwareEntityTrait.php @@ -22,6 +22,7 @@ public function getFieldName(): string public function setFieldName(string $fieldName): self { $this->fieldName = $fieldName; + return $this; } @@ -31,6 +32,7 @@ public function setFieldName(string $fieldName): self public function setField(NodeTypeFieldInterface $field): self { $this->fieldName = $field->getName(); + return $this; } diff --git a/lib/RoadizCoreBundle/src/Entity/Folder.php b/lib/RoadizCoreBundle/src/Entity/Folder.php index c583b4e9..4d655f31 100644 --- a/lib/RoadizCoreBundle/src/Entity/Folder.php +++ b/lib/RoadizCoreBundle/src/Entity/Folder.php @@ -29,34 +29,31 @@ #[ ORM\Entity(repositoryClass: FolderRepository::class), ORM\HasLifecycleCallbacks, - ORM\Table(name: "folders"), - ORM\Index(columns: ["visible"]), - ORM\Index(columns: ["locked"]), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["created_at"]), - ORM\Index(columns: ["updated_at"]), - ORM\Index(columns: ["parent_id", "position"], name: "folder_parent_position"), - ORM\Index(columns: ["visible", "position"], name: "folder_visible_position"), - ORM\Index(columns: ["parent_id", "visible"], name: "folder_parent_visible"), - ORM\Index(columns: ["parent_id", "visible", "position"], name: "folder_parent_visible_position"), - UniqueEntity(fields: ["folderName"]), + ORM\Table(name: 'folders'), + ORM\Index(columns: ['visible']), + ORM\Index(columns: ['locked']), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['created_at']), + ORM\Index(columns: ['updated_at']), + ORM\Index(columns: ['parent_id', 'position'], name: 'folder_parent_position'), + ORM\Index(columns: ['visible', 'position'], name: 'folder_visible_position'), + ORM\Index(columns: ['parent_id', 'visible'], name: 'folder_parent_visible'), + ORM\Index(columns: ['parent_id', 'visible', 'position'], name: 'folder_parent_visible_position'), + UniqueEntity(fields: ['folderName']), ApiFilter(PropertyFilter::class), ApiFilter(BaseFilter\OrderFilter::class, properties: [ - "position", - "createdAt", - "updatedAt" + 'position', + 'createdAt', + 'updatedAt', ]) ] class Folder extends AbstractDateTimedPositioned implements FolderInterface, LeafInterface { use LeafTrait; - /** - * @var Folder|null - */ #[ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "parent.id" => "exact", - "parent.folderName" => "exact" + 'parent.id' => 'exact', + 'parent.folderName' => 'exact', ])] #[ORM\ManyToOne(targetEntity: Folder::class, inversedBy: 'children')] #[ORM\JoinColumn(name: 'parent_id', referencedColumnName: 'id', onDelete: 'CASCADE')] @@ -88,8 +85,8 @@ class Folder extends AbstractDateTimedPositioned implements FolderInterface, Lea protected Collection $documents; /** - * @var string * @Serializer\Groups({"folder", "folder_color"}) + * * @Serializer\Type("string") */ #[ORM\Column( @@ -104,7 +101,7 @@ class Folder extends AbstractDateTimedPositioned implements FolderInterface, Lea #[SymfonySerializer\Groups(['folder', 'folder_color'])] protected string $color = '#000000'; - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "partial")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'partial')] #[ORM\Column(name: 'folder_name', type: 'string', length: 250, unique: true, nullable: false)] #[Serializer\Groups(['folder', 'document_folders'])] #[SymfonySerializer\Groups(['folder', 'document_folders'])] @@ -151,7 +148,6 @@ public function __construct() } /** - * @param DocumentInterface $document * @return $this */ public function addDocument(DocumentInterface $document): static @@ -172,7 +168,6 @@ public function getDocuments(): Collection } /** - * @param DocumentInterface $document * @return $this */ public function removeDocument(DocumentInterface $document): static @@ -184,34 +179,27 @@ public function removeDocument(DocumentInterface $document): static return $this; } - /** - * @return boolean - */ public function getVisible(): bool { return $this->isVisible(); } - /** - * @return boolean - */ public function isVisible(): bool { return $this->visible; } /** - * @param bool $visible * @return $this */ public function setVisible(bool $visible): static { $this->visible = $visible; + return $this; } /** - * @param TranslationInterface $translation * @return Collection */ #[SymfonySerializer\Ignore] @@ -232,8 +220,8 @@ public function getTranslatedFoldersByDefaultTranslation(): ?FolderTranslation } /** - * @return string|null * @Serializer\VirtualProperty + * * @Serializer\Groups({"folder", "document_folders"}) */ #[SymfonySerializer\Groups(['folder', 'document_folders'])] @@ -254,91 +242,73 @@ public function getTranslatedFolders(): Collection /** * @param Collection $translatedFolders + * * @return $this */ public function setTranslatedFolders(Collection $translatedFolders): static { $this->translatedFolders = $translatedFolders; + return $this; } - /** - * @return string - */ public function getFolderName(): string { return $this->folderName ?? ''; } /** - * @param string $folderName * @return $this */ public function setFolderName(string $folderName): static { $this->dirtyFolderName = $folderName; $this->folderName = StringHandler::slugify($folderName); + return $this; } - /** - * @return string - */ public function getDirtyFolderName(): string { return $this->dirtyFolderName; } /** - * @param string $dirtyFolderName * @return $this */ public function setDirtyFolderName(string $dirtyFolderName): static { $this->dirtyFolderName = $dirtyFolderName; + return $this; } - /** - * @return bool - */ public function isLocked(): bool { return $this->locked; } - /** - * @param bool $locked - * @return Folder - */ public function setLocked(bool $locked): Folder { $this->locked = $locked; + return $this; } - /** - * @return string - */ public function getColor(): string { return $this->color; } - /** - * @param string $color - * @return Folder - */ public function setColor(string $color): Folder { $this->color = $color; + return $this; } /** * Get folder full path using folder names. - * - * @return string */ #[SymfonySerializer\Ignore] public function getFullPath(): string diff --git a/lib/RoadizCoreBundle/src/Entity/FolderTranslation.php b/lib/RoadizCoreBundle/src/Entity/FolderTranslation.php index 76a78b84..c9bca9c5 100644 --- a/lib/RoadizCoreBundle/src/Entity/FolderTranslation.php +++ b/lib/RoadizCoreBundle/src/Entity/FolderTranslation.php @@ -20,9 +20,9 @@ */ #[ ORM\Entity(repositoryClass: FolderTranslationRepository::class), - ORM\Table(name: "folders_translations"), - ORM\UniqueConstraint(columns: ["folder_id", "translation_id"]), - UniqueEntity(fields: ["folder", "translation"]) + ORM\Table(name: 'folders_translations'), + ORM\UniqueConstraint(columns: ['folder_id', 'translation_id']), + UniqueEntity(fields: ['folder', 'translation']) ] class FolderTranslation extends AbstractEntity { @@ -48,50 +48,38 @@ public function __construct(Folder $original, TranslationInterface $translation) { $this->setFolder($original); $this->setTranslation($translation); - $this->name = $original->getDirtyFolderName() != '' ? $original->getDirtyFolderName() : $original->getFolderName(); + $this->name = '' != $original->getDirtyFolderName() ? $original->getDirtyFolderName() : $original->getFolderName(); } - /** - * @return string - */ public function getName(): string { return $this->name ?? ''; } /** - * @param string $name * @return $this */ public function setName(string $name): FolderTranslation { $this->name = $name; + return $this; } - /** - * @return Folder - */ public function getFolder(): Folder { return $this->folder; } - /** - * @param Folder $folder - * @return FolderTranslation - */ public function setFolder(Folder $folder): FolderTranslation { $this->folder = $folder; + return $this; } - /** * Gets the value of translation. - * - * @return TranslationInterface */ public function getTranslation(): TranslationInterface { @@ -102,11 +90,11 @@ public function getTranslation(): TranslationInterface * Sets the value of translation. * * @param TranslationInterface $translation the translation - * @return self */ public function setTranslation(TranslationInterface $translation): FolderTranslation { $this->translation = $translation; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Group.php b/lib/RoadizCoreBundle/src/Entity/Group.php index 5bb7efd0..599f1d5f 100644 --- a/lib/RoadizCoreBundle/src/Entity/Group.php +++ b/lib/RoadizCoreBundle/src/Entity/Group.php @@ -7,8 +7,8 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; -use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; use RZ\Roadiz\CoreBundle\Repository\GroupRepository; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Serializer\Annotation as SymfonySerializer; @@ -19,8 +19,8 @@ */ #[ ORM\Entity(repositoryClass: GroupRepository::class), - ORM\Table(name: "usergroups"), - UniqueEntity(fields: ["name"]) + ORM\Table(name: 'usergroups'), + UniqueEntity(fields: ['name']) ] class Group extends AbstractEntity { @@ -53,8 +53,8 @@ class Group extends AbstractEntity private Collection $roleEntities; /** - * @var array|null * @Serializer\Groups({"group", "user"}) + * * @Serializer\Type("array") */ #[SymfonySerializer\Groups(['group', 'user'])] @@ -66,17 +66,12 @@ public function __construct() $this->users = new ArrayCollection(); } - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string $name - * * @return $this */ public function setName(string $name) @@ -86,9 +81,6 @@ public function setName(string $name) return $this; } - /** - * @return Collection - */ public function getUsers(): Collection { return $this->users; @@ -101,7 +93,7 @@ public function getUsers(): Collection */ public function getRoles(): array { - if ($this->roles === null) { + if (null === $this->roles) { $this->roles = array_map(function (Role $role) { return $role->getRole(); }, $this->getRolesEntities()->toArray()); @@ -112,8 +104,6 @@ public function getRoles(): array /** * Get roles entities. - * - * @return Collection */ public function getRolesEntities(): ?Collection { @@ -122,10 +112,6 @@ public function getRolesEntities(): ?Collection /** * Get roles entities. - * - * @param Collection $roles - * - * @return Group */ public function setRolesEntities(Collection $roles): self { @@ -134,12 +120,13 @@ public function setRolesEntities(Collection $roles): self foreach ($this->roleEntities as $role) { $role->addGroup($this); } + return $this; } /** - * @param Role $role * @return $this + * * @deprecated Use addRoleEntity */ public function addRole(Role $role): Group @@ -148,8 +135,6 @@ public function addRole(Role $role): Group } /** - * @param Role $role - * * @return $this */ public function addRoleEntity(Role $role): Group @@ -162,8 +147,8 @@ public function addRoleEntity(Role $role): Group } /** - * @param Role $role * @return $this + * * @deprecated Use removeRoleEntity */ public function removeRole(Role $role): Group @@ -172,8 +157,6 @@ public function removeRole(Role $role): Group } /** - * @param Role $role - * * @return $this */ public function removeRoleEntity(Role $role): Group diff --git a/lib/RoadizCoreBundle/src/Entity/Node.php b/lib/RoadizCoreBundle/src/Entity/Node.php index 369d1a63..23a90607 100644 --- a/lib/RoadizCoreBundle/src/Entity/Node.php +++ b/lib/RoadizCoreBundle/src/Entity/Node.php @@ -37,26 +37,26 @@ */ #[ ORM\Entity(repositoryClass: NodeRepository::class), - ORM\Table(name: "nodes"), - ORM\Index(columns: ["visible"]), - ORM\Index(columns: ["status"]), - ORM\Index(columns: ["locked"]), - ORM\Index(columns: ["sterile"]), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["created_at"]), - ORM\Index(columns: ["updated_at"]), - ORM\Index(columns: ["hide_children"]), - ORM\Index(columns: ["home"]), - ORM\Index(columns: ["node_name", "status"]), - ORM\Index(columns: ["visible", "status"]), - ORM\Index(columns: ["visible", "status", "parent_node_id"], name: "node_visible_status_parent"), - ORM\Index(columns: ["status", "parent_node_id"], name: "node_status_parent"), - ORM\Index(columns: ["nodeType_id", "status", "parent_node_id"], name: "node_nodetype_status_parent"), - ORM\Index(columns: ["nodeType_id", "status", "parent_node_id", "position"], name: "node_nodetype_status_parent_position"), - ORM\Index(columns: ["visible", "parent_node_id"], name: "node_visible_parent"), - ORM\Index(columns: ["parent_node_id", "position"], name: "node_parent_position"), - ORM\Index(columns: ["visible", "parent_node_id", "position"], name: "node_visible_parent_position"), - ORM\Index(columns: ["status", "visible", "parent_node_id", "position"], name: "node_status_visible_parent_position"), + ORM\Table(name: 'nodes'), + ORM\Index(columns: ['visible']), + ORM\Index(columns: ['status']), + ORM\Index(columns: ['locked']), + ORM\Index(columns: ['sterile']), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['created_at']), + ORM\Index(columns: ['updated_at']), + ORM\Index(columns: ['hide_children']), + ORM\Index(columns: ['home']), + ORM\Index(columns: ['node_name', 'status']), + ORM\Index(columns: ['visible', 'status']), + ORM\Index(columns: ['visible', 'status', 'parent_node_id'], name: 'node_visible_status_parent'), + ORM\Index(columns: ['status', 'parent_node_id'], name: 'node_status_parent'), + ORM\Index(columns: ['nodeType_id', 'status', 'parent_node_id'], name: 'node_nodetype_status_parent'), + ORM\Index(columns: ['nodeType_id', 'status', 'parent_node_id', 'position'], name: 'node_nodetype_status_parent_position'), + ORM\Index(columns: ['visible', 'parent_node_id'], name: 'node_visible_parent'), + ORM\Index(columns: ['parent_node_id', 'position'], name: 'node_parent_position'), + ORM\Index(columns: ['visible', 'parent_node_id', 'position'], name: 'node_visible_parent_position'), + ORM\Index(columns: ['status', 'visible', 'parent_node_id', 'position'], name: 'node_status_visible_parent_position'), ORM\HasLifecycleCallbacks, Gedmo\Loggable(logEntryClass: UserLogEntry::class), // Need to override repository method to see all nodes @@ -91,7 +91,7 @@ class Node extends AbstractDateTimedPositioned implements LeafInterface, Attribu #[ORM\Column(name: 'node_name', type: 'string', length: 255, unique: true)] #[SymfonySerializer\Groups(['nodes_sources', 'nodes_sources_base', 'node', 'log_sources'])] #[Serializer\Groups(['nodes_sources', 'nodes_sources_base', 'node', 'log_sources'])] - #[Serializer\Accessor(getter: "getNodeName", setter: "setNodeName")] + #[Serializer\Accessor(getter: 'getNodeName', setter: 'setNodeName')] #[Assert\NotNull] #[Assert\NotBlank] #[Assert\Length(max: 255)] @@ -121,7 +121,7 @@ class Node extends AbstractDateTimedPositioned implements LeafInterface, Attribu private bool $visible = true; /** - * @internal You should use node Workflow to perform change on status. + * @internal you should use node Workflow to perform change on status */ #[ORM\Column(type: 'integer')] #[Serializer\Exclude] @@ -178,7 +178,7 @@ class Node extends AbstractDateTimedPositioned implements LeafInterface, Attribu schema: [ 'type' => 'string', 'enum' => ['position', 'nodeName', 'createdAt', 'updatedAt', 'publishedAt'], - 'example' => 'position' + 'example' => 'position', ], )] private string $childrenOrder = 'position'; @@ -195,13 +195,13 @@ class Node extends AbstractDateTimedPositioned implements LeafInterface, Attribu schema: [ 'type' => 'string', 'enum' => ['ASC', 'DESC'], - 'example' => 'ASC' + 'example' => 'ASC', ], )] private string $childrenOrderDirection = 'ASC'; #[ORM\ManyToOne(targetEntity: NodeTypeInterface::class)] - #[ORM\JoinColumn(name: 'nodeType_id', referencedColumnName: 'id', nullable:false, onDelete: 'CASCADE')] + #[ORM\JoinColumn(name: 'nodeType_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] #[SymfonySerializer\Groups(['node'])] #[Serializer\Groups(['node'])] #[SymfonySerializer\Ignore] @@ -238,16 +238,16 @@ class Node extends AbstractDateTimedPositioned implements LeafInterface, Attribu #[SymfonySerializer\Ignore] #[Serializer\Exclude] #[ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "nodesTags.tag" => "exact", - "nodesTags.tag.tagName" => "exact", + 'nodesTags.tag' => 'exact', + 'nodesTags.tag.tagName' => 'exact', ])] #[ApiFilter(RoadizFilter\NotFilter::class, properties: [ - "nodesTags.tag.tagName", + 'nodesTags.tag.tagName', ])] - # Use IntersectionFilter after SearchFilter! + // Use IntersectionFilter after SearchFilter! #[ApiFilter(RoadizFilter\IntersectionFilter::class, properties: [ - "nodesTags.tag", - "nodesTags.tag.tagName", + 'nodesTags.tag', + 'nodesTags.tag.tagName', ])] private Collection $nodesTags; @@ -335,7 +335,6 @@ public function __construct() /** * @param int $status - * @return string */ public static function getStatusLabel($status): string { @@ -360,8 +359,6 @@ public static function getStatusLabel($status): string * * Disable this parameter if you need to protect your nodeName * from title changes. - * - * @return bool */ public function isDynamicNodeName(): bool { @@ -369,36 +366,30 @@ public function isDynamicNodeName(): bool } /** - * @param bool $dynamicNodeName * @return $this */ public function setDynamicNodeName(bool $dynamicNodeName): Node { $this->dynamicNodeName = (bool) $dynamicNodeName; + return $this; } - /** - * @return bool - */ public function isHome(): bool { return $this->home; } /** - * @param bool $home * @return $this */ public function setHome(bool $home): Node { $this->home = $home; + return $this; } - /** - * @return int - */ public function getStatus(): int { return $this->status; @@ -406,180 +397,142 @@ public function getStatus(): int /** * @param int|string $status Workflow only use marking places + * * @return $this - * @internal You should use node Workflow to perform change on status. + * + * @internal you should use node Workflow to perform change on status */ public function setStatus(int|string $status): Node { $this->status = (int) $status; + return $this; } - /** - * @return int - */ public function getTtl(): int { return $this->ttl ?? 0; } - /** - * @param int|null $ttl - * - * @return Node - */ public function setTtl(?int $ttl): Node { $this->ttl = $ttl; + return $this; } - /** - * @return bool - */ public function isPublished(): bool { - return ($this->status === Node::PUBLISHED); + return Node::PUBLISHED === $this->status; } - /** - * @return bool - */ public function isPending(): bool { - return ($this->status === Node::PENDING); + return Node::PENDING === $this->status; } - /** - * @return bool - */ public function isDraft(): bool { - return ($this->status === Node::DRAFT); + return Node::DRAFT === $this->status; } - /** - * @return bool - */ public function isDeleted(): bool { - return ($this->status === Node::DELETED); + return Node::DELETED === $this->status; } - /** - * @return bool - */ public function isLocked(): bool { return $this->locked; } /** - * @param bool $locked * @return $this */ public function setLocked(bool $locked): static { $this->locked = $locked; + return $this; } - /** - * @return bool - */ public function getHideChildren(): bool { return $this->hideChildren; } /** - * @param bool $hideChildren * @return $this */ public function setHideChildren(bool $hideChildren): static { $this->hideChildren = $hideChildren; + return $this; } - /** - * @return bool - */ public function isHidingChildren(): bool { return $this->hideChildren; } /** - * @param bool $hideChildren - * * @return $this */ public function setHidingChildren(bool $hideChildren): static { $this->hideChildren = $hideChildren; + return $this; } - /** - * @return bool - */ public function isArchived(): bool { - return ($this->status === Node::ARCHIVED); + return Node::ARCHIVED === $this->status; } - /** - * @return bool - */ public function isSterile(): bool { return $this->sterile; } /** - * @param bool $sterile * @return $this */ public function setSterile(bool $sterile): static { $this->sterile = $sterile; + return $this; } - /** - * @return string - */ public function getChildrenOrder(): string { return $this->childrenOrder; } /** - * @param string $childrenOrder * @return $this */ public function setChildrenOrder(string $childrenOrder): static { $this->childrenOrder = $childrenOrder; + return $this; } - /** - * @return string - */ public function getChildrenOrderDirection(): string { return $this->childrenOrderDirection; } /** - * @param string $childrenOrderDirection * @return $this */ public function setChildrenOrderDirection(string $childrenOrderDirection): static { $this->childrenOrderDirection = $childrenOrderDirection; + return $this; } @@ -593,6 +546,7 @@ public function getNodesTags(): Collection /** * @param Collection $nodesTags + * * @return $this */ public function setNodesTags(Collection $nodesTags): static @@ -632,12 +586,11 @@ public function setTags(iterable $tags): static (new NodesTags())->setNode($this)->setTag($tag)->setPosition(++$i) ); } + return $this; } /** - * @param Tag $tag - * * @return $this */ public function addTag(Tag $tag): static @@ -683,18 +636,19 @@ public function getCustomForms(): Collection /** * @param Collection $customForms + * * @return $this */ public function setCustomForms(Collection $customForms): static { $this->customForms = $customForms; + return $this; } /** * Used by generated nodes-sources. * - * @param NodesCustomForms $nodesCustomForms * @return $this */ public function addCustomForm(NodesCustomForms $nodesCustomForms): static @@ -702,12 +656,11 @@ public function addCustomForm(NodesCustomForms $nodesCustomForms): static if (!$this->customForms->contains($nodesCustomForms)) { $this->customForms->add($nodesCustomForms); } + return $this; } /** - * @param NodeType $stackType - * * @return $this */ public function removeStackType(NodeType $stackType): static @@ -728,8 +681,6 @@ public function getStackTypes(): Collection } /** - * @param NodeType $stackType - * * @return $this */ public function addStackType(NodeType $stackType): static @@ -744,7 +695,6 @@ public function addStackType(NodeType $stackType): static /** * Get node-sources using a given translation. * - * @param TranslationInterface $translation * @return Collection */ #[SymfonySerializer\Ignore] @@ -756,8 +706,6 @@ public function getNodeSourcesByTranslation(TranslationInterface $translation): } /** - * @param NodesSources $ns - * * @return $this */ public function removeNodeSources(NodesSources $ns): static @@ -778,8 +726,6 @@ public function getNodeSources(): Collection } /** - * @param NodesSources $ns - * * @return $this */ public function addNodeSources(NodesSources $ns): static @@ -802,6 +748,7 @@ public function getBNodesByField(NodeTypeFieldInterface $field): Collection $criteria = Criteria::create(); $criteria->andWhere(Criteria::expr()->eq('fieldName', $field->getName())); $criteria->orderBy(['position' => 'ASC']); + return $this->getBNodes()->matching($criteria); } @@ -817,6 +764,7 @@ public function getBNodes(): Collection /** * @param Collection $bNodes + * * @return $this */ public function setBNodes(Collection $bNodes): static @@ -827,20 +775,20 @@ public function setBNodes(Collection $bNodes): static $this->addBNode($bNode); } } + return $this; } public function hasBNode(NodesToNodes $bNode): bool { return $this->getBNodes()->exists(function ($key, NodesToNodes $element) use ($bNode) { - return $bNode->getNodeB()->getId() !== null && - $element->getNodeB()->getId() === $bNode->getNodeB()->getId() && - $element->getFieldName() === $bNode->getFieldName(); + return null !== $bNode->getNodeB()->getId() + && $element->getNodeB()->getId() === $bNode->getNodeB()->getId() + && $element->getFieldName() === $bNode->getFieldName(); }); } /** - * @param NodesToNodes $bNode * @return $this */ public function addBNode(NodesToNodes $bNode): static @@ -849,6 +797,7 @@ public function addBNode(NodesToNodes $bNode): static $this->getBNodes()->add($bNode); $bNode->setNodeA($this); } + return $this; } @@ -861,6 +810,7 @@ public function clearBNodesForField(NodeTypeFieldInterface $field): Node foreach ($toRemoveCollection as $toRemove) { $this->getBNodes()->removeElement($toRemove); } + return $this; } @@ -874,31 +824,25 @@ public function getANodes(): Collection return $this->aNodes; } - /** - * @return string - */ #[SymfonySerializer\Ignore] public function getOneLineSummary(): string { - return $this->getId() . " — " . $this->getNodeName() . " — " . $this->getNodeType()->getName() . - " — Visible : " . ($this->isVisible() ? 'true' : 'false') . PHP_EOL; + return $this->getId().' — '.$this->getNodeName().' — '.$this->getNodeType()->getName(). + ' — Visible : '.($this->isVisible() ? 'true' : 'false').PHP_EOL; } - /** - * @return string - */ public function getNodeName(): string { return $this->nodeName; } /** - * @param string $nodeName * @return $this */ public function setNodeName(string $nodeName): static { $this->nodeName = StringHandler::slugify($nodeName); + return $this; } @@ -910,45 +854,40 @@ public function getNodeType(): NodeTypeInterface public function setNodeType(NodeTypeInterface $nodeType): Node { $this->nodeType = $nodeType; + return $this; } - /** - * @return bool - */ public function isVisible(): bool { return $this->visible; } /** - * @param bool $visible * @return $this */ public function setVisible(bool $visible): Node { $this->visible = $visible; + return $this; } - /** - * @return string - */ #[SymfonySerializer\Ignore] public function getOneLineSourceSummary(): string { - $text = "Source " . + $text = 'Source '. ( $this->getNodeSources()->first() ? $this->getNodeSources()->first()->getId() : '' - ) . + ). PHP_EOL; foreach ($this->getNodeType()->getFields() as $field) { $getterName = $field->getGetterName(); - $text .= '[' . $field->getLabel() . ']: ' . - ($this->getNodeSources()->first() ? $this->getNodeSources()->first()->$getterName() : '') . + $text .= '['.$field->getLabel().']: '. + ($this->getNodeSources()->first() ? $this->getNodeSources()->first()->$getterName() : ''). PHP_EOL; } @@ -965,6 +904,7 @@ public function __clone() if ($this->id) { $this->id = null; $this->home = false; + /** @var Collection $children */ $children = $this->getChildren(); $this->children = new ArrayCollection(); foreach ($children as $child) { @@ -974,7 +914,7 @@ public function __clone() /** @var NodesTags[] $nodesTags */ $nodesTags = $this->nodesTags->toArray(); - if ($nodesTags !== null) { + if (null !== $nodesTags) { $this->nodesTags = new ArrayCollection(); foreach ($nodesTags as $nodesTag) { $this->addTag($nodesTag->getTag()); @@ -1001,14 +941,14 @@ public function __clone() // This is for safety reasons // NodeDuplicator service will override it $nodeSource = $this->getNodeSources()->first(); - if ($nodeSource !== false) { - $namePrefix = $nodeSource->getTitle() != "" ? + if (false !== $nodeSource) { + $namePrefix = '' != $nodeSource->getTitle() ? $nodeSource->getTitle() : $this->nodeName; } else { $namePrefix = $this->nodeName; } - $this->setNodeName($namePrefix . "-" . uniqid()); + $this->setNodeName($namePrefix.'-'.uniqid()); $this->setCreatedAt(new \DateTime()); $this->setUpdatedAt(new \DateTime()); } @@ -1028,9 +968,6 @@ public function setParent(?LeafInterface $parent = null): static return $this; } - /** - * @return string - */ public function __toString(): string { return (string) $this->getId(); diff --git a/lib/RoadizCoreBundle/src/Entity/NodeType.php b/lib/RoadizCoreBundle/src/Entity/NodeType.php index 53ab01ff..e41f85ad 100644 --- a/lib/RoadizCoreBundle/src/Entity/NodeType.php +++ b/lib/RoadizCoreBundle/src/Entity/NodeType.php @@ -24,33 +24,33 @@ */ #[ ORM\Entity(repositoryClass: NodeTypeRepository::class), - ORM\Table(name: "node_types"), - ORM\Index(columns: ["name"], name: "node_type_name"), - ORM\Index(columns: ["visible"]), - ORM\Index(columns: ["publishable"]), - ORM\Index(columns: ["attributable"]), - ORM\Index(columns: ["hiding_nodes"]), - ORM\Index(columns: ["hiding_non_reachable_nodes"]), - ORM\Index(columns: ["reachable"]), - ORM\Index(columns: ["searchable"], name: "nt_searchable"), - UniqueEntity(fields: ["name"]), - UniqueEntity(fields: ["displayName"]) + ORM\Table(name: 'node_types'), + ORM\Index(columns: ['name'], name: 'node_type_name'), + ORM\Index(columns: ['visible']), + ORM\Index(columns: ['publishable']), + ORM\Index(columns: ['attributable']), + ORM\Index(columns: ['hiding_nodes']), + ORM\Index(columns: ['hiding_non_reachable_nodes']), + ORM\Index(columns: ['reachable']), + ORM\Index(columns: ['searchable'], name: 'nt_searchable'), + UniqueEntity(fields: ['name']), + UniqueEntity(fields: ['displayName']) ] class NodeType extends AbstractEntity implements NodeTypeInterface { #[ - ORM\Column(name: "color", type: "string", length: 7, unique: false, nullable: true), - Serializer\Groups(["node_type", "color"]), - SymfonySerializer\Groups(["node_type", "color"]), - Serializer\Type("string"), + ORM\Column(name: 'color', type: 'string', length: 7, unique: false, nullable: true), + Serializer\Groups(['node_type', 'color']), + SymfonySerializer\Groups(['node_type', 'color']), + Serializer\Type('string'), Assert\Length(max: 7), ] protected ?string $color = '#000000'; #[ - ORM\Column(type: "string", length: 30, unique: true), - Serializer\Groups(["node_type", "node"]), - SymfonySerializer\Groups(["node_type", "node"]), - Serializer\Type("string"), + ORM\Column(type: 'string', length: 30, unique: true), + Serializer\Groups(['node_type', 'node']), + SymfonySerializer\Groups(['node_type', 'node']), + Serializer\Type('string'), Assert\NotNull(), Assert\NotBlank(), RoadizAssert\NonSqlReservedWord(), @@ -60,52 +60,52 @@ class NodeType extends AbstractEntity implements NodeTypeInterface ] private string $name = ''; #[ - ORM\Column(name: "display_name", type: "string", length: 250), - Serializer\Groups(["node_type", "node"]), - SymfonySerializer\Groups(["node_type", "node"]), - Serializer\Type("string"), + ORM\Column(name: 'display_name', type: 'string', length: 250), + Serializer\Groups(['node_type', 'node']), + SymfonySerializer\Groups(['node_type', 'node']), + Serializer\Type('string'), Assert\NotNull(), Assert\NotBlank(), Assert\Length(max: 250) ] private string $displayName = ''; #[ - ORM\Column(type: "text", nullable: true), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("string") + ORM\Column(type: 'text', nullable: true), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('string') ] private ?string $description = null; #[ - ORM\Column(type: "boolean", nullable: false, options: ["default" => true]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(type: 'boolean', nullable: false, options: ['default' => true]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $visible = true; #[ - ORM\Column(type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $publishable = false; /** - * @var bool Define if this node-type produces nodes that will have attributes. + * @var bool define if this node-type produces nodes that will have attributes */ #[ - ORM\Column(type: "boolean", nullable: false, options: ["default" => true]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(type: 'boolean', nullable: false, options: ['default' => true]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $attributable = false; #[ - ORM\Column(name: "attributable_by_weight", type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(name: 'attributable_by_weight', type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $sortingAttributesByWeight = false; /** @@ -115,24 +115,24 @@ class NodeType extends AbstractEntity implements NodeTypeInterface * Typically, if a node has a URL. */ #[ - ORM\Column(name: "reachable", type: "boolean", nullable: false, options: ["default" => true]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(name: 'reachable', type: 'boolean', nullable: false, options: ['default' => true]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $reachable = true; #[ - ORM\Column(name: "hiding_nodes", type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(name: 'hiding_nodes', type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $hidingNodes = false; #[ - ORM\Column(name: "hiding_non_reachable_nodes", type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(name: 'hiding_non_reachable_nodes', type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $hidingNonReachableNodes = false; /** @@ -140,23 +140,23 @@ class NodeType extends AbstractEntity implements NodeTypeInterface */ #[ ORM\OneToMany( - mappedBy: "nodeType", + mappedBy: 'nodeType', targetEntity: NodeTypeField::class, - cascade: ["all"], + cascade: ['all'], orphanRemoval: true ), - ORM\OrderBy(["position" => "ASC"]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), + ORM\OrderBy(['position' => 'ASC']), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), Serializer\Type("ArrayCollection"), - Serializer\Accessor(getter: "getFields", setter: "setFields") + Serializer\Accessor(getter: 'getFields', setter: 'setFields') ] private Collection $fields; #[ - ORM\Column(name: "default_ttl", type: "integer", nullable: false, options: ["default" => 0]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("int"), + ORM\Column(name: 'default_ttl', type: 'integer', nullable: false, options: ['default' => 0]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('int'), Assert\GreaterThanOrEqual(value: 0), Assert\NotNull ] @@ -166,10 +166,10 @@ class NodeType extends AbstractEntity implements NodeTypeInterface * Define if this node-type title will be indexed during its parent indexation. */ #[ - ORM\Column(name: "searchable", type: "boolean", nullable: false, options: ["default" => true]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("boolean") + ORM\Column(name: 'searchable', type: 'boolean', nullable: false, options: ['default' => true]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('boolean') ] private bool $searchable = true; @@ -188,147 +188,109 @@ public function getLabel(): string return $this->getDisplayName(); } - /** - * @return string - */ public function getDisplayName(): string { return $this->displayName; } /** - * @param string|null $displayName - * * @return $this */ public function setDisplayName(?string $displayName): NodeType { $this->displayName = $displayName ?? ''; + return $this; } - /** - * @return string|null - */ public function getDescription(): ?string { return $this->description; } /** - * @param string|null $description * @return $this */ public function setDescription(?string $description = null): NodeType { $this->description = $description; + return $this; } - /** - * @return boolean - */ public function isVisible(): bool { return $this->visible; } /** - * @param boolean $visible * @return $this */ public function setVisible(bool $visible): NodeType { $this->visible = $visible; + return $this; } - /** - * @return bool - */ public function isPublishable(): bool { return $this->publishable; } - /** - * @param bool $publishable - * @return NodeType - */ public function setPublishable(bool $publishable): NodeType { $this->publishable = $publishable; + return $this; } - /** - * @return bool - */ public function getReachable(): bool { return $this->reachable; } - /** - * @return bool - */ public function isReachable(): bool { return $this->getReachable(); } - /** - * @param bool $reachable - * @return NodeType - */ public function setReachable(bool $reachable): NodeType { $this->reachable = $reachable; + return $this; } - /** - * @return boolean - */ public function isHidingNodes(): bool { return $this->hidingNodes; } /** - * @param boolean $hidingNodes - * * @return $this */ public function setHidingNodes(bool $hidingNodes): NodeType { $this->hidingNodes = $hidingNodes; + return $this; } - /** - * @return bool - */ public function isHidingNonReachableNodes(): bool { return $this->hidingNonReachableNodes; } - /** - * @param bool $hidingNonReachableNodes - * - * @return NodeType - */ public function setHidingNonReachableNodes(bool $hidingNonReachableNodes): NodeType { $this->hidingNonReachableNodes = $hidingNonReachableNodes; + return $this; } /** * Gets the value of color. - * - * @return string|null */ public function getColor(): ?string { @@ -338,8 +300,6 @@ public function getColor(): ?string /** * Sets the value of color. * - * @param string|null $color - * * @return $this */ public function setColor(?string $color): NodeType @@ -349,19 +309,11 @@ public function setColor(?string $color): NodeType return $this; } - /** - * @return int - */ public function getDefaultTtl(): int { return $this->defaultTtl ?? 0; } - /** - * @param int|null $defaultTtl - * - * @return NodeType - */ public function setDefaultTtl(?int $defaultTtl): NodeType { $this->defaultTtl = $defaultTtl; @@ -369,17 +321,13 @@ public function setDefaultTtl(?int $defaultTtl): NodeType return $this; } - /** - * @param string $name - * - * @return NodeTypeField|null - */ public function getFieldByName(string $name): ?NodeTypeField { $fieldCriteria = Criteria::create(); $fieldCriteria->andWhere(Criteria::expr()->eq('name', $name)); $fieldCriteria->setMaxResults(1); $field = $this->getFields()->matching($fieldCriteria)->first(); + return $field ?: null; } @@ -393,8 +341,6 @@ public function getFields(): Collection /** * @param Collection $fields - * - * @return NodeType */ public function setFields(Collection $fields): NodeType { @@ -409,8 +355,6 @@ public function setFields(Collection $fields): NodeType /** * Get every node-type fields names in * a simple array. - * - * @return array */ #[SymfonySerializer\Ignore] public function getFieldsNames(): array @@ -420,29 +364,21 @@ public function getFieldsNames(): array }, $this->getFields()->toArray()); } - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string|null $name * @return $this */ public function setName(?string $name): NodeType { $this->name = StringHandler::classify($name ?? ''); + return $this; } - /** - * @param NodeTypeField $field - * - * @return NodeType - */ public function addField(NodeTypeField $field): NodeType { if (!$this->getFields()->contains($field)) { @@ -453,11 +389,6 @@ public function addField(NodeTypeField $field): NodeType return $this; } - /** - * @param NodeTypeField $field - * - * @return NodeType - */ public function removeField(NodeTypeField $field): NodeType { if ($this->getFields()->contains($field)) { @@ -474,12 +405,9 @@ public function removeField(NodeTypeField $field): NodeType public function getSourceEntityFullQualifiedClassName(): string { // @phpstan-ignore-next-line - return static::getGeneratedEntitiesNamespace() . '\\' . $this->getSourceEntityClassName(); + return static::getGeneratedEntitiesNamespace().'\\'.$this->getSourceEntityClassName(); } - /** - * @return string - */ #[SymfonySerializer\Ignore] public static function getGeneratedEntitiesNamespace(): string { @@ -488,29 +416,22 @@ public static function getGeneratedEntitiesNamespace(): string /** * Get node-source entity class name without its namespace. - * - * @return string */ #[SymfonySerializer\Ignore] public function getSourceEntityClassName(): string { - return 'NS' . ucwords($this->getName()); + return 'NS'.ucwords($this->getName()); } /** * Get node-source entity database table name. - * - * @return string */ #[SymfonySerializer\Ignore] public function getSourceEntityTableName(): string { - return 'ns_' . \mb_strtolower($this->getName()); + return 'ns_'.\mb_strtolower($this->getName()); } - /** - * @return string - */ public function __toString(): string { return (string) $this->getId(); @@ -518,8 +439,6 @@ public function __toString(): string /** * Get every searchable node-type fields as a Doctrine ArrayCollection. - * - * @return Collection */ #[SymfonySerializer\Ignore] public function getSearchableFields(): Collection @@ -529,21 +448,15 @@ public function getSearchableFields(): Collection }); } - /** - * @return bool - */ public function isSearchable(): bool { return $this->searchable; } - /** - * @param bool $searchable - * @return NodeType - */ public function setSearchable(bool $searchable): NodeType { $this->searchable = $searchable; + return $this; } @@ -555,6 +468,7 @@ public function isAttributable(): bool public function setAttributable(bool $attributable): NodeType { $this->attributable = $attributable; + return $this; } @@ -566,6 +480,7 @@ public function isSortingAttributesByWeight(): bool public function setSortingAttributesByWeight(bool $sortingAttributesByWeight): NodeType { $this->sortingAttributesByWeight = $sortingAttributesByWeight; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/NodeTypeField.php b/lib/RoadizCoreBundle/src/Entity/NodeTypeField.php index 07dd18bf..b9bbcb06 100644 --- a/lib/RoadizCoreBundle/src/Entity/NodeTypeField.php +++ b/lib/RoadizCoreBundle/src/Entity/NodeTypeField.php @@ -22,30 +22,30 @@ */ #[ ORM\Entity(repositoryClass: NodeTypeFieldRepository::class), - ORM\Table(name: "node_type_fields"), - ORM\Index(columns: ["visible"]), - ORM\Index(columns: ["indexed"]), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["group_name"]), - ORM\Index(columns: ["group_name_canonical"]), - ORM\Index(columns: ["type"]), - ORM\Index(columns: ["name"], name: 'ntf_name'), - ORM\Index(columns: ["universal"]), - ORM\Index(columns: ["node_type_id", "position"], name: "ntf_type_position"), - ORM\UniqueConstraint(columns: ["name", "node_type_id"]), + ORM\Table(name: 'node_type_fields'), + ORM\Index(columns: ['visible']), + ORM\Index(columns: ['indexed']), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['group_name']), + ORM\Index(columns: ['group_name_canonical']), + ORM\Index(columns: ['type']), + ORM\Index(columns: ['name'], name: 'ntf_name'), + ORM\Index(columns: ['universal']), + ORM\Index(columns: ['node_type_id', 'position'], name: 'ntf_type_position'), + ORM\UniqueConstraint(columns: ['name', 'node_type_id']), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["name", "nodeType"]), + UniqueEntity(fields: ['name', 'nodeType']), RoadizAssert\NodeTypeField ] class NodeTypeField extends AbstractField implements NodeTypeFieldInterface, SerializableInterface { #[ - ORM\Column(type: "string", length: 50), + ORM\Column(type: 'string', length: 50), Serializer\Expose, - Serializer\Groups(["node_type", "setting"]), - SymfonySerializer\Groups(["node_type", "setting"]), + Serializer\Groups(['node_type', 'setting']), + SymfonySerializer\Groups(['node_type', 'setting']), Assert\Length(max: 50), - Serializer\Type("string"), + Serializer\Type('string'), RoadizAssert\NonSqlReservedWord(), RoadizAssert\SimpleLatinString() ] @@ -55,10 +55,10 @@ class NodeTypeField extends AbstractField implements NodeTypeFieldInterface, Ser * If current field data should be the same over translations or not. */ #[ - ORM\Column(name: "universal", type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("bool") + ORM\Column(name: 'universal', type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('bool') ] private bool $universal = false; @@ -66,87 +66,87 @@ class NodeTypeField extends AbstractField implements NodeTypeFieldInterface, Ser * Exclude current field from full-text search engines. */ #[ - ORM\Column(name: "exclude_from_search", type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("bool") + ORM\Column(name: 'exclude_from_search', type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('bool') ] private bool $excludeFromSearch = false; #[ - ORM\ManyToOne(targetEntity: NodeType::class, inversedBy: "fields"), - ORM\JoinColumn(name: "node_type_id", nullable: false, onDelete: "CASCADE"), + ORM\ManyToOne(targetEntity: NodeType::class, inversedBy: 'fields'), + ORM\JoinColumn(name: 'node_type_id', nullable: false, onDelete: 'CASCADE'), Serializer\Exclude(), SymfonySerializer\Ignore ] private NodeTypeInterface $nodeType; #[ - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("string"), - ORM\Column(name: "serialization_exclusion_expression", type: "text", nullable: true) + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('string'), + ORM\Column(name: 'serialization_exclusion_expression', type: 'text', nullable: true) ] private ?string $serializationExclusionExpression = null; #[ - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("array"), - ORM\Column(name: "serialization_groups", type: "json", nullable: true) + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('array'), + ORM\Column(name: 'serialization_groups', type: 'json', nullable: true) ] private ?array $serializationGroups = null; #[ - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("int"), - ORM\Column(name: "serialization_max_depth", type: "integer", nullable: true) + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('int'), + ORM\Column(name: 'serialization_max_depth', type: 'integer', nullable: true) ] private ?int $serializationMaxDepth = null; #[ - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("bool"), - ORM\Column(name: "excluded_from_serialization", type: "boolean", nullable: false, options: ["default" => false]) + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('bool'), + ORM\Column(name: 'excluded_from_serialization', type: 'boolean', nullable: false, options: ['default' => false]) ] private bool $excludedFromSerialization = false; #[ - ORM\Column(name: "min_length", type: "integer", nullable: true), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("int") + ORM\Column(name: 'min_length', type: 'integer', nullable: true), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('int') ] private ?int $minLength = null; #[ - ORM\Column(name: "max_length", type: "integer", nullable: true), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("int") + ORM\Column(name: 'max_length', type: 'integer', nullable: true), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('int') ] private ?int $maxLength = null; #[ - ORM\Column(type: "boolean", nullable: false, options: ["default" => false]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("bool") + ORM\Column(type: 'boolean', nullable: false, options: ['default' => false]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('bool') ] private bool $indexed = false; #[ - ORM\Column(type: "boolean", nullable: false, options: ["default" => true]), - Serializer\Groups(["node_type"]), - SymfonySerializer\Groups(["node_type"]), - Serializer\Type("bool") + ORM\Column(type: 'boolean', nullable: false, options: ['default' => true]), + Serializer\Groups(['node_type']), + SymfonySerializer\Groups(['node_type']), + Serializer\Type('bool') ] private bool $visible = true; #[ - SymfonySerializer\Groups(["node_type"]) + SymfonySerializer\Groups(['node_type']) ] public function getNodeTypeName(): string { @@ -161,6 +161,7 @@ public function getNodeType(): NodeTypeInterface public function setNodeType(NodeTypeInterface $nodeType): NodeTypeField { $this->nodeType = $nodeType; + return $this; } @@ -172,12 +173,10 @@ public function getMinLength(): ?int public function setMinLength(?int $minLength): NodeTypeField { $this->minLength = $minLength; + return $this; } - /** - * @return int|null - */ public function getMaxLength(): ?int { return $this->maxLength; @@ -186,49 +185,43 @@ public function getMaxLength(): ?int public function setMaxLength(?int $maxLength): NodeTypeField { $this->maxLength = $maxLength; + return $this; } /** * Tell if current field can be searched and indexed in a Search engine server. - * - * @return bool */ public function isSearchable(): bool { return !$this->excludeFromSearch && in_array($this->getType(), static::$searchableTypes); } - /** - * @return string - */ #[SymfonySerializer\Ignore] public function getOneLineSummary(): string { - return $this->getId() . " — " . $this->getLabel() . ' [' . $this->getName() . ']' . - ' - ' . $this->getTypeName() . - ($this->isIndexed() ? ' - indexed' : '') . - (!$this->isVisible() ? ' - hidden' : '') . PHP_EOL; + return $this->getId().' — '.$this->getLabel().' ['.$this->getName().']'. + ' - '.$this->getTypeName(). + ($this->isIndexed() ? ' - indexed' : ''). + (!$this->isVisible() ? ' - hidden' : '').PHP_EOL; } /** - * @return boolean $isIndexed + * @return bool $isIndexed */ public function isIndexed(): bool { // JSON types cannot be indexed - return $this->indexed && $this->getDoctrineType() !== 'json'; + return $this->indexed && 'json' !== $this->getDoctrineType(); } public function setIndexed(bool $indexed): NodeTypeField { $this->indexed = $indexed; + return $this; } - /** - * @return bool - */ public function isVisible(): bool { return $this->visible; @@ -237,12 +230,10 @@ public function isVisible(): bool public function setVisible(bool $visible): NodeTypeField { $this->visible = $visible; + return $this; } - /** - * @return bool - */ public function isUniversal(): bool { return $this->universal; @@ -250,34 +241,24 @@ public function isUniversal(): bool /** * @see Same as isUniversal - * @return bool */ public function getUniversal(): bool { return $this->universal; } - /** - * @param bool $universal - * @return NodeTypeField - */ public function setUniversal(bool $universal): NodeTypeField { $this->universal = $universal; + return $this; } - /** - * @return bool - */ public function isExcludedFromSearch(): bool { return $this->getExcludeFromSearch(); } - /** - * @return bool - */ public function getExcludeFromSearch(): bool { return $this->excludeFromSearch; @@ -300,28 +281,18 @@ public function getSerializationExclusionExpression(): ?string return $this->serializationExclusionExpression; } - /** - * @param string|null $serializationExclusionExpression - * @return NodeTypeField - */ public function setSerializationExclusionExpression(?string $serializationExclusionExpression): NodeTypeField { $this->serializationExclusionExpression = $serializationExclusionExpression; + return $this; } - /** - * @return array - */ public function getSerializationGroups(): array { return array_filter($this->serializationGroups ?? []); } - /** - * @param array|null $serializationGroups - * @return NodeTypeField - */ public function setSerializationGroups(?array $serializationGroups): NodeTypeField { $this->serializationGroups = $serializationGroups; @@ -331,42 +302,31 @@ public function setSerializationGroups(?array $serializationGroups): NodeTypeFie if (empty($this->serializationGroups)) { $this->serializationGroups = null; } + return $this; } - /** - * @return int|null - */ public function getSerializationMaxDepth(): ?int { return $this->serializationMaxDepth; } - /** - * @param int|null $serializationMaxDepth - * @return NodeTypeField - */ public function setSerializationMaxDepth(?int $serializationMaxDepth): NodeTypeField { $this->serializationMaxDepth = $serializationMaxDepth; + return $this; } - /** - * @return bool - */ public function isExcludedFromSerialization(): bool { return $this->excludedFromSerialization; } - /** - * @param bool $excludedFromSerialization - * @return NodeTypeField - */ public function setExcludedFromSerialization(bool $excludedFromSerialization): NodeTypeField { $this->excludedFromSerialization = $excludedFromSerialization; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/NodesCustomForms.php b/lib/RoadizCoreBundle/src/Entity/NodesCustomForms.php index 8f7d4a39..fc4a2ec8 100644 --- a/lib/RoadizCoreBundle/src/Entity/NodesCustomForms.php +++ b/lib/RoadizCoreBundle/src/Entity/NodesCustomForms.php @@ -15,10 +15,10 @@ */ #[ ORM\Entity(repositoryClass: NodesCustomFormsRepository::class), - ORM\Table(name: "nodes_custom_forms"), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["node_id", "position"], name: "customform_node_position"), - ORM\Index(columns: ["node_id", "field_name", "position"], name: "customform_node_field_position") + ORM\Table(name: 'nodes_custom_forms'), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['node_id', 'position'], name: 'customform_node_position'), + ORM\Index(columns: ['node_id', 'field_name', 'position'], name: 'customform_node_field_position') ] class NodesCustomForms extends AbstractPositioned { @@ -35,8 +35,6 @@ class NodesCustomForms extends AbstractPositioned /** * Create a new relation between a Node, a CustomForm and a NodeTypeField. * - * @param Node $node - * @param CustomForm $customForm * @param NodeTypeFieldInterface|null $field NodeTypeField */ public function __construct(Node $node, CustomForm $customForm, ?NodeTypeFieldInterface $field = null) @@ -58,8 +56,6 @@ public function __clone() /** * Gets the value of node. - * - * @return Node */ public function getNode(): Node { @@ -70,19 +66,16 @@ public function getNode(): Node * Sets the value of node. * * @param Node $node the node - * - * @return self */ public function setNode(Node $node): NodesCustomForms { $this->node = $node; + return $this; } /** * Gets the value of customForm. - * - * @return CustomForm */ public function getCustomForm(): CustomForm { @@ -93,12 +86,11 @@ public function getCustomForm(): CustomForm * Sets the value of customForm. * * @param CustomForm $customForm the custom form - * - * @return self */ public function setCustomForm(CustomForm $customForm): NodesCustomForms { $this->customForm = $customForm; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/NodesSources.php b/lib/RoadizCoreBundle/src/Entity/NodesSources.php index ab8e0152..4d86338f 100644 --- a/lib/RoadizCoreBundle/src/Entity/NodesSources.php +++ b/lib/RoadizCoreBundle/src/Entity/NodesSources.php @@ -31,26 +31,26 @@ */ #[ ORM\Entity(repositoryClass: NodesSourcesRepository::class), - ORM\Table(name: "nodes_sources"), - ORM\Index(columns: ["discr"]), - ORM\Index(columns: ["title"]), - ORM\Index(columns: ["published_at"]), - ORM\Index(columns: ["no_index"], name: 'ns_no_index'), - ORM\Index(columns: ["node_id", "translation_id", "published_at"], name: "ns_node_translation_published"), - ORM\Index(columns: ["node_id", "discr", "translation_id"], name: "ns_node_discr_translation"), - ORM\Index(columns: ["node_id", "discr", "translation_id", "published_at"], name: "ns_node_discr_translation_published"), - ORM\Index(columns: ["translation_id", "published_at"], name: "ns_translation_published"), - ORM\Index(columns: ["discr", "translation_id"], name: "ns_discr_translation"), - ORM\Index(columns: ["discr", "translation_id", "published_at"], name: "ns_discr_translation_published"), - ORM\Index(columns: ["title", "published_at"], name: "ns_title_published"), - ORM\Index(columns: ["title", "translation_id", "published_at"], name: "ns_title_translation_published"), - ORM\UniqueConstraint(columns: ["node_id", "translation_id"]), - ORM\InheritanceType("JOINED"), + ORM\Table(name: 'nodes_sources'), + ORM\Index(columns: ['discr']), + ORM\Index(columns: ['title']), + ORM\Index(columns: ['published_at']), + ORM\Index(columns: ['no_index'], name: 'ns_no_index'), + ORM\Index(columns: ['node_id', 'translation_id', 'published_at'], name: 'ns_node_translation_published'), + ORM\Index(columns: ['node_id', 'discr', 'translation_id'], name: 'ns_node_discr_translation'), + ORM\Index(columns: ['node_id', 'discr', 'translation_id', 'published_at'], name: 'ns_node_discr_translation_published'), + ORM\Index(columns: ['translation_id', 'published_at'], name: 'ns_translation_published'), + ORM\Index(columns: ['discr', 'translation_id'], name: 'ns_discr_translation'), + ORM\Index(columns: ['discr', 'translation_id', 'published_at'], name: 'ns_discr_translation_published'), + ORM\Index(columns: ['title', 'published_at'], name: 'ns_title_published'), + ORM\Index(columns: ['title', 'translation_id', 'published_at'], name: 'ns_title_translation_published'), + ORM\UniqueConstraint(columns: ['node_id', 'translation_id']), + ORM\InheritanceType('JOINED'), // Limit discriminator column to 30 characters for indexing optimization - ORM\DiscriminatorColumn(name: "discr", type: "string", length: 30), + ORM\DiscriminatorColumn(name: 'discr', type: 'string', length: 30), ORM\HasLifecycleCallbacks, Gedmo\Loggable(logEntryClass: UserLogEntry::class), - UniqueEntity(fields: ["node", "translation"]), + UniqueEntity(fields: ['node', 'translation']), ApiFilter(PropertyFilter::class), ApiFilter(RoadizFilter\LocaleFilter::class) ] @@ -68,7 +68,7 @@ class NodesSources extends AbstractEntity implements Loggable #[Serializer\Exclude] protected Collection $redirections; - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "partial")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'partial')] #[ORM\Column(name: 'title', type: 'string', length: 250, unique: false, nullable: true)] #[SymfonySerializer\Groups(['nodes_sources', 'nodes_sources_base', 'log_sources'])] #[Serializer\Groups(['nodes_sources', 'nodes_sources_base', 'log_sources'])] @@ -92,7 +92,7 @@ class NodesSources extends AbstractEntity implements Loggable )] protected ?\DateTime $publishedAt = null; - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "partial")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'partial')] #[ORM\Column(name: 'meta_title', type: 'string', length: 150, unique: false)] #[SymfonySerializer\Groups(['nodes_sources'])] #[Serializer\Groups(['nodes_sources'])] @@ -104,7 +104,7 @@ class NodesSources extends AbstractEntity implements Loggable )] protected string $metaTitle = ''; - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "partial")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'partial')] #[ORM\Column(name: 'meta_description', type: 'text')] #[SymfonySerializer\Groups(['nodes_sources'])] #[Serializer\Groups(['nodes_sources'])] @@ -127,45 +127,45 @@ class NodesSources extends AbstractEntity implements Loggable protected bool $noIndex = false; #[ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "node.id" => "exact", - "node.nodeName" => "exact", - "node.parent" => "exact", - "node.parent.nodeName" => "exact", - "node.nodesTags.tag" => "exact", - "node.nodesTags.tag.tagName" => "exact", - "node.nodeType" => "exact", - "node.nodeType.name" => "exact" + 'node.id' => 'exact', + 'node.nodeName' => 'exact', + 'node.parent' => 'exact', + 'node.parent.nodeName' => 'exact', + 'node.nodesTags.tag' => 'exact', + 'node.nodesTags.tag.tagName' => 'exact', + 'node.nodeType' => 'exact', + 'node.nodeType.name' => 'exact', ])] #[ApiFilter(BaseFilter\OrderFilter::class, properties: [ - "node.position", - "node.createdAt", - "node.updatedAt" + 'node.position', + 'node.createdAt', + 'node.updatedAt', ])] #[ApiFilter(BaseFilter\NumericFilter::class, properties: [ - "node.position", + 'node.position', ])] #[ApiFilter(BaseFilter\RangeFilter::class, properties: [ - "node.position", + 'node.position', ])] #[ApiFilter(BaseFilter\DateFilter::class, properties: [ - "node.createdAt", - "node.updatedAt" + 'node.createdAt', + 'node.updatedAt', ])] #[ApiFilter(BaseFilter\BooleanFilter::class, properties: [ - "node.visible", - "node.home", - "node.nodeType.reachable", - "node.nodeType.publishable" + 'node.visible', + 'node.home', + 'node.nodeType.reachable', + 'node.nodeType.publishable', ])] #[ApiFilter(RoadizFilter\NotFilter::class, properties: [ - "node.nodeType.name", - "node.id", - "node.nodesTags.tag.tagName", + 'node.nodeType.name', + 'node.id', + 'node.nodesTags.tag.tagName', ])] - # Use IntersectionFilter after SearchFilter! + // Use IntersectionFilter after SearchFilter! #[ApiFilter(RoadizFilter\IntersectionFilter::class, properties: [ - "node.nodesTags.tag", - "node.nodesTags.tag.tagName", + 'node.nodesTags.tag', + 'node.nodesTags.tag.tagName', ])] #[ORM\ManyToOne(targetEntity: Node::class, cascade: ['persist'], fetch: 'EAGER', inversedBy: 'nodeSources')] #[ORM\JoinColumn(name: 'node_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] @@ -176,8 +176,8 @@ class NodesSources extends AbstractEntity implements Loggable private Node $node; #[ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "translation.id" => "exact", - "translation.locale" => "exact", + 'translation.id' => 'exact', + 'translation.locale' => 'exact', ])] #[ORM\ManyToOne(targetEntity: Translation::class, inversedBy: 'nodeSources')] #[ORM\JoinColumn(name: 'translation_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] @@ -213,9 +213,6 @@ class NodesSources extends AbstractEntity implements Loggable /** * Create a new NodeSource with its Node and Translation. - * - * @param Node $node - * @param TranslationInterface $translation */ public function __construct(Node $node, TranslationInterface $translation) { @@ -235,7 +232,7 @@ public function injectObjectManager(ObjectManager $objectManager): void #[ORM\PreUpdate] public function preUpdate(): void { - $this->getNode()->setUpdatedAt(new \DateTime("now")); + $this->getNode()->setUpdatedAt(new \DateTime('now')); } public function getNode(): Node @@ -252,7 +249,6 @@ public function setNode(Node $node): NodesSources } /** - * @param UrlAlias $urlAlias * @return $this */ public function addUrlAlias(UrlAlias $urlAlias): NodesSources @@ -290,17 +286,15 @@ public function getDocumentsByFields(): Collection /** * Get at least one document to represent this node-source as image. - * - * @return DocumentInterface|null */ #[SymfonySerializer\Ignore] public function getOneDisplayableDocument(): ?DocumentInterface { return $this->getDocumentsByFields()->filter(function (NodesSourcesDocuments $nsd) { - return null !== $nsd->getDocument() && - !$nsd->getDocument()->isPrivate() && - ($nsd->getDocument()->isImage() || $nsd->getDocument()->isSvg()) && - $nsd->getDocument()->isProcessable(); + return null !== $nsd->getDocument() + && !$nsd->getDocument()->isPrivate() + && ($nsd->getDocument()->isImage() || $nsd->getDocument()->isSvg()) + && $nsd->getDocument()->isProcessable(); })->map(function (NodesSourcesDocuments $nsd) { return $nsd->getDocument(); })->first() ?: null; @@ -308,8 +302,6 @@ public function getOneDisplayableDocument(): ?DocumentInterface /** * @param Collection $documentsByFields - * - * @return NodesSources */ public function setDocumentsByFields(Collection $documentsByFields): NodesSources { @@ -323,18 +315,14 @@ public function setDocumentsByFields(Collection $documentsByFields): NodesSource return $this; } - /** - * @param NodesSourcesDocuments $nodesSourcesDocuments - * @return bool - */ #[SymfonySerializer\Ignore] public function hasNodesSourcesDocuments(NodesSourcesDocuments $nodesSourcesDocuments): bool { return $this->getDocumentsByFields()->exists( function ($key, NodesSourcesDocuments $element) use ($nodesSourcesDocuments) { - return $nodesSourcesDocuments->getDocument()->getId() !== null && - $element->getDocument()->getId() === $nodesSourcesDocuments->getDocument()->getId() && - $element->getFieldName() === $nodesSourcesDocuments->getFieldName(); + return null !== $nodesSourcesDocuments->getDocument()->getId() + && $element->getDocument()->getId() === $nodesSourcesDocuments->getDocument()->getId() + && $element->getFieldName() === $nodesSourcesDocuments->getFieldName(); } ); } @@ -342,8 +330,6 @@ function ($key, NodesSourcesDocuments $element) use ($nodesSourcesDocuments) { /** * Used by any NSClass to add directly new documents to source. * - * @param NodesSourcesDocuments $nodesSourcesDocuments - * * @return $this */ public function addDocumentsByFields(NodesSourcesDocuments $nodesSourcesDocuments): NodesSources @@ -352,6 +338,7 @@ public function addDocumentsByFields(NodesSourcesDocuments $nodesSourcesDocument $this->getDocumentsByFields()->add($nodesSourcesDocuments); $nodesSourcesDocuments->setNodeSource($this); } + return $this; } @@ -364,6 +351,7 @@ public function getDocumentsByFieldsWithField(NodeTypeFieldInterface $field): ar { $criteria = Criteria::create(); $criteria->orderBy(['position' => 'ASC']); + return $this->getDocumentsByFields() ->matching($criteria) ->filter(function (NodesSourcesDocuments $element) use ($field) { @@ -377,13 +365,13 @@ public function getDocumentsByFieldsWithField(NodeTypeFieldInterface $field): ar } /** - * @param string $fieldName * @return Document[] */ public function getDocumentsByFieldsWithName(string $fieldName): array { $criteria = Criteria::create(); $criteria->orderBy(['position' => 'ASC']); + return $this->getDocumentsByFields() ->matching($criteria) ->filter(function (NodesSourcesDocuments $element) use ($fieldName) { @@ -406,43 +394,32 @@ public function getRedirections(): Collection /** * @param Collection $redirections - * @return NodesSources */ public function setRedirections(Collection $redirections): NodesSources { $this->redirections = $redirections; + return $this; } - /** - * @return \DateTime|null - */ public function getPublishedAt(): ?\DateTime { return $this->publishedAt; } - /** - * @param \DateTime|null $publishedAt - * @return NodesSources - */ - public function setPublishedAt(\DateTime $publishedAt = null): NodesSources + public function setPublishedAt(?\DateTime $publishedAt = null): NodesSources { $this->publishedAt = $publishedAt; + return $this; } - /** - * @return string - */ public function getMetaTitle(): string { return $this->metaTitle; } /** - * @param string|null $metaTitle - * * @return $this */ public function setMetaTitle(?string $metaTitle): NodesSources @@ -452,17 +429,12 @@ public function setMetaTitle(?string $metaTitle): NodesSources return $this; } - /** - * @return string - */ public function getMetaDescription(): string { return $this->metaDescription; } /** - * @param string|null $metaDescription - * * @return $this */ public function setMetaDescription(?string $metaDescription): NodesSources @@ -472,28 +444,23 @@ public function setMetaDescription(?string $metaDescription): NodesSources return $this; } - /** - * @return bool - */ public function isNoIndex(): bool { return $this->noIndex; } - /** - * @param bool $noIndex - * @return NodesSources - */ public function setNoIndex(bool $noIndex): NodesSources { $this->noIndex = $noIndex; + return $this; } /** - * @return string * @Serializer\VirtualProperty + * * @Serializer\SerializedName("slug") + * * @Serializer\Groups({"nodes_sources", "nodes_sources_base"}) */ #[SymfonySerializer\SerializedName('slug')] @@ -501,7 +468,7 @@ public function setNoIndex(bool $noIndex): NodesSources public function getIdentifier(): string { $urlAlias = $this->getUrlAliases()->first(); - if (false !== $urlAlias && $urlAlias->getAlias() !== '') { + if (false !== $urlAlias && '' !== $urlAlias->getAlias()) { return $urlAlias->getAlias(); } @@ -519,7 +486,6 @@ public function getUrlAliases(): Collection /** * Get parent node’ source based on the same translation. * - * @return NodesSources|null * @Serializer\Exclude */ #[SymfonySerializer\Ignore] @@ -530,61 +496,53 @@ public function getParent(): ?NodesSources if (null !== $parent) { /** @var NodesSources|false $nodeSources */ $nodeSources = $parent->getNodeSourcesByTranslation($this->translation)->first(); + return $nodeSources ?: null; } else { return null; } } - /** - * @return string - */ public function __toString(): string { return (string) $this->getId(); } - /** - * @return string|null - */ public function getTitle(): ?string { return $this->title; } /** - * @param string|null $title * @return $this */ public function setTitle(?string $title): NodesSources { $this->title = null !== $title ? trim($title) : null; + return $this; } - /** - * @return TranslationInterface - */ public function getTranslation(): TranslationInterface { return $this->translation; } /** - * @param TranslationInterface $translation - * * @return $this */ public function setTranslation(TranslationInterface $translation): NodesSources { $this->translation = $translation; + return $this; } /** - * @return string * @Serializer\VirtualProperty + * * @Serializer\Groups({"nodes_sources", "nodes_sources_default"}) + * * @Serializer\SerializedName("@type") */ #[SymfonySerializer\Groups(['nodes_sources', 'nodes_sources_default'])] @@ -596,8 +554,6 @@ public function getNodeTypeName(): string /** * Overridden in NS classes. - * - * @return bool */ public function isPublishable(): bool { @@ -606,8 +562,6 @@ public function isPublishable(): bool /** * Overridden in NS classes. - * - * @return bool */ public function isReachable(): bool { @@ -616,8 +570,6 @@ public function isReachable(): bool /** * Returns current listing sort options OR parent node's if parent node is hiding children. - * - * @return array */ #[Serializer\Groups(['node_listing'])] #[SymfonySerializer\Groups(['node_listing'])] @@ -626,21 +578,22 @@ public function getListingSortOptions(): array if (null !== $this->getParent() && $this->getParent()->getNode()->isHidingChildren()) { return $this->getParent()->getListingSortOptions(); } + return match ($this->getNode()->getChildrenOrder()) { 'position' => [ - 'node.position' => $this->getNode()->getChildrenOrderDirection() + 'node.position' => $this->getNode()->getChildrenOrderDirection(), ], 'nodeName' => [ - 'node.nodeName' => $this->getNode()->getChildrenOrderDirection() + 'node.nodeName' => $this->getNode()->getChildrenOrderDirection(), ], 'createdAt' => [ - 'node.createdAt' => $this->getNode()->getChildrenOrderDirection() + 'node.createdAt' => $this->getNode()->getChildrenOrderDirection(), ], 'updatedAt' => [ - 'node.updatedAt' => $this->getNode()->getChildrenOrderDirection() + 'node.updatedAt' => $this->getNode()->getChildrenOrderDirection(), ], default => [ - 'publishedAt' => $this->getNode()->getChildrenOrderDirection() + 'publishedAt' => $this->getNode()->getChildrenOrderDirection(), ], }; } diff --git a/lib/RoadizCoreBundle/src/Entity/NodesSourcesDocuments.php b/lib/RoadizCoreBundle/src/Entity/NodesSourcesDocuments.php index 6842bba9..f0472cc2 100644 --- a/lib/RoadizCoreBundle/src/Entity/NodesSourcesDocuments.php +++ b/lib/RoadizCoreBundle/src/Entity/NodesSourcesDocuments.php @@ -16,18 +16,15 @@ */ #[ ORM\Entity(repositoryClass: NodesSourcesDocumentsRepository::class), - ORM\Table(name: "nodes_sources_documents"), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["ns_id", "field_name"], name: "nsdoc_field"), - ORM\Index(columns: ["ns_id", "field_name", "position"], name: "nsdoc_field_position") + ORM\Table(name: 'nodes_sources_documents'), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['ns_id', 'field_name'], name: 'nsdoc_field'), + ORM\Index(columns: ['ns_id', 'field_name', 'position'], name: 'nsdoc_field_position') ] class NodesSourcesDocuments extends AbstractPositioned { use FieldAwareEntityTrait; - /** - * @var NodesSources - */ #[ORM\ManyToOne( targetEntity: NodesSources::class, cascade: ['persist'], @@ -38,9 +35,6 @@ class NodesSourcesDocuments extends AbstractPositioned #[ORM\JoinColumn(name: 'ns_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] protected NodesSources $nodeSource; - /** - * @var Document - */ #[ORM\ManyToOne( targetEntity: Document::class, cascade: ['persist'], @@ -54,9 +48,9 @@ class NodesSourcesDocuments extends AbstractPositioned /** * Create a new relation between NodeSource, a Document and a NodeTypeField. * - * @param NodesSources $nodeSource NodesSources and inherited types - * @param Document $document Document to link - * @param NodeTypeFieldInterface|null $field NodeTypeField + * @param NodesSources $nodeSource NodesSources and inherited types + * @param Document $document Document to link + * @param NodeTypeFieldInterface|null $field NodeTypeField */ public function __construct(NodesSources $nodeSource, Document $document, ?NodeTypeFieldInterface $field = null) { @@ -77,8 +71,6 @@ public function __clone() /** * Gets the value of nodeSource. - * - * @return NodesSources */ public function getNodeSource(): NodesSources { @@ -89,8 +81,6 @@ public function getNodeSource(): NodesSources * Sets the value of nodeSource. * * @param NodesSources $nodeSource the node source - * - * @return self */ public function setNodeSource(NodesSources $nodeSource): NodesSourcesDocuments { @@ -101,8 +91,6 @@ public function setNodeSource(NodesSources $nodeSource): NodesSourcesDocuments /** * Gets the value of document. - * - * @return Document */ public function getDocument(): Document { @@ -113,8 +101,6 @@ public function getDocument(): Document * Sets the value of document. * * @param Document $document the document - * - * @return self */ public function setDocument(Document $document): NodesSourcesDocuments { diff --git a/lib/RoadizCoreBundle/src/Entity/NodesTags.php b/lib/RoadizCoreBundle/src/Entity/NodesTags.php index e2e82b67..746dff6d 100644 --- a/lib/RoadizCoreBundle/src/Entity/NodesTags.php +++ b/lib/RoadizCoreBundle/src/Entity/NodesTags.php @@ -14,7 +14,7 @@ #[ ORM\Entity(repositoryClass: NodesTagsRepository::class), - ORM\Table(name: "nodes_tags"), + ORM\Table(name: 'nodes_tags'), ORM\Index(columns: ['node_id', 'position'], name: 'nodes_tags_node_id_position'), ORM\Index(columns: ['tag_id', 'position'], name: 'nodes_tags_tag_id_position'), ORM\Index(columns: ['position'], name: 'nodes_tags_position'), @@ -27,17 +27,17 @@ class NodesTags implements PositionedInterface, Comparable #[ ORM\Id, - ORM\Column(type:"string", length:36), + ORM\Column(type: 'string', length: 36), SymfonySerializer\Ignore ] /** @phpstan-ignore-next-line */ protected ?string $id = null; #[ - ORM\ManyToOne(targetEntity: Node::class, inversedBy: "nodesTags"), + ORM\ManyToOne(targetEntity: Node::class, inversedBy: 'nodesTags'), ORM\JoinColumn( - name: "node_id", - referencedColumnName: "id", + name: 'node_id', + referencedColumnName: 'id', unique: false, nullable: false, onDelete: 'CASCADE' @@ -48,10 +48,10 @@ class NodesTags implements PositionedInterface, Comparable private Node $node; #[ - ORM\ManyToOne(targetEntity: Tag::class, inversedBy: "nodesTags"), + ORM\ManyToOne(targetEntity: Tag::class, inversedBy: 'nodesTags'), ORM\JoinColumn( - name: "tag_id", - referencedColumnName: "id", + name: 'tag_id', + referencedColumnName: 'id', unique: false, nullable: false, onDelete: 'CASCADE' @@ -62,7 +62,7 @@ class NodesTags implements PositionedInterface, Comparable private Tag $tag; #[ - ORM\Column(type: "float", nullable: false, options: ['default' => 1]), + ORM\Column(type: 'float', nullable: false, options: ['default' => 1]), SymfonySerializer\Ignore, Serializer\Exclude, ] @@ -73,39 +73,27 @@ public function __construct(?string $uuid = null) $this->id = $uuid ?? \Ramsey\Uuid\Uuid::uuid4()->toString(); } - /** - * @return Node - */ public function getNode(): Node { return $this->node; } - /** - * @param Node $node - * @return NodesTags - */ public function setNode(Node $node): NodesTags { $this->node = $node; + return $this; } - /** - * @return Tag - */ public function getTag(): Tag { return $this->tag; } - /** - * @param Tag $tag - * @return NodesTags - */ public function setTag(Tag $tag): NodesTags { $this->tag = $tag; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/NodesToNodes.php b/lib/RoadizCoreBundle/src/Entity/NodesToNodes.php index b80836c9..6b24f4ca 100644 --- a/lib/RoadizCoreBundle/src/Entity/NodesToNodes.php +++ b/lib/RoadizCoreBundle/src/Entity/NodesToNodes.php @@ -15,12 +15,12 @@ */ #[ ORM\Entity(repositoryClass: NodesToNodesRepository::class), - ORM\Table(name: "nodes_to_nodes"), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["node_a_id", "field_name"], name: "node_a_field"), - ORM\Index(columns: ["node_a_id", "field_name", "position"], name: "node_a_field_position"), - ORM\Index(columns: ["node_b_id", "field_name"], name: "node_b_field"), - ORM\Index(columns: ["node_b_id", "field_name", "position"], name: "node_b_field_position") + ORM\Table(name: 'nodes_to_nodes'), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['node_a_id', 'field_name'], name: 'node_a_field'), + ORM\Index(columns: ['node_a_id', 'field_name', 'position'], name: 'node_a_field_position'), + ORM\Index(columns: ['node_b_id', 'field_name'], name: 'node_b_field'), + ORM\Index(columns: ['node_b_id', 'field_name', 'position'], name: 'node_b_field_position') ] class NodesToNodes extends AbstractPositioned { @@ -50,8 +50,6 @@ public function __clone() /** * Gets the value of nodeA. - * - * @return Node */ public function getNodeA(): Node { @@ -62,8 +60,6 @@ public function getNodeA(): Node * Sets the value of nodeA. * * @param Node $nodeA the node - * - * @return self */ public function setNodeA(Node $nodeA): NodesToNodes { @@ -74,8 +70,6 @@ public function setNodeA(Node $nodeA): NodesToNodes /** * Gets the value of nodeB. - * - * @return Node */ public function getNodeB(): Node { @@ -86,12 +80,11 @@ public function getNodeB(): Node * Sets the value of nodeB. * * @param Node $nodeB the node - * - * @return self */ public function setNodeB(Node $nodeB): NodesToNodes { $this->nodeB = $nodeB; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Realm.php b/lib/RoadizCoreBundle/src/Entity/Realm.php index 9cf68e49..7f66eb4b 100644 --- a/lib/RoadizCoreBundle/src/Entity/Realm.php +++ b/lib/RoadizCoreBundle/src/Entity/Realm.php @@ -27,15 +27,15 @@ */ #[ ORM\Entity(repositoryClass: RealmRepository::class), - ORM\Table(name: "realms"), - ORM\Index(columns: ["type"], name: "realms_type"), - ORM\Index(columns: ["behaviour"], name: "realms_behaviour"), - UniqueEntity(fields: ["name"]), + ORM\Table(name: 'realms'), + ORM\Index(columns: ['type'], name: 'realms_type'), + ORM\Index(columns: ['behaviour'], name: 'realms_behaviour'), + UniqueEntity(fields: ['name']), ApiFilter(PropertyFilter::class), ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "type" => "exact", - "behaviour" => "exact", - "name" => "exact" + 'type' => 'exact', + 'behaviour' => 'exact', + 'name' => 'exact', ]) ] class Realm extends AbstractEntity implements RealmInterface @@ -62,7 +62,6 @@ class Realm extends AbstractEntity implements RealmInterface private string $name = ''; /** - * @var string|null * @Serializer\Exclude() */ #[ORM\Column(name: 'plain_password', type: 'string', length: 255, unique: false, nullable: true)] @@ -105,73 +104,53 @@ public function __construct() $this->realmNodes = new ArrayCollection(); } - /** - * @return string|null - */ public function getRole(): ?string { if (null === $this->roleEntity) { return null; } + return $this->roleEntity->getRole(); } - /** - * @return Role|null - */ public function getRoleEntity(): ?Role { return $this->roleEntity; } - /** - * @param Role|null $roleEntity - * @return Realm - */ public function setRoleEntity(?Role $roleEntity): Realm { $this->roleEntity = $roleEntity; + return $this; } - /** - * @return string|null - */ public function getSerializationGroup(): ?string { return $this->serializationGroup; } - /** - * @param string|null $serializationGroup - * @return Realm - */ public function setSerializationGroup(?string $serializationGroup): Realm { $this->serializationGroup = null !== $serializationGroup ? (new AsciiSlugger())->slug($serializationGroup, '_')->lower()->toString() : null; + return $this; } - /** - * @return string - */ public function getName(): string { return $this->name ?? ''; } - /** - * @param string $name - * @return Realm - */ public function setName(string $name): Realm { $this->name = $name; if (null === $this->serializationGroup) { $this->serializationGroup = (new AsciiSlugger())->slug($this->name, '_')->lower()->toString(); } + return $this; } @@ -185,11 +164,13 @@ public function getRealmNodes(): Collection /** * @param Collection $realmNodes + * * @return Realm */ public function setRealmNodes(Collection $realmNodes) { $this->realmNodes = $realmNodes; + return $this; } @@ -203,58 +184,45 @@ public function getUsers(): Collection /** * @param Collection $users + * * @return Realm */ public function setUsers(Collection $users) { $this->users = $users; + return $this; } - /** - * @return string|null - */ public function getPlainPassword(): ?string { return $this->plainPassword; } - /** - * @param string|null $plainPassword - * @return Realm - */ public function setPlainPassword(?string $plainPassword): Realm { $this->plainPassword = $plainPassword; + return $this; } - /** - * @return string - */ public function getBehaviour(): string { return $this->behaviour; } - /** - * @param string $behaviour - * @return Realm - */ public function setBehaviour(string $behaviour): Realm { $this->behaviour = $behaviour; + return $this; } public function getChallenge(): string { - return $this->getAuthenticationScheme() . ' realm="' . addslashes($this->getName()) . '"'; + return $this->getAuthenticationScheme().' realm="'.addslashes($this->getName()).'"'; } - /** - * @return string - */ #[SymfonySerializer\Groups(['get', 'realm', 'web_response'])] #[Serializer\Groups(['get', 'realm', 'web_response'])] public function getAuthenticationScheme(): string @@ -267,21 +235,15 @@ public function getAuthenticationScheme(): string } } - /** - * @return string - */ public function getType(): string { return $this->type; } - /** - * @param string $type - * @return Realm - */ public function setType(string $type): Realm { $this->type = $type; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/RealmNode.php b/lib/RoadizCoreBundle/src/Entity/RealmNode.php index 8007a309..e0623569 100644 --- a/lib/RoadizCoreBundle/src/Entity/RealmNode.php +++ b/lib/RoadizCoreBundle/src/Entity/RealmNode.php @@ -7,21 +7,21 @@ use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; +use RZ\Roadiz\CoreBundle\Model\RealmInterface; use RZ\Roadiz\CoreBundle\Repository\RealmNodeRepository; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Serializer\Annotation as SymfonySerializer; -use RZ\Roadiz\CoreBundle\Model\RealmInterface; use Symfony\Component\Validator\Constraints as Assert; #[ ORM\Entity(repositoryClass: RealmNodeRepository::class), - ORM\Table(name: "realms_nodes"), - ORM\Index(columns: ["inheritance_type"], name: "realms_nodes_inheritance_type"), - ORM\Index(columns: ["realm_id"], name: "realms_nodes_realm"), - ORM\Index(columns: ["node_id"], name: "realms_nodes_node"), - ORM\Index(columns: ["node_id", "inheritance_type"], name: "realms_nodes_node_inheritance_type"), - ORM\UniqueConstraint(name: "realms_nodes_unique", columns: ["node_id", "realm_id"]), - UniqueEntity(fields: ["node", "realm"]) + ORM\Table(name: 'realms_nodes'), + ORM\Index(columns: ['inheritance_type'], name: 'realms_nodes_inheritance_type'), + ORM\Index(columns: ['realm_id'], name: 'realms_nodes_realm'), + ORM\Index(columns: ['node_id'], name: 'realms_nodes_node'), + ORM\Index(columns: ['node_id', 'inheritance_type'], name: 'realms_nodes_node_inheritance_type'), + ORM\UniqueConstraint(name: 'realms_nodes_unique', columns: ['node_id', 'realm_id']), + UniqueEntity(fields: ['node', 'realm']) ] class RealmNode extends AbstractEntity { @@ -55,57 +55,39 @@ class RealmNode extends AbstractEntity #[Serializer\Exclude] private string $inheritanceType = RealmInterface::INHERITANCE_AUTO; - /** - * @return Node - */ public function getNode(): Node { return $this->node; } - /** - * @param Node $node - * @return RealmNode - */ public function setNode(Node $node): RealmNode { $this->node = $node; + return $this; } - /** - * @return Realm - */ public function getRealm(): Realm { return $this->realm; } - /** - * @param Realm $realm - * @return RealmNode - */ public function setRealm(Realm $realm): RealmNode { $this->realm = $realm; + return $this; } - /** - * @return string - */ public function getInheritanceType(): string { return $this->inheritanceType; } - /** - * @param string $inheritanceType - * @return RealmNode - */ public function setInheritanceType(string $inheritanceType): RealmNode { $this->inheritanceType = $inheritanceType; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Redirection.php b/lib/RoadizCoreBundle/src/Entity/Redirection.php index 469222ef..bf642a74 100644 --- a/lib/RoadizCoreBundle/src/Entity/Redirection.php +++ b/lib/RoadizCoreBundle/src/Entity/Redirection.php @@ -16,19 +16,19 @@ */ #[ ORM\Entity(repositoryClass: RedirectionRepository::class), - ORM\Table(name: "redirections"), + ORM\Table(name: 'redirections'), ORM\HasLifecycleCallbacks, - UniqueEntity(fields: ["query"]), - ORM\Index(columns: ["use_count"], name: 'redirection_use_count'), - ORM\Index(columns: ["created_at"], name: "redirection_created_at"), - ORM\Index(columns: ["updated_at"], name: "redirection_updated_at"), + UniqueEntity(fields: ['query']), + ORM\Index(columns: ['use_count'], name: 'redirection_use_count'), + ORM\Index(columns: ['created_at'], name: 'redirection_created_at'), + ORM\Index(columns: ['updated_at'], name: 'redirection_updated_at'), ] class Redirection extends AbstractDateTimed { #[ORM\Column(type: 'string', length: 255, unique: true)] #[Assert\NotBlank] #[Assert\Length(max: 255)] - private string $query = ""; + private string $query = ''; #[ORM\Column(name: 'redirectUri', type: 'text', length: 2048, nullable: true)] #[Assert\Length(max: 2048)] @@ -38,84 +38,54 @@ class Redirection extends AbstractDateTimed #[Assert\Length(max: 2048)] private int $useCount = 0; - /** - * @var NodesSources|null - */ #[ORM\ManyToOne(targetEntity: NodesSources::class, cascade: ['persist'], inversedBy: 'redirections')] #[ORM\JoinColumn(name: 'ns_id', referencedColumnName: 'id', onDelete: 'CASCADE')] private ?NodesSources $redirectNodeSource = null; - /** - * @var int - */ #[ORM\Column(type: 'integer')] private int $type = 301; - /** - * @return string - */ public function getQuery(): string { return $this->query; } - /** - * @param string|null $query - * @return Redirection - */ public function setQuery(?string $query): Redirection { $this->query = $query ?? ''; + return $this; } - /** - * @return string|null - */ public function getRedirectUri(): ?string { return $this->redirectUri; } - /** - * @param string|null $redirectUri - * @return Redirection - */ public function setRedirectUri(?string $redirectUri): Redirection { $this->redirectUri = $redirectUri; + return $this; } - /** - * @return NodesSources|null - */ public function getRedirectNodeSource(): ?NodesSources { return $this->redirectNodeSource; } - /** - * @param NodesSources|null $redirectNodeSource - * @return Redirection - */ - public function setRedirectNodeSource(NodesSources $redirectNodeSource = null): Redirection + public function setRedirectNodeSource(?NodesSources $redirectNodeSource = null): Redirection { $this->redirectNodeSource = $redirectNodeSource; + return $this; } - /** - * @return int - */ public function getType(): int { return $this->type; } - /** - * @return string - */ public function getTypeAsString(): string { $types = [ @@ -126,13 +96,10 @@ public function getTypeAsString(): string return $types[$this->type] ?? ''; } - /** - * @param int $type - * @return Redirection - */ public function setType(int $type): Redirection { $this->type = $type; + return $this; } @@ -142,9 +109,6 @@ public function __construct() $this->initAbstractDateTimed(); } - /** - * @return int - */ public function getUseCount(): int { return $this->useCount; @@ -152,7 +116,8 @@ public function getUseCount(): int public function incrementUseCount(): self { - $this->useCount++; + ++$this->useCount; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Role.php b/lib/RoadizCoreBundle/src/Entity/Role.php index d1a03ca8..9c76c739 100644 --- a/lib/RoadizCoreBundle/src/Entity/Role.php +++ b/lib/RoadizCoreBundle/src/Entity/Role.php @@ -20,8 +20,8 @@ */ #[ ORM\Entity(repositoryClass: RoleRepository::class), - ORM\Table(name: "roles"), - UniqueEntity(fields: ["name"]) + ORM\Table(name: 'roles'), + UniqueEntity(fields: ['name']) ] class Role implements PersistableInterface { @@ -31,8 +31,8 @@ class Role implements PersistableInterface #[ ORM\Id, - ORM\Column(type: "integer"), - ORM\GeneratedValue(strategy: "AUTO") + ORM\Column(type: 'integer'), + ORM\GeneratedValue(strategy: 'AUTO') ] protected ?int $id = null; @@ -51,7 +51,7 @@ class Role implements PersistableInterface #[ORM\ManyToMany(targetEntity: Group::class, mappedBy: 'roleEntities', cascade: ['persist', 'merge'])] #[SymfonySerializer\Groups(['role'])] #[Serializer\Groups(['role'])] - #[Serializer\Accessor(getter: "getGroups", setter: "setGroups")] + #[Serializer\Accessor(getter: 'getGroups', setter: 'setGroups')] #[Serializer\Type("ArrayCollection")] private Collection $groups; @@ -66,26 +66,19 @@ public function __construct(string $name) $this->groups = new ArrayCollection(); } - /** - * @return int|null - */ public function getId(): ?int { return $this->id; } - /** - * @param int|null $id - * @return Role - */ public function setId(?int $id): Role { $this->id = $id; + return $this; } /** - * @return string * @deprecated Use getRole method */ public function getName(): string @@ -94,8 +87,6 @@ public function getName(): string } /** - * @param string $name - * @return Role * @deprecated Use setRole method */ public function setName(string $name): Role @@ -103,21 +94,13 @@ public function setName(string $name): Role return $this->setRole($name); } - /** - * @param string $role - * @return Role - */ public function setRole(string $role): Role { $this->name = static::cleanName($role); + return $this; } - /** - * @param string $name - * - * @return string - */ public static function cleanName(string $name): string { $string = (new UnicodeString($name)) @@ -134,7 +117,6 @@ public static function cleanName(string $name): string } /** - * @param Group $group * @return $this */ public function addGroup(Group $group): Role @@ -146,16 +128,12 @@ public function addGroup(Group $group): Role return $this; } - /** - * @return Collection - */ public function getGroups(): Collection { return $this->groups; } /** - * @param Collection $groups * @return $this */ public function setGroups(Collection $groups): Role @@ -170,7 +148,6 @@ public function setGroups(Collection $groups): Role } /** - * @param Group $group * @return $this */ public function removeGroup(Group $group): Role @@ -187,7 +164,6 @@ public function removeGroup(Group $group): Role * * It replaces underscores by dashes and lowercase. * - * @return string * @Serializer\Groups({"role"}) */ #[SymfonySerializer\Groups(['role'])] @@ -196,23 +172,17 @@ public function getClassName(): string return str_replace('_', '-', \mb_strtolower($this->getRole())); } - /** - * @return string - */ public function getRole(): string { return $this->name; } - /** - * @return bool - */ public function required(): bool { if ( - $this->getRole() == static::ROLE_DEFAULT || - $this->getRole() == static::ROLE_SUPERADMIN || - $this->getRole() == static::ROLE_BACKEND_USER + $this->getRole() == static::ROLE_DEFAULT + || $this->getRole() == static::ROLE_SUPERADMIN + || $this->getRole() == static::ROLE_BACKEND_USER ) { return true; } @@ -220,9 +190,6 @@ public function required(): bool return false; } - /** - * @return string - */ public function __toString(): string { return $this->getRole(); diff --git a/lib/RoadizCoreBundle/src/Entity/Setting.php b/lib/RoadizCoreBundle/src/Entity/Setting.php index 2670a463..63630bbc 100644 --- a/lib/RoadizCoreBundle/src/Entity/Setting.php +++ b/lib/RoadizCoreBundle/src/Entity/Setting.php @@ -6,11 +6,11 @@ use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; +use RZ\Roadiz\Core\AbstractEntities\AbstractField; use RZ\Roadiz\CoreBundle\Repository\SettingRepository; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Serializer\Annotation as SymfonySerializer; -use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; -use RZ\Roadiz\Core\AbstractEntities\AbstractField; use Symfony\Component\String\UnicodeString; use Symfony\Component\Validator\Constraints as Assert; @@ -19,11 +19,11 @@ */ #[ ORM\Entity(repositoryClass: SettingRepository::class), - ORM\Table(name: "settings"), - ORM\Index(columns: ["type"]), - ORM\Index(columns: ["name"]), - ORM\Index(columns: ["visible"]), - UniqueEntity(fields: ["name"]) + ORM\Table(name: 'settings'), + ORM\Index(columns: ['type']), + ORM\Index(columns: ['name']), + ORM\Index(columns: ['visible']), + UniqueEntity(fields: ['name']) ] class Setting extends AbstractEntity { @@ -85,7 +85,7 @@ class Setting extends AbstractEntity #[SymfonySerializer\Groups(['setting'])] #[Serializer\Groups(['setting'])] #[Serializer\AccessType(type: 'public_method')] - #[Serializer\Accessor(getter: "getSettingGroup", setter: "setSettingGroup")] + #[Serializer\Accessor(getter: 'getSettingGroup', setter: 'setSettingGroup')] private ?SettingGroup $settingGroup; /** @@ -105,17 +105,12 @@ class Setting extends AbstractEntity #[Serializer\Groups(['setting'])] private ?string $defaultValues; - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string|null $name - * * @return $this */ public function setName(?string $name): self @@ -129,19 +124,11 @@ public function setName(?string $name): self return $this; } - /** - * @return string|null - */ public function getDescription(): ?string { return $this->description; } - /** - * @param string|null $description - * - * @return Setting - */ public function setDescription(?string $description): Setting { $this->description = $description; @@ -149,30 +136,26 @@ public function setDescription(?string $description): Setting return $this; } - /** - * @return string|null - */ public function getRawValue(): ?string { return $this->value; } /** - * @return string|bool|\DateTime|int|null * @throws \Exception */ #[SymfonySerializer\Ignore] public function getValue(): string|bool|\DateTime|int|null { - if ($this->getType() == AbstractField::BOOLEAN_T) { + if (AbstractField::BOOLEAN_T == $this->getType()) { return (bool) $this->value; } if (null !== $this->value) { - if ($this->getType() == AbstractField::DATETIME_T) { + if (AbstractField::DATETIME_T == $this->getType()) { return new \DateTime($this->value); } - if ($this->getType() == AbstractField::DOCUMENTS_T) { + if (AbstractField::DOCUMENTS_T == $this->getType()) { return (int) $this->value; } } @@ -181,8 +164,6 @@ public function getValue(): string|bool|\DateTime|int|null } /** - * @param mixed $value - * * @return $this */ public function setValue(mixed $value): self @@ -198,17 +179,12 @@ public function setValue(mixed $value): self return $this; } - /** - * @return int - */ public function getType(): int { return $this->type; } /** - * @param int $type - * * @return $this */ public function setType(int $type): self @@ -218,17 +194,12 @@ public function setType(int $type): self return $this; } - /** - * @return boolean - */ public function isVisible(): bool { return $this->visible; } /** - * @param bool $visible - * * @return $this */ public function setVisible(bool $visible): self @@ -238,17 +209,12 @@ public function setVisible(bool $visible): self return $this; } - /** - * @return SettingGroup|null - */ public function getSettingGroup(): ?SettingGroup { return $this->settingGroup; } /** - * @param SettingGroup|null $settingGroup - * * @return $this */ public function setSettingGroup(?SettingGroup $settingGroup): self @@ -258,19 +224,11 @@ public function setSettingGroup(?SettingGroup $settingGroup): self return $this; } - /** - * @return string|null - */ public function getDefaultValues(): ?string { return $this->defaultValues; } - /** - * @param string|null $defaultValues - * - * @return Setting - */ public function setDefaultValues(?string $defaultValues): self { $this->defaultValues = $defaultValues; diff --git a/lib/RoadizCoreBundle/src/Entity/SettingGroup.php b/lib/RoadizCoreBundle/src/Entity/SettingGroup.php index a8d73195..364661b4 100644 --- a/lib/RoadizCoreBundle/src/Entity/SettingGroup.php +++ b/lib/RoadizCoreBundle/src/Entity/SettingGroup.php @@ -19,8 +19,8 @@ */ #[ ORM\Entity(repositoryClass: SettingGroupRepository::class), - ORM\Table(name: "settings_groups"), - UniqueEntity(fields: ["name"]) + ORM\Table(name: 'settings_groups'), + UniqueEntity(fields: ['name']) ] class SettingGroup extends AbstractEntity { @@ -50,35 +50,27 @@ public function __construct() $this->settings = new ArrayCollection(); } - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string $name - * * @return SettingGroup */ public function setName(string $name) { $this->name = $name; + return $this; } - /** - * @return bool - */ public function isInMenu(): bool { return $this->inMenu; } /** - * @param bool $newinMenu * @return SettingGroup */ public function setInMenu(bool $newinMenu) @@ -89,7 +81,6 @@ public function setInMenu(bool $newinMenu) } /** - * @param Setting $setting * @return SettingGroup */ public function addSetting(Setting $setting) @@ -97,6 +88,7 @@ public function addSetting(Setting $setting) if (!$this->getSettings()->contains($setting)) { $this->settings->add($setting); } + return $this; } @@ -110,6 +102,7 @@ public function getSettings(): Collection /** * @param Collection $settings + * * @return SettingGroup */ public function addSettings(Collection $settings) @@ -119,6 +112,7 @@ public function addSettings(Collection $settings) $this->settings->add($setting); } } + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Tag.php b/lib/RoadizCoreBundle/src/Entity/Tag.php index e8503dea..e166e3b1 100644 --- a/lib/RoadizCoreBundle/src/Entity/Tag.php +++ b/lib/RoadizCoreBundle/src/Entity/Tag.php @@ -28,22 +28,22 @@ #[ ORM\Entity(repositoryClass: TagRepository::class), ORM\HasLifecycleCallbacks, - ORM\Table(name: "tags"), - ORM\Index(columns: ["visible"]), - ORM\Index(columns: ["locked"]), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["created_at"]), - ORM\Index(columns: ["updated_at"]), - ORM\Index(columns: ["parent_tag_id", "position"], name: "tag_parent_position"), - ORM\Index(columns: ["visible", "position"], name: "tag_visible_position"), - ORM\Index(columns: ["parent_tag_id", "visible"], name: "tag_parent_visible"), - ORM\Index(columns: ["parent_tag_id", "visible", "position"], name: "tag_parent_visible_position"), - UniqueEntity(fields: ["tagName"]), + ORM\Table(name: 'tags'), + ORM\Index(columns: ['visible']), + ORM\Index(columns: ['locked']), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['created_at']), + ORM\Index(columns: ['updated_at']), + ORM\Index(columns: ['parent_tag_id', 'position'], name: 'tag_parent_position'), + ORM\Index(columns: ['visible', 'position'], name: 'tag_visible_position'), + ORM\Index(columns: ['parent_tag_id', 'visible'], name: 'tag_parent_visible'), + ORM\Index(columns: ['parent_tag_id', 'visible', 'position'], name: 'tag_parent_visible_position'), + UniqueEntity(fields: ['tagName']), ApiFilter(PropertyFilter::class), ApiFilter(BaseFilter\OrderFilter::class, properties: [ - "position", - "createdAt", - "updatedAt" + 'position', + 'createdAt', + 'updatedAt', ]) ] class Tag extends AbstractDateTimedPositioned implements LeafInterface @@ -71,12 +71,12 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface * @var Tag|null */ #[ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "parent.id" => "exact", - "parent.tagName" => "exact" + 'parent.id' => 'exact', + 'parent.tagName' => 'exact', ])] #[ApiFilter(NotFilter::class, properties: [ - "parent.id", - "parent.tagName" + 'parent.id', + 'parent.tagName', ])] #[ORM\ManyToOne(targetEntity: Tag::class, fetch: 'EXTRA_LAZY', inversedBy: 'children')] #[ORM\JoinColumn(name: 'parent_tag_id', referencedColumnName: 'id', onDelete: 'CASCADE')] @@ -97,7 +97,7 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface #[ORM\OrderBy(['position' => 'ASC'])] #[SymfonySerializer\Groups(['tag_children'])] #[Serializer\Groups(['tag_children'])] - #[Serializer\AccessType(type: "public_method")] + #[Serializer\AccessType(type: 'public_method')] protected Collection $children; /** @@ -113,11 +113,11 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface #[Serializer\Groups(['translated_tag'])] protected Collection $translatedTags; - #[ApiFilter(BaseFilter\SearchFilter::class, strategy: "partial")] + #[ApiFilter(BaseFilter\SearchFilter::class, strategy: 'partial')] #[ORM\Column(name: 'tag_name', type: 'string', length: 250, unique: true)] #[SymfonySerializer\Ignore] #[Serializer\Groups(['tag'])] - #[Serializer\Accessor(getter: "getTagName", setter: "setTagName")] + #[Serializer\Accessor(getter: 'getTagName', setter: 'setTagName')] #[Assert\NotNull] #[Assert\NotBlank] #[Assert\Length(max: 250)] @@ -143,7 +143,7 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface #[ORM\Column(name: 'children_order', type: 'string', length: 60, options: ['default' => 'position'])] #[SymfonySerializer\Ignore] - #[Serializer\Groups(["tag", "tag_children_order"])] + #[Serializer\Groups(['tag', 'tag_children_order'])] #[Assert\Length(max: 60)] #[ApiProperty( description: 'This tag children will be sorted by a given field', @@ -151,14 +151,14 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface schema: [ 'type' => 'string', 'enum' => ['position', 'tagName', 'createdAt', 'updatedAt', 'publishedAt'], - 'example' => 'position' + 'example' => 'position', ], )] private string $childrenOrder = 'position'; #[ORM\Column(name: 'children_order_direction', type: 'string', length: 4, options: ['default' => 'ASC'])] #[SymfonySerializer\Ignore] - #[Serializer\Groups(["tag", "tag_children_order"])] + #[Serializer\Groups(['tag', 'tag_children_order'])] #[Assert\Length(max: 4)] #[ApiProperty( description: 'This tag children will be sorted ascendant or descendant', @@ -166,7 +166,7 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface schema: [ 'type' => 'string', 'enum' => ['ASC', 'DESC'], - 'example' => 'ASC' + 'example' => 'ASC', ], )] private string $childrenOrderDirection = 'ASC'; @@ -174,7 +174,7 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface #[ApiFilter(BaseFilter\BooleanFilter::class)] #[ORM\Column(type: 'boolean', nullable: false, options: ['default' => false])] #[SymfonySerializer\Ignore] - #[Serializer\Groups(["tag"])] + #[Serializer\Groups(['tag'])] #[ApiProperty( description: 'Is this tag locked to prevent deletion and renaming?', example: 'false', @@ -194,18 +194,18 @@ class Tag extends AbstractDateTimedPositioned implements LeafInterface #[SymfonySerializer\Ignore] #[Serializer\Exclude] #[ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "nodesTags.node" => "exact", - "nodesTags.node.nodeName" => "exact", - "nodesTags.node.parent" => "exact", - "nodesTags.node.parent.nodeName" => "exact", - "nodesTags.node.nodeType" => "exact", - "nodesTags.node.nodeType.name" => "exact", - "nodesTags.node.nodesTags.tag" => "exact", - "nodesTags.node.nodesTags.tag.tagName" => "exact", + 'nodesTags.node' => 'exact', + 'nodesTags.node.nodeName' => 'exact', + 'nodesTags.node.parent' => 'exact', + 'nodesTags.node.parent.nodeName' => 'exact', + 'nodesTags.node.nodeType' => 'exact', + 'nodesTags.node.nodeType.name' => 'exact', + 'nodesTags.node.nodesTags.tag' => 'exact', + 'nodesTags.node.nodesTags.tag.tagName' => 'exact', ])] #[ApiFilter(BaseFilter\BooleanFilter::class, properties: [ - "nodesTags.node.visible", - "nodesTags.node.nodeType.reachable", + 'nodesTags.node.visible', + 'nodesTags.node.nodeType.reachable', ])] private Collection $nodesTags; @@ -222,25 +222,18 @@ public function __construct() /** * Gets the value of dirtyTagName. - * - * @return string */ public function getDirtyTagName(): string { return $this->dirtyTagName; } - /** - * @return boolean - */ public function isLocked(): bool { return $this->locked; } /** - * @param boolean $locked - * * @return $this */ public function setLocked(bool $locked): static @@ -262,8 +255,6 @@ public function getNodes(): Collection /** * Get tag full path using tag names. - * - * @return string */ public function getFullPath(): string { @@ -281,17 +272,12 @@ public function getFullPath(): string return implode('/', $path); } - /** - * @return string - */ public function getTagName(): string { return $this->tagName; } /** - * @param string $tagName - * * @return $this */ public function setTagName(string $tagName): static @@ -303,7 +289,6 @@ public function setTagName(string $tagName): static } /** - * @param TranslationInterface $translation * @return Collection */ #[SymfonySerializer\Ignore] @@ -322,38 +307,29 @@ public function getTranslatedTagsByDefaultTranslation(): ?TagTranslation }); } - /** - * @return string - */ public function getOneLineSummary(): string { - return $this->getId() . " — " . $this->getTagName() . - " — Visible : " . ($this->isVisible() ? 'true' : 'false') . PHP_EOL; + return $this->getId().' — '.$this->getTagName(). + ' — Visible : '.($this->isVisible() ? 'true' : 'false').PHP_EOL; } - /** - * @return boolean - */ public function isVisible(): bool { return $this->visible; } /** - * @param boolean $visible - * * @return $this */ public function setVisible(bool $visible): static { $this->visible = $visible; + return $this; } /** * Gets the value of color. - * - * @return string */ public function getColor(): string { @@ -364,8 +340,6 @@ public function getColor(): string * Sets the value of color. * * @param string|null $color the color - * - * @return static */ public function setColor(?string $color): static { @@ -376,8 +350,6 @@ public function setColor(?string $color): static /** * Gets the value of childrenOrder. - * - * @return string */ public function getChildrenOrder(): string { @@ -388,8 +360,6 @@ public function getChildrenOrder(): string * Sets the value of childrenOrder. * * @param string $childrenOrder the children order - * - * @return static */ public function setChildrenOrder(string $childrenOrder): static { @@ -400,8 +370,6 @@ public function setChildrenOrder(string $childrenOrder): static /** * Gets the value of childrenOrderDirection. - * - * @return string */ public function getChildrenOrderDirection(): string { @@ -412,8 +380,6 @@ public function getChildrenOrderDirection(): string * Sets the value of childrenOrderDirection. * * @param string $childrenOrderDirection the children order direction - * - * @return static */ public function setChildrenOrderDirection(string $childrenOrderDirection): static { @@ -422,19 +388,16 @@ public function setChildrenOrderDirection(string $childrenOrderDirection): stati return $this; } - /** - * @return string - */ public function __toString(): string { return (string) $this->getId(); } /** - * @return string|null - * * @Serializer\Groups({"tag", "tag_base", "node", "nodes_sources"}) + * * @Serializer\VirtualProperty + * * @Serializer\Type("string|null") */ #[SymfonySerializer\Ignore] @@ -455,6 +418,7 @@ public function getTranslatedTags(): Collection /** * @param Collection $translatedTags + * * @return $this */ public function setTranslatedTags(Collection $translatedTags): static @@ -464,14 +428,15 @@ public function setTranslatedTags(Collection $translatedTags): static foreach ($this->translatedTags as $translatedTag) { $translatedTag->setTag($this); } + return $this; } /** - * @return string|null - * * @Serializer\Groups({"tag", "node", "nodes_sources"}) + * * @Serializer\VirtualProperty + * * @Serializer\Type("string|null") */ #[SymfonySerializer\Ignore] @@ -483,10 +448,10 @@ public function getDescription(): ?string } /** - * @return array - * * @Serializer\Groups({"tag", "node", "nodes_sources"}) + * * @Serializer\VirtualProperty + * * @Serializer\Type("array") */ #[SymfonySerializer\Ignore] @@ -511,7 +476,6 @@ public function setParent(?LeafInterface $parent = null): static return $this; } - #[ApiProperty( description: 'Unique tag name (slug) used to build content URL or filter queries.', example: 'this-is-a-tag-name', diff --git a/lib/RoadizCoreBundle/src/Entity/TagTranslation.php b/lib/RoadizCoreBundle/src/Entity/TagTranslation.php index 36017fe1..58e8b880 100644 --- a/lib/RoadizCoreBundle/src/Entity/TagTranslation.php +++ b/lib/RoadizCoreBundle/src/Entity/TagTranslation.php @@ -23,10 +23,10 @@ */ #[ ORM\Entity(repositoryClass: TagTranslationRepository::class), - ORM\Table(name: "tags_translations"), - ORM\UniqueConstraint(columns: ["tag_id", "translation_id"]), + ORM\Table(name: 'tags_translations'), + ORM\UniqueConstraint(columns: ['tag_id', 'translation_id']), Gedmo\Loggable(logEntryClass: UserLogEntry::class), - UniqueEntity(fields: ["tag", "translation"]) + UniqueEntity(fields: ['tag', 'translation']) ] class TagTranslation extends AbstractEntity { @@ -58,6 +58,7 @@ class TagTranslation extends AbstractEntity /** * @var Collection + * * @Serializer\Exclude */ #[ORM\OneToMany( @@ -72,16 +73,13 @@ class TagTranslation extends AbstractEntity /** * Create a new TagTranslation with its origin Tag and Translation. - * - * @param Tag $original - * @param TranslationInterface $translation */ public function __construct(Tag $original, TranslationInterface $translation) { $this->setTag($original); $this->setTranslation($translation); $this->tagTranslationDocuments = new ArrayCollection(); - $this->name = $original->getDirtyTagName() != '' ? $original->getDirtyTagName() : $original->getTagName(); + $this->name = '' != $original->getDirtyTagName() ? $original->getDirtyTagName() : $original->getTagName(); } public function getName(): string @@ -116,6 +114,7 @@ public function getTag(): Tag public function setTag(Tag $tag): TagTranslation { $this->tag = $tag; + return $this; } @@ -153,10 +152,10 @@ public function __clone() } /** - * @return array - * * @Serializer\Groups({"tag"}) + * * @Serializer\VirtualProperty + * * @Serializer\Type("array") */ #[SymfonySerializer\Groups(['tag'])] @@ -167,21 +166,15 @@ public function getDocuments(): array }, $this->getTagTranslationDocuments()->toArray()); } - /** - * @return Collection - */ public function getTagTranslationDocuments(): Collection { return $this->tagTranslationDocuments; } - /** - * @param Collection $tagTranslationDocuments - * @return TagTranslation - */ public function setTagTranslationDocuments(Collection $tagTranslationDocuments): TagTranslation { $this->tagTranslationDocuments = $tagTranslationDocuments; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/TagTranslationDocuments.php b/lib/RoadizCoreBundle/src/Entity/TagTranslationDocuments.php index d06683da..cb350fb9 100644 --- a/lib/RoadizCoreBundle/src/Entity/TagTranslationDocuments.php +++ b/lib/RoadizCoreBundle/src/Entity/TagTranslationDocuments.php @@ -5,8 +5,8 @@ namespace RZ\Roadiz\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use RZ\Roadiz\Core\AbstractEntities\AbstractPositioned; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\AbstractPositioned; use RZ\Roadiz\CoreBundle\Repository\TagTranslationDocumentsRepository; use Symfony\Component\Serializer\Annotation as SymfonySerializer; @@ -16,9 +16,9 @@ */ #[ ORM\Entity(repositoryClass: TagTranslationDocumentsRepository::class), - ORM\Table(name: "tags_translations_documents"), - ORM\Index(columns: ["position"]), - ORM\Index(columns: ["tag_translation_id", "position"], name: "tagtranslation_position") + ORM\Table(name: 'tags_translations_documents'), + ORM\Index(columns: ['position']), + ORM\Index(columns: ['tag_translation_id', 'position'], name: 'tagtranslation_position') ] class TagTranslationDocuments extends AbstractPositioned { @@ -46,9 +46,6 @@ class TagTranslationDocuments extends AbstractPositioned /** * Create a new relation between NodeSource, a Document and a NodeTypeField. - * - * @param TagTranslation $tagTranslation - * @param Document $document */ public function __construct(TagTranslation $tagTranslation, Document $document) { @@ -71,6 +68,7 @@ public function getDocument(): Document public function setDocument(Document $document): TagTranslationDocuments { $this->document = $document; + return $this; } @@ -82,6 +80,7 @@ public function getTagTranslation(): TagTranslation public function setTagTranslation(TagTranslation $tagTranslation): TagTranslationDocuments { $this->tagTranslation = $tagTranslation; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Theme.php b/lib/RoadizCoreBundle/src/Entity/Theme.php index 57d5afd6..69234999 100644 --- a/lib/RoadizCoreBundle/src/Entity/Theme.php +++ b/lib/RoadizCoreBundle/src/Entity/Theme.php @@ -22,30 +22,24 @@ class Theme extends AbstractEntity private string $routePrefix = ''; private bool $backendTheme = false; - /** - * @return boolean - */ public function isAvailable(): bool { return $this->available; } /** - * @param boolean $available - * * @return $this */ public function setAvailable(bool $available): Theme { $this->available = $available; + return $this; } /** * Static means that your theme is not suitable for responding from * nodes urls but only static routes. - * - * @return boolean */ public function isStaticTheme(): bool { @@ -53,19 +47,17 @@ public function isStaticTheme(): bool } /** - * @param boolean $staticTheme * @return $this */ public function setStaticTheme(bool $staticTheme): Theme { $this->staticTheme = (bool) $staticTheme; + return $this; } /** * Alias for getInformations. - * - * @return array */ public function getInformation(): array { @@ -79,8 +71,6 @@ public function getInformation(): array * - author * - copyright * - dir - * - * @return array */ public function getInformations(): array { @@ -91,6 +81,7 @@ public function getInformations(): array $authorCallable = [$class, 'getThemeAuthor']; $copyrightCallable = [$class, 'getThemeCopyright']; $dirCallable = [$class, 'getThemeDir']; + return [ 'name' => \is_callable($nameCallable) ? call_user_func($nameCallable) : null, 'author' => \is_callable($authorCallable) ? call_user_func($authorCallable) : null, @@ -112,67 +103,58 @@ public function getClassName(): string /** * @param class-string $className + * * @return $this */ public function setClassName(string $className): Theme { $this->className = $className; + return $this; } - /** - * @return string - */ public function getHostname(): string { return $this->hostname; } /** - * @param string $hostname - * * @return $this */ public function setHostname(string $hostname): Theme { $this->hostname = $hostname; + return $this; } - /** - * @return string - */ public function getRoutePrefix(): string { return $this->routePrefix; } /** - * @param string $routePrefix - * * @return $this */ public function setRoutePrefix(string $routePrefix): Theme { $this->routePrefix = $routePrefix; + return $this; } - /** - * @return boolean - */ public function isBackendTheme(): bool { return $this->backendTheme; } /** - * @param boolean $backendTheme * @return $this */ public function setBackendTheme(bool $backendTheme): Theme { $this->backendTheme = $backendTheme; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/Translation.php b/lib/RoadizCoreBundle/src/Entity/Translation.php index 549360e8..1ff9def6 100644 --- a/lib/RoadizCoreBundle/src/Entity/Translation.php +++ b/lib/RoadizCoreBundle/src/Entity/Translation.php @@ -4,10 +4,10 @@ namespace RZ\Roadiz\CoreBundle\Entity; +use ApiPlatform\Doctrine\Orm\Filter as BaseFilter; +use ApiPlatform\Metadata\ApiFilter; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use ApiPlatform\Metadata\ApiFilter; -use ApiPlatform\Doctrine\Orm\Filter as BaseFilter; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; @@ -26,32 +26,32 @@ */ #[ ORM\Entity(repositoryClass: TranslationRepository::class), - ORM\Table(name: "translations"), - ORM\Index(columns: ["available"]), - ORM\Index(columns: ["default_translation"]), - ORM\Index(columns: ["created_at"]), - ORM\Index(columns: ["updated_at"]), - ORM\Index(columns: ["available", "default_translation"]), - ORM\Index(columns: ["available", "locale"]), - ORM\Index(columns: ["available", "override_locale"]), - UniqueEntity(fields: ["name"]), - UniqueEntity(fields: ["locale"]), - UniqueEntity(fields: ["overrideLocale"]), + ORM\Table(name: 'translations'), + ORM\Index(columns: ['available']), + ORM\Index(columns: ['default_translation']), + ORM\Index(columns: ['created_at']), + ORM\Index(columns: ['updated_at']), + ORM\Index(columns: ['available', 'default_translation']), + ORM\Index(columns: ['available', 'locale']), + ORM\Index(columns: ['available', 'override_locale']), + UniqueEntity(fields: ['name']), + UniqueEntity(fields: ['locale']), + UniqueEntity(fields: ['overrideLocale']), ApiFilter(PropertyFilter::class), ApiFilter(BaseFilter\OrderFilter::class, properties: [ - "createdAt", - "updatedAt", - "locale", - "available", - "defaultTranslation" + 'createdAt', + 'updatedAt', + 'locale', + 'available', + 'defaultTranslation', ]), ApiFilter(BaseFilter\BooleanFilter::class, properties: [ - "available", - "defaultTranslation" + 'available', + 'defaultTranslation', ]), ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "locale" => "exact", - "name" => "exact" + 'locale' => 'exact', + 'name' => 'exact', ]) ] class Translation extends AbstractDateTimed implements TranslationInterface @@ -62,470 +62,470 @@ class Translation extends AbstractDateTimed implements TranslationInterface #[SymfonySerializer\Ignore] #[Serializer\Exclude] public static array $availableLocales = [ - 'af_NA' => "Afrikaans (Namibia)", - 'af_ZA' => "Afrikaans (South Africa)", - 'af' => "Afrikaans", - 'ak_GH' => "Akan (Ghana)", - 'ak' => "Akan", - 'sq_AL' => "Albanian (Albania)", - 'sq' => "Albanian", - 'am_ET' => "Amharic (Ethiopia)", - 'am' => "Amharic", - 'ar_DZ' => "Arabic (Algeria)", - 'ar_BH' => "Arabic (Bahrain)", - 'ar_EG' => "Arabic (Egypt)", - 'ar_IQ' => "Arabic (Iraq)", - 'ar_JO' => "Arabic (Jordan)", - 'ar_KW' => "Arabic (Kuwait)", - 'ar_LB' => "Arabic (Lebanon)", - 'ar_LY' => "Arabic (Libya)", - 'ar_MA' => "Arabic (Morocco)", - 'ar_OM' => "Arabic (Oman)", - 'ar_QA' => "Arabic (Qatar)", - 'ar_SA' => "Arabic (Saudi Arabia)", - 'ar_SD' => "Arabic (Sudan)", - 'ar_SY' => "Arabic (Syria)", - 'ar_TN' => "Arabic (Tunisia)", - 'ar_AE' => "Arabic (United Arab Emirates)", - 'ar_YE' => "Arabic (Yemen)", - 'ar' => "Arabic", - 'hy_AM' => "Armenian (Armenia)", - 'hy' => "Armenian", - 'as_IN' => "Assamese (India)", - 'as' => "Assamese", - 'asa_TZ' => "Asu (Tanzania)", - 'asa' => "Asu", - 'az_Cyrl' => "Azerbaijani (Cyrillic)", - 'az_Cyrl_AZ' => "Azerbaijani (Cyrillic, Azerbaijan)", - 'az_Latn' => "Azerbaijani (Latin)", - 'az_Latn_AZ' => "Azerbaijani (Latin, Azerbaijan)", - 'az' => "Azerbaijani", - 'bm_ML' => "Bambara (Mali)", - 'bm' => "Bambara", - 'eu_ES' => "Basque (Spain)", - 'eu' => "Basque", - 'be_BY' => "Belarusian (Belarus)", - 'be' => "Belarusian", - 'bem_ZM' => "Bemba (Zambia)", - 'bem' => "Bemba", - 'bez_TZ' => "Bena (Tanzania)", - 'bez' => "Bena", - 'bn_BD' => "Bengali (Bangladesh)", - 'bn_IN' => "Bengali (India)", - 'bn' => "Bengali", - 'bs_BA' => "Bosnian (Bosnia and Herzegovina)", - 'bs' => "Bosnian", - 'bg_BG' => "Bulgarian (Bulgaria)", - 'bg' => "Bulgarian", - 'my_MM' => "Burmese (Myanmar [Burma])", - 'my' => "Burmese", - 'ca_ES' => "Catalan (Spain)", - 'ca' => "Catalan", - 'tzm_Latn' => "Central Morocco Tamazight (Latin)", - 'tzm_Latn_MA' => "Central Morocco Tamazight (Latin, Morocco)", - 'tzm' => "Central Morocco Tamazight", - 'chr_US' => "Cherokee (United States)", - 'chr' => "Cherokee", - 'cgg_UG' => "Chiga (Uganda)", - 'cgg' => "Chiga", - 'zh_Hans' => "Chinese (Simplified Han)", - 'zh_Hans_CN' => "Chinese (Simplified Han, China)", - 'zh_Hans_HK' => "Chinese (Simplified Han, Hong Kong SAR China)", - 'zh_Hans_MO' => "Chinese (Simplified Han, Macau SAR China)", - 'zh_Hans_SG' => "Chinese (Simplified Han, Singapore)", - 'zh_Hant' => "Chinese (Traditional Han)", - 'zh_Hant_HK' => "Chinese (Traditional Han, Hong Kong SAR China)", - 'zh_Hant_MO' => "Chinese (Traditional Han, Macau SAR China)", - 'zh_Hant_TW' => "Chinese (Traditional Han, Taiwan)", - 'zh' => "Chinese", - 'kw_GB' => "Cornish (United Kingdom)", - 'kw' => "Cornish", - 'hr_HR' => "Croatian (Croatia)", - 'hr' => "Croatian", - 'cs_CZ' => "Czech (Czech Republic)", - 'cs' => "Czech", - 'da_DK' => "Danish (Denmark)", - 'da' => "Danish", - 'nl_BE' => "Dutch (Belgium)", - 'nl_NL' => "Dutch (Netherlands)", - 'nl' => "Dutch", - 'ebu_KE' => "Embu (Kenya)", - 'ebu' => "Embu", - 'en_AS' => "English (American Samoa)", - 'en_AU' => "English (Australia)", - 'en_BE' => "English (Belgium)", - 'en_BZ' => "English (Belize)", - 'en_BW' => "English (Botswana)", - 'en_CA' => "English (Canada)", - 'en_GU' => "English (Guam)", - 'en_HK' => "English (Hong Kong SAR China)", - 'en_IN' => "English (India)", - 'en_IE' => "English (Ireland)", - 'en_JM' => "English (Jamaica)", - 'en_MT' => "English (Malta)", - 'en_MH' => "English (Marshall Islands)", - 'en_MU' => "English (Mauritius)", - 'en_NA' => "English (Namibia)", - 'en_NZ' => "English (New Zealand)", - 'en_MP' => "English (Northern Mariana Islands)", - 'en_PK' => "English (Pakistan)", - 'en_PH' => "English (Philippines)", - 'en_SG' => "English (Singapore)", - 'en_ZA' => "English (South Africa)", - 'en_TT' => "English (Trinidad and Tobago)", - 'en_UM' => "English (U.S. Minor Outlying Islands)", - 'en_VI' => "English (U.S. Virgin Islands)", - 'en_GB' => "English (United Kingdom)", - 'en_US' => "English (United States)", - 'en_ZW' => "English (Zimbabwe)", - 'en' => "English", - 'eo' => "Esperanto", - 'et_EE' => "Estonian (Estonia)", - 'et' => "Estonian", - 'ee_GH' => "Ewe (Ghana)", - 'ee_TG' => "Ewe (Togo)", - 'ee' => "Ewe", - 'fo_FO' => "Faroese (Faroe Islands)", - 'fo' => "Faroese", - 'fil_PH' => "Filipino (Philippines)", - 'fil' => "Filipino", - 'fi_FI' => "Finnish (Finland)", - 'fi' => "Finnish", - 'fr_BE' => "French (Belgium)", - 'fr_BJ' => "French (Benin)", - 'fr_BF' => "French (Burkina Faso)", - 'fr_BI' => "French (Burundi)", - 'fr_CM' => "French (Cameroon)", - 'fr_CA' => "French (Canada)", - 'fr_CF' => "French (Central African Republic)", - 'fr_TD' => "French (Chad)", - 'fr_KM' => "French (Comoros)", - 'fr_CG' => "French (Congo - Brazzaville)", - 'fr_CD' => "French (Congo - Kinshasa)", - 'fr_CI' => "French (Côte d’Ivoire)", - 'fr_DJ' => "French (Djibouti)", - 'fr_GQ' => "French (Equatorial Guinea)", - 'fr_FR' => "French (France)", - 'fr_GA' => "French (Gabon)", - 'fr_GP' => "French (Guadeloupe)", - 'fr_GN' => "French (Guinea)", - 'fr_LU' => "French (Luxembourg)", - 'fr_MG' => "French (Madagascar)", - 'fr_ML' => "French (Mali)", - 'fr_MQ' => "French (Martinique)", - 'fr_MC' => "French (Monaco)", - 'fr_NE' => "French (Niger)", - 'fr_RW' => "French (Rwanda)", - 'fr_RE' => "French (Réunion)", - 'fr_BL' => "French (Saint Barthélemy)", - 'fr_MF' => "French (Saint Martin)", - 'fr_SN' => "French (Senegal)", - 'fr_CH' => "French (Switzerland)", - 'fr_TG' => "French (Togo)", - 'fr' => "French", - 'ff_SN' => "Fulah (Senegal)", - 'ff' => "Fulah", - 'gl_ES' => "Galician (Spain)", - 'gl' => "Galician", - 'lg_UG' => "Ganda (Uganda)", - 'lg' => "Ganda", - 'ka_GE' => "Georgian (Georgia)", - 'ka' => "Georgian", - 'de_AT' => "German (Austria)", - 'de_BE' => "German (Belgium)", - 'de_DE' => "German (Germany)", - 'de_LI' => "German (Liechtenstein)", - 'de_LU' => "German (Luxembourg)", - 'de_CH' => "German (Switzerland)", - 'de' => "German", - 'el_CY' => "Greek (Cyprus)", - 'el_GR' => "Greek (Greece)", - 'el' => "Greek", - 'gu_IN' => "Gujarati (India)", - 'gu' => "Gujarati", - 'guz_KE' => "Gusii (Kenya)", - 'guz' => "Gusii", - 'ha_Latn' => "Hausa (Latin)", - 'ha_Latn_GH' => "Hausa (Latin, Ghana)", - 'ha_Latn_NE' => "Hausa (Latin, Niger)", - 'ha_Latn_NG' => "Hausa (Latin, Nigeria)", - 'ha' => "Hausa", - 'haw_US' => "Hawaiian (United States)", - 'haw' => "Hawaiian", - 'he_IL' => "Hebrew (Israel)", - 'he' => "Hebrew", - 'hi_IN' => "Hindi (India)", - 'hi' => "Hindi", - 'hu_HU' => "Hungarian (Hungary)", - 'hu' => "Hungarian", - 'is_IS' => "Icelandic (Iceland)", - 'is' => "Icelandic", - 'ig_NG' => "Igbo (Nigeria)", - 'ig' => "Igbo", - 'id_ID' => "Indonesian (Indonesia)", - 'id' => "Indonesian", - 'ga_IE' => "Irish (Ireland)", - 'ga' => "Irish", - 'it_IT' => "Italian (Italy)", - 'it_CH' => "Italian (Switzerland)", - 'it' => "Italian", - 'ja_JP' => "Japanese (Japan)", - 'ja' => "Japanese", - 'kea_CV' => "Kabuverdianu (Cape Verde)", - 'kea' => "Kabuverdianu", - 'kab_DZ' => "Kabyle (Algeria)", - 'kab' => "Kabyle", - 'kl_GL' => "Kalaallisut (Greenland)", - 'kl' => "Kalaallisut", - 'kln_KE' => "Kalenjin (Kenya)", - 'kln' => "Kalenjin", - 'kam_KE' => "Kamba (Kenya)", - 'kam' => "Kamba", - 'kn_IN' => "Kannada (India)", - 'kn' => "Kannada", - 'kk_Cyrl' => "Kazakh (Cyrillic)", - 'kk_Cyrl_KZ' => "Kazakh (Cyrillic, Kazakhstan)", - 'kk' => "Kazakh", - 'km_KH' => "Khmer (Cambodia)", - 'km' => "Khmer", - 'ki_KE' => "Kikuyu (Kenya)", - 'ki' => "Kikuyu", - 'rw_RW' => "Kinyarwanda (Rwanda)", - 'rw' => "Kinyarwanda", - 'kok_IN' => "Konkani (India)", - 'kok' => "Konkani", - 'ko_KR' => "Korean (South Korea)", - 'ko' => "Korean", - 'khq_ML' => "Koyra Chiini (Mali)", - 'khq' => "Koyra Chiini", - 'ses_ML' => "Koyraboro Senni (Mali)", - 'ses' => "Koyraboro Senni", - 'lag_TZ' => "Langi (Tanzania)", - 'lag' => "Langi", - 'lv_LV' => "Latvian (Latvia)", - 'lv' => "Latvian", - 'lt_LT' => "Lithuanian (Lithuania)", - 'lt' => "Lithuanian", - 'luo_KE' => "Luo (Kenya)", - 'luo' => "Luo", - 'luy_KE' => "Luyia (Kenya)", - 'luy' => "Luyia", - 'mk_MK' => "Macedonian (Macedonia)", - 'mk' => "Macedonian", - 'jmc_TZ' => "Machame (Tanzania)", - 'jmc' => "Machame", - 'kde_TZ' => "Makonde (Tanzania)", - 'kde' => "Makonde", - 'mg_MG' => "Malagasy (Madagascar)", - 'mg' => "Malagasy", - 'ms_BN' => "Malay (Brunei)", - 'ms_MY' => "Malay (Malaysia)", - 'ms' => "Malay", - 'ml_IN' => "Malayalam (India)", - 'ml' => "Malayalam", - 'mt_MT' => "Maltese (Malta)", - 'mt' => "Maltese", - 'gv_GB' => "Manx (United Kingdom)", - 'gv' => "Manx", - 'mr_IN' => "Marathi (India)", - 'mr' => "Marathi", - 'mas_KE' => "Masai (Kenya)", - 'mas_TZ' => "Masai (Tanzania)", - 'mas' => "Masai", - 'mer_KE' => "Meru (Kenya)", - 'mer' => "Meru", - 'mfe_MU' => "Morisyen (Mauritius)", - 'mfe' => "Morisyen", - 'naq_NA' => "Nama (Namibia)", - 'naq' => "Nama", - 'ne_IN' => "Nepali (India)", - 'ne_NP' => "Nepali (Nepal)", - 'ne' => "Nepali", - 'nd_ZW' => "North Ndebele (Zimbabwe)", - 'nd' => "North Ndebele", - 'nb_NO' => "Norwegian Bokmål (Norway)", - 'nb' => "Norwegian Bokmål", - 'nn_NO' => "Norwegian Nynorsk (Norway)", - 'nn' => "Norwegian Nynorsk", - 'nyn_UG' => "Nyankole (Uganda)", - 'nyn' => "Nyankole", - 'or_IN' => "Oriya (India)", - 'or' => "Oriya", - 'om_ET' => "Oromo (Ethiopia)", - 'm_KE' => "Oromo (Kenya)", - 'om' => "Oromo", - 'ps_AF' => "Pashto (Afghanistan)", - 'ps' => "Pashto", - 'fa_AF' => "Persian (Afghanistan)", - 'fa_IR' => "Persian (Iran)", - 'fa' => "Persian", - 'pl_PL' => "Polish (Poland)", - 'pl' => "Polish", - 'pt_BR' => "Portuguese (Brazil)", - 'pt_GW' => "Portuguese (Guinea-Bissau)", - 'pt_MZ' => "Portuguese (Mozambique)", - 'pt_PT' => "Portuguese (Portugal)", - 'pt' => "Portuguese", - 'pa_Arab' => "Punjabi (Arabic)", - 'pa_Arab_PK' => "Punjabi (Arabic, Pakistan)", - 'pa_Guru' => "Punjabi (Gurmukhi)", - 'pa_Guru_IN' => "Punjabi (Gurmukhi, India)", - 'pa' => "Punjabi", - 'ro_MD' => "Romanian (Moldova)", - 'ro_RO' => "Romanian (Romania)", - 'ro' => "Romanian", - 'rm_CH' => "Romansh (Switzerland)", - 'rm' => "Romansh", - 'rof_TZ' => "Rombo (Tanzania)", - 'rof' => "Rombo", - 'ru_MD' => "Russian (Moldova)", - 'ru_RU' => "Russian (Russia)", - 'ru_UA' => "Russian (Ukraine)", - 'ru' => "Russian", - 'rwk_TZ' => "Rwa (Tanzania)", - 'rwk' => "Rwa", - 'saq_KE' => "Samburu (Kenya)", - 'saq' => "Samburu", - 'sg_CF' => "Sango (Central African Republic)", - 'sg' => "Sango", - 'seh_MZ' => "Sena (Mozambique)", - 'seh' => "Sena", - 'sr_Cyrl' => "Serbian (Cyrillic)", - 'sr_Cyrl_BA' => "Serbian (Cyrillic, Bosnia and Herzegovina)", - 'sr_Cyrl_ME' => "Serbian (Cyrillic, Montenegro)", - 'sr_Cyrl_RS' => "Serbian (Cyrillic, Serbia)", - 'sr_Latn' => "Serbian (Latin)", - 'sr_Latn_BA' => "Serbian (Latin, Bosnia and Herzegovina)", - 'sr_Latn_ME' => "Serbian (Latin, Montenegro)", - 'sr_Latn_RS' => "Serbian (Latin, Serbia)", - 'sr' => "Serbian", - 'sn_ZW' => "Shona (Zimbabwe)", - 'sn' => "Shona", - 'ii_CN' => "Sichuan Yi (China)", - 'ii' => "Sichuan Yi", - 'si_LK' => "Sinhala (Sri Lanka)", - 'si' => "Sinhala", - 'sk_SK' => "Slovak (Slovakia)", - 'sk' => "Slovak", - 'sl_SI' => "Slovenian (Slovenia)", - 'sl' => "Slovenian", - 'xog_UG' => "Soga (Uganda)", - 'xog' => "Soga", - 'so_DJ' => "Somali (Djibouti)", - 'so_ET' => "Somali (Ethiopia)", - 'so_KE' => "Somali (Kenya)", - 'so_SO' => "Somali (Somalia)", - 'so' => "Somali", - 'es_AR' => "Spanish (Argentina)", - 'es_BO' => "Spanish (Bolivia)", - 'es_CL' => "Spanish (Chile)", - 'es_CO' => "Spanish (Colombia)", - 'es_CR' => "Spanish (Costa Rica)", - 'es_DO' => "Spanish (Dominican Republic)", - 'es_EC' => "Spanish (Ecuador)", - 'es_SV' => "Spanish (El Salvador)", - 'es_GQ' => "Spanish (Equatorial Guinea)", - 'es_GT' => "Spanish (Guatemala)", - 'es_HN' => "Spanish (Honduras)", - 'es_419' => "Spanish (Latin America)", - 'es_MX' => "Spanish (Mexico)", - 'es_NI' => "Spanish (Nicaragua)", - 'es_PA' => "Spanish (Panama)", - 'es_PY' => "Spanish (Paraguay)", - 'es_PE' => "Spanish (Peru)", - 'es_PR' => "Spanish (Puerto Rico)", - 'es_ES' => "Spanish (Spain)", - 'es_US' => "Spanish (United States)", - 'es_UY' => "Spanish (Uruguay)", - 'es_VE' => "Spanish (Venezuela)", - 'es' => "Spanish", - 'sw_KE' => "Swahili (Kenya)", - 'sw_TZ' => "Swahili (Tanzania)", - 'sw' => "Swahili", - 'sv_FI' => "Swedish (Finland)", - 'sv_SE' => "Swedish (Sweden)", - 'sv' => "Swedish", - 'gsw_CH' => "Swiss German (Switzerland)", - 'gsw' => "Swiss German", - 'shi_Latn' => "Tachelhit (Latin)", - 'shi_Latn_MA' => "Tachelhit (Latin, Morocco)", - 'shi_Tfng' => "Tachelhit (Tifinagh)", - 'shi_Tfng_MA' => "Tachelhit (Tifinagh, Morocco)", - 'shi' => "Tachelhit", - 'dav_KE' => "Taita (Kenya)", - 'dav' => "Taita", - 'ta_IN' => "Tamil (India)", - 'ta_LK' => "Tamil (Sri Lanka)", - 'ta' => "Tamil", - 'te_IN' => "Telugu (India)", - 'te' => "Telugu", - 'teo_KE' => "Teso (Kenya)", - 'teo_UG' => "Teso (Uganda)", - 'teo' => "Teso", - 'th_TH' => "Thai (Thailand)", - 'th' => "Thai", - 'bo_CN' => "Tibetan (China)", - 'bo_IN' => "Tibetan (India)", - 'bo' => "Tibetan", - 'ti_ER' => "Tigrinya (Eritrea)", - 'ti_ET' => "Tigrinya (Ethiopia)", - 'ti' => "Tigrinya", - 'to_TO' => "Tonga (Tonga)", - 'to' => "Tonga", - 'tr_TR' => "Turkish (Turkey)", - 'tr' => "Turkish", - 'uk_UA' => "Ukrainian (Ukraine)", - 'uk' => "Ukrainian", - 'ur_IN' => "Urdu (India)", - 'ur_PK' => "Urdu (Pakistan)", - 'ur' => "Urdu", - 'uz_Arab' => "Uzbek (Arabic)", - 'uz_Arab_AF' => "Uzbek (Arabic, Afghanistan)", - 'uz_Cyrl' => "Uzbek (Cyrillic)", - 'uz_Cyrl_UZ' => "Uzbek (Cyrillic, Uzbekistan)", - 'uz_Latn' => "Uzbek (Latin)", - 'uz_Latn_UZ' => "Uzbek (Latin, Uzbekistan)", - 'uz' => "Uzbek", - 'vi_VN' => "Vietnamese (Vietnam)", - 'vi' => "Vietnamese", - 'vun_TZ' => "Vunjo (Tanzania)", - 'vun' => "Vunjo", - 'cy_GB' => "Welsh (United Kingdom)", - 'cy' => "Welsh", - 'yo_NG' => "Yoruba (Nigeria)", - 'yo' => "Yoruba", - 'zu_ZA' => "Zulu (South Africa)", - 'zu' => "Zulu", + 'af_NA' => 'Afrikaans (Namibia)', + 'af_ZA' => 'Afrikaans (South Africa)', + 'af' => 'Afrikaans', + 'ak_GH' => 'Akan (Ghana)', + 'ak' => 'Akan', + 'sq_AL' => 'Albanian (Albania)', + 'sq' => 'Albanian', + 'am_ET' => 'Amharic (Ethiopia)', + 'am' => 'Amharic', + 'ar_DZ' => 'Arabic (Algeria)', + 'ar_BH' => 'Arabic (Bahrain)', + 'ar_EG' => 'Arabic (Egypt)', + 'ar_IQ' => 'Arabic (Iraq)', + 'ar_JO' => 'Arabic (Jordan)', + 'ar_KW' => 'Arabic (Kuwait)', + 'ar_LB' => 'Arabic (Lebanon)', + 'ar_LY' => 'Arabic (Libya)', + 'ar_MA' => 'Arabic (Morocco)', + 'ar_OM' => 'Arabic (Oman)', + 'ar_QA' => 'Arabic (Qatar)', + 'ar_SA' => 'Arabic (Saudi Arabia)', + 'ar_SD' => 'Arabic (Sudan)', + 'ar_SY' => 'Arabic (Syria)', + 'ar_TN' => 'Arabic (Tunisia)', + 'ar_AE' => 'Arabic (United Arab Emirates)', + 'ar_YE' => 'Arabic (Yemen)', + 'ar' => 'Arabic', + 'hy_AM' => 'Armenian (Armenia)', + 'hy' => 'Armenian', + 'as_IN' => 'Assamese (India)', + 'as' => 'Assamese', + 'asa_TZ' => 'Asu (Tanzania)', + 'asa' => 'Asu', + 'az_Cyrl' => 'Azerbaijani (Cyrillic)', + 'az_Cyrl_AZ' => 'Azerbaijani (Cyrillic, Azerbaijan)', + 'az_Latn' => 'Azerbaijani (Latin)', + 'az_Latn_AZ' => 'Azerbaijani (Latin, Azerbaijan)', + 'az' => 'Azerbaijani', + 'bm_ML' => 'Bambara (Mali)', + 'bm' => 'Bambara', + 'eu_ES' => 'Basque (Spain)', + 'eu' => 'Basque', + 'be_BY' => 'Belarusian (Belarus)', + 'be' => 'Belarusian', + 'bem_ZM' => 'Bemba (Zambia)', + 'bem' => 'Bemba', + 'bez_TZ' => 'Bena (Tanzania)', + 'bez' => 'Bena', + 'bn_BD' => 'Bengali (Bangladesh)', + 'bn_IN' => 'Bengali (India)', + 'bn' => 'Bengali', + 'bs_BA' => 'Bosnian (Bosnia and Herzegovina)', + 'bs' => 'Bosnian', + 'bg_BG' => 'Bulgarian (Bulgaria)', + 'bg' => 'Bulgarian', + 'my_MM' => 'Burmese (Myanmar [Burma])', + 'my' => 'Burmese', + 'ca_ES' => 'Catalan (Spain)', + 'ca' => 'Catalan', + 'tzm_Latn' => 'Central Morocco Tamazight (Latin)', + 'tzm_Latn_MA' => 'Central Morocco Tamazight (Latin, Morocco)', + 'tzm' => 'Central Morocco Tamazight', + 'chr_US' => 'Cherokee (United States)', + 'chr' => 'Cherokee', + 'cgg_UG' => 'Chiga (Uganda)', + 'cgg' => 'Chiga', + 'zh_Hans' => 'Chinese (Simplified Han)', + 'zh_Hans_CN' => 'Chinese (Simplified Han, China)', + 'zh_Hans_HK' => 'Chinese (Simplified Han, Hong Kong SAR China)', + 'zh_Hans_MO' => 'Chinese (Simplified Han, Macau SAR China)', + 'zh_Hans_SG' => 'Chinese (Simplified Han, Singapore)', + 'zh_Hant' => 'Chinese (Traditional Han)', + 'zh_Hant_HK' => 'Chinese (Traditional Han, Hong Kong SAR China)', + 'zh_Hant_MO' => 'Chinese (Traditional Han, Macau SAR China)', + 'zh_Hant_TW' => 'Chinese (Traditional Han, Taiwan)', + 'zh' => 'Chinese', + 'kw_GB' => 'Cornish (United Kingdom)', + 'kw' => 'Cornish', + 'hr_HR' => 'Croatian (Croatia)', + 'hr' => 'Croatian', + 'cs_CZ' => 'Czech (Czech Republic)', + 'cs' => 'Czech', + 'da_DK' => 'Danish (Denmark)', + 'da' => 'Danish', + 'nl_BE' => 'Dutch (Belgium)', + 'nl_NL' => 'Dutch (Netherlands)', + 'nl' => 'Dutch', + 'ebu_KE' => 'Embu (Kenya)', + 'ebu' => 'Embu', + 'en_AS' => 'English (American Samoa)', + 'en_AU' => 'English (Australia)', + 'en_BE' => 'English (Belgium)', + 'en_BZ' => 'English (Belize)', + 'en_BW' => 'English (Botswana)', + 'en_CA' => 'English (Canada)', + 'en_GU' => 'English (Guam)', + 'en_HK' => 'English (Hong Kong SAR China)', + 'en_IN' => 'English (India)', + 'en_IE' => 'English (Ireland)', + 'en_JM' => 'English (Jamaica)', + 'en_MT' => 'English (Malta)', + 'en_MH' => 'English (Marshall Islands)', + 'en_MU' => 'English (Mauritius)', + 'en_NA' => 'English (Namibia)', + 'en_NZ' => 'English (New Zealand)', + 'en_MP' => 'English (Northern Mariana Islands)', + 'en_PK' => 'English (Pakistan)', + 'en_PH' => 'English (Philippines)', + 'en_SG' => 'English (Singapore)', + 'en_ZA' => 'English (South Africa)', + 'en_TT' => 'English (Trinidad and Tobago)', + 'en_UM' => 'English (U.S. Minor Outlying Islands)', + 'en_VI' => 'English (U.S. Virgin Islands)', + 'en_GB' => 'English (United Kingdom)', + 'en_US' => 'English (United States)', + 'en_ZW' => 'English (Zimbabwe)', + 'en' => 'English', + 'eo' => 'Esperanto', + 'et_EE' => 'Estonian (Estonia)', + 'et' => 'Estonian', + 'ee_GH' => 'Ewe (Ghana)', + 'ee_TG' => 'Ewe (Togo)', + 'ee' => 'Ewe', + 'fo_FO' => 'Faroese (Faroe Islands)', + 'fo' => 'Faroese', + 'fil_PH' => 'Filipino (Philippines)', + 'fil' => 'Filipino', + 'fi_FI' => 'Finnish (Finland)', + 'fi' => 'Finnish', + 'fr_BE' => 'French (Belgium)', + 'fr_BJ' => 'French (Benin)', + 'fr_BF' => 'French (Burkina Faso)', + 'fr_BI' => 'French (Burundi)', + 'fr_CM' => 'French (Cameroon)', + 'fr_CA' => 'French (Canada)', + 'fr_CF' => 'French (Central African Republic)', + 'fr_TD' => 'French (Chad)', + 'fr_KM' => 'French (Comoros)', + 'fr_CG' => 'French (Congo - Brazzaville)', + 'fr_CD' => 'French (Congo - Kinshasa)', + 'fr_CI' => 'French (Côte d’Ivoire)', + 'fr_DJ' => 'French (Djibouti)', + 'fr_GQ' => 'French (Equatorial Guinea)', + 'fr_FR' => 'French (France)', + 'fr_GA' => 'French (Gabon)', + 'fr_GP' => 'French (Guadeloupe)', + 'fr_GN' => 'French (Guinea)', + 'fr_LU' => 'French (Luxembourg)', + 'fr_MG' => 'French (Madagascar)', + 'fr_ML' => 'French (Mali)', + 'fr_MQ' => 'French (Martinique)', + 'fr_MC' => 'French (Monaco)', + 'fr_NE' => 'French (Niger)', + 'fr_RW' => 'French (Rwanda)', + 'fr_RE' => 'French (Réunion)', + 'fr_BL' => 'French (Saint Barthélemy)', + 'fr_MF' => 'French (Saint Martin)', + 'fr_SN' => 'French (Senegal)', + 'fr_CH' => 'French (Switzerland)', + 'fr_TG' => 'French (Togo)', + 'fr' => 'French', + 'ff_SN' => 'Fulah (Senegal)', + 'ff' => 'Fulah', + 'gl_ES' => 'Galician (Spain)', + 'gl' => 'Galician', + 'lg_UG' => 'Ganda (Uganda)', + 'lg' => 'Ganda', + 'ka_GE' => 'Georgian (Georgia)', + 'ka' => 'Georgian', + 'de_AT' => 'German (Austria)', + 'de_BE' => 'German (Belgium)', + 'de_DE' => 'German (Germany)', + 'de_LI' => 'German (Liechtenstein)', + 'de_LU' => 'German (Luxembourg)', + 'de_CH' => 'German (Switzerland)', + 'de' => 'German', + 'el_CY' => 'Greek (Cyprus)', + 'el_GR' => 'Greek (Greece)', + 'el' => 'Greek', + 'gu_IN' => 'Gujarati (India)', + 'gu' => 'Gujarati', + 'guz_KE' => 'Gusii (Kenya)', + 'guz' => 'Gusii', + 'ha_Latn' => 'Hausa (Latin)', + 'ha_Latn_GH' => 'Hausa (Latin, Ghana)', + 'ha_Latn_NE' => 'Hausa (Latin, Niger)', + 'ha_Latn_NG' => 'Hausa (Latin, Nigeria)', + 'ha' => 'Hausa', + 'haw_US' => 'Hawaiian (United States)', + 'haw' => 'Hawaiian', + 'he_IL' => 'Hebrew (Israel)', + 'he' => 'Hebrew', + 'hi_IN' => 'Hindi (India)', + 'hi' => 'Hindi', + 'hu_HU' => 'Hungarian (Hungary)', + 'hu' => 'Hungarian', + 'is_IS' => 'Icelandic (Iceland)', + 'is' => 'Icelandic', + 'ig_NG' => 'Igbo (Nigeria)', + 'ig' => 'Igbo', + 'id_ID' => 'Indonesian (Indonesia)', + 'id' => 'Indonesian', + 'ga_IE' => 'Irish (Ireland)', + 'ga' => 'Irish', + 'it_IT' => 'Italian (Italy)', + 'it_CH' => 'Italian (Switzerland)', + 'it' => 'Italian', + 'ja_JP' => 'Japanese (Japan)', + 'ja' => 'Japanese', + 'kea_CV' => 'Kabuverdianu (Cape Verde)', + 'kea' => 'Kabuverdianu', + 'kab_DZ' => 'Kabyle (Algeria)', + 'kab' => 'Kabyle', + 'kl_GL' => 'Kalaallisut (Greenland)', + 'kl' => 'Kalaallisut', + 'kln_KE' => 'Kalenjin (Kenya)', + 'kln' => 'Kalenjin', + 'kam_KE' => 'Kamba (Kenya)', + 'kam' => 'Kamba', + 'kn_IN' => 'Kannada (India)', + 'kn' => 'Kannada', + 'kk_Cyrl' => 'Kazakh (Cyrillic)', + 'kk_Cyrl_KZ' => 'Kazakh (Cyrillic, Kazakhstan)', + 'kk' => 'Kazakh', + 'km_KH' => 'Khmer (Cambodia)', + 'km' => 'Khmer', + 'ki_KE' => 'Kikuyu (Kenya)', + 'ki' => 'Kikuyu', + 'rw_RW' => 'Kinyarwanda (Rwanda)', + 'rw' => 'Kinyarwanda', + 'kok_IN' => 'Konkani (India)', + 'kok' => 'Konkani', + 'ko_KR' => 'Korean (South Korea)', + 'ko' => 'Korean', + 'khq_ML' => 'Koyra Chiini (Mali)', + 'khq' => 'Koyra Chiini', + 'ses_ML' => 'Koyraboro Senni (Mali)', + 'ses' => 'Koyraboro Senni', + 'lag_TZ' => 'Langi (Tanzania)', + 'lag' => 'Langi', + 'lv_LV' => 'Latvian (Latvia)', + 'lv' => 'Latvian', + 'lt_LT' => 'Lithuanian (Lithuania)', + 'lt' => 'Lithuanian', + 'luo_KE' => 'Luo (Kenya)', + 'luo' => 'Luo', + 'luy_KE' => 'Luyia (Kenya)', + 'luy' => 'Luyia', + 'mk_MK' => 'Macedonian (Macedonia)', + 'mk' => 'Macedonian', + 'jmc_TZ' => 'Machame (Tanzania)', + 'jmc' => 'Machame', + 'kde_TZ' => 'Makonde (Tanzania)', + 'kde' => 'Makonde', + 'mg_MG' => 'Malagasy (Madagascar)', + 'mg' => 'Malagasy', + 'ms_BN' => 'Malay (Brunei)', + 'ms_MY' => 'Malay (Malaysia)', + 'ms' => 'Malay', + 'ml_IN' => 'Malayalam (India)', + 'ml' => 'Malayalam', + 'mt_MT' => 'Maltese (Malta)', + 'mt' => 'Maltese', + 'gv_GB' => 'Manx (United Kingdom)', + 'gv' => 'Manx', + 'mr_IN' => 'Marathi (India)', + 'mr' => 'Marathi', + 'mas_KE' => 'Masai (Kenya)', + 'mas_TZ' => 'Masai (Tanzania)', + 'mas' => 'Masai', + 'mer_KE' => 'Meru (Kenya)', + 'mer' => 'Meru', + 'mfe_MU' => 'Morisyen (Mauritius)', + 'mfe' => 'Morisyen', + 'naq_NA' => 'Nama (Namibia)', + 'naq' => 'Nama', + 'ne_IN' => 'Nepali (India)', + 'ne_NP' => 'Nepali (Nepal)', + 'ne' => 'Nepali', + 'nd_ZW' => 'North Ndebele (Zimbabwe)', + 'nd' => 'North Ndebele', + 'nb_NO' => 'Norwegian Bokmål (Norway)', + 'nb' => 'Norwegian Bokmål', + 'nn_NO' => 'Norwegian Nynorsk (Norway)', + 'nn' => 'Norwegian Nynorsk', + 'nyn_UG' => 'Nyankole (Uganda)', + 'nyn' => 'Nyankole', + 'or_IN' => 'Oriya (India)', + 'or' => 'Oriya', + 'om_ET' => 'Oromo (Ethiopia)', + 'm_KE' => 'Oromo (Kenya)', + 'om' => 'Oromo', + 'ps_AF' => 'Pashto (Afghanistan)', + 'ps' => 'Pashto', + 'fa_AF' => 'Persian (Afghanistan)', + 'fa_IR' => 'Persian (Iran)', + 'fa' => 'Persian', + 'pl_PL' => 'Polish (Poland)', + 'pl' => 'Polish', + 'pt_BR' => 'Portuguese (Brazil)', + 'pt_GW' => 'Portuguese (Guinea-Bissau)', + 'pt_MZ' => 'Portuguese (Mozambique)', + 'pt_PT' => 'Portuguese (Portugal)', + 'pt' => 'Portuguese', + 'pa_Arab' => 'Punjabi (Arabic)', + 'pa_Arab_PK' => 'Punjabi (Arabic, Pakistan)', + 'pa_Guru' => 'Punjabi (Gurmukhi)', + 'pa_Guru_IN' => 'Punjabi (Gurmukhi, India)', + 'pa' => 'Punjabi', + 'ro_MD' => 'Romanian (Moldova)', + 'ro_RO' => 'Romanian (Romania)', + 'ro' => 'Romanian', + 'rm_CH' => 'Romansh (Switzerland)', + 'rm' => 'Romansh', + 'rof_TZ' => 'Rombo (Tanzania)', + 'rof' => 'Rombo', + 'ru_MD' => 'Russian (Moldova)', + 'ru_RU' => 'Russian (Russia)', + 'ru_UA' => 'Russian (Ukraine)', + 'ru' => 'Russian', + 'rwk_TZ' => 'Rwa (Tanzania)', + 'rwk' => 'Rwa', + 'saq_KE' => 'Samburu (Kenya)', + 'saq' => 'Samburu', + 'sg_CF' => 'Sango (Central African Republic)', + 'sg' => 'Sango', + 'seh_MZ' => 'Sena (Mozambique)', + 'seh' => 'Sena', + 'sr_Cyrl' => 'Serbian (Cyrillic)', + 'sr_Cyrl_BA' => 'Serbian (Cyrillic, Bosnia and Herzegovina)', + 'sr_Cyrl_ME' => 'Serbian (Cyrillic, Montenegro)', + 'sr_Cyrl_RS' => 'Serbian (Cyrillic, Serbia)', + 'sr_Latn' => 'Serbian (Latin)', + 'sr_Latn_BA' => 'Serbian (Latin, Bosnia and Herzegovina)', + 'sr_Latn_ME' => 'Serbian (Latin, Montenegro)', + 'sr_Latn_RS' => 'Serbian (Latin, Serbia)', + 'sr' => 'Serbian', + 'sn_ZW' => 'Shona (Zimbabwe)', + 'sn' => 'Shona', + 'ii_CN' => 'Sichuan Yi (China)', + 'ii' => 'Sichuan Yi', + 'si_LK' => 'Sinhala (Sri Lanka)', + 'si' => 'Sinhala', + 'sk_SK' => 'Slovak (Slovakia)', + 'sk' => 'Slovak', + 'sl_SI' => 'Slovenian (Slovenia)', + 'sl' => 'Slovenian', + 'xog_UG' => 'Soga (Uganda)', + 'xog' => 'Soga', + 'so_DJ' => 'Somali (Djibouti)', + 'so_ET' => 'Somali (Ethiopia)', + 'so_KE' => 'Somali (Kenya)', + 'so_SO' => 'Somali (Somalia)', + 'so' => 'Somali', + 'es_AR' => 'Spanish (Argentina)', + 'es_BO' => 'Spanish (Bolivia)', + 'es_CL' => 'Spanish (Chile)', + 'es_CO' => 'Spanish (Colombia)', + 'es_CR' => 'Spanish (Costa Rica)', + 'es_DO' => 'Spanish (Dominican Republic)', + 'es_EC' => 'Spanish (Ecuador)', + 'es_SV' => 'Spanish (El Salvador)', + 'es_GQ' => 'Spanish (Equatorial Guinea)', + 'es_GT' => 'Spanish (Guatemala)', + 'es_HN' => 'Spanish (Honduras)', + 'es_419' => 'Spanish (Latin America)', + 'es_MX' => 'Spanish (Mexico)', + 'es_NI' => 'Spanish (Nicaragua)', + 'es_PA' => 'Spanish (Panama)', + 'es_PY' => 'Spanish (Paraguay)', + 'es_PE' => 'Spanish (Peru)', + 'es_PR' => 'Spanish (Puerto Rico)', + 'es_ES' => 'Spanish (Spain)', + 'es_US' => 'Spanish (United States)', + 'es_UY' => 'Spanish (Uruguay)', + 'es_VE' => 'Spanish (Venezuela)', + 'es' => 'Spanish', + 'sw_KE' => 'Swahili (Kenya)', + 'sw_TZ' => 'Swahili (Tanzania)', + 'sw' => 'Swahili', + 'sv_FI' => 'Swedish (Finland)', + 'sv_SE' => 'Swedish (Sweden)', + 'sv' => 'Swedish', + 'gsw_CH' => 'Swiss German (Switzerland)', + 'gsw' => 'Swiss German', + 'shi_Latn' => 'Tachelhit (Latin)', + 'shi_Latn_MA' => 'Tachelhit (Latin, Morocco)', + 'shi_Tfng' => 'Tachelhit (Tifinagh)', + 'shi_Tfng_MA' => 'Tachelhit (Tifinagh, Morocco)', + 'shi' => 'Tachelhit', + 'dav_KE' => 'Taita (Kenya)', + 'dav' => 'Taita', + 'ta_IN' => 'Tamil (India)', + 'ta_LK' => 'Tamil (Sri Lanka)', + 'ta' => 'Tamil', + 'te_IN' => 'Telugu (India)', + 'te' => 'Telugu', + 'teo_KE' => 'Teso (Kenya)', + 'teo_UG' => 'Teso (Uganda)', + 'teo' => 'Teso', + 'th_TH' => 'Thai (Thailand)', + 'th' => 'Thai', + 'bo_CN' => 'Tibetan (China)', + 'bo_IN' => 'Tibetan (India)', + 'bo' => 'Tibetan', + 'ti_ER' => 'Tigrinya (Eritrea)', + 'ti_ET' => 'Tigrinya (Ethiopia)', + 'ti' => 'Tigrinya', + 'to_TO' => 'Tonga (Tonga)', + 'to' => 'Tonga', + 'tr_TR' => 'Turkish (Turkey)', + 'tr' => 'Turkish', + 'uk_UA' => 'Ukrainian (Ukraine)', + 'uk' => 'Ukrainian', + 'ur_IN' => 'Urdu (India)', + 'ur_PK' => 'Urdu (Pakistan)', + 'ur' => 'Urdu', + 'uz_Arab' => 'Uzbek (Arabic)', + 'uz_Arab_AF' => 'Uzbek (Arabic, Afghanistan)', + 'uz_Cyrl' => 'Uzbek (Cyrillic)', + 'uz_Cyrl_UZ' => 'Uzbek (Cyrillic, Uzbekistan)', + 'uz_Latn' => 'Uzbek (Latin)', + 'uz_Latn_UZ' => 'Uzbek (Latin, Uzbekistan)', + 'uz' => 'Uzbek', + 'vi_VN' => 'Vietnamese (Vietnam)', + 'vi' => 'Vietnamese', + 'vun_TZ' => 'Vunjo (Tanzania)', + 'vun' => 'Vunjo', + 'cy_GB' => 'Welsh (United Kingdom)', + 'cy' => 'Welsh', + 'yo_NG' => 'Yoruba (Nigeria)', + 'yo' => 'Yoruba', + 'zu_ZA' => 'Zulu (South Africa)', + 'zu' => 'Zulu', ]; #[SymfonySerializer\Ignore] #[Serializer\Exclude] public static array $rtlLanguages = [ - 'ar_DZ' => "Arabic (Algeria)", - 'ar_BH' => "Arabic (Bahrain)", - 'ar_EG' => "Arabic (Egypt)", - 'ar_IQ' => "Arabic (Iraq)", - 'ar_JO' => "Arabic (Jordan)", - 'ar_KW' => "Arabic (Kuwait)", - 'ar_LB' => "Arabic (Lebanon)", - 'ar_LY' => "Arabic (Libya)", - 'ar_MA' => "Arabic (Morocco)", - 'ar_OM' => "Arabic (Oman)", - 'ar_QA' => "Arabic (Qatar)", - 'ar_SA' => "Arabic (Saudi Arabia)", - 'ar_SD' => "Arabic (Sudan)", - 'ar_SY' => "Arabic (Syria)", - 'ar_TN' => "Arabic (Tunisia)", - 'ar_AE' => "Arabic (United Arab Emirates)", - 'ar_YE' => "Arabic (Yemen)", - 'ar' => "Arabic", - 'he_IL' => "Hebrew (Israel)", - 'he' => "Hebrew", - 'ur_IN' => "Urdu (India)", - 'ur_PK' => "Urdu (Pakistan)", - 'fa_AF' => "Persian (Afghanistan)", - 'fa_IR' => "Persian (Iran)", - 'fa' => "Persian", + 'ar_DZ' => 'Arabic (Algeria)', + 'ar_BH' => 'Arabic (Bahrain)', + 'ar_EG' => 'Arabic (Egypt)', + 'ar_IQ' => 'Arabic (Iraq)', + 'ar_JO' => 'Arabic (Jordan)', + 'ar_KW' => 'Arabic (Kuwait)', + 'ar_LB' => 'Arabic (Lebanon)', + 'ar_LY' => 'Arabic (Libya)', + 'ar_MA' => 'Arabic (Morocco)', + 'ar_OM' => 'Arabic (Oman)', + 'ar_QA' => 'Arabic (Qatar)', + 'ar_SA' => 'Arabic (Saudi Arabia)', + 'ar_SD' => 'Arabic (Sudan)', + 'ar_SY' => 'Arabic (Syria)', + 'ar_TN' => 'Arabic (Tunisia)', + 'ar_AE' => 'Arabic (United Arab Emirates)', + 'ar_YE' => 'Arabic (Yemen)', + 'ar' => 'Arabic', + 'he_IL' => 'Hebrew (Israel)', + 'he' => 'Hebrew', + 'ur_IN' => 'Urdu (India)', + 'ur_PK' => 'Urdu (Pakistan)', + 'fa_AF' => 'Persian (Afghanistan)', + 'fa_IR' => 'Persian (Iran)', + 'fa' => 'Persian', ]; /** * @var Collection @@ -548,9 +548,10 @@ class Translation extends AbstractDateTimed implements TranslationInterface * * fr or en for example * - * @var string * @see https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes + * * @Serializer\Groups({"translation", "document", "nodes_sources", "tag", "attribute", "folder", "log_sources"}) + * * @Serializer\Type("string") */ #[ORM\Column(type: 'string', length: 10, unique: true, nullable: false)] @@ -565,8 +566,8 @@ class Translation extends AbstractDateTimed implements TranslationInterface private string $locale = ''; /** - * @var string|null * @Serializer\Groups({"translation", "document", "nodes_sources", "tag", "attribute", "folder"}) + * * @Serializer\Type("string") */ #[ORM\Column(name: 'override_locale', type: 'string', length: 10, unique: true, nullable: true)] @@ -579,8 +580,8 @@ class Translation extends AbstractDateTimed implements TranslationInterface private ?string $overrideLocale = null; /** - * @var string * @Serializer\Groups({"translation", "translation_base"}) + * * @Serializer\Type("string") */ #[ORM\Column(type: 'string', length: 250, unique: true)] @@ -595,8 +596,8 @@ class Translation extends AbstractDateTimed implements TranslationInterface private string $name = ''; /** - * @var bool * @Serializer\Groups({"translation", "translation_base"}) + * * @Serializer\Type("bool") */ #[ORM\Column(name: 'default_translation', type: 'boolean', nullable: false, options: ['default' => false])] @@ -608,8 +609,8 @@ class Translation extends AbstractDateTimed implements TranslationInterface private bool $defaultTranslation = false; /** - * @var bool * @Serializer\Groups({"translation", "translation_base"}) + * * @Serializer\Type("bool") */ #[ORM\Column(type: 'boolean', nullable: false, options: ['default' => true])] @@ -657,8 +658,6 @@ public function __construct() /** * Return available locales in an array. - * - * @return array */ #[SymfonySerializer\Ignore] public static function getAvailableLocales(): array @@ -666,120 +665,89 @@ public static function getAvailableLocales(): array return array_keys(static::$availableLocales); } - /** - * @return string - */ #[SymfonySerializer\Ignore] public function getOneLineSummary(): string { - return $this->getId() . " — " . $this->getName() . " (" . $this->getLocale() . ')' . - " — " . ($this->isAvailable() ? 'Enabled' : 'Disabled') . - ($this->isDefaultTranslation() ? ' - Default' : '') . PHP_EOL; + return $this->getId().' — '.$this->getName().' ('.$this->getLocale().')'. + ' — '.($this->isAvailable() ? 'Enabled' : 'Disabled'). + ($this->isDefaultTranslation() ? ' - Default' : '').PHP_EOL; } - /** - * @return string - */ public function __toString(): string { return (string) $this->getId(); } - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string|null $name - * * @return $this */ public function setName(?string $name): Translation { $this->name = $name ?? ''; + return $this; } - /** - * @return string - */ public function getLocale(): string { return $this->locale; } /** - * @param string $locale - * * @return $this */ public function setLocale(string $locale): Translation { $this->locale = $locale; + return $this; } - /** - * @return boolean - */ public function isAvailable(): bool { return $this->available; } /** - * @param boolean $available - * * @return $this */ public function setAvailable(bool $available): Translation { $this->available = $available; + return $this; } - /** - * @return boolean - */ public function isDefaultTranslation(): bool { return $this->defaultTranslation; } /** - * @param boolean $defaultTranslation - * * @return $this */ public function setDefaultTranslation(bool $defaultTranslation): Translation { $this->defaultTranslation = $defaultTranslation; + return $this; } - /** - * @return Collection - */ public function getNodeSources(): Collection { return $this->nodeSources; } - /** - * @return Collection - */ public function getTagTranslations(): Collection { return $this->tagTranslations; } - /** - * @return Collection - */ public function getDocumentTranslations(): Collection { return $this->documentTranslations; @@ -787,8 +755,6 @@ public function getDocumentTranslations(): Collection /** * Gets the value of overrideLocale. - * - * @return string */ public function getOverrideLocale(): ?string { @@ -799,8 +765,6 @@ public function getOverrideLocale(): ?string * Sets the value of overrideLocale. * * @param string|null $overrideLocale the override locale - * - * @return self */ public function setOverrideLocale(?string $overrideLocale): Translation { @@ -811,8 +775,6 @@ public function setOverrideLocale(?string $overrideLocale): Translation /** * Get preferred locale between overrideLocale or locale. - * - * @return string */ #[SymfonySerializer\SerializedName('locale')] #[SymfonySerializer\Groups(['translation_base'])] @@ -825,26 +787,17 @@ public function getPreferredLocale(): string return !empty($this->overrideLocale) ? $this->overrideLocale : $this->locale; } - /** - * @return bool - */ public function isRtl(): bool { return in_array($this->getLocale(), static::getRightToLeftLocales()); } - /** - * @return array - */ #[SymfonySerializer\Ignore] public static function getRightToLeftLocales(): array { return array_keys(static::$rtlLanguages); } - /** - * @return Collection - */ #[SymfonySerializer\Ignore] public function getFolderTranslations(): Collection { diff --git a/lib/RoadizCoreBundle/src/Entity/UrlAlias.php b/lib/RoadizCoreBundle/src/Entity/UrlAlias.php index 9f713fef..9718184a 100644 --- a/lib/RoadizCoreBundle/src/Entity/UrlAlias.php +++ b/lib/RoadizCoreBundle/src/Entity/UrlAlias.php @@ -5,20 +5,20 @@ namespace RZ\Roadiz\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; +use JMS\Serializer\Annotation as Serializer; use RZ\Roadiz\Core\AbstractEntities\AbstractEntity; +use RZ\Roadiz\CoreBundle\Form\Constraint as RoadizAssert; use RZ\Roadiz\CoreBundle\Repository\UrlAliasRepository; use RZ\Roadiz\Utils\StringHandler; -use JMS\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation as SymfonySerializer; use Symfony\Component\Validator\Constraints as Assert; -use RZ\Roadiz\CoreBundle\Form\Constraint as RoadizAssert; /** * UrlAliases are used to translate Nodes URLs. */ #[ ORM\Entity(repositoryClass: UrlAliasRepository::class), - ORM\Table(name: "url_aliases") + ORM\Table(name: 'url_aliases') ] class UrlAlias extends AbstractEntity { @@ -37,22 +37,18 @@ class UrlAlias extends AbstractEntity #[Serializer\Exclude] private NodesSources $nodeSource; - /** - * @return string - */ public function getAlias(): string { return $this->alias; } /** - * @param string $alias - * * @return $this */ public function setAlias(string $alias): UrlAlias { $this->alias = StringHandler::slugify($alias); + return $this; } @@ -64,6 +60,7 @@ public function getNodeSource(): NodesSources public function setNodeSource(NodesSources $nodeSource): UrlAlias { $this->nodeSource = $nodeSource; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Entity/User.php b/lib/RoadizCoreBundle/src/Entity/User.php index a5d39a62..9a82b308 100644 --- a/lib/RoadizCoreBundle/src/Entity/User.php +++ b/lib/RoadizCoreBundle/src/Entity/User.php @@ -22,21 +22,21 @@ #[ ORM\Entity(repositoryClass: UserRepository::class), - ORM\Table(name: "users"), - ORM\Index(columns: ["username"], name: "idx_users_username"), - ORM\Index(columns: ["email"], name: "idx_users_email"), - ORM\Index(columns: ["enabled"], name: "idx_users_enabled"), - ORM\Index(columns: ["credentials_expires_at"], name: "idx_users_credentials_expires_at"), - ORM\Index(columns: ["password_requested_at"], name: "idx_users_password_requested_at"), - ORM\Index(columns: ["expires_at"], name: "idx_users_expires_at"), - ORM\Index(columns: ["last_login"], name: "idx_users_last_login"), - ORM\Index(columns: ["locked"], name: "idx_users_locked"), - ORM\Index(columns: ["locale"], name: "idx_users_locale"), - ORM\Index(columns: ["created_at"], name: "idx_user_created_at"), - ORM\Index(columns: ["updated_at"], name: "idx_user_updated_at"), + ORM\Table(name: 'users'), + ORM\Index(columns: ['username'], name: 'idx_users_username'), + ORM\Index(columns: ['email'], name: 'idx_users_email'), + ORM\Index(columns: ['enabled'], name: 'idx_users_enabled'), + ORM\Index(columns: ['credentials_expires_at'], name: 'idx_users_credentials_expires_at'), + ORM\Index(columns: ['password_requested_at'], name: 'idx_users_password_requested_at'), + ORM\Index(columns: ['expires_at'], name: 'idx_users_expires_at'), + ORM\Index(columns: ['last_login'], name: 'idx_users_last_login'), + ORM\Index(columns: ['locked'], name: 'idx_users_locked'), + ORM\Index(columns: ['locale'], name: 'idx_users_locale'), + ORM\Index(columns: ['created_at'], name: 'idx_user_created_at'), + ORM\Index(columns: ['updated_at'], name: 'idx_user_updated_at'), ORM\HasLifecycleCallbacks, - UniqueEntity("email"), - UniqueEntity("username") + UniqueEntity('email'), + UniqueEntity('username') ] class User extends AbstractHuman implements UserInterface, AdvancedUserInterface, EquatableInterface, PasswordAuthenticatedUserInterface { @@ -50,7 +50,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @Serializer\Groups({"user_personal", "human"}) - * @var string|null */ #[ORM\Column(type: 'string', length: 200, unique: true, nullable: false)] #[SymfonySerializer\Groups(['user_personal', 'human'])] @@ -62,7 +61,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface protected ?string $email = null; /** - * @var bool * @Serializer\Exclude() */ #[SymfonySerializer\Ignore] @@ -76,7 +74,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface protected ?string $facebookName = null; /** - * @var string|null * @Serializer\Groups({"user"}) */ #[ORM\Column(name: 'picture_url', type: 'text', nullable: true)] @@ -85,7 +82,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface protected ?string $pictureUrl = null; /** - * @var boolean * @Serializer\Groups({"user_security"}) */ #[ORM\Column(type: 'boolean', nullable: false, options: ['default' => true])] @@ -94,7 +90,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @Serializer\Groups({"user_security"}) - * @var string|null */ #[ORM\Column(name: 'confirmation_token', type: 'string', length: 128, unique: true, nullable: true)] #[SymfonySerializer\Groups(['user_security'])] @@ -103,7 +98,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @Serializer\Groups({"user_security"}) - * @var \DateTime|null */ #[ORM\Column(name: 'password_requested_at', type: 'datetime', nullable: true)] #[SymfonySerializer\Groups(['user_security'])] @@ -111,7 +105,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @Serializer\Groups({"user_personal", "log_user"}) - * @var string */ #[ORM\Column(type: 'string', length: 200, unique: true)] #[SymfonySerializer\Groups(['user_personal', 'log_user'])] @@ -131,10 +124,10 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * Plain password. Used for model validation. - * **Must not be persisted.** + * **Must not be persisted.**. * - * @var string|null * @Serializer\Groups({"user:write"}) + * * @PasswordStrength(minLength=8, minStrength=3) */ #[SymfonySerializer\Groups(['user:write'])] @@ -142,7 +135,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface private ?string $plainPassword = null; /** - * @var \DateTime|null * @Serializer\Groups({"user_security"}) */ #[ORM\Column(name: 'last_login', type: 'datetime', nullable: true)] @@ -162,7 +154,7 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * Names of current User roles - * to be compatible with symfony security scheme + * to be compatible with symfony security scheme. * * @var array|null */ @@ -172,6 +164,7 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @var Collection + * * @Serializer\Groups({"user_group"}) */ #[ORM\JoinTable(name: 'users_groups')] @@ -182,7 +175,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface private Collection $groups; /** - * @var boolean * @Serializer\Groups({"user_security"}) */ #[ORM\Column(type: 'boolean', nullable: false, options: ['default' => false])] @@ -191,7 +183,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @Serializer\Groups({"user_security"}) - * @var \DateTime|null */ #[ORM\Column(name: 'credentials_expires_at', type: 'datetime', nullable: true)] #[SymfonySerializer\Groups(['user_security'])] @@ -199,7 +190,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @Serializer\Groups({"user_security"}) - * @var \DateTime|null */ #[ORM\Column(name: 'expires_at', type: 'datetime', nullable: true)] #[SymfonySerializer\Groups(['user_security'])] @@ -207,7 +197,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface /** * @Serializer\Groups({"user_chroot"}) - * @var Node|null */ #[ORM\ManyToOne(targetEntity: Node::class)] #[ORM\JoinColumn(name: 'chroot_id', referencedColumnName: 'id', onDelete: 'SET NULL')] @@ -215,7 +204,6 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface private ?Node $chroot = null; /** - * @var null|string * @Serializer\Groups({"user"}) */ #[ORM\Column(name: 'locale', type: 'string', length: 7, nullable: true)] @@ -234,21 +222,17 @@ public function __construct() /** * Set if we need Roadiz to send a default email * when User will be persisted. - * - * @param bool $sendCreationConfirmationEmail - * @return User */ public function sendCreationConfirmationEmail(bool $sendCreationConfirmationEmail): User { $this->sendCreationConfirmationEmail = $sendCreationConfirmationEmail; + return $this; } /** * Tells if we need Roadiz to send a default email * when User will be persisted. Default: false. - * - * @return bool */ public function willSendCreationConfirmationEmail(): bool { @@ -259,15 +243,14 @@ public function willSendCreationConfirmationEmail(): bool * Get available username data, first name and last name * or username as a last try. * - * @return string * @Serializer\Exclude() */ #[SymfonySerializer\Ignore] public function getIdentifier(): string { - if ($this->getFirstName() != "" && $this->getLastName() != "") { - return $this->getFirstName() . " " . $this->getLastName(); - } elseif ($this->getFirstName() != "") { + if ('' != $this->getFirstName() && '' != $this->getLastName()) { + return $this->getFirstName().' '.$this->getLastName(); + } elseif ('' != $this->getFirstName()) { return $this->getFirstName(); } else { return $this->getUsername(); @@ -275,8 +258,8 @@ public function getIdentifier(): string } /** - * @return string * @Serializer\Groups({"user_identifier", "user_personal"}) + * * @Serializer\VirtualProperty() */ #[SymfonySerializer\SerializedName('identifier')] @@ -295,20 +278,17 @@ public function getUsername(): string } /** - * @param string $username - * * @return $this */ public function setUsername(string $username): User { $this->username = $username; + return $this; } /** - * Get facebook profile name to grab public infos such as picture - * - * @return string|null + * Get facebook profile name to grab public infos such as picture. */ public function getFacebookName(): ?string { @@ -316,36 +296,30 @@ public function getFacebookName(): ?string } /** - * @param string|null $facebookName * @return $this */ public function setFacebookName(?string $facebookName): User { $this->facebookName = $facebookName; + return $this; } - /** - * @return string|null - */ public function getPictureUrl(): ?string { return $this->pictureUrl; } /** - * @param string|null $pictureUrl * @return $this */ public function setPictureUrl(?string $pictureUrl): User { $this->pictureUrl = $pictureUrl; + return $this; } - /** - * @return string|null - */ public function getSalt(): ?string { return null; @@ -360,12 +334,12 @@ public function getPassword(): string } /** - * @param string $password * @return $this */ public function setPassword(string $password): User { $this->password = $password; + return $this; } @@ -377,19 +351,16 @@ public function getPlainPassword(): ?string return $this->plainPassword; } - /** - * @param string|null $plainPassword - * @return User - */ public function setPlainPassword(?string $plainPassword): User { $this->plainPassword = $plainPassword; - if (null !== $plainPassword && $plainPassword != '') { + if (null !== $plainPassword && '' != $plainPassword) { /* * We MUST change password to trigger preUpdate lifeCycle event. */ - $this->password = '--password-changed--' . uniqid(); + $this->password = '--password-changed--'.uniqid(); } + return $this; } @@ -401,20 +372,15 @@ public function getLastLogin(): ?\DateTime return $this->lastLogin; } - /** - * @param \DateTime|null $lastLogin - * @return User - */ public function setLastLogin(?\DateTime $lastLogin): User { $this->lastLogin = $lastLogin; + return $this; } /** * Get random string sent to the user email address in order to verify it. - * - * @return string|null */ public function getConfirmationToken(): ?string { @@ -424,7 +390,6 @@ public function getConfirmationToken(): ?string /** * Set random string sent to the user email address in order to verify it. * - * @param string|null $confirmationToken * @return $this */ public function setConfirmationToken(?string $confirmationToken): User @@ -437,20 +402,16 @@ public function setConfirmationToken(?string $confirmationToken): User /** * Check if password reset request has expired. * - * @param int $ttl Password request time to live. - * - * @return boolean + * @param int $ttl password request time to live */ public function isPasswordRequestNonExpired(int $ttl): bool { - return $this->getPasswordRequestedAt() instanceof \DateTime && - $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time(); + return $this->getPasswordRequestedAt() instanceof \DateTime + && $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time(); } /** * Gets the timestamp that the user requested a password reset. - * - * @return null|\DateTime */ public function getPasswordRequestedAt(): ?\DateTime { @@ -460,18 +421,18 @@ public function getPasswordRequestedAt(): ?\DateTime /** * Sets the timestamp that the user requested a password reset. * - * @param \DateTime|null $date * @return $this */ - public function setPasswordRequestedAt(\DateTime $date = null): User + public function setPasswordRequestedAt(?\DateTime $date = null): User { $this->passwordRequestedAt = $date; + return $this; } /** - * @param Role $role * @return $this + * * @deprecated Use addRoleEntity */ public function addRole(Role $role): User @@ -482,8 +443,6 @@ public function addRole(Role $role): User /** * Add a role object to current user. * - * @param Role $role - * * @return $this */ public function addRoleEntity(Role $role): User @@ -496,28 +455,23 @@ public function addRoleEntity(Role $role): User } /** - * Get roles entities - * - * @return Collection|null + * Get roles entities. */ public function getRolesEntities(): ?Collection { return $this->roleEntities; } - /** - * @param ArrayCollection $roles - * @return User - */ public function setRolesEntities(ArrayCollection $roles): User { $this->roleEntities = $roles; + return $this; } /** - * @param Role $role * @return $this + * * @deprecated Use removeRoleEntity */ public function removeRole(Role $role): User @@ -528,8 +482,6 @@ public function removeRole(Role $role): User /** * Remove role from current user. * - * @param Role $role - * * @return $this */ public function removeRoleEntity(Role $role): User @@ -537,13 +489,12 @@ public function removeRoleEntity(Role $role): User if ($this->getRolesEntities()->contains($role)) { $this->getRolesEntities()->removeElement($role); } + return $this; } /** * Removes sensitive data from the user. - * - * @return User */ public function eraseCredentials(): User { @@ -553,8 +504,6 @@ public function eraseCredentials(): User /** * Insert user into group. * - * @param Group $group - * * @return $this */ public function addGroup(Group $group): User @@ -566,18 +515,13 @@ public function addGroup(Group $group): User return $this; } - /** - * @return Collection - */ public function getGroups(): ?Collection { return $this->groups; } /** - * Remove user from group - * - * @param Group $group + * Remove user from group. * * @return $this */ @@ -594,7 +538,9 @@ public function removeGroup(Group $group): User * Get current user groups name. * * @return array Array of strings + * * @Serializer\Groups({"user"}) + * * @Serializer\VirtualProperty() */ #[SymfonySerializer\Groups(['user'])] @@ -616,16 +562,18 @@ public function getGroupNames(): array * Internally, if this method returns false, the authentication system * will throw an AccountExpiredException and prevent login. * - * @return bool true if the user's account is non expired, false otherwise + * @return bool true if the user's account is non expired, false otherwise * * @see AccountExpiredException + * * @Serializer\Groups({"user_security"}) + * * @Serializer\VirtualProperty() */ #[SymfonySerializer\Groups(['user_security'])] public function isAccountNonExpired(): bool { - return $this->expiresAt === null || $this->expiresAt->getTimestamp() > time(); + return null === $this->expiresAt || $this->expiresAt->getTimestamp() > time(); } /** @@ -637,7 +585,9 @@ public function isAccountNonExpired(): bool * @return bool true if the user is not locked, false otherwise * * @see LockedException + * * @Serializer\Groups({"user_security"}) + * * @Serializer\VirtualProperty() */ #[SymfonySerializer\Groups(['user_security'])] @@ -649,43 +599,28 @@ public function isAccountNonLocked(): bool public function setLocked(bool $locked): self { $this->locked = $locked; + return $this; } - /** - * @return bool - */ public function isLocked(): bool { return $this->locked; } - /** - * @param User $user - * - * @return boolean - */ public function equals(User $user): bool { - return ( - $this->username == $user->getUsername() || - $this->email == $user->getEmail() - ); + return + $this->username == $user->getUsername() + || $this->email == $user->getEmail() + ; } - /** - * @return \DateTime|null - */ public function getCredentialsExpiresAt(): ?\DateTime { return $this->credentialsExpiresAt; } - /** - * @param \DateTime|null $date - * - * @return User - */ public function setCredentialsExpiresAt(?\DateTime $date = null): User { $this->credentialsExpiresAt = $date; @@ -694,7 +629,6 @@ public function setCredentialsExpiresAt(?\DateTime $date = null): User } /** - * @return Node|null * @internal Do use directly, use NodeChrootResolver class to support external users (SSO, oauth2, …) */ public function getChroot(): ?Node @@ -702,11 +636,7 @@ public function getChroot(): ?Node return $this->chroot; } - /** - * @param Node|null $chroot - * @return User - */ - public function setChroot(Node $chroot = null): User + public function setChroot(?Node $chroot = null): User { $this->chroot = $chroot; @@ -717,16 +647,17 @@ public function setChroot(Node $chroot = null): User * Get prototype abstract Gravatar url. * * @Serializer\Exclude() + * * @param string $type Default: "identicon" * @param string $size Default: "200" - * @return string */ #[SymfonySerializer\Ignore] - public function getGravatarUrl(string $type = "identicon", string $size = "200"): string + public function getGravatarUrl(string $type = 'identicon', string $size = '200'): string { if (null !== $this->getEmail()) { - return "https://www.gravatar.com/avatar/" . md5(\mb_strtolower(trim($this->getEmail()))) . "?d=" . $type . "&s=" . $size; + return 'https://www.gravatar.com/avatar/'.md5(\mb_strtolower(trim($this->getEmail()))).'?d='.$type.'&s='.$size; } + return ''; } @@ -753,11 +684,6 @@ public function isEnabled(): bool return $this->enabled; } - /** - * @param boolean $enabled - * - * @return User - */ public function setEnabled(bool $enabled): User { $this->enabled = $enabled; @@ -773,31 +699,25 @@ public function setEnabled(bool $enabled): User * Internally, if this method returns false, the authentication system * will throw a CredentialsExpiredException and prevent login. * - * @return bool true if the user's credentials are non expired, false otherwise + * @return bool true if the user's credentials are non expired, false otherwise * * @see CredentialsExpiredException */ #[SymfonySerializer\Ignore] public function isCredentialsNonExpired(): bool { - return $this->credentialsExpiresAt === null || $this->credentialsExpiresAt->getTimestamp() > time(); + return null === $this->credentialsExpiresAt || $this->credentialsExpiresAt->getTimestamp() > time(); } - /** - * @return \DateTime|null - */ public function getExpiresAt(): ?\DateTime { return $this->expiresAt; } - /** - * @param \DateTime|null $expiresAt - * @return User - */ public function setExpiresAt(?\DateTime $expiresAt): User { $this->expiresAt = $expiresAt; + return $this; } @@ -836,21 +756,15 @@ public function getRoles(): array return $this->roles; } - /** - * @return null|string - */ public function getLocale(): ?string { return $this->locale; } - /** - * @param null|string $locale - * @return User - */ public function setLocale(?string $locale): User { $this->locale = $locale; + return $this; } @@ -900,21 +814,11 @@ public function isSuperAdmin(): bool return $this->hasRole(Role::ROLE_SUPERADMIN); } - /** - * @param string $name - * - * @return bool - */ public function hasGroup(string $name): bool { return in_array((string) $name, $this->getGroupNames()); } - /** - * @param string $role - * - * @return bool - */ public function hasRole(string $role): bool { return in_array(\mb_strtoupper((string) $role), $this->getRoles(), true); @@ -922,10 +826,6 @@ public function hasRole(string $role): bool /** * Every field tested in this methods must be serialized in token. - * - * @param UserInterface $user - * - * @return bool */ #[SymfonySerializer\Ignore] public function isEqualTo(UserInterface $user): bool diff --git a/lib/RoadizCoreBundle/src/Entity/UserLogEntry.php b/lib/RoadizCoreBundle/src/Entity/UserLogEntry.php index 9714f502..84dc6b61 100644 --- a/lib/RoadizCoreBundle/src/Entity/UserLogEntry.php +++ b/lib/RoadizCoreBundle/src/Entity/UserLogEntry.php @@ -9,15 +9,15 @@ use RZ\Roadiz\CoreBundle\Repository\UserLogEntryRepository; /** - * Add User to Gedmo\Loggable\Entity\LogEntry + * Add User to Gedmo\Loggable\Entity\LogEntry. */ #[ ORM\Entity(repositoryClass: UserLogEntryRepository::class), - ORM\Table(name: "user_log_entries", options: ["row_format" => "DYNAMIC"]), - ORM\Index(columns: ["object_class"], name: "log_class_lookup_idx"), - ORM\Index(columns: ["logged_at"], name: "log_date_lookup_idx"), - ORM\Index(columns: ["username"], name: "log_user_lookup_idx"), - ORM\Index(columns: ["object_id", "object_class", "version"], name: "log_version_lookup_idx") + ORM\Table(name: 'user_log_entries', options: ['row_format' => 'DYNAMIC']), + ORM\Index(columns: ['object_class'], name: 'log_class_lookup_idx'), + ORM\Index(columns: ['logged_at'], name: 'log_date_lookup_idx'), + ORM\Index(columns: ['username'], name: 'log_user_lookup_idx'), + ORM\Index(columns: ['object_id', 'object_class', 'version'], name: 'log_version_lookup_idx') ] class UserLogEntry extends AbstractLogEntry { diff --git a/lib/RoadizCoreBundle/src/Entity/Webhook.php b/lib/RoadizCoreBundle/src/Entity/Webhook.php index 840cff92..bb02f6ed 100644 --- a/lib/RoadizCoreBundle/src/Entity/Webhook.php +++ b/lib/RoadizCoreBundle/src/Entity/Webhook.php @@ -14,62 +14,50 @@ #[ ORM\Entity(repositoryClass: WebhookRepository::class), - ORM\Table(name: "webhooks"), - ORM\Index(columns: ["message_type"], name: "webhook_message_type"), - ORM\Index(columns: ["created_at"], name: "webhook_created_at"), - ORM\Index(columns: ["updated_at"], name: "webhook_updated_at"), - ORM\Index(columns: ["automatic"], name: "webhook_automatic"), - ORM\Index(columns: ["root_node"], name: "webhook_root_node"), - ORM\Index(columns: ["last_triggered_at"], name: "webhook_last_triggered_at"), + ORM\Table(name: 'webhooks'), + ORM\Index(columns: ['message_type'], name: 'webhook_message_type'), + ORM\Index(columns: ['created_at'], name: 'webhook_created_at'), + ORM\Index(columns: ['updated_at'], name: 'webhook_updated_at'), + ORM\Index(columns: ['automatic'], name: 'webhook_automatic'), + ORM\Index(columns: ['root_node'], name: 'webhook_root_node'), + ORM\Index(columns: ['last_triggered_at'], name: 'webhook_last_triggered_at'), ORM\HasLifecycleCallbacks ] class Webhook extends AbstractDateTimed implements WebhookInterface { #[ ORM\Id, - ORM\Column(type:"string", length:36), - Serializer\Groups(["id"]), - SymfonySerializer\Groups(["id"]), - Serializer\Type("string") + ORM\Column(type: 'string', length: 36), + Serializer\Groups(['id']), + SymfonySerializer\Groups(['id']), + Serializer\Type('string') ] /** @phpstan-ignore-next-line */ protected int|string|null $id = null; - /** - * @var string|null - */ #[ORM\Column(type: 'text', nullable: true)] #[Assert\NotBlank] #[Assert\Length(min: 1, max: 250)] #[Serializer\Type('string')] protected ?string $description = null; - /** - * @var string|null - */ #[ORM\Column(name: 'message_type', type: 'string', length: 255, nullable: true)] #[Serializer\Type('string')] #[Assert\Length(max: 255)] protected ?string $messageType = null; - /** - * @var string|null - */ #[ORM\Column(type: 'text', nullable: true)] #[Assert\NotBlank] #[Assert\Url] #[Serializer\Type('string')] protected ?string $uri = null; - /** - * @var array|null - */ #[ORM\Column(type: 'json', nullable: true)] #[Serializer\Type('array')] protected ?array $payload = null; /** - * @var int Wait between webhook call and webhook triggering request. + * @var int wait between webhook call and webhook triggering request */ #[ORM\Column(name: 'throttleseconds', type: 'integer', nullable: false)] #[Assert\NotNull] @@ -77,23 +65,14 @@ class Webhook extends AbstractDateTimed implements WebhookInterface #[Serializer\Type('int')] protected int $throttleSeconds = 60; - /** - * @var \DateTime|null - */ #[ORM\Column(name: 'last_triggered_at', type: 'datetime', nullable: true)] #[Serializer\Type('\DateTime')] protected ?\DateTime $lastTriggeredAt = null; - /** - * @var bool - */ #[ORM\Column(name: 'automatic', type: 'boolean', nullable: false, options: ['default' => false])] #[Serializer\Type('boolean')] protected bool $automatic = false; - /** - * @var Node|null - */ #[ORM\ManyToOne(targetEntity: Node::class)] #[ORM\JoinColumn(name: 'root_node', onDelete: 'SET NULL')] #[SymfonySerializer\Ignore] @@ -104,97 +83,68 @@ public function __construct(?string $uuid = null) $this->id = $uuid ?? \Ramsey\Uuid\Uuid::uuid4()->toString(); } - /** - * @return string|null - */ public function getDescription(): ?string { return $this->description; } - /** - * @param string|null $description - * @return Webhook - */ public function setDescription(?string $description): Webhook { $this->description = $description; + return $this; } - /** - * @return string|null - */ public function getMessageType(): ?string { return $this->messageType; } - /** - * @param string|null $messageType - * @return Webhook - */ public function setMessageType(?string $messageType): Webhook { $this->messageType = $messageType; + return $this; } - /** - * @return string|null - */ public function getUri(): ?string { return $this->uri; } - /** - * @param string|null $uri - * @return Webhook - */ public function setUri(?string $uri): Webhook { $this->uri = $uri; + return $this; } - /** - * @return array|null - */ public function getPayload(): ?array { return $this->payload; } - /** - * @param array|null $payload - * @return Webhook - */ public function setPayload(?array $payload): Webhook { $this->payload = $payload; + return $this; } - /** - * @return int - */ public function getThrottleSeconds(): int { return $this->throttleSeconds; } /** - * @return \DateInterval * @throws \Exception */ public function getThrottleInterval(): \DateInterval { - return new \DateInterval('PT' . $this->getThrottleSeconds() . 'S'); + return new \DateInterval('PT'.$this->getThrottleSeconds().'S'); } /** - * @return \DateTime|null * @throws \Exception */ public function doNotTriggerBefore(): ?\DateTime @@ -203,70 +153,50 @@ public function doNotTriggerBefore(): ?\DateTime return null; } $doNotTriggerBefore = clone $this->getLastTriggeredAt(); + return $doNotTriggerBefore->add($this->getThrottleInterval()); } - /** - * @param int $throttleSeconds - * @return Webhook - */ public function setThrottleSeconds(int $throttleSeconds): Webhook { $this->throttleSeconds = $throttleSeconds; + return $this; } - /** - * @return \DateTime|null - */ public function getLastTriggeredAt(): ?\DateTime { return $this->lastTriggeredAt; } - /** - * @param \DateTime|null $lastTriggeredAt - * @return Webhook - */ public function setLastTriggeredAt(?\DateTime $lastTriggeredAt): Webhook { $this->lastTriggeredAt = $lastTriggeredAt; + return $this; } - /** - * @return bool - */ public function isAutomatic(): bool { return $this->automatic; } - /** - * @param bool $automatic - * @return Webhook - */ public function setAutomatic(bool $automatic): Webhook { $this->automatic = $automatic; + return $this; } - /** - * @return Node|null - */ public function getRootNode(): ?Node { return $this->rootNode; } - /** - * @param Node|null $rootNode - * @return Webhook - */ public function setRootNode(?Node $rootNode): Webhook { $this->rootNode = $rootNode; + return $this; } diff --git a/lib/RoadizCoreBundle/src/EntityApi/AbstractApi.php b/lib/RoadizCoreBundle/src/EntityApi/AbstractApi.php index 0e32d72f..1e4037db 100644 --- a/lib/RoadizCoreBundle/src/EntityApi/AbstractApi.php +++ b/lib/RoadizCoreBundle/src/EntityApi/AbstractApi.php @@ -4,52 +4,34 @@ namespace RZ\Roadiz\CoreBundle\EntityApi; +use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Tools\Pagination\Paginator; use Doctrine\Persistence\ManagerRegistry; +use RZ\Roadiz\Core\AbstractEntities\PersistableInterface; /** * @deprecated Use EntityRepository directly */ abstract class AbstractApi { - protected ManagerRegistry $managerRegistry; - - /** - * @param ManagerRegistry $managerRegistry - */ - public function __construct(ManagerRegistry $managerRegistry) + public function __construct(protected ManagerRegistry $managerRegistry) { - $this->managerRegistry = $managerRegistry; } - /** - * Return entity path for current API. - * - * @return \Doctrine\ORM\EntityRepository - */ - abstract public function getRepository(); + abstract public function getRepository(): EntityRepository; /** * Return an array of entities matching criteria array. - * - * @param array $criteria - * @return array|Paginator */ - abstract public function getBy(array $criteria); + abstract public function getBy(array $criteria): array|Paginator; /** * Return one entity matching criteria array. - * - * @param array $criteria - * @return mixed */ - abstract public function getOneBy(array $criteria); + abstract public function getOneBy(array $criteria): ?PersistableInterface; /** * Count entities matching criteria array. - * - * @param array $criteria - * @return int */ - abstract public function countBy(array $criteria); + abstract public function countBy(array $criteria): int; } diff --git a/lib/RoadizCoreBundle/src/EntityApi/NodeApi.php b/lib/RoadizCoreBundle/src/EntityApi/NodeApi.php index d30b99ae..108e7673 100644 --- a/lib/RoadizCoreBundle/src/EntityApi/NodeApi.php +++ b/lib/RoadizCoreBundle/src/EntityApi/NodeApi.php @@ -13,9 +13,6 @@ */ class NodeApi extends AbstractApi { - /** - * @return NodeRepository - */ public function getRepository(): NodeRepository { // phpstan cannot resolve repository type. @@ -24,22 +21,19 @@ public function getRepository(): NodeRepository ->getRepository(Node::class) ->setDisplayingNotPublishedNodes(false) ->setDisplayingAllNodesStatuses(false); + return $repository; } /** - * @param array $criteria - * @param array|null $order - * @param int|null $limit - * @param int|null $offset - * @return array|Paginator + * @return array|Paginator */ public function getBy( array $criteria, - array $order = null, + ?array $order = null, ?int $limit = null, - ?int $offset = null - ) { + ?int $offset = null, + ): array|Paginator { if (!in_array('translation.available', $criteria, true)) { $criteria['translation.available'] = true; } @@ -53,10 +47,8 @@ public function getBy( null ); } - /** - * {@inheritdoc} - */ - public function countBy(array $criteria) + + public function countBy(array $criteria): int { if (!in_array('translation.available', $criteria, true)) { $criteria['translation.available'] = true; @@ -68,10 +60,8 @@ public function countBy(array $criteria) null ); } - /** - * {@inheritdoc} - */ - public function getOneBy(array $criteria, array $order = null) + + public function getOneBy(array $criteria, ?array $order = null): ?Node { if (!in_array('translation.available', $criteria, true)) { $criteria['translation.available'] = true; diff --git a/lib/RoadizCoreBundle/src/EntityApi/NodeSourceApi.php b/lib/RoadizCoreBundle/src/EntityApi/NodeSourceApi.php index 7234cbd6..ba4eb6f6 100644 --- a/lib/RoadizCoreBundle/src/EntityApi/NodeSourceApi.php +++ b/lib/RoadizCoreBundle/src/EntityApi/NodeSourceApi.php @@ -21,19 +21,18 @@ class NodeSourceApi extends AbstractApi protected string $nodeSourceClassName = NodesSources::class; /** - * @param array|null $criteria * @return class-string */ - protected function getNodeSourceClassName(array $criteria = null): string + protected function getNodeSourceClassName(?array $criteria = null): string { if (isset($criteria['node.nodeType']) && $criteria['node.nodeType'] instanceof NodeType) { $this->nodeSourceClassName = $criteria['node.nodeType']->getSourceEntityFullQualifiedClassName(); unset($criteria['node.nodeType']); } elseif ( - isset($criteria['node.nodeType']) && - is_array($criteria['node.nodeType']) && - count($criteria['node.nodeType']) === 1 && - $criteria['node.nodeType'][0] instanceof NodeType + isset($criteria['node.nodeType']) + && is_array($criteria['node.nodeType']) + && 1 === count($criteria['node.nodeType']) + && $criteria['node.nodeType'][0] instanceof NodeType ) { $this->nodeSourceClassName = $criteria['node.nodeType'][0]->getSourceEntityFullQualifiedClassName(); unset($criteria['node.nodeType']); @@ -44,9 +43,6 @@ protected function getNodeSourceClassName(array $criteria = null): string return $this->nodeSourceClassName; } - /** - * @return NodesSourcesRepository - */ public function getRepository(): NodesSourcesRepository { // @phpstan-ignore-next-line @@ -54,18 +50,14 @@ public function getRepository(): NodesSourcesRepository } /** - * @param array $criteria - * @param array|null $order - * @param int|null $limit - * @param int|null $offset - * @return array|Paginator + * @return array|Paginator */ public function getBy( array $criteria, - array $order = null, + ?array $order = null, ?int $limit = null, - ?int $offset = null - ) { + ?int $offset = null, + ): array|Paginator { $this->getNodeSourceClassName($criteria); return $this->getRepository() @@ -78,14 +70,13 @@ public function getBy( } /** - * @param array $criteria - * @return int * @throws \Doctrine\ORM\NoResultException - * @throws \Doctrine\ORM\NonUniqueResultException + * @throws NonUniqueResultException */ - public function countBy(array $criteria) + public function countBy(array $criteria): int { $this->getNodeSourceClassName($criteria); + return $this->getRepository() ->countBy( $criteria @@ -93,14 +84,12 @@ public function countBy(array $criteria) } /** - * @param array $criteria - * @param array|null $order - * @return null|NodesSources * @throws NonUniqueResultException */ - public function getOneBy(array $criteria, array $order = null) + public function getOneBy(array $criteria, ?array $order = null): ?NodesSources { $this->getNodeSourceClassName($criteria); + return $this->getRepository() ->findOneBy( $criteria, @@ -111,21 +100,14 @@ public function getOneBy(array $criteria, array $order = null) /** * Search Nodes-Sources using LIKE condition on title, * meta-title, meta-keywords and meta-description. - * - * @param string $textQuery - * @param int $limit - * @param array $nodeTypes - * @param bool $onlyVisible - * @param array $additionalCriteria - * @return array */ public function searchBy( string $textQuery, int $limit = 0, array $nodeTypes = [], bool $onlyVisible = false, - array $additionalCriteria = [] - ) { + array $additionalCriteria = [], + ): array { return $this->getRepository() ->findByTextQuery( $textQuery, diff --git a/lib/RoadizCoreBundle/src/EntityApi/NodeTypeApi.php b/lib/RoadizCoreBundle/src/EntityApi/NodeTypeApi.php index 2f550af5..43ebde2b 100644 --- a/lib/RoadizCoreBundle/src/EntityApi/NodeTypeApi.php +++ b/lib/RoadizCoreBundle/src/EntityApi/NodeTypeApi.php @@ -4,6 +4,7 @@ namespace RZ\Roadiz\CoreBundle\EntityApi; +use Doctrine\ORM\Tools\Pagination\Paginator; use RZ\Roadiz\CoreBundle\Entity\NodeType; use RZ\Roadiz\CoreBundle\Repository\NodeTypeRepository; @@ -12,31 +13,22 @@ */ class NodeTypeApi extends AbstractApi { - /** - * @return NodeTypeRepository - */ - public function getRepository() + public function getRepository(): NodeTypeRepository { return $this->managerRegistry->getRepository(NodeType::class); } - /** - * {@inheritdoc} - */ - public function getBy(array $criteria, array $order = null) + + public function getBy(array $criteria, ?array $order = null): array|Paginator { return $this->getRepository()->findBy($criteria, $order); } - /** - * {@inheritdoc} - */ - public function getOneBy(array $criteria, array $order = null) + + public function getOneBy(array $criteria, ?array $order = null): ?NodeType { return $this->getRepository()->findOneBy($criteria, $order); } - /** - * {@inheritdoc} - */ - public function countBy(array $criteria) + + public function countBy(array $criteria): int { return $this->getRepository()->countBy($criteria); } diff --git a/lib/RoadizCoreBundle/src/EntityApi/TagApi.php b/lib/RoadizCoreBundle/src/EntityApi/TagApi.php index 55b00910..c894b897 100644 --- a/lib/RoadizCoreBundle/src/EntityApi/TagApi.php +++ b/lib/RoadizCoreBundle/src/EntityApi/TagApi.php @@ -13,10 +13,7 @@ */ class TagApi extends AbstractApi { - /** - * @return TagRepository - */ - public function getRepository() + public function getRepository(): TagRepository { return $this->managerRegistry->getRepository(Tag::class); } @@ -26,19 +23,14 @@ public function getRepository() * * When no order is defined, tags are ordered by position. * - * @param array $criteria - * @param array|null $order - * @param int|null $limit - * @param int|null $offset - * - * @return array|Paginator + * @return array|Paginator */ public function getBy( array $criteria, - array $order = null, + ?array $order = null, ?int $limit = null, - ?int $offset = null - ) { + ?int $offset = null, + ): array|Paginator { if (null === $order) { $order = [ 'position' => 'ASC', @@ -54,10 +46,8 @@ public function getBy( null ); } - /** - * {@inheritdoc} - */ - public function countBy(array $criteria) + + public function countBy(array $criteria): int { return $this->getRepository() ->countBy( @@ -65,10 +55,8 @@ public function countBy(array $criteria) null ); } - /** - * {@inheritdoc} - */ - public function getOneBy(array $criteria, array $order = null) + + public function getOneBy(array $criteria, ?array $order = null): ?Tag { return $this->getRepository() ->findOneBy( diff --git a/lib/RoadizCoreBundle/src/EntityHandler/CustomFormFieldHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/CustomFormFieldHandler.php index dfa24595..38fc7b1b 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/CustomFormFieldHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/CustomFormFieldHandler.php @@ -15,31 +15,26 @@ final class CustomFormFieldHandler extends AbstractHandler { private ?CustomFormField $customFormField = null; - /** - * @param ObjectManager $objectManager - * @param CustomFormHandler $customFormHandler - */ public function __construct( ObjectManager $objectManager, - private readonly CustomFormHandler $customFormHandler + private readonly CustomFormHandler $customFormHandler, ) { parent::__construct($objectManager); } /** - * @param CustomFormField $customFormField * @return $this */ public function setCustomFormField(CustomFormField $customFormField): self { $this->customFormField = $customFormField; + return $this; } /** * Clean position for current customForm siblings. * - * @param bool $setPositions * @return float Return the next position after the **last** customFormField */ public function cleanPositions(bool $setPositions = true): float @@ -49,6 +44,7 @@ public function cleanPositions(bool $setPositions = true): float } $this->customFormHandler->setCustomForm($this->customFormField->getCustomForm()); + return $this->customFormHandler->cleanFieldsPositions($setPositions); } } diff --git a/lib/RoadizCoreBundle/src/EntityHandler/CustomFormHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/CustomFormHandler.php index 721e121a..a04f0fd4 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/CustomFormHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/CustomFormHandler.php @@ -18,13 +18,13 @@ final class CustomFormHandler extends AbstractHandler public function setCustomForm(CustomForm $customForm): self { $this->customForm = $customForm; + return $this; } /** * Reset current node-type fields positions. * - * @param bool $setPositions * @return float Return the next position after the **last** field */ public function cleanFieldsPositions(bool $setPositions = true): float @@ -41,7 +41,7 @@ public function cleanFieldsPositions(bool $setPositions = true): float if ($setPositions) { $field->setPosition($i); } - $i++; + ++$i; } if ($setPositions) { diff --git a/lib/RoadizCoreBundle/src/EntityHandler/DocumentHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/DocumentHandler.php index 44e9d885..75381fe9 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/DocumentHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/DocumentHandler.php @@ -34,8 +34,6 @@ public function __construct(ObjectManager $objectManager, private readonly Files * Get a Response object to force download document. * This method works for both private and public documents. * - * @param bool $asAttachment - * @return StreamedResponse * @throws FilesystemException */ public function getDownloadResponse(bool $asAttachment = true): StreamedResponse @@ -45,12 +43,13 @@ public function getDownloadResponse(bool $asAttachment = true): StreamedResponse if ($this->documentStorage->fileExists($documentPath)) { $headers = [ - "Content-Type" => $this->documentStorage->mimeType($documentPath), - "Content-Length" => $this->documentStorage->fileSize($documentPath), + 'Content-Type' => $this->documentStorage->mimeType($documentPath), + 'Content-Length' => $this->documentStorage->fileSize($documentPath), ]; if ($asAttachment) { - $headers["Content-disposition"] = "attachment; filename=\"" . basename($this->document->getFilename()) . "\""; + $headers['Content-disposition'] = 'attachment; filename="'.basename($this->document->getFilename()).'"'; } + return new StreamedResponse(function () use ($documentPath) { \fpassthru($this->documentStorage->readStream($documentPath)); }, Response::HTTP_OK, $headers); @@ -63,11 +62,8 @@ public function getDownloadResponse(bool $asAttachment = true): StreamedResponse /** * Return documents folders with the same translation as * current document. - * - * @param Translation|null $translation - * @return array */ - public function getFolders(Translation $translation = null): array + public function getFolders(?Translation $translation = null): array { if (!$this->document instanceof Document) { return []; @@ -92,12 +88,12 @@ public function getDocument(): ?DocumentInterface } /** - * @param DocumentInterface $document * @return $this */ public function setDocument(DocumentInterface $document): self { $this->document = $document; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/EntityHandler/FolderHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/FolderHandler.php index 5cb16fdb..5233f87d 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/FolderHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/FolderHandler.php @@ -20,16 +20,17 @@ public function getFolder(): Folder if (null === $this->folder) { throw new \BadMethodCallException('Folder is null'); } + return $this->folder; } /** - * @param Folder $folder * @return $this */ public function setFolder(Folder $folder): self { $this->folder = $folder; + return $this; } @@ -65,22 +66,23 @@ public function removeWithChildrenAndAssociations(): self * Final flush */ $this->objectManager->flush(); + return $this; } /** * Clean position for current folder siblings. * - * @param bool $setPositions * @return float Return the next position after the **last** folder */ public function cleanPositions(bool $setPositions = true): float { - if ($this->getFolder()->getParent() !== null) { + if (null !== $this->getFolder()->getParent()) { $parentHandler = new FolderHandler($this->objectManager); /** @var Folder|null $parent */ $parent = $this->getFolder()->getParent(); $parentHandler->setFolder($parent); + return $parentHandler->cleanChildrenPositions($setPositions); } else { return $this->cleanRootFoldersPositions($setPositions); @@ -92,7 +94,6 @@ public function cleanPositions(bool $setPositions = true): float * * Warning, this method does not flush. * - * @param bool $setPositions * @return float Return the next position after the **last** folder */ public function cleanChildrenPositions(bool $setPositions = true): float @@ -102,7 +103,7 @@ public function cleanChildrenPositions(bool $setPositions = true): float */ $sort = Criteria::create(); $sort->orderBy([ - 'position' => Criteria::ASC + 'position' => Criteria::ASC, ]); $children = $this->getFolder()->getChildren()->matching($sort); @@ -112,7 +113,7 @@ public function cleanChildrenPositions(bool $setPositions = true): float if ($setPositions) { $child->setPosition($i); } - $i++; + ++$i; } return $i; @@ -123,7 +124,6 @@ public function cleanChildrenPositions(bool $setPositions = true): float * * Warning, this method does not flush. * - * @param bool $setPositions * @return float Return the next position after the **last** folder */ public function cleanRootFoldersPositions(bool $setPositions = true): float @@ -138,7 +138,7 @@ public function cleanRootFoldersPositions(bool $setPositions = true): float if ($setPositions) { $child->setPosition($i); } - $i++; + ++$i; } return $i; diff --git a/lib/RoadizCoreBundle/src/EntityHandler/GroupHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/GroupHandler.php index 9fb78ea9..751157bd 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/GroupHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/GroupHandler.php @@ -4,9 +4,9 @@ namespace RZ\Roadiz\CoreBundle\EntityHandler; +use RZ\Roadiz\Core\Handlers\AbstractHandler; use RZ\Roadiz\CoreBundle\Entity\Group; use RZ\Roadiz\CoreBundle\Entity\Role; -use RZ\Roadiz\Core\Handlers\AbstractHandler; /** * Handle operations with Group entities. @@ -20,27 +20,26 @@ public function getGroup(): Group if (null === $this->group) { throw new \BadMethodCallException('Group is null'); } + return $this->group; } /** - * @param Group $group * @return $this */ public function setGroup(Group $group): self { $this->group = $group; + return $this; } /** * This method does not flush ORM. You'll need to manually call it. - * - * @param Group $newGroup */ public function diff(Group $newGroup): void { - if ("" != $newGroup->getName()) { + if ('' != $newGroup->getName()) { $this->getGroup()->setName($newGroup->getName()); } diff --git a/lib/RoadizCoreBundle/src/EntityHandler/HandlerFactory.php b/lib/RoadizCoreBundle/src/EntityHandler/HandlerFactory.php index 860b941e..ef81c55f 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/HandlerFactory.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/HandlerFactory.php @@ -27,38 +27,36 @@ public function __construct(private readonly ContainerInterface $container) } /** - * @param AbstractEntity $entity - * @return AbstractHandler * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ public function getHandler(AbstractEntity $entity): AbstractHandler { switch (true) { - case ($entity instanceof Node): + case $entity instanceof Node: return $this->container->get(NodeHandler::class)->setNode($entity); - case ($entity instanceof NodesSources): + case $entity instanceof NodesSources: return $this->container->get(NodesSourcesHandler::class)->setNodeSource($entity); - case ($entity instanceof NodeType): + case $entity instanceof NodeType: return $this->container->get(NodeTypeHandler::class)->setNodeType($entity); - case ($entity instanceof NodeTypeField): + case $entity instanceof NodeTypeField: return $this->container->get(NodeTypeFieldHandler::class)->setNodeTypeField($entity); - case ($entity instanceof Document): + case $entity instanceof Document: return $this->container->get(DocumentHandler::class)->setDocument($entity); - case ($entity instanceof CustomForm): + case $entity instanceof CustomForm: return $this->container->get(CustomFormHandler::class)->setCustomForm($entity); - case ($entity instanceof CustomFormField): + case $entity instanceof CustomFormField: return $this->container->get(CustomFormFieldHandler::class)->setCustomFormField($entity); - case ($entity instanceof Folder): + case $entity instanceof Folder: return $this->container->get(FolderHandler::class)->setFolder($entity); - case ($entity instanceof Group): + case $entity instanceof Group: return $this->container->get(GroupHandler::class)->setGroup($entity); - case ($entity instanceof Tag): + case $entity instanceof Tag: return $this->container->get(TagHandler::class)->setTag($entity); - case ($entity instanceof Translation): + case $entity instanceof Translation: return $this->container->get(TranslationHandler::class)->setTranslation($entity); } - throw new \InvalidArgumentException('HandlerFactory does not support ' . get_class($entity)); + throw new \InvalidArgumentException('HandlerFactory does not support '.get_class($entity)); } } diff --git a/lib/RoadizCoreBundle/src/EntityHandler/NodeHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/NodeHandler.php index f81fa9c7..9cb0fd8c 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/NodeHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/NodeHandler.php @@ -35,7 +35,7 @@ final public function __construct( ObjectManager $objectManager, private readonly Registry $registry, private readonly NodeChrootResolver $chrootResolver, - private readonly NodeNamePolicyInterface $nodeNamePolicy + private readonly NodeNamePolicyInterface $nodeNamePolicy, ) { parent::__construct($objectManager); } @@ -50,24 +50,22 @@ protected function createSelf(): self ); } - /** - * @return Node - */ public function getNode(): Node { if (null === $this->node) { throw new \BadMethodCallException('Node is null'); } + return $this->node; } /** - * @param Node $node * @return $this */ public function setNode(Node $node): self { $this->node = $node; + return $this; } @@ -75,7 +73,7 @@ public function setNode(Node $node): self * Remove every node to custom-forms associations for a given field. * * @param NodeTypeField $field - * @param bool $flush + * * @return $this */ public function cleanCustomFormsFromField(NodeTypeFieldInterface $field, bool $flush = true): self @@ -98,17 +96,15 @@ public function cleanCustomFormsFromField(NodeTypeFieldInterface $field, bool $f /** * Add a node to current custom-forms for a given node-type field. * - * @param CustomForm $customForm * @param NodeTypeField $field - * @param bool $flush - * @param null|float $position + * * @return $this */ public function addCustomFormForField( CustomForm $customForm, NodeTypeFieldInterface $field, bool $flush = true, - ?float $position = null + ?float $position = null, ): self { $ncf = new NodesCustomForms($this->getNode(), $customForm, $field); @@ -134,7 +130,6 @@ public function addCustomFormForField( * Get custom forms linked to current node for a given field name. * * @param string $fieldName Name of the node-type field - * @return array */ public function getCustomFormsFromFieldName(string $fieldName): array { @@ -150,7 +145,7 @@ public function getCustomFormsFromFieldName(string $fieldName): array * Remove every node to node associations for a given field. * * @param NodeTypeField $field - * @param bool $flush + * * @return $this */ public function cleanNodesFromField(NodeTypeFieldInterface $field, bool $flush = true): self @@ -167,10 +162,8 @@ public function cleanNodesFromField(NodeTypeFieldInterface $field, bool $flush = /** * Add a node to current node for a given node-type field. * - * @param Node $node * @param NodeTypeField $field - * @param bool $flush - * @param null|float $position + * * @return $this */ public function addNodeForField(Node $node, NodeTypeFieldInterface $field, bool $flush = true, ?float $position = null): self @@ -200,7 +193,9 @@ public function addNodeForField(Node $node, NodeTypeFieldInterface $field, bool * Get nodes linked to current node for a given field name. * * @param string $fieldName Name of the node-type field + * * @return Node[] + * * @deprecated */ public function getNodesFromFieldName(string $fieldName): array @@ -213,6 +208,7 @@ public function getNodesFromFieldName(string $fieldName): array $field ); } + return []; } @@ -220,7 +216,9 @@ public function getNodesFromFieldName(string $fieldName): array * Get nodes reversed-linked to current node for a given field name. * * @param string $fieldName Name of the node-type field + * * @return Node[] + * * @deprecated */ public function getReverseNodesFromFieldName(string $fieldName): array @@ -233,6 +231,7 @@ public function getReverseNodesFromFieldName(string $fieldName): array $field ); } + return []; } @@ -241,14 +240,13 @@ public function getReverseNodesFromFieldName(string $fieldName): array * * @param Translation $translation * - * @return null|NodesSources - * @deprecated Use Node::getNodeSourcesByTranslation() instead. + * @deprecated use Node::getNodeSourcesByTranslation() instead */ public function getNodeSourceByTranslation($translation): ?NodesSources { return $this->objectManager ->getRepository(NodesSources::class) - ->findOneBy(["node" => $this->getNode(), "translation" => $translation]); + ->findOneBy(['node' => $this->getNode(), 'translation' => $translation]); } /** @@ -267,6 +265,7 @@ private function removeChildren(): self return $this; } + /** * Remove only current node associations. * @@ -281,6 +280,7 @@ public function removeAssociations(): self return $this; } + /** * Remove current node with its children recursively and * its associations. @@ -298,9 +298,6 @@ public function removeWithChildrenAndAssociations(): self return $this; } - /** - * @return WorkflowInterface - */ private function getWorkflow(): WorkflowInterface { return $this->registry->get($this->getNode()); @@ -374,6 +371,7 @@ public function publishWithChildren(): self $handler->setNode($node); $handler->publishWithChildren(); } + return $this; } @@ -403,10 +401,6 @@ public function archiveWithChildren(): self /** * Return if part of Node offspring. - * - * @param Node $relative - * - * @return bool */ public function isRelatedToNode(Node $relative): bool { @@ -420,13 +414,13 @@ public function isRelatedToNode(Node $relative): bool return true; } } + return false; } /** - * Return every node’s parents + * Return every node’s parents. * - * @param TokenStorageInterface|null $tokenStorage * @return array */ public function getParents(?TokenStorageInterface $tokenStorage = null): array @@ -435,13 +429,13 @@ public function getParents(?TokenStorageInterface $tokenStorage = null): array $parent = $this->getNode()->getParent(); $chroot = null; - if ($tokenStorage !== null) { + if (null !== $tokenStorage) { $user = $tokenStorage->getToken()->getUser(); /** @var Node|null $chroot */ $chroot = $this->chrootResolver->getChroot($user); } - while ($parent !== null && $parent !== $chroot) { + while (null !== $parent && $parent !== $chroot) { $parentsArray[] = $parent; $parent = $parent->getParent(); } @@ -454,16 +448,16 @@ public function getParents(?TokenStorageInterface $tokenStorage = null): array * * Warning, this method does not flush. * - * @param bool $setPositions * @return float Return the next position after the **last** node */ public function cleanPositions(bool $setPositions = true): float { - if ($this->getNode()->getParent() !== null) { + if (null !== $this->getNode()->getParent()) { $parentHandler = $this->createSelf(); /** @var Node|null $parent */ $parent = $this->getNode()->getParent(); $parentHandler->setNode($parent); + return $parentHandler->cleanChildrenPositions($setPositions); } else { return $this->cleanRootNodesPositions($setPositions); @@ -475,7 +469,6 @@ public function cleanPositions(bool $setPositions = true): float * * Warning, this method does not flush. * - * @param bool $setPositions * @return float Return the next position after the **last** node */ public function cleanChildrenPositions(bool $setPositions = true): float @@ -485,7 +478,7 @@ public function cleanChildrenPositions(bool $setPositions = true): float */ $sort = Criteria::create(); $sort->orderBy([ - 'position' => Criteria::ASC + 'position' => Criteria::ASC, ]); $children = $this->getNode()->getChildren()->matching($sort); @@ -495,7 +488,7 @@ public function cleanChildrenPositions(bool $setPositions = true): float if ($setPositions) { $child->setPosition($i); } - $i++; + ++$i; } return $i; @@ -506,7 +499,6 @@ public function cleanChildrenPositions(bool $setPositions = true): float * * Warning, this method does not flush. * - * @param bool $setPositions * @return float Return the next position after the **last** node */ public function cleanRootNodesPositions(bool $setPositions = true): float @@ -521,7 +513,7 @@ public function cleanRootNodesPositions(bool $setPositions = true): float if ($setPositions) { $child->setPosition($i); } - $i++; + ++$i; } return $i; @@ -530,8 +522,7 @@ public function cleanRootNodesPositions(bool $setPositions = true): float /** * Return all node offspring id. * - * @return array - * @deprecated Use NodeOffspringResolverInterface::getAllOffspringIds($chroot). + * @deprecated use NodeOffspringResolverInterface::getAllOffspringIds($chroot) */ public function getAllOffspringId(): array { @@ -562,8 +553,7 @@ public function makeHome(): self /** * Duplicate current node with all its children. * - * @return Node - * @deprecated Use NodeDuplicator::duplicate() instead. + * @deprecated use NodeDuplicator::duplicate() instead */ public function duplicate(): Node { @@ -572,22 +562,20 @@ public function duplicate(): Node $this->objectManager, $this->nodeNamePolicy ); + return $duplicator->duplicate(); } /** * Get previous node from hierarchy. * - * @param array|null $criteria - * @param array|null $order - * - * @return Node|null * @throws NonUniqueResultException - * @deprecated Use NodeRepository::findPreviousNode() instead. + * + * @deprecated use NodeRepository::findPreviousNode() instead */ public function getPrevious( ?array $criteria = null, - ?array $order = null + ?array $order = null, ): ?Node { if ($this->getNode()->getPosition() <= 1) { return null; @@ -621,16 +609,13 @@ public function getPrevious( /** * Get next node from hierarchy. * - * @param array|null $criteria - * @param array|null $order - * - * @return Node|null * @throws NonUniqueResultException - * @deprecated Use NodeRepository::findNextNode() instead. + * + * @deprecated use NodeRepository::findNextNode() instead */ public function getNext( ?array $criteria = null, - ?array $order = null + ?array $order = null, ): ?Node { if (null === $criteria) { $criteria = []; @@ -658,9 +643,6 @@ public function getNext( ); } - /** - * @return NodeRepository - */ protected function getRepository(): NodeRepository { return $this->objectManager->getRepository(Node::class); diff --git a/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeFieldHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeFieldHandler.php index 2a17f9d5..d660c2ec 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeFieldHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeFieldHandler.php @@ -5,9 +5,9 @@ namespace RZ\Roadiz\CoreBundle\EntityHandler; use Doctrine\Persistence\ObjectManager; +use RZ\Roadiz\Core\Handlers\AbstractHandler; use RZ\Roadiz\CoreBundle\Entity\NodeType; use RZ\Roadiz\CoreBundle\Entity\NodeTypeField; -use RZ\Roadiz\Core\Handlers\AbstractHandler; /** * Handle operations with node-type fields entities. @@ -21,16 +21,17 @@ public function getNodeTypeField(): NodeTypeField if (null === $this->nodeTypeField) { throw new \BadMethodCallException('NodeTypeField is null'); } + return $this->nodeTypeField; } /** - * @param NodeTypeField $nodeTypeField * @return $this */ public function setNodeTypeField(NodeTypeField $nodeTypeField): self { $this->nodeTypeField = $nodeTypeField; + return $this; } @@ -42,8 +43,8 @@ public function __construct(ObjectManager $objectManager, private readonly Handl /** * Clean position for current node siblings. * - * @param bool $setPositions * @return float Return the next position after the **last** node + * * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ @@ -52,6 +53,7 @@ public function cleanPositions(bool $setPositions = false): float if ($this->nodeTypeField->getNodeType() instanceof NodeType) { /** @var NodeTypeHandler $nodeTypeHandler */ $nodeTypeHandler = $this->handlerFactory->getHandler($this->nodeTypeField->getNodeType()); + return $nodeTypeHandler->cleanPositions(); } diff --git a/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeHandler.php index e391a276..5e423b64 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/NodeTypeHandler.php @@ -28,24 +28,22 @@ final class NodeTypeHandler extends AbstractHandler { private ?NodeType $nodeType = null; - /** - * @return NodeType - */ public function getNodeType(): NodeType { if (null === $this->nodeType) { throw new \BadMethodCallException('NodeType is null'); } + return $this->nodeType; } /** - * @param NodeType $nodeType * @return $this */ public function setNodeType(NodeType $nodeType): self { $this->nodeType = $nodeType; + return $this; } @@ -59,7 +57,7 @@ public function __construct( private readonly string $generatedEntitiesDir, private readonly string $serializedNodeTypesDir, private readonly string $importFilesConfigPath, - private readonly string $kernelProjectDir + private readonly string $kernelProjectDir, ) { parent::__construct($objectManager); } @@ -71,7 +69,7 @@ public function getGeneratedEntitiesFolder(): string public function getGeneratedRepositoriesFolder(): string { - return $this->getGeneratedEntitiesFolder() . DIRECTORY_SEPARATOR . 'Repository'; + return $this->getGeneratedEntitiesFolder().DIRECTORY_SEPARATOR.'Repository'; } /** @@ -96,6 +94,7 @@ public function removeSourceEntityClass(): bool 'file' => $file, 'repositoryFile' => $repositoryFile, ]); + return true; } @@ -111,20 +110,21 @@ public function exportNodeTypeJsonFile(): ?string 'json', SerializationContext::create()->setGroups(['node_type', 'position']) ); - $file = $this->serializedNodeTypesDir . DIRECTORY_SEPARATOR . $this->nodeType->getName() . '.json'; + $file = $this->serializedNodeTypesDir.DIRECTORY_SEPARATOR.$this->nodeType->getName().'.json'; @file_put_contents($file, $content); $this->addNodeTypeToImportFilesConfiguration($fileSystem, $file); return $file; } + return null; } protected function removeNodeTypeJsonFile(): void { $fileSystem = new Filesystem(); - $file = $this->serializedNodeTypesDir . DIRECTORY_SEPARATOR . $this->nodeType->getName() . '.json'; + $file = $this->serializedNodeTypesDir.DIRECTORY_SEPARATOR.$this->nodeType->getName().'.json'; if ($fileSystem->exists($file)) { @unlink($file); $this->removeNodeTypeFromImportFilesConfiguration($fileSystem, $file); @@ -140,7 +140,7 @@ protected function addNodeTypeToImportFilesConfiguration(Filesystem $fileSystem, $config = Yaml::parseFile($this->importFilesConfigPath); if (!isset($config['importFiles'])) { $config['importFiles'] = [ - 'nodetypes' => [] + 'nodetypes' => [], ]; } if (!isset($config['importFiles']['nodetypes'])) { @@ -148,7 +148,7 @@ protected function addNodeTypeToImportFilesConfiguration(Filesystem $fileSystem, } $relativePath = str_replace( - $this->kernelProjectDir . DIRECTORY_SEPARATOR, + $this->kernelProjectDir.DIRECTORY_SEPARATOR, '', $file ); @@ -181,7 +181,7 @@ protected function removeNodeTypeFromImportFilesConfiguration(Filesystem $fileSy } $relativePath = str_replace( - $this->kernelProjectDir . DIRECTORY_SEPARATOR, + $this->kernelProjectDir.DIRECTORY_SEPARATOR, '', $file ); @@ -201,8 +201,6 @@ protected function removeNodeTypeFromImportFilesConfiguration(Filesystem $fileSy /** * Generate Doctrine entity class for current node-type. - * - * @return bool */ public function generateSourceEntityClass(): bool { @@ -226,10 +224,10 @@ public function generateSourceEntityClass(): bool $repositoryContent = $repositoryGenerator->getClassContent(); if (false === @file_put_contents($file, $content)) { - throw new IOException("Impossible to write entity class file (" . $file . ").", 1); + throw new IOException('Impossible to write entity class file ('.$file.').', 1); } if (false === @file_put_contents($repositoryFile, $repositoryContent)) { - throw new IOException("Impossible to write entity class file (" . $repositoryFile . ").", 1); + throw new IOException('Impossible to write entity class file ('.$repositoryFile.').', 1); } /* * Force Zend OPcache to reset file @@ -252,19 +250,22 @@ public function generateSourceEntityClass(): bool return true; } + return false; } public function getSourceClassPath(): string { $folder = $this->getGeneratedEntitiesFolder(); - return $folder . DIRECTORY_SEPARATOR . $this->nodeType->getSourceEntityClassName() . '.php'; + + return $folder.DIRECTORY_SEPARATOR.$this->nodeType->getSourceEntityClassName().'.php'; } public function getRepositoryClassPath(): string { $folder = $this->getGeneratedRepositoriesFolder(); - return $folder . DIRECTORY_SEPARATOR . $this->nodeType->getSourceEntityClassName() . 'Repository.php'; + + return $folder.DIRECTORY_SEPARATOR.$this->nodeType->getSourceEntityClassName().'Repository.php'; } /** @@ -316,6 +317,7 @@ public function deleteSchema(): NodeTypeHandler * before removing it from node-types table. * * @return $this + * * @throws \Psr\Container\ContainerExceptionInterface * @throws \Psr\Container\NotFoundExceptionInterface */ @@ -355,7 +357,6 @@ public function deleteWithAssociations(): NodeTypeHandler /** * Reset current node-type fields positions. * - * @param bool $setPositions * @return float Return the next position after the **last** field */ public function cleanPositions(bool $setPositions = false): float @@ -367,7 +368,7 @@ public function cleanPositions(bool $setPositions = false): float /** @var NodeTypeField $field */ foreach ($fields as $field) { $field->setPosition($i); - $i++; + ++$i; } return $i; diff --git a/lib/RoadizCoreBundle/src/EntityHandler/NodesSourcesHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/NodesSourcesHandler.php index 7b747d45..1b4f8a8c 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/NodesSourcesHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/NodesSourcesHandler.php @@ -40,24 +40,22 @@ protected function getRepository(): EntityRepository return $this->objectManager->getRepository(NodesSources::class); } - /** - * @return NodesSources - */ public function getNodeSource(): NodesSources { if (null === $this->nodeSource) { throw new \BadMethodCallException('NodesSources is null'); } + return $this->nodeSource; } /** - * @param NodesSources $nodeSource * @return $this */ public function setNodeSource(NodesSources $nodeSource): self { $this->nodeSource = $nodeSource; + return $this; } @@ -65,7 +63,7 @@ public function setNodeSource(NodesSources $nodeSource): self * Remove every node-source documents associations for a given field. * * @param NodeTypeField $field - * @param bool $flush + * * @return $this */ public function cleanDocumentsFromField(NodeTypeFieldInterface $field, bool $flush = true): self @@ -82,17 +80,15 @@ public function cleanDocumentsFromField(NodeTypeFieldInterface $field, bool $flu /** * Add a document to current node-source for a given node-type field. * - * @param Document $document * @param NodeTypeField $field - * @param bool $flush - * @param null|float $position + * * @return $this */ public function addDocumentForField( Document $document, NodeTypeFieldInterface $field, bool $flush = true, - ?float $position = null + ?float $position = null, ): self { $nsDoc = new NodesSourcesDocuments($this->nodeSource, $document, $field); @@ -120,7 +116,9 @@ public function addDocumentForField( * Get documents linked to current node-source for a given field name. * * @param string $fieldName Name of the node-type field + * * @return array + * * @deprecated Use directly NodesSources::getDocumentsByFieldsWithName */ public function getDocumentsFromFieldName(string $fieldName): array @@ -137,8 +135,8 @@ public function getDocumentsFromFieldName(string $fieldName): array * Get a string describing uniquely the current nodeSource. * * Can be the urlAlias or the nodeName + * * @deprecated Use directly NodesSources::getIdentifier - * @return string */ public function getIdentifier(): string { @@ -154,7 +152,6 @@ public function getIdentifier(): string * Get parent node-source to get the current translation. * * @deprecated Use directly NodesSources::getParent - * @return NodesSources|null */ public function getParent(): ?NodesSources { @@ -164,12 +161,12 @@ public function getParent(): ?NodesSources /** * Get every nodeSources parents from direct parent to farest ancestor. * - * @param array|null $criteria * @return array + * * @deprecated Use NodesSourcesRepository::findParents */ public function getParents( - array $criteria = null + ?array $criteria = null, ): array { if (null === $this->parentsNodeSources) { $this->parentsNodeSources = []; @@ -208,14 +205,15 @@ public function getParents( * Get children nodes sources to lock with current translation. * * @param array|null $criteria Additional criteria - * @param array|null $order Non default ordering + * @param array|null $order Non default ordering * * @return array + * * @deprecated Use TreeWalker or NodesSourcesRepository::findChildren */ public function getChildren( - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): array { $defaultCrit = [ 'node.parent' => $this->nodeSource->getNode(), @@ -243,19 +241,15 @@ public function getChildren( /** * Get first node-source among current node-source children. * - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @deprecated Use NodesSourcesRepository::findFirstChild */ public function getFirstChild( - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { $defaultCrit = [ 'node.parent' => $this->nodeSource->getNode(), - 'translation' => $this->nodeSource->getTranslation() + 'translation' => $this->nodeSource->getTranslation(), ]; if (null !== $order) { @@ -275,18 +269,15 @@ public function getFirstChild( $defaultOrder ); } + /** * Get last node-source among current node-source children. * - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @deprecated Use NodesSourcesRepository::findLastChild */ public function getLastChild( - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { $defaultCrit = [ 'node.parent' => $this->nodeSource->getNode(), @@ -314,22 +305,20 @@ public function getLastChild( /** * Get first node-source in the same parent as current node-source. * - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @deprecated Use NodesSourcesRepository::findFirstSibling */ public function getFirstSibling( - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { if (null !== $this->nodeSource->getParent()) { $parentHandler = new NodesSourcesHandler($this->objectManager, $this->settingsBag); $parentHandler->setNodeSource($this->nodeSource->getParent()); + return $parentHandler->getFirstChild($criteria, $order); } else { $criteria['node.parent'] = null; + return $this->getFirstChild($criteria, $order); } } @@ -337,22 +326,20 @@ public function getFirstSibling( /** * Get last node-source in the same parent as current node-source. * - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @deprecated Use NodesSourcesRepository::findLastSibling */ public function getLastSibling( - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { if (null !== $this->nodeSource->getParent()) { $parentHandler = new NodesSourcesHandler($this->objectManager, $this->settingsBag); $parentHandler->setNodeSource($this->nodeSource->getParent()); + return $parentHandler->getLastChild($criteria, $order); } else { $criteria['node.parent'] = null; + return $this->getLastChild($criteria, $order); } } @@ -360,15 +347,11 @@ public function getLastSibling( /** * Get previous node-source from hierarchy. * - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @deprecated Use NodesSourcesRepository::findPrevious */ public function getPrevious( - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { if ($this->nodeSource->getNode()->getPosition() <= 1) { return null; @@ -407,15 +390,11 @@ public function getPrevious( /** * Get next node-source from hierarchy. * - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @deprecated Use NodesSourcesRepository::findNext */ public function getNext( - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { $defaultCrit = [ /* @@ -451,16 +430,17 @@ public function getNext( * Get node tags with current source translation. * * @return iterable + * * @deprecated Use TagRepository::findByNodesSources */ public function getTags(): iterable { - /** + /* * @phpstan-ignore-next-line */ return $this->objectManager->getRepository(Tag::class)->findBy([ - "nodes" => $this->nodeSource->getNode(), - "translation" => $this->nodeSource->getTranslation(), + 'nodes' => $this->nodeSource->getNode(), + 'translation' => $this->nodeSource->getTranslation(), ], [ 'position' => 'ASC', ]); @@ -480,12 +460,12 @@ public function getTags(): iterable public function getSEO(): array { return [ - 'title' => ($this->nodeSource->getMetaTitle() != "") ? + 'title' => ('' != $this->nodeSource->getMetaTitle()) ? $this->nodeSource->getMetaTitle() : - $this->nodeSource->getTitle() . ' – ' . $this->settingsBag->get('site_name'), - 'description' => ($this->nodeSource->getMetaDescription() != "") ? + $this->nodeSource->getTitle().' – '.$this->settingsBag->get('site_name'), + 'description' => ('' != $this->nodeSource->getMetaDescription()) ? $this->nodeSource->getMetaDescription() : - $this->nodeSource->getTitle() . ', ' . $this->settingsBag->get('seo_description'), + $this->nodeSource->getTitle().', '.$this->settingsBag->get('seo_description'), ]; } @@ -493,7 +473,9 @@ public function getSEO(): array * Get nodes linked to current node for a given fieldname. * * @param string $fieldName Name of the node-type field + * * @return array Collection of nodes + * * @deprecated */ public function getNodesFromFieldName(string $fieldName): array @@ -508,6 +490,7 @@ public function getNodesFromFieldName(string $fieldName): array $this->nodeSource->getTranslation() ); } + return []; } @@ -515,7 +498,9 @@ public function getNodesFromFieldName(string $fieldName): array * Get nodes which own a reference to current node for a given fieldname. * * @param string $fieldName Name of the node-type field + * * @return array Collection of nodes + * * @deprecated */ public function getReverseNodesFromFieldName(string $fieldName): array @@ -530,6 +515,7 @@ public function getReverseNodesFromFieldName(string $fieldName): array $this->nodeSource->getTranslation() ); } + return []; } } diff --git a/lib/RoadizCoreBundle/src/EntityHandler/TagHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/TagHandler.php index 355d583a..180a1a5e 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/TagHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/TagHandler.php @@ -16,12 +16,12 @@ final class TagHandler extends AbstractHandler private ?Tag $tag = null; /** - * @param Tag $tag * @return $this */ public function setTag(Tag $tag): self { $this->tag = $tag; + return $this; } @@ -41,6 +41,7 @@ private function removeChildren(): self return $this; } + /** * Remove only current tag associations. * @@ -54,6 +55,7 @@ public function removeAssociations(): self return $this; } + /** * Remove current tag with its children recursively and * its associations. @@ -78,16 +80,16 @@ public function removeWithChildrenAndAssociations(): self /** * Clean position for current tag siblings. * - * @param bool $setPositions * @return float Return the next position after the **last** tag */ public function cleanPositions(bool $setPositions = true): float { - if ($this->tag->getParent() !== null) { + if (null !== $this->tag->getParent()) { $tagHandler = new TagHandler($this->objectManager); /** @var Tag|null $parent */ $parent = $this->tag->getParent(); $tagHandler->setTag($parent); + return $tagHandler->cleanChildrenPositions($setPositions); } else { return $this->cleanRootTagsPositions($setPositions); @@ -99,7 +101,6 @@ public function cleanPositions(bool $setPositions = true): float * * Warning, this method does not flush. * - * @param bool $setPositions * @return float Return the next position after the **last** tag */ public function cleanChildrenPositions(bool $setPositions = true): float @@ -109,7 +110,7 @@ public function cleanChildrenPositions(bool $setPositions = true): float */ $sort = Criteria::create(); $sort->orderBy([ - 'position' => Criteria::ASC + 'position' => Criteria::ASC, ]); $children = $this->tag->getChildren()->matching($sort); @@ -119,7 +120,7 @@ public function cleanChildrenPositions(bool $setPositions = true): float if ($setPositions) { $child->setPosition($i); } - $i++; + ++$i; } return $i; @@ -130,7 +131,6 @@ public function cleanChildrenPositions(bool $setPositions = true): float * * Warning, this method does not flush. * - * @param bool $setPositions * @return float Return the next position after the **last** tag */ public function cleanRootTagsPositions(bool $setPositions = true): float @@ -145,7 +145,7 @@ public function cleanRootTagsPositions(bool $setPositions = true): float if ($setPositions) { $child->setPosition($i); } - $i++; + ++$i; } return $i; diff --git a/lib/RoadizCoreBundle/src/EntityHandler/TranslationHandler.php b/lib/RoadizCoreBundle/src/EntityHandler/TranslationHandler.php index 6f3f30ea..e55c70b3 100644 --- a/lib/RoadizCoreBundle/src/EntityHandler/TranslationHandler.php +++ b/lib/RoadizCoreBundle/src/EntityHandler/TranslationHandler.php @@ -19,13 +19,12 @@ final class TranslationHandler extends AbstractHandler private ?TranslationInterface $translation = null; /** - * @param TranslationInterface $translation - * * @return $this */ public function setTranslation(TranslationInterface $translation): self { $this->translation = $translation; + return $this; } diff --git a/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationIndexingEvent.php b/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationIndexingEvent.php index 1130fb58..692ce82e 100644 --- a/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationIndexingEvent.php +++ b/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationIndexingEvent.php @@ -14,49 +14,34 @@ public function __construct( private readonly DocumentTranslation $documentTranslation, private array $associations, private readonly AbstractSolarium $solariumDocument, - private readonly bool $subResource = false + private readonly bool $subResource = false, ) { } - /** - * @return DocumentTranslation - */ public function getDocumentTranslation(): DocumentTranslation { return $this->documentTranslation; } - /** - * @return array - */ public function getAssociations(): array { return $this->associations; } - /** - * @return AbstractSolarium - */ public function getSolariumDocument(): AbstractSolarium { return $this->solariumDocument; } - /** - * @return bool - */ public function isSubResource(): bool { return $this->subResource; } - /** - * @param array $associations - * @return DocumentTranslationIndexingEvent - */ public function setAssociations(array $associations): DocumentTranslationIndexingEvent { $this->associations = $associations; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationUpdatedEvent.php b/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationUpdatedEvent.php index bf889883..80aa9284 100644 --- a/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationUpdatedEvent.php +++ b/lib/RoadizCoreBundle/src/Event/Document/DocumentTranslationUpdatedEvent.php @@ -12,14 +12,11 @@ final class DocumentTranslationUpdatedEvent extends FilterDocumentEvent { public function __construct( DocumentInterface $document, - private readonly ?DocumentTranslation $documentTranslation = null + private readonly ?DocumentTranslation $documentTranslation = null, ) { parent::__construct($document); } - /** - * @return DocumentTranslation|null - */ public function getDocumentTranslation(): ?DocumentTranslation { return $this->documentTranslation; diff --git a/lib/RoadizCoreBundle/src/Event/FilterCacheEvent.php b/lib/RoadizCoreBundle/src/Event/FilterCacheEvent.php index 934e18b5..5a6ef779 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterCacheEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterCacheEvent.php @@ -8,9 +8,6 @@ use Doctrine\Common\Collections\Collection; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterCacheEvent extends Event { private Collection $messageCollection; @@ -22,45 +19,29 @@ public function __construct() $this->errorCollection = new ArrayCollection(); } - /** - * @param string $message - * @param string|null $classname - * @param string|null $description - */ public function addMessage(string $message, ?string $classname = null, ?string $description = null): void { $this->messageCollection->add([ - "clearer" => $classname, - "description" => $description, - "message" => $message, + 'clearer' => $classname, + 'description' => $description, + 'message' => $message, ]); } - /** - * @param string $message - * @param string|null $classname - * @param string|null $description - */ public function addError(string $message, ?string $classname = null, ?string $description = null): void { $this->errorCollection->add([ - "clearer" => $classname, - "description" => $description, - "message" => $message, + 'clearer' => $classname, + 'description' => $description, + 'message' => $message, ]); } - /** - * @return array - */ public function getErrors(): array { return $this->errorCollection->toArray(); } - /** - * @return array - */ public function getMessages(): array { return $this->messageCollection->toArray(); diff --git a/lib/RoadizCoreBundle/src/Event/FilterFolderEvent.php b/lib/RoadizCoreBundle/src/Event/FilterFolderEvent.php index eb426b11..8efa7857 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterFolderEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterFolderEvent.php @@ -7,9 +7,6 @@ use RZ\Roadiz\CoreBundle\Entity\Folder; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterFolderEvent extends Event { protected Folder $folder; diff --git a/lib/RoadizCoreBundle/src/Event/FilterNodeEvent.php b/lib/RoadizCoreBundle/src/Event/FilterNodeEvent.php index c04c2639..4ecf9c76 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterNodeEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterNodeEvent.php @@ -7,9 +7,6 @@ use RZ\Roadiz\CoreBundle\Entity\Node; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterNodeEvent extends Event { protected Node $node; diff --git a/lib/RoadizCoreBundle/src/Event/FilterNodePathEvent.php b/lib/RoadizCoreBundle/src/Event/FilterNodePathEvent.php index ed4cc2f9..810fe6bb 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterNodePathEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterNodePathEvent.php @@ -6,37 +6,23 @@ use RZ\Roadiz\CoreBundle\Entity\Node; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterNodePathEvent extends FilterNodeEvent { protected array $paths; protected ?\DateTime $updatedAt; - /** - * @param Node $node - * @param array $paths - * @param \DateTime|null $updatedAt - */ - public function __construct(Node $node, array $paths = [], \DateTime $updatedAt = null) + public function __construct(Node $node, array $paths = [], ?\DateTime $updatedAt = null) { parent::__construct($node); $this->paths = $paths; $this->updatedAt = $updatedAt; } - /** - * @return array - */ public function getPaths(): array { return $this->paths; } - /** - * @return \DateTime|null - */ public function getUpdatedAt(): ?\DateTime { return $this->updatedAt; diff --git a/lib/RoadizCoreBundle/src/Event/FilterNodesSourcesEvent.php b/lib/RoadizCoreBundle/src/Event/FilterNodesSourcesEvent.php index be277645..b5c38a0f 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterNodesSourcesEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterNodesSourcesEvent.php @@ -7,9 +7,6 @@ use RZ\Roadiz\CoreBundle\Entity\NodesSources; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterNodesSourcesEvent extends Event { protected NodesSources $nodeSource; diff --git a/lib/RoadizCoreBundle/src/Event/FilterTagEvent.php b/lib/RoadizCoreBundle/src/Event/FilterTagEvent.php index 9bb701d0..e2b40aa2 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterTagEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterTagEvent.php @@ -7,16 +7,10 @@ use RZ\Roadiz\CoreBundle\Entity\Tag; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterTagEvent extends Event { protected Tag $tag; - /** - * @param Tag $tag - */ public function __construct(Tag $tag) { $this->tag = $tag; diff --git a/lib/RoadizCoreBundle/src/Event/FilterTranslationEvent.php b/lib/RoadizCoreBundle/src/Event/FilterTranslationEvent.php index 2e66b738..d4abc71f 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterTranslationEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterTranslationEvent.php @@ -7,9 +7,6 @@ use RZ\Roadiz\CoreBundle\Entity\Translation; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterTranslationEvent extends Event { protected Translation $translation; diff --git a/lib/RoadizCoreBundle/src/Event/FilterUrlAliasEvent.php b/lib/RoadizCoreBundle/src/Event/FilterUrlAliasEvent.php index 922c8c70..d86ec15a 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterUrlAliasEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterUrlAliasEvent.php @@ -7,9 +7,6 @@ use RZ\Roadiz\CoreBundle\Entity\UrlAlias; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterUrlAliasEvent extends Event { protected UrlAlias $urlAlias; diff --git a/lib/RoadizCoreBundle/src/Event/FilterUserEvent.php b/lib/RoadizCoreBundle/src/Event/FilterUserEvent.php index 449e75a6..9bd5d756 100644 --- a/lib/RoadizCoreBundle/src/Event/FilterUserEvent.php +++ b/lib/RoadizCoreBundle/src/Event/FilterUserEvent.php @@ -7,9 +7,6 @@ use RZ\Roadiz\CoreBundle\Entity\User; use Symfony\Contracts\EventDispatcher\Event; -/** - * @package RZ\Roadiz\CoreBundle\Event - */ abstract class FilterUserEvent extends Event { private User $user; diff --git a/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesIndexingEvent.php b/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesIndexingEvent.php index 9e8381e0..10a2e931 100644 --- a/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesIndexingEvent.php +++ b/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesIndexingEvent.php @@ -14,7 +14,7 @@ public function __construct( private readonly NodesSources $nodeSource, private array $associations, private readonly AbstractSolarium $solariumDocument, - private readonly bool $subResource = false + private readonly bool $subResource = false, ) { } @@ -25,8 +25,6 @@ public function getNodeSource(): NodesSources /** * Get Solr document data to index. - * - * @return array */ public function getAssociations(): array { @@ -35,13 +33,11 @@ public function getAssociations(): array /** * Set Solr document data to index. - * - * @param array $associations - * @return NodesSourcesIndexingEvent */ public function setAssociations(array $associations): NodesSourcesIndexingEvent { $this->associations = $associations; + return $this; } diff --git a/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesPathGeneratingEvent.php b/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesPathGeneratingEvent.php index 2efc28d3..c3c613be 100644 --- a/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesPathGeneratingEvent.php +++ b/lib/RoadizCoreBundle/src/Event/NodesSources/NodesSourcesPathGeneratingEvent.php @@ -13,50 +13,31 @@ final class NodesSourcesPathGeneratingEvent extends Event { private ?string $path; /** - * @var bool Tells Node Router to prepend request context information to path or not. + * @var bool tells Node Router to prepend request context information to path or not */ private bool $isComplete = false; protected bool $containsScheme = false; - /** - * @param Theme|null $theme - * @param NodesSources|null $nodeSource - * @param RequestContext|null $requestContext - * @param array $parameters - * @param bool $forceLocale - * @param bool $forceLocaleWithUrlAlias - */ public function __construct( private readonly ?Theme $theme, private ?NodesSources $nodeSource, private readonly ?RequestContext $requestContext, private array $parameters = [], private readonly bool $forceLocale = false, - private bool $forceLocaleWithUrlAlias = false + private bool $forceLocaleWithUrlAlias = false, ) { } - /** - * @return Theme|null - */ public function getTheme(): ?Theme { return $this->theme; } - /** - * @return NodesSources|null - */ public function getNodeSource(): ?NodesSources { return $this->nodeSource; } - /** - * @param NodesSources|null $nodeSource - * - * @return NodesSourcesPathGeneratingEvent - */ public function setNodeSource(?NodesSources $nodeSource): NodesSourcesPathGeneratingEvent { $this->nodeSource = $nodeSource; @@ -64,35 +45,21 @@ public function setNodeSource(?NodesSources $nodeSource): NodesSourcesPathGenera return $this; } - /** - * @return RequestContext|null - */ public function getRequestContext(): ?RequestContext { return $this->requestContext; } - /** - * @return bool - */ public function isForceLocale(): bool { return $this->forceLocale; } - /** - * @return string|null - */ public function getPath(): ?string { return $this->path; } - /** - * @param string|null $path - * - * @return NodesSourcesPathGeneratingEvent - */ public function setPath(?string $path): NodesSourcesPathGeneratingEvent { $this->path = $path; @@ -100,19 +67,11 @@ public function setPath(?string $path): NodesSourcesPathGeneratingEvent return $this; } - /** - * @return array|null - */ public function getParameters(): ?array { return $this->parameters; } - /** - * @param array|null $parameters - * - * @return NodesSourcesPathGeneratingEvent - */ public function setParameters(?array $parameters): NodesSourcesPathGeneratingEvent { $this->parameters = $parameters; @@ -120,19 +79,11 @@ public function setParameters(?array $parameters): NodesSourcesPathGeneratingEve return $this; } - /** - * @return bool - */ public function isComplete(): bool { return $this->isComplete; } - /** - * @param bool $isComplete - * - * @return NodesSourcesPathGeneratingEvent - */ public function setComplete(bool $isComplete): NodesSourcesPathGeneratingEvent { $this->isComplete = $isComplete; @@ -140,19 +91,11 @@ public function setComplete(bool $isComplete): NodesSourcesPathGeneratingEvent return $this; } - /** - * @return bool - */ public function containsScheme(): bool { return $this->containsScheme; } - /** - * @param bool $containsScheme - * - * @return NodesSourcesPathGeneratingEvent - */ public function setContainsScheme(bool $containsScheme): NodesSourcesPathGeneratingEvent { $this->containsScheme = $containsScheme; @@ -160,19 +103,11 @@ public function setContainsScheme(bool $containsScheme): NodesSourcesPathGenerat return $this; } - /** - * @return bool - */ public function isForceLocaleWithUrlAlias(): bool { return $this->forceLocaleWithUrlAlias; } - /** - * @param bool $forceLocaleWithUrlAlias - * - * @return NodesSourcesPathGeneratingEvent - */ public function setForceLocaleWithUrlAlias(bool $forceLocaleWithUrlAlias): NodesSourcesPathGeneratingEvent { $this->forceLocaleWithUrlAlias = $forceLocaleWithUrlAlias; diff --git a/lib/RoadizCoreBundle/src/Event/Realm/AbstractRealmNodeEvent.php b/lib/RoadizCoreBundle/src/Event/Realm/AbstractRealmNodeEvent.php index ab6554c1..433663fe 100644 --- a/lib/RoadizCoreBundle/src/Event/Realm/AbstractRealmNodeEvent.php +++ b/lib/RoadizCoreBundle/src/Event/Realm/AbstractRealmNodeEvent.php @@ -4,8 +4,6 @@ namespace RZ\Roadiz\CoreBundle\Event\Realm; -use RZ\Roadiz\CoreBundle\Entity\Node; -use RZ\Roadiz\CoreBundle\Entity\Realm; use RZ\Roadiz\CoreBundle\Entity\RealmNode; use Symfony\Contracts\EventDispatcher\Event; @@ -18,9 +16,6 @@ public function __construct(RealmNode $realmNode) $this->realmNode = $realmNode; } - /** - * @return RealmNode - */ public function getRealmNode(): RealmNode { return $this->realmNode; diff --git a/lib/RoadizCoreBundle/src/Event/Redirection/RedirectionEvent.php b/lib/RoadizCoreBundle/src/Event/Redirection/RedirectionEvent.php index 3d379471..60c0a07f 100644 --- a/lib/RoadizCoreBundle/src/Event/Redirection/RedirectionEvent.php +++ b/lib/RoadizCoreBundle/src/Event/Redirection/RedirectionEvent.php @@ -11,29 +11,20 @@ abstract class RedirectionEvent extends Event { protected ?Redirection $redirection; - /** - * @param Redirection|null $redirection - */ public function __construct(?Redirection $redirection) { $this->redirection = $redirection; } - /** - * @return Redirection|null - */ public function getRedirection(): ?Redirection { return $this->redirection; } - /** - * @param Redirection|null $redirection - * @return RedirectionEvent - */ public function setRedirection(?Redirection $redirection): RedirectionEvent { $this->redirection = $redirection; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Event/Role/RoleEvent.php b/lib/RoadizCoreBundle/src/Event/Role/RoleEvent.php index 7f292e06..73d1b4d9 100644 --- a/lib/RoadizCoreBundle/src/Event/Role/RoleEvent.php +++ b/lib/RoadizCoreBundle/src/Event/Role/RoleEvent.php @@ -14,29 +14,20 @@ abstract class RoleEvent extends Event */ protected $role; - /** - * @param Role|null $role - */ public function __construct(?Role $role) { $this->role = $role; } - /** - * @return Role|null - */ public function getRole(): ?Role { return $this->role; } - /** - * @param Role|null $role - * @return RoleEvent - */ public function setRole(?Role $role): RoleEvent { $this->role = $role; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Event/User/UserJoinedGroupEvent.php b/lib/RoadizCoreBundle/src/Event/User/UserJoinedGroupEvent.php index 77c1ef3b..2e778f53 100644 --- a/lib/RoadizCoreBundle/src/Event/User/UserJoinedGroupEvent.php +++ b/lib/RoadizCoreBundle/src/Event/User/UserJoinedGroupEvent.php @@ -15,9 +15,6 @@ public function __construct(User $user, private readonly Group $group) parent::__construct($user); } - /** - * @return Group - */ public function getGroup(): Group { return $this->group; diff --git a/lib/RoadizCoreBundle/src/Event/User/UserLeavedGroupEvent.php b/lib/RoadizCoreBundle/src/Event/User/UserLeavedGroupEvent.php index e776a374..105ce030 100644 --- a/lib/RoadizCoreBundle/src/Event/User/UserLeavedGroupEvent.php +++ b/lib/RoadizCoreBundle/src/Event/User/UserLeavedGroupEvent.php @@ -15,9 +15,6 @@ public function __construct(User $user, private readonly Group $group) parent::__construct($user); } - /** - * @return Group - */ public function getGroup(): Group { return $this->group; diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/AssetsCacheEventSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/AssetsCacheEventSubscriber.php index 664344d0..892f60a1 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/AssetsCacheEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/AssetsCacheEventSubscriber.php @@ -13,14 +13,14 @@ final class AssetsCacheEventSubscriber implements EventSubscriberInterface { public function __construct( private readonly AssetsFileClearer $assetsClearer, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } public static function getSubscribedEvents(): array { return [ - CachePurgeAssetsRequestEvent::class => ['onPurgeAssetsRequest', 0] + CachePurgeAssetsRequestEvent::class => ['onPurgeAssetsRequest', 0], ]; } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/AutomaticWebhookSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/AutomaticWebhookSubscriber.php index fb29b2fc..98836861 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/AutomaticWebhookSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/AutomaticWebhookSubscriber.php @@ -28,7 +28,7 @@ final class AutomaticWebhookSubscriber implements EventSubscriberInterface public function __construct( private readonly WebhookDispatcher $webhookDispatcher, private readonly ManagerRegistry $managerRegistry, - private readonly HandlerFactoryInterface $handlerFactory + private readonly HandlerFactoryInterface $handlerFactory, ) { } @@ -48,19 +48,15 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param mixed $event - * @return bool - */ protected function isEventRelatedToNode(mixed $event): bool { - return $event instanceof Event || - $event instanceof NodeVisibilityChangedEvent || - $event instanceof NodesSourcesPreUpdatedEvent || - $event instanceof NodesSourcesDeletedEvent || - $event instanceof NodeUpdatedEvent || - $event instanceof NodeDeletedEvent || - $event instanceof NodeTaggedEvent; + return $event instanceof Event + || $event instanceof NodeVisibilityChangedEvent + || $event instanceof NodesSourcesPreUpdatedEvent + || $event instanceof NodesSourcesDeletedEvent + || $event instanceof NodeUpdatedEvent + || $event instanceof NodeDeletedEvent + || $event instanceof NodeTaggedEvent; } /** @@ -70,7 +66,7 @@ public function onAutomaticWebhook(mixed $event): void { /** @var Webhook[] $webhooks */ $webhooks = $this->managerRegistry->getRepository(Webhook::class)->findBy([ - 'automatic' => true + 'automatic' => true, ]); foreach ($webhooks as $webhook) { if (!$this->isEventRelatedToNode($event) || $this->isEventSubjectInRootNode($event, $webhook->getRootNode())) { diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/CloudflareCacheEventSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/CloudflareCacheEventSubscriber.php index 48fd5f2e..be4f1da7 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/CloudflareCacheEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/CloudflareCacheEventSubscriber.php @@ -28,12 +28,10 @@ public function __construct( private readonly MessageBusInterface $bus, private readonly ReverseProxyCacheLocator $reverseProxyCacheLocator, private readonly UrlGeneratorInterface $urlGenerator, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } - /** - * @inheritDoc - */ + public static function getSubscribedEvents(): array { return [ @@ -118,12 +116,11 @@ private function getCloudflareCacheProxy(): CloudflareProxyCache if (null === $proxy) { throw new \RuntimeException('Cloudflare cache proxy is not configured'); } + return $proxy; } /** - * @param array $body - * @return Request * @throws \JsonException */ protected function createRequest(array $body): Request @@ -131,7 +128,7 @@ protected function createRequest(array $body): Request $headers = [ 'Content-type' => 'application/json', ]; - $headers['Authorization'] = 'Bearer ' . trim($this->getCloudflareCacheProxy()->getBearer()); + $headers['Authorization'] = 'Bearer '.trim($this->getCloudflareCacheProxy()->getBearer()); $headers['X-Auth-Email'] = $this->getCloudflareCacheProxy()->getEmail(); $headers['X-Auth-Key'] = $this->getCloudflareCacheProxy()->getKey(); @@ -141,6 +138,7 @@ protected function createRequest(array $body): Request $this->getCloudflareCacheProxy()->getZone() ); $body = \json_encode($body, JSON_THROW_ON_ERROR); + return new Request( 'POST', $uri, @@ -150,7 +148,6 @@ protected function createRequest(array $body): Request } /** - * @return Request * @throws \JsonException */ protected function createBanRequest(): Request @@ -162,26 +159,22 @@ protected function createBanRequest(): Request /** * @param string[] $uris - * @return Request + * * @throws \JsonException */ protected function createPurgeRequest(array $uris = []): Request { return $this->createRequest([ - 'files' => $uris + 'files' => $uris, ]); } - /** - * @param RequestInterface $request - * @return void - */ protected function sendRequest(RequestInterface $request): void { try { $this->bus->dispatch(new Envelope(new GuzzleRequestMessage($request, [ 'debug' => false, - 'timeout' => $this->getCloudflareCacheProxy()->getTimeout() + 'timeout' => $this->getCloudflareCacheProxy()->getTimeout(), ]))); } catch (ExceptionInterface $exception) { $this->logger->error($exception->getMessage()); diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/DocumentTimestampSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/DocumentTimestampSubscriber.php index 54dac92d..7e9b6792 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/DocumentTimestampSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/DocumentTimestampSubscriber.php @@ -10,13 +10,10 @@ class DocumentTimestampSubscriber implements EventSubscriberInterface { - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ - DocumentTranslationUpdatedEvent::class => 'onDocumentTranslationUpdatedEvent' + DocumentTranslationUpdatedEvent::class => 'onDocumentTranslationUpdatedEvent', ]; } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/JwtAuthenticationSuccessEventSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/JwtAuthenticationSuccessEventSubscriber.php index 3624b404..b39f1a69 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/JwtAuthenticationSuccessEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/JwtAuthenticationSuccessEventSubscriber.php @@ -16,9 +16,6 @@ public function __construct( ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/LocaleSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/LocaleSubscriber.php index 8583550f..e6804ba7 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/LocaleSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/LocaleSubscriber.php @@ -19,13 +19,10 @@ final class LocaleSubscriber implements EventSubscriberInterface public function __construct( private readonly PreviewResolverInterface $previewResolver, private readonly ManagerRegistry $managerRegistry, - private readonly RequestContextAwareInterface $router + private readonly RequestContextAwareInterface $router, ) { } - /** - * @return array - */ public static function getSubscribedEvents(): array { return [ @@ -46,7 +43,7 @@ private function getDefaultTranslation(): ?TranslationInterface private function supportsLocale(?string $locale): bool { - if (null === $locale || $locale === '') { + if (null === $locale || '' === $locale) { return false; } @@ -55,6 +52,7 @@ private function supportsLocale(?string $locale): bool } else { $locales = $this->getRepository()->getAvailableLocales(); } + return \in_array( $locale, $locales, @@ -67,6 +65,7 @@ private function getTranslationByLocale(string $locale): ?TranslationInterface if ($this->previewResolver->isPreview()) { return $this->getRepository()->findOneByLocaleOrOverrideLocale($locale); } + return $this->getRepository()->findOneAvailableByLocaleOrOverrideLocale($locale); } @@ -80,6 +79,7 @@ public function onKernelRequest(RequestEvent $event): void */ if ($this->supportsLocale($locale)) { $this->setTranslation($request, $this->getTranslationByLocale($locale)); + return; } @@ -93,19 +93,21 @@ public function onKernelRequest(RequestEvent $event): void 'interventionRequestProcess', ]; if ( - !\in_array($request->attributes->getString('_route'), $statelessRoutes, true) && - !$request->attributes->getBoolean('_stateless') && - $request->hasPreviousSession() + !\in_array($request->attributes->getString('_route'), $statelessRoutes, true) + && !$request->attributes->getBoolean('_stateless') + && $request->hasPreviousSession() ) { $sessionLocale = $request->getSession()->get('_locale', null); if ($this->supportsLocale($sessionLocale)) { $this->setTranslation($request, $this->getTranslationByLocale($sessionLocale)); + return; } } if (null !== $translation = $this->getDefaultTranslation()) { $this->setTranslation($request, $translation); + return; } } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/LoggableSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/LoggableSubscriber.php index 8bec9f86..e035a1ef 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/LoggableSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/LoggableSubscriber.php @@ -36,8 +36,8 @@ public function onKernelRequest(RequestEvent $event): void public static function getSubscribedEvents(): array { - return array( + return [ KernelEvents::REQUEST => 'onKernelRequest', - ); + ]; } } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodeDuplicationSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodeDuplicationSubscriber.php index 6990f179..dac5f138 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodeDuplicationSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodeDuplicationSubscriber.php @@ -6,15 +6,15 @@ use Doctrine\Persistence\ManagerRegistry; use RZ\Roadiz\Core\Handlers\HandlerFactoryInterface; -use RZ\Roadiz\CoreBundle\Event\Node\NodeDuplicatedEvent; use RZ\Roadiz\CoreBundle\EntityHandler\NodeHandler; +use RZ\Roadiz\CoreBundle\Event\Node\NodeDuplicatedEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; final class NodeDuplicationSubscriber implements EventSubscriberInterface { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly HandlerFactoryInterface $handlerFactory + private readonly HandlerFactoryInterface $handlerFactory, ) { } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodeNameSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodeNameSubscriber.php index 6f9288a9..f565974f 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodeNameSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodeNameSubscriber.php @@ -22,13 +22,10 @@ final class NodeNameSubscriber implements EventSubscriberInterface public function __construct( private readonly LoggerInterface $logger, private readonly NodeNamePolicyInterface $nodeNamePolicy, - private readonly NodeMover $nodeMover + private readonly NodeMover $nodeMover, ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ @@ -39,7 +36,7 @@ public static function getSubscribedEvents(): array public function onBeforeUpdate( NodesSourcesPreUpdatedEvent $event, string $eventName, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ): void { $nodeSource = $event->getNodeSource(); $title = $nodeSource->getTitle(); @@ -49,9 +46,9 @@ public function onBeforeUpdate( * default translation */ if ( - "" != $title && - true === $nodeSource->getNode()->isDynamicNodeName() && - $nodeSource->getTranslation()->isDefaultTranslation() + '' != $title + && true === $nodeSource->getNode()->isDynamicNodeName() + && $nodeSource->getTranslation()->isDefaultTranslation() ) { $testingNodeName = $this->nodeNamePolicy->getCanonicalNodeName($nodeSource); @@ -60,9 +57,9 @@ public function onBeforeUpdate( * if it is ALREADY suffixed with a unique ID. */ if ( - $testingNodeName != $nodeSource->getNode()->getNodeName() && - $this->nodeNamePolicy->isNodeNameValid($testingNodeName) && - !$this->nodeNamePolicy->isNodeNameWithUniqId( + $testingNodeName != $nodeSource->getNode()->getNodeName() + && $this->nodeNamePolicy->isNodeNameValid($testingNodeName) + && !$this->nodeNamePolicy->isNodeNameWithUniqId( $testingNodeName, $nodeSource->getNode()->getNodeName() ) diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodeRedirectionSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodeRedirectionSubscriber.php index 2b3e00e8..7579b523 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodeRedirectionSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodeRedirectionSubscriber.php @@ -19,7 +19,7 @@ class NodeRedirectionSubscriber implements EventSubscriberInterface public function __construct( protected readonly NodeMover $nodeMover, protected readonly string $kernelEnvironment, - protected readonly PreviewResolverInterface $previewResolver + protected readonly PreviewResolverInterface $previewResolver, ) { } @@ -31,24 +31,20 @@ public static function getSubscribedEvents(): array } /** - * Empty nodeSources Url cache - * - * @param NodePathChangedEvent $event - * @param string $eventName - * @param EventDispatcherInterface $dispatcher + * Empty nodeSources Url cache. */ public function redirectOldPaths( NodePathChangedEvent $event, string $eventName, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ): void { if ( - $this->kernelEnvironment === 'prod' && - !$this->previewResolver->isPreview() && - null !== $event->getNode() && - $event->getNode()->isPublished() && - $event->getNode()->getNodeType()->isReachable() && - count($event->getPaths()) > 0 + 'prod' === $this->kernelEnvironment + && !$this->previewResolver->isPreview() + && null !== $event->getNode() + && $event->getNode()->isPublished() + && $event->getNode()->getNodeType()->isReachable() + && count($event->getPaths()) > 0 ) { $this->nodeMover->redirectAll($event->getNode(), $event->getPaths()); $dispatcher->dispatch(new CachePurgeRequestEvent()); diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodeSourcePathSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodeSourcePathSubscriber.php index 0165266b..20211574 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodeSourcePathSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodeSourcePathSubscriber.php @@ -12,13 +12,10 @@ final class NodeSourcePathSubscriber implements EventSubscriberInterface { public function __construct( - private readonly NodesSourcesPathAggregator $pathAggregator + private readonly NodesSourcesPathAggregator $pathAggregator, ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ @@ -26,9 +23,6 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param NodesSourcesPathGeneratingEvent $event - */ public function onNodesSourcesPath(NodesSourcesPathGeneratingEvent $event): void { $urlGenerator = new NodesSourcesUrlGenerator( diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesAddHeadersSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesAddHeadersSubscriber.php index 2cd80491..b1fd6797 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesAddHeadersSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesAddHeadersSubscriber.php @@ -17,14 +17,14 @@ final class NodesSourcesAddHeadersSubscriber implements EventSubscriberInterface { public function __construct( private readonly PreviewResolverInterface $previewResolver, - private readonly Security $security + private readonly Security $security, ) { } public static function getSubscribedEvents(): array { return [ - KernelEvents::RESPONSE => ['onKernelResponse', 0] + KernelEvents::RESPONSE => ['onKernelResponse', 0], ]; } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesLinkHeaderEventSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesLinkHeaderEventSubscriber.php index 3c0b5c91..a2d37d7e 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesLinkHeaderEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesLinkHeaderEventSubscriber.php @@ -19,17 +19,14 @@ final class NodesSourcesLinkHeaderEventSubscriber implements EventSubscriberInte { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ - ViewEvent::class => ['onKernelView', 15] + ViewEvent::class => ['onKernelView', 15], ]; } @@ -61,7 +58,7 @@ public function onKernelView(ViewEvent $event): void (new Link( 'alternate', $this->urlGenerator->generate(RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ - RouteObjectInterface::ROUTE_OBJECT => $singleSource + RouteObjectInterface::ROUTE_OBJECT => $singleSource, ]) )) ->withAttribute('hreflang', $singleSource->getTranslation()->getLocale()) diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUniversalSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUniversalSubscriber.php index b16cb180..1e0b4318 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUniversalSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUniversalSubscriber.php @@ -16,19 +16,12 @@ class NodesSourcesUniversalSubscriber implements EventSubscriberInterface private ManagerRegistry $managerRegistry; private UniversalDataDuplicator $universalDataDuplicator; - /** - * @param ManagerRegistry $managerRegistry - * @param UniversalDataDuplicator $universalDataDuplicator - */ public function __construct(ManagerRegistry $managerRegistry, UniversalDataDuplicator $universalDataDuplicator) { $this->universalDataDuplicator = $universalDataDuplicator; $this->managerRegistry = $managerRegistry; } - /** - * @return array - */ public static function getSubscribedEvents(): array { return [ @@ -37,8 +30,6 @@ public static function getSubscribedEvents(): array } /** - * @param NodesSourcesUpdatedEvent $event - * * @throws ORMException * @throws OptimisticLockException */ diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUrlsCacheEventSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUrlsCacheEventSubscriber.php index d6d9ccae..b51f7b08 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUrlsCacheEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/NodesSourcesUrlsCacheEventSubscriber.php @@ -24,9 +24,6 @@ public function __construct(private readonly NodesSourcesUrlsCacheClearer $cache { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/OPCacheEventSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/OPCacheEventSubscriber.php index fb080645..465fd2e6 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/OPCacheEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/OPCacheEventSubscriber.php @@ -10,9 +10,6 @@ final class OPCacheEventSubscriber implements EventSubscriberInterface { - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ @@ -20,9 +17,6 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param CachePurgeRequestEvent $event - */ public function onPurgeRequest(CachePurgeRequestEvent $event): void { try { diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/RealmNodeInheritanceSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/RealmNodeInheritanceSubscriber.php index d41b9d7e..de2670ce 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/RealmNodeInheritanceSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/RealmNodeInheritanceSubscriber.php @@ -23,9 +23,6 @@ public function __construct(private readonly MessageBusInterface $bus) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/RedirectionCacheSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/RedirectionCacheSubscriber.php index 49dece5c..baf657ad 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/RedirectionCacheSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/RedirectionCacheSubscriber.php @@ -21,9 +21,6 @@ public function __construct(CacheItemPoolInterface $cacheAdapter) $this->cacheAdapter = $cacheAdapter; } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/ReverseProxyCacheEventSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/ReverseProxyCacheEventSubscriber.php index 4285e7f4..270a423e 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/ReverseProxyCacheEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/ReverseProxyCacheEventSubscriber.php @@ -24,12 +24,10 @@ final class ReverseProxyCacheEventSubscriber implements EventSubscriberInterface public function __construct( private readonly ReverseProxyCacheLocator $reverseProxyCacheLocator, private readonly MessageBusInterface $bus, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } - /** - * @inheritDoc - */ + public static function getSubscribedEvents(): array { return [ @@ -39,17 +37,11 @@ public static function getSubscribedEvents(): array ]; } - /** - * @return bool - */ protected function supportConfig(): bool { return count($this->reverseProxyCacheLocator->getFrontends()) > 0; } - /** - * @param Event $event - */ public function onNodeWorkflowCompleted(Event $event): void { $node = $event->getSubject(); @@ -63,9 +55,6 @@ public function onNodeWorkflowCompleted(Event $event): void } } - /** - * @param CachePurgeRequestEvent $event - */ public function onBanRequest(CachePurgeRequestEvent $event): void { if (!$this->supportConfig()) { @@ -77,14 +66,11 @@ public function onBanRequest(CachePurgeRequestEvent $event): void $event->addMessage( 'Reverse proxy cache cleared.', self::class, - 'Reverse proxy cache [' . $name . ']' + 'Reverse proxy cache ['.$name.']' ); } } - /** - * @param NodesSourcesUpdatedEvent $event - */ public function onPurgeRequest(NodesSourcesUpdatedEvent $event): void { if (!$this->supportConfig()) { @@ -104,7 +90,7 @@ protected function createBanRequests(): array // Add protocol if host does not start with it if (!\str_starts_with($frontend->getHost(), 'http')) { // Use HTTP to be able to call Varnish from a Docker network - $uri = 'http://' . $frontend->getHost(); + $uri = 'http://'.$frontend->getHost(); } else { $uri = $frontend->getHost(); } @@ -112,16 +98,14 @@ protected function createBanRequests(): array 'BAN', $uri, [ - 'Host' => $frontend->getDomainName() + 'Host' => $frontend->getDomainName(), ] ); } + return $requests; } - /** - * @param NodesSources $nodeSource - */ protected function purgeNodesSources(NodesSources $nodeSource): void { try { @@ -131,16 +115,12 @@ protected function purgeNodesSources(NodesSources $nodeSource): void } } - /** - * @param Request $request - * @return void - */ protected function sendRequest(Request $request): void { try { $this->bus->dispatch(new Envelope(new GuzzleRequestMessage($request, [ 'debug' => false, - 'timeout' => 3 + 'timeout' => 3, ]))); } catch (ExceptionInterface $exception) { $this->logger->error($exception->getMessage()); diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/RoleSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/RoleSubscriber.php index b3547449..b1a60e04 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/RoleSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/RoleSubscriber.php @@ -20,19 +20,12 @@ class RoleSubscriber implements EventSubscriberInterface protected ?LazyParameterBag $roles; private ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - * @param LazyParameterBag|null $roles - */ public function __construct(ManagerRegistry $managerRegistry, ?LazyParameterBag $roles) { $this->roles = $roles; $this->managerRegistry = $managerRegistry; } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ @@ -47,8 +40,8 @@ public function onRoleChanged(RoleEvent $event): void $manager = $this->managerRegistry->getManagerForClass(Role::class); // Clear result cache if ( - $manager instanceof EntityManagerInterface && - $manager->getConfiguration()->getResultCacheImpl() instanceof CacheProvider + $manager instanceof EntityManagerInterface + && $manager->getConfiguration()->getResultCacheImpl() instanceof CacheProvider ) { $manager->getConfiguration()->getResultCacheImpl()->deleteAll(); } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/SignatureSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/SignatureSubscriber.php index 68bcb97c..e884f083 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/SignatureSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/SignatureSubscriber.php @@ -13,9 +13,10 @@ final class SignatureSubscriber implements EventSubscriberInterface public function __construct( private readonly string $cmsVersion, private readonly bool $hideRoadizVersion, - private readonly bool $debug = false + private readonly bool $debug = false, ) { } + /** * Filters the Response. * diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/TagTimestampSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/TagTimestampSubscriber.php index 86b30b43..ca7aaa1b 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/TagTimestampSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/TagTimestampSubscriber.php @@ -4,19 +4,15 @@ namespace RZ\Roadiz\CoreBundle\EventSubscriber; -use RZ\Roadiz\Core\AbstractEntities\AbstractDateTimed; use RZ\Roadiz\CoreBundle\Event\Tag\TagUpdatedEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class TagTimestampSubscriber implements EventSubscriberInterface { - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ - TagUpdatedEvent::class => 'onTagUpdatedEvent' + TagUpdatedEvent::class => 'onTagUpdatedEvent', ]; } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/TranslationSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/TranslationSubscriber.php index d9b85f68..e929f02d 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/TranslationSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/TranslationSubscriber.php @@ -34,15 +34,15 @@ public static function getSubscribedEvents(): array } /** - * Empty nodeSources Url cache + * Empty nodeSources Url cache. */ public function purgeCache(Event $event, string $eventName, EventDispatcherInterface $dispatcher): void { $manager = $this->managerRegistry->getManager(); // Clear result cache if ( - $manager instanceof EntityManagerInterface && - $manager->getConfiguration()->getResultCacheImpl() instanceof CacheProvider + $manager instanceof EntityManagerInterface + && $manager->getConfiguration()->getResultCacheImpl() instanceof CacheProvider ) { $manager->getConfiguration()->getResultCacheImpl()->deleteAll(); } diff --git a/lib/RoadizCoreBundle/src/EventSubscriber/UserLocaleSubscriber.php b/lib/RoadizCoreBundle/src/EventSubscriber/UserLocaleSubscriber.php index 5b865a5c..5fdf19ee 100644 --- a/lib/RoadizCoreBundle/src/EventSubscriber/UserLocaleSubscriber.php +++ b/lib/RoadizCoreBundle/src/EventSubscriber/UserLocaleSubscriber.php @@ -17,13 +17,10 @@ final class UserLocaleSubscriber implements EventSubscriberInterface { public function __construct( private readonly RequestStack $requestStack, - private readonly TokenStorageInterface $tokenStorage + private readonly TokenStorageInterface $tokenStorage, ) { } - /** - * @return array - */ public static function getSubscribedEvents(): array { // must be registered after the default Locale listener @@ -33,9 +30,6 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param InteractiveLoginEvent $event - */ public function onInteractiveLogin(InteractiveLoginEvent $event): void { if ($this->requestStack->getMainRequest()?->attributes->getBoolean('_stateless')) { @@ -45,16 +39,13 @@ public function onInteractiveLogin(InteractiveLoginEvent $event): void $user = $event->getAuthenticationToken()->getUser(); if ( - $user instanceof User && - null !== $user->getLocale() + $user instanceof User + && null !== $user->getLocale() ) { $this->requestStack->getSession()->set('_locale', $user->getLocale()); } } - /** - * @param FilterUserEvent $event - */ public function onUserUpdated(FilterUserEvent $event): void { if ($this->requestStack->getMainRequest()?->attributes->getBoolean('_stateless')) { @@ -63,9 +54,9 @@ public function onUserUpdated(FilterUserEvent $event): void $user = $event->getUser(); if ( - null !== $this->tokenStorage->getToken() && - $this->tokenStorage->getToken()->getUser() instanceof User && - $this->tokenStorage->getToken()->getUserIdentifier() === $user->getUserIdentifier() + null !== $this->tokenStorage->getToken() + && $this->tokenStorage->getToken()->getUser() instanceof User + && $this->tokenStorage->getToken()->getUserIdentifier() === $user->getUserIdentifier() ) { if (null === $user->getLocale()) { $this->requestStack->getSession()->remove('_locale'); diff --git a/lib/RoadizCoreBundle/src/Exception/BadFormRequestException.php b/lib/RoadizCoreBundle/src/Exception/BadFormRequestException.php index c0ba063e..8afeaa0b 100644 --- a/lib/RoadizCoreBundle/src/Exception/BadFormRequestException.php +++ b/lib/RoadizCoreBundle/src/Exception/BadFormRequestException.php @@ -12,12 +12,6 @@ class BadFormRequestException extends \Exception protected string $statusText; protected ?string $fieldErrored; - /** - * @param string|null $message - * @param int $code - * @param string $statusText - * @param string|null $fieldErrored - */ public function __construct(?string $message = null, int $code = 403, string $statusText = 'danger', ?string $fieldErrored = null) { parent::__construct($message, $code); diff --git a/lib/RoadizCoreBundle/src/Exception/ForceResponseException.php b/lib/RoadizCoreBundle/src/Exception/ForceResponseException.php index 9265bc7c..cf3a9a88 100644 --- a/lib/RoadizCoreBundle/src/Exception/ForceResponseException.php +++ b/lib/RoadizCoreBundle/src/Exception/ForceResponseException.php @@ -21,8 +21,6 @@ public function __construct(Response $response) /** * Gets the value of response. - * - * @return Response */ public function getResponse(): Response { diff --git a/lib/RoadizCoreBundle/src/Exception/MaintenanceModeException.php b/lib/RoadizCoreBundle/src/Exception/MaintenanceModeException.php index 434bbeb3..371fd747 100644 --- a/lib/RoadizCoreBundle/src/Exception/MaintenanceModeException.php +++ b/lib/RoadizCoreBundle/src/Exception/MaintenanceModeException.php @@ -22,9 +22,8 @@ public function getController(): ?AbstractController protected $message = 'Website is currently under maintenance. We will be back shortly.'; /** - * @param AbstractController|null $controller * @param string $message - * @param int $code + * @param int $code */ public function __construct(?AbstractController $controller = null, $message = null, $code = 0) { diff --git a/lib/RoadizCoreBundle/src/Exception/NoConfigurationFoundException.php b/lib/RoadizCoreBundle/src/Exception/NoConfigurationFoundException.php index 47753fc5..33afc988 100644 --- a/lib/RoadizCoreBundle/src/Exception/NoConfigurationFoundException.php +++ b/lib/RoadizCoreBundle/src/Exception/NoConfigurationFoundException.php @@ -14,5 +14,5 @@ class NoConfigurationFoundException extends InvalidConfigurationException /** * @var string */ - protected $message = "No configuration file was found. Make sure that conf/config.json exists."; + protected $message = 'No configuration file was found. Make sure that conf/config.json exists.'; } diff --git a/lib/RoadizCoreBundle/src/Exception/NoYamlConfigurationFoundException.php b/lib/RoadizCoreBundle/src/Exception/NoYamlConfigurationFoundException.php index fad6e7a6..ebc57330 100644 --- a/lib/RoadizCoreBundle/src/Exception/NoYamlConfigurationFoundException.php +++ b/lib/RoadizCoreBundle/src/Exception/NoYamlConfigurationFoundException.php @@ -12,5 +12,5 @@ class NoYamlConfigurationFoundException extends NoConfigurationFoundException /** * @var string */ - protected $message = "No configuration file was found. Make sure that conf/config.yml exists."; + protected $message = 'No configuration file was found. Make sure that conf/config.yml exists.'; } diff --git a/lib/RoadizCoreBundle/src/Explorer/AbstractDoctrineExplorerProvider.php b/lib/RoadizCoreBundle/src/Explorer/AbstractDoctrineExplorerProvider.php index 94a10dd2..d70ee0c4 100644 --- a/lib/RoadizCoreBundle/src/Explorer/AbstractDoctrineExplorerProvider.php +++ b/lib/RoadizCoreBundle/src/Explorer/AbstractDoctrineExplorerProvider.php @@ -18,7 +18,7 @@ public function __construct( protected ExplorerItemFactoryInterface $explorerItemFactory, protected ManagerRegistry $managerRegistry, protected RequestStack $requestStack, - protected UrlGeneratorInterface $urlGenerator + protected UrlGeneratorInterface $urlGenerator, ) { } @@ -27,20 +27,11 @@ public function __construct( */ abstract protected function getProvidedClassname(): string; - /** - * @return array - */ abstract protected function getDefaultCriteria(): array; - /** - * @return array - */ abstract protected function getDefaultOrdering(): array; /** - * @param array $options - * - * @return EntityListManagerInterface * @throws \ReflectionException */ protected function doFetchItems(array $options = []): EntityListManagerInterface @@ -64,9 +55,7 @@ protected function doFetchItems(array $options = []): EntityListManagerInterface return $listManager; } - /** - * @inheritDoc - */ + public function getItems($options = []): array { $listManager = $this->doFetchItems($options); @@ -79,9 +68,6 @@ public function getItems($options = []): array return $items; } - /** - * @inheritDoc - */ public function getFilters($options = []): array { $listManager = $this->doFetchItems($options); @@ -89,14 +75,11 @@ public function getFilters($options = []): array return $listManager->getAssignation(); } - /** - * @inheritDoc - */ public function getItemsById(array $ids = []): array { if (is_array($ids) && count($ids) > 0) { $entities = $this->managerRegistry->getRepository($this->getProvidedClassname())->findBy([ - 'id' => $ids + 'id' => $ids, ]); /* diff --git a/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerItem.php b/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerItem.php index 602da532..2dc54089 100644 --- a/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerItem.php +++ b/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerItem.php @@ -28,9 +28,6 @@ protected function getColor(): ?string return null; } - /** - * @inheritDoc - */ public function toArray(): array { return [ diff --git a/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerProvider.php b/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerProvider.php index 1365661e..3b3ad7ec 100644 --- a/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerProvider.php +++ b/lib/RoadizCoreBundle/src/Explorer/AbstractExplorerProvider.php @@ -22,18 +22,16 @@ abstract class AbstractExplorerProvider implements ExplorerProviderInterface public function setContainer(ContainerInterface $container): self { $this->container = $container; + return $this; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ - 'page' => 1, - 'search' => null, - 'itemPerPage' => 30 + 'page' => 1, + 'search' => null, + 'itemPerPage' => 30, ]); } } diff --git a/lib/RoadizCoreBundle/src/Explorer/ExplorerItemInterface.php b/lib/RoadizCoreBundle/src/Explorer/ExplorerItemInterface.php index 373c8bb7..29b74cb0 100644 --- a/lib/RoadizCoreBundle/src/Explorer/ExplorerItemInterface.php +++ b/lib/RoadizCoreBundle/src/Explorer/ExplorerItemInterface.php @@ -6,32 +6,19 @@ interface ExplorerItemInterface { - /** - * @return string|int - */ public function getId(): string|int; - /** - * @return string|null - */ public function getAlternativeDisplayable(): ?string; - /** - * @return string - */ public function getDisplayable(): string; /** * Get original item. - * - * @return mixed */ public function getOriginal(): mixed; /** * Return a structured array of data. - * - * @return array */ public function toArray(): array; } diff --git a/lib/RoadizCoreBundle/src/Explorer/ExplorerProviderInterface.php b/lib/RoadizCoreBundle/src/Explorer/ExplorerProviderInterface.php index 02e63302..77ba3879 100644 --- a/lib/RoadizCoreBundle/src/Explorer/ExplorerProviderInterface.php +++ b/lib/RoadizCoreBundle/src/Explorer/ExplorerProviderInterface.php @@ -6,35 +6,29 @@ interface ExplorerProviderInterface { - /** - * @param mixed $item - * @return ExplorerItemInterface|null - */ public function toExplorerItem(mixed $item): ?ExplorerItemInterface; /** * @param array $options Options (search, page, itemPerPage…) + * * @return ExplorerItemInterface[] */ public function getItems(array $options = []): array; /** * @param array $options Options (search, page, itemPerPage…) - * @return array */ public function getFilters(array $options = []): array; /** * @param array $ids + * * @return ExplorerItemInterface[] */ public function getItemsById(array $ids = []): array; /** * Check if object can be handled be current ExplorerProvider. - * - * @param mixed $item - * @return bool */ public function supports(mixed $item): bool; } diff --git a/lib/RoadizCoreBundle/src/Filesystem/RoadizFileDirectories.php b/lib/RoadizCoreBundle/src/Filesystem/RoadizFileDirectories.php index 8a475cb9..1e8ee689 100644 --- a/lib/RoadizCoreBundle/src/Filesystem/RoadizFileDirectories.php +++ b/lib/RoadizCoreBundle/src/Filesystem/RoadizFileDirectories.php @@ -14,7 +14,7 @@ public function __construct(private readonly string $projectDir) public function getPublicFilesPath(): string { - return $this->projectDir . '/public' . $this->getPublicFilesBasePath(); + return $this->projectDir.'/public'.$this->getPublicFilesBasePath(); } public function getPublicFilesBasePath(): string @@ -24,7 +24,7 @@ public function getPublicFilesBasePath(): string public function getPrivateFilesPath(): string { - return $this->projectDir . '/var' . $this->getPrivateFilesBasePath(); + return $this->projectDir.'/var'.$this->getPrivateFilesBasePath(); } public function getPrivateFilesBasePath(): string @@ -34,7 +34,7 @@ public function getPrivateFilesBasePath(): string public function getFontsFilesPath(): string { - return $this->projectDir . '/var' . $this->getFontsFilesBasePath(); + return $this->projectDir.'/var'.$this->getFontsFilesBasePath(); } public function getFontsFilesBasePath(): string @@ -44,7 +44,7 @@ public function getFontsFilesBasePath(): string public function getPublicCachePath(): string { - return $this->projectDir . '/public' . $this->getPublicCacheBasePath(); + return $this->projectDir.'/public'.$this->getPublicCacheBasePath(); } public function getPublicCacheBasePath(): string diff --git a/lib/RoadizCoreBundle/src/Form/AttributeChoiceType.php b/lib/RoadizCoreBundle/src/Form/AttributeChoiceType.php index 1a385c3e..3b3fa9b0 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeChoiceType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeChoiceType.php @@ -20,9 +20,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) { } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addModelTransformer(new CallbackTransformer( @@ -30,6 +27,7 @@ function ($dataToForm) { if ($dataToForm instanceof Attribute) { return $dataToForm->getId(); } + return null; }, function ($formToData) { @@ -38,9 +36,6 @@ function ($formToData) { )); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -57,8 +52,8 @@ public function configureOptions(OptionsResolver $resolver): void foreach ($attributes as $attribute) { $label = $attribute->getLabelOrCode($options['translation']); if ( - null !== $attribute->getGroup() && - null !== $groupName = $attribute->getGroup()->getName() + null !== $attribute->getGroup() + && null !== $groupName = $attribute->getGroup()->getName() ) { if (!isset($choices[$groupName]) || !is_array($choices[$groupName])) { $choices[$groupName] = []; @@ -68,13 +63,11 @@ public function configureOptions(OptionsResolver $resolver): void $choices[$label] = $attribute->getId(); } } + return $choices; }); } - /** - * @inheritDoc - */ public function getParent(): ?string { return ChoiceType::class; diff --git a/lib/RoadizCoreBundle/src/Form/AttributeDocumentType.php b/lib/RoadizCoreBundle/src/Form/AttributeDocumentType.php index f361f14c..e827ed77 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeDocumentType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeDocumentType.php @@ -5,10 +5,10 @@ namespace RZ\Roadiz\CoreBundle\Form; use Doctrine\ORM\EntityManagerInterface; -use RZ\Roadiz\CoreBundle\Form\DataTransformer\AttributeDocumentsTransformer; -use RZ\Roadiz\CoreBundle\Model\AttributeInterface; use RZ\Roadiz\CoreBundle\Entity\Attribute; use RZ\Roadiz\CoreBundle\Entity\AttributeDocuments; +use RZ\Roadiz\CoreBundle\Form\DataTransformer\AttributeDocumentsTransformer; +use RZ\Roadiz\CoreBundle\Model\AttributeInterface; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\FormBuilderInterface; @@ -20,18 +20,11 @@ class AttributeDocumentType extends AbstractType { protected EntityManagerInterface $entityManager; - /** - * @param EntityManagerInterface $entityManager - */ public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener( @@ -44,9 +37,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void )); } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -60,17 +50,11 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('attribute', [AttributeInterface::class]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'documents'; } - /** - * @inheritDoc - */ public function getParent(): ?string { return CollectionType::class; @@ -78,8 +62,6 @@ public function getParent(): ?string /** * Delete existing document association. - * - * @param FormEvent $event */ public function onPostSubmit(FormEvent $event): void { diff --git a/lib/RoadizCoreBundle/src/Form/AttributeGroupTranslationType.php b/lib/RoadizCoreBundle/src/Form/AttributeGroupTranslationType.php index d5de4b4b..9cf7ab68 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeGroupTranslationType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeGroupTranslationType.php @@ -17,48 +17,36 @@ class AttributeGroupTranslationType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('name', TextType::class, [ - 'empty_data' => '', - 'label' => false, - 'required' => false, - ]) + 'empty_data' => '', + 'label' => false, + 'required' => false, + ]) ->add('translation', TranslationsType::class, [ 'label' => false, 'required' => true, 'constraints' => [ - new NotNull() - ] + new NotNull(), + ], ]) ; $builder->get('translation')->addModelTransformer(new TranslationTransformer($this->managerRegistry)); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); $resolver->setDefault('data_class', AttributeGroupTranslation::class); } - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'attribute_group_translation'; diff --git a/lib/RoadizCoreBundle/src/Form/AttributeGroupType.php b/lib/RoadizCoreBundle/src/Form/AttributeGroupType.php index 3e2c1b58..aa38df8b 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeGroupType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeGroupType.php @@ -16,9 +16,9 @@ class AttributeGroupType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('canonicalName', TextType::class, [ - 'label' => 'attribute_group.form.canonicalName', - 'empty_data' => '', - ]) + 'label' => 'attribute_group.form.canonicalName', + 'empty_data' => '', + ]) ->add('attributeGroupTranslations', CollectionType::class, [ 'label' => 'attribute_group.form.attributeGroupTranslations', 'allow_add' => true, @@ -29,12 +29,12 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'entry_options' => [ 'label' => false, 'attr' => [ - 'class' => 'uk-form uk-form-horizontal' - ] + 'class' => 'uk-form uk-form-horizontal', + ], ], 'attr' => [ - 'class' => 'rz-collection-form-type' - ] + 'class' => 'rz-collection-form-type', + ], ]) ; } diff --git a/lib/RoadizCoreBundle/src/Form/AttributeGroupsType.php b/lib/RoadizCoreBundle/src/Form/AttributeGroupsType.php index 39d0c4f6..2ac851c2 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeGroupsType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeGroupsType.php @@ -5,8 +5,8 @@ namespace RZ\Roadiz\CoreBundle\Form; use Doctrine\ORM\EntityManagerInterface; -use RZ\Roadiz\CoreBundle\Form\DataTransformer\AttributeGroupTransformer; use RZ\Roadiz\CoreBundle\Entity\AttributeGroup; +use RZ\Roadiz\CoreBundle\Form\DataTransformer\AttributeGroupTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\FormBuilderInterface; @@ -29,15 +29,12 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->addModelTransformer(new AttributeGroupTransformer($this->entityManager)); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setNormalizer('choices', function (Options $options, $choices) { $criteria = []; $ordering = [ - 'canonicalName' => 'ASC' + 'canonicalName' => 'ASC', ]; $attributeGroups = $this->entityManager ->getRepository(AttributeGroup::class) @@ -51,16 +48,12 @@ public function configureOptions(OptionsResolver $resolver): void return $choices; }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'attribute_groups'; diff --git a/lib/RoadizCoreBundle/src/Form/AttributeImportType.php b/lib/RoadizCoreBundle/src/Form/AttributeImportType.php index 7f006640..97e9cb6e 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeImportType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeImportType.php @@ -11,9 +11,6 @@ class AttributeImportType extends AbstractType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('file', FileType::class, [ @@ -21,9 +18,9 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'help' => 'attributes.import_form.file.help', 'constraints' => [ new File([ - 'mimeTypes' => ['application/json', 'text/json', 'text/plain'] - ]) - ] + 'mimeTypes' => ['application/json', 'text/json', 'text/plain'], + ]), + ], ]); } } diff --git a/lib/RoadizCoreBundle/src/Form/AttributeTranslationType.php b/lib/RoadizCoreBundle/src/Form/AttributeTranslationType.php index 2074be9a..c0838414 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeTranslationType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeTranslationType.php @@ -19,30 +19,24 @@ class AttributeTranslationType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('label', TextType::class, [ - 'empty_data' => '', - 'label' => false, - 'required' => false, - ]) + 'empty_data' => '', + 'label' => false, + 'required' => false, + ]) ->add('translation', TranslationsType::class, [ 'label' => false, 'required' => true, 'constraints' => [ - new NotNull() - ] + new NotNull(), + ], ]) ->add('options', CollectionType::class, [ 'label' => 'attributes.form.options', @@ -53,7 +47,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'required' => false, ], 'attr' => [ - 'class' => 'rz-collection-form-type' + 'class' => 'rz-collection-form-type', ], ]) ; @@ -61,9 +55,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->get('translation')->addModelTransformer(new TranslationTransformer($this->managerRegistry)); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -72,14 +63,11 @@ public function configureOptions(OptionsResolver $resolver): void // Keep this constraint as class annotation is not validated new UniqueEntity([ 'fields' => ['attribute', 'translation'], - 'errorPath' => 'translation' - ]) + 'errorPath' => 'translation', + ]), ]); } - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'attribute_translation'; diff --git a/lib/RoadizCoreBundle/src/Form/AttributeType.php b/lib/RoadizCoreBundle/src/Form/AttributeType.php index cd461657..46053a9f 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeType.php @@ -17,21 +17,18 @@ class AttributeType extends AbstractType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('code', TextType::class, [ - 'label' => 'attributes.form.code', - 'required' => true, - 'help' => 'attributes.form_help.code', - ]) + 'label' => 'attributes.form.code', + 'required' => true, + 'help' => 'attributes.form_help.code', + ]) ->add('group', AttributeGroupsType::class, [ 'label' => 'attributes.form.group', 'required' => false, 'help' => 'attributes.form_help.group', - 'placeholder' => 'attributes.form.group.placeholder' + 'placeholder' => 'attributes.form.group.placeholder', ]) ->add('color', ColorType::class, [ 'label' => 'attributes.form.color', @@ -58,13 +55,13 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ->add('searchable', CheckboxType::class, [ 'label' => 'attributes.form.searchable', 'required' => false, - 'help' => 'attributes.form_help.searchable' + 'help' => 'attributes.form_help.searchable', ]) ->add('weight', NumberType::class, [ 'label' => 'attributes.weight', 'required' => false, 'scale' => 1, - 'help' => 'attributes.form_help.weight' + 'help' => 'attributes.form_help.weight', ]) ->add('defaultRealm', RealmChoiceType::class, [ 'label' => 'attributes.defaultRealm', @@ -82,34 +79,28 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'entry_options' => [ 'label' => false, 'attr' => [ - 'class' => 'uk-form uk-form-horizontal' - ] + 'class' => 'uk-form uk-form-horizontal', + ], ], 'attr' => [ - 'class' => 'rz-collection-form-type' - ] + 'class' => 'rz-collection-form-type', + ], ]) ->add('attributeDocuments', AttributeDocumentType::class, [ 'label' => 'attributes.form.documents', 'help' => 'attributes.form_help.documents', 'required' => false, - 'attribute' => $builder->getForm()->getData() + 'attribute' => $builder->getForm()->getData(), ]) ; } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); $resolver->setDefault('data_class', Attribute::class); } - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'attribute'; diff --git a/lib/RoadizCoreBundle/src/Form/AttributeValueTranslationType.php b/lib/RoadizCoreBundle/src/Form/AttributeValueTranslationType.php index 0e3b2e8b..a5beaa3d 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeValueTranslationType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeValueTranslationType.php @@ -13,7 +13,6 @@ use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\EmailType; -use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Extension\Core\Type\TextType; @@ -24,9 +23,6 @@ class AttributeValueTranslationType extends AbstractType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $attributeValueTranslation = $builder->getData(); @@ -38,9 +34,9 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'label' => false, 'constraints' => [ new Length([ - 'max' => 254 - ]) - ] + 'max' => 254, + ]), + ], ]; switch ($attributeValueTranslation->getAttributeValue()->getType()) { case AttributeInterface::INTEGER_T: @@ -54,14 +50,14 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'placeholder' => [ 'year' => 'year', 'month' => 'month', - 'day' => 'day' + 'day' => 'day', ], 'widget' => 'single_text', 'format' => 'yyyy-MM-dd', 'attr' => [ 'class' => 'rz-datetime-field', ], - 'constraints' => [] + 'constraints' => [], ])); break; case AttributeInterface::COLOUR_T: @@ -81,7 +77,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'attr' => [ 'class' => 'rz-datetime-field', ], - 'constraints' => [] + 'constraints' => [], ])); break; case AttributeInterface::BOOLEAN_T: @@ -90,14 +86,14 @@ public function buildForm(FormBuilderInterface $builder, array $options): void case AttributeInterface::ENUM_T: $builder->add('value', ChoiceType::class, array_merge($defaultOptions, [ 'required' => true, - 'choices' => $this->getOptions($attributeValueTranslation) + 'choices' => $this->getOptions($attributeValueTranslation), ])); break; case AttributeInterface::EMAIL_T: $builder->add('value', EmailType::class, array_merge($defaultOptions, [ 'constraints' => [ - new Email() - ] + new Email(), + ], ])); break; default: @@ -110,21 +106,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * @param AttributeValueTranslationInterface $attributeValueTranslation - * - * @return AttributeInterface|null - */ protected function getAttribute(AttributeValueTranslationInterface $attributeValueTranslation): ?AttributeInterface { return $attributeValueTranslation->getAttributeValue()->getAttribute(); } - /** - * @param AttributeValueTranslationInterface $attributeValueTranslation - * - * @return array - */ protected function getOptions(AttributeValueTranslationInterface $attributeValueTranslation): array { $options = $this->getAttribute($attributeValueTranslation)->getOptions( @@ -147,10 +133,6 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'attribute_value_translation'; diff --git a/lib/RoadizCoreBundle/src/Form/AttributeValueType.php b/lib/RoadizCoreBundle/src/Form/AttributeValueType.php index 452523da..d7bdcf3e 100644 --- a/lib/RoadizCoreBundle/src/Form/AttributeValueType.php +++ b/lib/RoadizCoreBundle/src/Form/AttributeValueType.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\CoreBundle\Form; -use Doctrine\ORM\EntityManagerInterface; use RZ\Roadiz\CoreBundle\Entity\Translation; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; @@ -12,9 +11,6 @@ class AttributeValueType extends AbstractType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('attribute', AttributeChoiceType::class, [ @@ -23,9 +19,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -34,9 +27,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('translation', [Translation::class]); } - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'attribute_value'; diff --git a/lib/RoadizCoreBundle/src/Form/ColorType.php b/lib/RoadizCoreBundle/src/Form/ColorType.php index 695e9c54..567866c7 100644 --- a/lib/RoadizCoreBundle/src/Form/ColorType.php +++ b/lib/RoadizCoreBundle/src/Form/ColorType.php @@ -13,9 +13,6 @@ class ColorType extends AbstractType { - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); diff --git a/lib/RoadizCoreBundle/src/Form/CompareDateType.php b/lib/RoadizCoreBundle/src/Form/CompareDateType.php index b8bb779f..f28a1fee 100644 --- a/lib/RoadizCoreBundle/src/Form/CompareDateType.php +++ b/lib/RoadizCoreBundle/src/Form/CompareDateType.php @@ -21,8 +21,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void '>' => '>', '<=' => '<=', '>=' => '>=', - '=' => '=' - ] + '=' => '=', + ], ]) ->add('compareDate', DateType::class, [ 'label' => false, @@ -35,9 +35,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ diff --git a/lib/RoadizCoreBundle/src/Form/CompareDatetimeType.php b/lib/RoadizCoreBundle/src/Form/CompareDatetimeType.php index ea3f86d1..c3f69eab 100644 --- a/lib/RoadizCoreBundle/src/Form/CompareDatetimeType.php +++ b/lib/RoadizCoreBundle/src/Form/CompareDatetimeType.php @@ -23,8 +23,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void '>' => '>', '<=' => '<=', '>=' => '>=', - '=' => '=' - ] + '=' => '=', + ], ]) ->add('compareDatetime', DateTimeType::class, [ 'label' => false, @@ -41,9 +41,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); @@ -51,9 +48,6 @@ public function buildView(FormView $view, FormInterface $form, array $options): $view->vars['attr']['class'] = 'rz-compare-datetype'; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/HexadecimalColorValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/HexadecimalColorValidator.php index 4b637d11..f0c62054 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/HexadecimalColorValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/HexadecimalColorValidator.php @@ -12,7 +12,7 @@ class HexadecimalColorValidator extends ConstraintValidator public function validate(mixed $value, Constraint $constraint): void { if ($constraint instanceof HexadecimalColor) { - if (null !== $value && preg_match('#\#[0-9a-f]{6}#', \mb_strtolower($value)) === 0) { + if (null !== $value && 0 === preg_match('#\#[0-9a-f]{6}#', \mb_strtolower($value))) { $this->context->addViolation($constraint->message); } } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeField.php b/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeField.php index 34cc19c6..215ba5f9 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeField.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeField.php @@ -15,9 +15,6 @@ class NodeTypeField extends Constraint { public string $message = 'default_values_do_not_match_field_type'; - /** - * {@inheritdoc} - */ public function getTargets(): string { return self::CLASS_CONSTRAINT; diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeFieldValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeFieldValidator.php index 696252df..4ab74c3f 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeFieldValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/NodeTypeFieldValidator.php @@ -29,6 +29,7 @@ public function validate(mixed $value, Constraint $constraint): void { if (!$value instanceof NodeTypeFieldEntity) { $this->context->buildViolation('Value is not a valid NodeTypeField.')->addViolation(); + return; } @@ -63,10 +64,6 @@ public function validate(mixed $value, Constraint $constraint): void } } - /** - * @param NodeTypeFieldEntity $value - * @param Constraint $constraint - */ protected function validateJoinTypes(NodeTypeFieldEntity $value, Constraint $constraint): void { try { @@ -88,6 +85,7 @@ protected function validateJoinTypes(NodeTypeFieldEntity $value, Constraint $con ->setParameter('%classname%', $configuration['classname']) ->atPath('classname') ->addViolation(); + return; } @@ -135,9 +133,6 @@ protected function validateJoinTypes(NodeTypeFieldEntity $value, Constraint $con } /** - * @param NodeTypeFieldEntity $value - * @param Constraint $constraint - * * @throws \ReflectionException */ protected function validateProviderTypes(NodeTypeFieldEntity $value, Constraint $constraint): void @@ -164,6 +159,7 @@ protected function validateProviderTypes(NodeTypeFieldEntity $value, Constraint ->setParameter('%classname%', $configuration['classname']) ->atPath('defaultValues') ->addViolation(); + return; } @@ -183,10 +179,6 @@ protected function validateProviderTypes(NodeTypeFieldEntity $value, Constraint } } - /** - * @param NodeTypeFieldEntity $value - * @param Constraint $constraint - */ protected function validateCollectionTypes(NodeTypeFieldEntity $value, Constraint $constraint): void { try { @@ -208,6 +200,7 @@ protected function validateCollectionTypes(NodeTypeFieldEntity $value, Constrain ->setParameter('%classname%', $configuration['entry_type']) ->atPath('defaultValues') ->addViolation(); + return; } @@ -226,9 +219,6 @@ protected function validateCollectionTypes(NodeTypeFieldEntity $value, Constrain } } - /** - * @param NodeTypeFieldEntity $value - */ protected function validateMarkdownOptions(NodeTypeFieldEntity $value): void { try { diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWord.php b/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWord.php index 5190f76c..deb5ff7e 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWord.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWord.php @@ -17,6 +17,7 @@ class NonSqlReservedWord extends Constraint * List of forbidden field names. These are SQL reserved words. * * @see https://dev.mysql.com/doc/refman/8.0/en/keywords.html + * * @var array */ public static array $forbiddenNames = [ diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWordValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWordValidator.php index da6f1a7d..939a391e 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWordValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/NonSqlReservedWordValidator.php @@ -16,9 +16,9 @@ public function validate(mixed $value, Constraint $constraint): void $fieldName = StringHandler::variablize($value); $lowerName = \mb_strtolower($value); if ( - in_array($value, NonSqlReservedWord::$forbiddenNames) || - in_array($lowerName, NonSqlReservedWord::$forbiddenNames) || - in_array($fieldName, NonSqlReservedWord::$forbiddenNames) + in_array($value, NonSqlReservedWord::$forbiddenNames) + || in_array($lowerName, NonSqlReservedWord::$forbiddenNames) + || in_array($fieldName, NonSqlReservedWord::$forbiddenNames) ) { if ($constraint instanceof NonSqlReservedWord) { $this->context->addViolation($constraint->message); diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaServiceInterface.php b/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaServiceInterface.php index 362a60c7..48121a18 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaServiceInterface.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaServiceInterface.php @@ -10,12 +10,10 @@ interface RecaptchaServiceInterface * Makes a request to recaptcha service and checks if recaptcha field is valid. * Returns Google error-codes if recaptcha fails. * - * @param string $responseValue - * @param string $verifyUrl * @return true|mixed */ public function check( string $responseValue, - string $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify' + string $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify', ): mixed; } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaValidator.php index b662918e..f6ab3d4c 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/RecaptchaValidator.php @@ -24,9 +24,8 @@ public function __construct(RequestStack $requestStack, ?string $recaptchaPrivat } /** - * @param mixed $data - * @param Constraint $constraint * @throws \GuzzleHttp\Exception\GuzzleException + * * @see \Symfony\Component\Validator\ConstraintValidator::validate() */ public function validate(mixed $data, Constraint $constraint): void @@ -70,14 +69,13 @@ public function validate(mixed $data, Constraint $constraint): void * Makes a request to recaptcha service and checks if recaptcha field is valid. * Returns Google error-codes if recaptcha fails. * - * @param string $responseValue - * @param string $verifyUrl * @return true|mixed + * * @throws \GuzzleHttp\Exception\GuzzleException */ public function check( string $responseValue, - string $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify' + string $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify', ): mixed { if (empty($this->recaptchaPrivateKey)) { return true; @@ -94,12 +92,12 @@ public function check( 'connect_timeout' => 10, 'timeout' => 10, 'headers' => [ - 'Accept' => 'application/json', - ] + 'Accept' => 'application/json', + ], ]); $jsonResponse = json_decode($response->getBody()->getContents(), true); - return (isset($jsonResponse['success']) && $jsonResponse['success'] === true) ? + return (isset($jsonResponse['success']) && true === $jsonResponse['success']) ? (true) : ($jsonResponse['error-codes']); } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/SimpleLatinStringValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/SimpleLatinStringValidator.php index af4918a2..93e0f094 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/SimpleLatinStringValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/SimpleLatinStringValidator.php @@ -12,7 +12,7 @@ class SimpleLatinStringValidator extends ConstraintValidator public function validate(mixed $value, Constraint $constraint): void { if ($constraint instanceof SimpleLatinString) { - if (null !== $value && preg_match('#[^a-z_\s\-]#', \mb_strtolower($value)) === 1) { + if (null !== $value && 1 === preg_match('#[^a-z_\s\-]#', \mb_strtolower($value))) { $this->context->addViolation($constraint->message); } } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilename.php b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilename.php index 3293d75c..b14bd089 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilename.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilename.php @@ -7,9 +7,6 @@ use RZ\Roadiz\Documents\Models\DocumentInterface; use Symfony\Component\Validator\Constraint; -/** - * @package RZ\Roadiz\CoreBundle\Form\Constraint - */ class UniqueFilename extends Constraint { public ?DocumentInterface $document = null; diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilenameValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilenameValidator.php index c677d7e2..a55d2f44 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilenameValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueFilenameValidator.php @@ -19,8 +19,6 @@ public function __construct(FilesystemOperator $documentsStorage) } /** - * @param mixed $value - * @param Constraint $constraint * @throws FilesystemException */ public function validate(mixed $value, Constraint $constraint): void @@ -32,15 +30,15 @@ public function validate(mixed $value, Constraint $constraint): void * do nothing. */ if ( - null !== $document && - $value == $document->getFilename() + null !== $document + && $value == $document->getFilename() ) { return; } $folder = $document->getMountFolderPath(); - if ($this->documentsStorage->fileExists($folder . '/' . $value)) { + if ($this->documentsStorage->fileExists($folder.'/'.$value)) { $this->context->addViolation($constraint->message); } } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueNodeNameValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueNodeNameValidator.php index 00bb3d48..4e66cb46 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueNodeNameValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueNodeNameValidator.php @@ -18,17 +18,14 @@ class UniqueNodeNameValidator extends ConstraintValidator { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } /** - * @param mixed $value * @param UniqueNodeName $constraint + * * @throws NoResultException * @throws NonUniqueResultException */ @@ -51,27 +48,20 @@ public function validate(mixed $value, Constraint $constraint): void } } - /** - * @param string $name - * - * @return bool - */ protected function urlAliasExists(string $name): bool { return (bool) $this->managerRegistry->getRepository(UrlAlias::class)->exists($name); } /** - * @param string $name - * - * @return bool - * @throws \Doctrine\ORM\NonUniqueResultException|\Doctrine\ORM\NoResultException + * @throws NonUniqueResultException|NoResultException */ protected function nodeNameExists(string $name): bool { /** @var NodeRepository $nodeRepo */ $nodeRepo = $this->managerRegistry->getRepository(Node::class); $nodeRepo->setDisplayingNotPublishedNodes(true); + return $nodeRepo->exists($name); } } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueTagNameValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueTagNameValidator.php index c7d396b6..b023daf0 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/UniqueTagNameValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/UniqueTagNameValidator.php @@ -14,16 +14,13 @@ class UniqueTagNameValidator extends ConstraintValidator { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } /** - * @param string $value + * @param string $value * @param UniqueTagName $constraint */ public function validate(mixed $value, Constraint $constraint): void @@ -40,7 +37,6 @@ public function validate(mixed $value, Constraint $constraint): void } /** - * @param string|null $value * @param UniqueTagName $constraint */ protected function testSingleValue(?string $value, Constraint $constraint): void @@ -62,22 +58,13 @@ protected function testSingleValue(?string $value, Constraint $constraint): void } } - /** - * @param string $name - * - * @return bool - */ protected function tagNameExists(string $name): bool { $entity = $this->managerRegistry->getRepository(Tag::class)->findOneByTagName($name); - return (null !== $entity); + return null !== $entity; } - /** - * @param string|null $value - * @return bool - */ protected function isMulti(?string $value): bool { return (bool) \mb_strpos($value ?? '', ','); diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationToken.php b/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationToken.php index 74a7c642..7f3010e1 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationToken.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationToken.php @@ -9,9 +9,7 @@ class ValidAccountConfirmationToken extends Constraint { /** - * Confirmation token time to live, in seconds - * - * @var integer + * Confirmation token time to live, in seconds. */ public int $ttl = 60; diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationTokenValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationTokenValidator.php index 6907e90b..7ba50844 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationTokenValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountConfirmationTokenValidator.php @@ -13,18 +13,13 @@ class ValidAccountConfirmationTokenValidator extends ConstraintValidator { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } /** - * @param mixed $value * @param ValidAccountConfirmationToken $constraint - * @return void */ public function validate(mixed $value, Constraint $constraint): void { diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountEmailValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountEmailValidator.php index 97240c4c..05d341f6 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountEmailValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/ValidAccountEmailValidator.php @@ -13,18 +13,13 @@ class ValidAccountEmailValidator extends ConstraintValidator { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } /** - * @param mixed $value * @param ValidAccountEmail $constraint - * @return void */ public function validate(mixed $value, Constraint $constraint): void { diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/ValidFacebookNameValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/ValidFacebookNameValidator.php index e9b1be15..a04127b3 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/ValidFacebookNameValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/ValidFacebookNameValidator.php @@ -10,24 +10,26 @@ class ValidFacebookNameValidator extends ConstraintValidator { + public function __construct(private readonly FacebookPictureFinder $facebookPictureFinder) + { + } + /** - * @param mixed $value * @param ValidFacebookName $constraint - * @return void + * * @throws \GuzzleHttp\Exception\GuzzleException */ public function validate(mixed $value, Constraint $constraint): void { - if ($value != "") { - if (0 === preg_match("#^[0-9]*$#", $value)) { + if ('' != $value) { + if (0 === preg_match('#^[0-9]*$#', $value)) { $this->context->addViolation($constraint->message); } else { /* * Test if the username really exists. */ - $facebook = new FacebookPictureFinder($value); try { - $facebook->getPictureUrl(); + $this->facebookPictureFinder->getPictureUrl($value); } catch (\Exception $e) { $this->context->addViolation($constraint->message); } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/ValidJsonValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/ValidJsonValidator.php index afa16613..b754d331 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/ValidJsonValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/ValidJsonValidator.php @@ -4,27 +4,22 @@ namespace RZ\Roadiz\CoreBundle\Form\Constraint; -use JsonException; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; -use Symfony\Component\Yaml\Exception\ParseException; -use Symfony\Component\Yaml\Yaml; class ValidJsonValidator extends ConstraintValidator { /** - * @param mixed $value * @param ValidJson $constraint - * @return void */ public function validate(mixed $value, Constraint $constraint): void { if (!empty($value)) { try { \json_decode($value, true, 512, JSON_THROW_ON_ERROR); - } catch (JsonException $e) { + } catch (\JsonException $e) { $this->context->addViolation($constraint->message, [ - '{{ error }}' => $e->getMessage() + '{{ error }}' => $e->getMessage(), ]); } } diff --git a/lib/RoadizCoreBundle/src/Form/Constraint/ValidYamlValidator.php b/lib/RoadizCoreBundle/src/Form/Constraint/ValidYamlValidator.php index e9e96c97..bbc2c31c 100644 --- a/lib/RoadizCoreBundle/src/Form/Constraint/ValidYamlValidator.php +++ b/lib/RoadizCoreBundle/src/Form/Constraint/ValidYamlValidator.php @@ -12,13 +12,11 @@ class ValidYamlValidator extends ConstraintValidator { /** - * @param mixed $value * @param ValidYaml $constraint - * @return void */ public function validate(mixed $value, Constraint $constraint): void { - if ($value != "") { + if ('' != $value) { try { if (is_array($value)) { // value already has been parsed into array @@ -27,7 +25,7 @@ public function validate(mixed $value, Constraint $constraint): void Yaml::parse($value); } catch (ParseException $e) { $this->context->addViolation($constraint->message, [ - '{{ error }}' => $e->getMessage() + '{{ error }}' => $e->getMessage(), ]); } } diff --git a/lib/RoadizCoreBundle/src/Form/CreatePasswordType.php b/lib/RoadizCoreBundle/src/Form/CreatePasswordType.php index edb2630e..58e25014 100644 --- a/lib/RoadizCoreBundle/src/Form/CreatePasswordType.php +++ b/lib/RoadizCoreBundle/src/Form/CreatePasswordType.php @@ -12,9 +12,6 @@ class CreatePasswordType extends RepeatedType { - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -24,8 +21,8 @@ public function configureOptions(OptionsResolver $resolver): void 'invalid_message' => 'password.must.match', 'options' => [ 'constraints' => [ - new NotInPasswordCommonList() - ] + new NotInPasswordCommonList(), + ], ], 'first_options' => [ 'label' => 'choose.a.new.password', @@ -40,9 +37,6 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'repeated'; diff --git a/lib/RoadizCoreBundle/src/Form/CssType.php b/lib/RoadizCoreBundle/src/Form/CssType.php index f1b124ea..9abfa5be 100644 --- a/lib/RoadizCoreBundle/src/Form/CssType.php +++ b/lib/RoadizCoreBundle/src/Form/CssType.php @@ -15,24 +15,16 @@ */ class CssType extends AbstractType { - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextareaType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'css'; } - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); diff --git a/lib/RoadizCoreBundle/src/Form/CustomFormsType.php b/lib/RoadizCoreBundle/src/Form/CustomFormsType.php index 059f5e28..844e9f49 100644 --- a/lib/RoadizCoreBundle/src/Form/CustomFormsType.php +++ b/lib/RoadizCoreBundle/src/Form/CustomFormsType.php @@ -4,10 +4,10 @@ namespace RZ\Roadiz\CoreBundle\Form; -use RZ\Roadiz\CoreBundle\Form\Constraint\Recaptcha; use RZ\Roadiz\Core\AbstractEntities\AbstractField; use RZ\Roadiz\CoreBundle\Entity\CustomForm; use RZ\Roadiz\CoreBundle\Entity\CustomFormField; +use RZ\Roadiz\CoreBundle\Form\Constraint\Recaptcha; use RZ\Roadiz\Utils\StringHandler; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; @@ -29,9 +29,6 @@ use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Validator\Constraints\NotBlank; -/** - * @package RZ\Roadiz\CoreBundle\Form - */ class CustomFormsType extends AbstractType { protected ?string $recaptchaPrivateKey; @@ -43,10 +40,6 @@ public function __construct(?string $recaptchaPrivateKey, ?string $recaptchaPubl $this->recaptchaPublicKey = $recaptchaPublicKey; } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $fieldsArray = $this->getFieldsByGroups($options); @@ -62,7 +55,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'inherit_data' => true, 'attr' => [ 'data-group-wrapper' => $groupCanonical, - ] + ], ]); /** @var CustomFormField $subfield */ foreach ($field as $subfield) { @@ -76,8 +69,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void * Add Google Recaptcha if setting optional options. */ if ( - !empty($this->recaptchaPublicKey) && - !empty($this->recaptchaPrivateKey) + !empty($this->recaptchaPublicKey) + && !empty($this->recaptchaPrivateKey) ) { $builder->add($options['recaptcha_name'], RecaptchaType::class, [ 'label' => false, @@ -87,17 +80,13 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'constraints' => [ new Recaptcha([ 'privateKey' => $this->recaptchaPrivateKey, - 'fieldName' => $options['recaptcha_name'] + 'fieldName' => $options['recaptcha_name'], ]), ], ]); } } - /** - * @param array $options - * @return array - */ protected function getFieldsByGroups(array $options): array { $fieldsArray = []; @@ -106,7 +95,7 @@ protected function getFieldsByGroups(array $options): array /** @var CustomFormField $field */ foreach ($fields as $field) { $groupName = $field->getGroupName(); - if (\is_string($groupName) && $groupName !== '') { + if (\is_string($groupName) && '' !== $groupName) { if (!isset($fieldsArray[$groupName]) || !\is_array($fieldsArray[$groupName])) { $fieldsArray[$groupName] = []; } @@ -120,9 +109,6 @@ protected function getFieldsByGroups(array $options): array } /** - * @param FormBuilderInterface $builder - * @param CustomFormField $field - * @param array $formOptions * @return $this */ protected function addSingleField(FormBuilderInterface $builder, CustomFormField $field, array $formOptions): self @@ -132,11 +118,11 @@ protected function addSingleField(FormBuilderInterface $builder, CustomFormField $this->getTypeForField($field), $this->getOptionsForField($field, $formOptions) ); + return $this; } /** - * @param CustomFormField $field * @return class-string */ protected function getTypeForField(CustomFormField $field): string @@ -159,14 +145,12 @@ protected function getTypeForField(CustomFormField $field): string } /** - * @param CustomFormField $field - * @param array $formOptions * @return array */ protected function getOptionsForField(CustomFormField $field, array $formOptions): array { $option = [ - "label" => $field->getLabel(), + 'label' => $field->getLabel(), 'help' => $field->getDescription(), 'attr' => [ 'data-group' => $field->getGroupName(), @@ -177,7 +161,7 @@ protected function getOptionsForField(CustomFormField $field, array $formOptions $option['attr']['placeholder'] = $field->getPlaceholder(); } - if ($field->getAutocomplete() !== null) { + if (null !== $field->getAutocomplete()) { $option['attr']['autocomplete'] = $field->getAutocomplete(); } @@ -185,8 +169,8 @@ protected function getOptionsForField(CustomFormField $field, array $formOptions $option['required'] = true; $option['constraints'] = [ new NotBlank([ - 'message' => 'you.need.to.fill.this.required.field' - ]) + 'message' => 'you.need.to.fill.this.required.field', + ]), ]; } else { $option['required'] = false; @@ -194,24 +178,24 @@ protected function getOptionsForField(CustomFormField $field, array $formOptions switch ($field->getType()) { case AbstractField::DATETIME_T: - $option["widget"] = 'single_text'; - $option["format"] = DateTimeType::HTML5_FORMAT; + $option['widget'] = 'single_text'; + $option['format'] = DateTimeType::HTML5_FORMAT; break; case AbstractField::DATE_T: - $option["widget"] = 'single_text'; - $option["format"] = DateType::HTML5_FORMAT; + $option['widget'] = 'single_text'; + $option['format'] = DateType::HTML5_FORMAT; break; case AbstractField::ENUM_T: if (!empty($field->getPlaceholder())) { $option['placeholder'] = $field->getPlaceholder(); } - $option["choices"] = $this->getChoices($field); - $option["expanded"] = $field->isExpanded(); + $option['choices'] = $this->getChoices($field); + $option['expanded'] = $field->isExpanded(); if ($formOptions['forceExpanded']) { - $option["expanded"] = true; + $option['expanded'] = true; } - if ($field->isRequired() === false) { + if (false === $field->isRequired()) { $option['placeholder'] = 'none'; } break; @@ -219,14 +203,14 @@ protected function getOptionsForField(CustomFormField $field, array $formOptions if (!empty($field->getPlaceholder())) { $option['placeholder'] = $field->getPlaceholder(); } - $option["choices"] = $this->getChoices($field); - $option["multiple"] = true; - $option["expanded"] = $field->isExpanded(); + $option['choices'] = $this->getChoices($field); + $option['multiple'] = true; + $option['expanded'] = $field->isExpanded(); if ($formOptions['forceExpanded']) { - $option["expanded"] = true; + $option['expanded'] = true; } - if ($field->isRequired() === false) { + if (false === $field->isRequired()) { $option['placeholder'] = 'none'; } break; @@ -252,13 +236,13 @@ protected function getOptionsForField(CustomFormField $field, array $formOptions 'constraints' => [ new File([ 'maxSize' => $formOptions['fileUploadMaxSize'], - 'mimeTypes' => $mimeTypes - ]) - ] + 'mimeTypes' => $mimeTypes, + ]), + ], ]); break; case AbstractField::COUNTRY_T: - $option["expanded"] = $field->isExpanded(); + $option['expanded'] = $field->isExpanded(); if (!empty($field->getPlaceholder())) { $option['placeholder'] = $field->getPlaceholder(); } @@ -277,23 +261,18 @@ protected function getOptionsForField(CustomFormField $field, array $formOptions default: break; } + return $option; } - /** - * @param CustomFormField $field - * @return array - */ protected function getChoices(CustomFormField $field): array { $choices = explode(',', $field->getDefaultValues() ?? ''); $choices = array_map('trim', $choices); + return array_combine(array_values($choices), array_values($choices)); } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -312,9 +291,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('recaptcha_name', ['string']); } - /** - * @return string - */ public function getBlockPrefix(): string { return 'custom_form_public'; diff --git a/lib/RoadizCoreBundle/src/Form/DataListTextType.php b/lib/RoadizCoreBundle/src/Form/DataListTextType.php index 4cf6b095..13c74561 100644 --- a/lib/RoadizCoreBundle/src/Form/DataListTextType.php +++ b/lib/RoadizCoreBundle/src/Form/DataListTextType.php @@ -30,7 +30,6 @@ public function buildView(FormView $view, FormInterface $form, array $options): $view->vars['list'] = $options['list']; } - public function getBlockPrefix(): string { return 'data_list_text'; diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeDocumentsTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeDocumentsTransformer.php index da372aef..d98dbe2e 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeDocumentsTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeDocumentsTransformer.php @@ -6,9 +6,9 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Persistence\ObjectManager; -use RZ\Roadiz\CoreBundle\Entity\Document; use RZ\Roadiz\CoreBundle\Entity\Attribute; use RZ\Roadiz\CoreBundle\Entity\AttributeDocuments; +use RZ\Roadiz\CoreBundle\Entity\Document; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; @@ -23,6 +23,7 @@ public function __construct(private readonly ObjectManager $manager, private rea * to Document entities for displaying in document VueJS component. * * @param AttributeDocuments[]|null $value + * * @return Document[] */ public function transform(mixed $value): array @@ -40,7 +41,6 @@ public function transform(mixed $value): array /** * @param array $value - * @return ArrayCollection */ public function reverseTransform(mixed $value): ArrayCollection { @@ -56,10 +56,7 @@ public function reverseTransform(mixed $value): ArrayCollection ->find($documentId) ; if (null === $document) { - throw new TransformationFailedException(sprintf( - 'A document with id "%s" does not exist!', - $documentId - )); + throw new TransformationFailedException(sprintf('A document with id "%s" does not exist!', $documentId)); } $ttd = new AttributeDocuments($this->attribute, $document); @@ -67,7 +64,7 @@ public function reverseTransform(mixed $value): ArrayCollection $this->manager->persist($ttd); $documents->add($ttd); - $position++; + ++$position; } return $documents; diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeGroupTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeGroupTransformer.php index 8fb7c550..7180052a 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeGroupTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/AttributeGroupTransformer.php @@ -10,16 +10,12 @@ use Symfony\Component\Form\Exception\TransformationFailedException; /** - * Class AttributeGroupTransformer - * @package RZ\Roadiz\CoreBundle\Form\DataTransformer + * Class AttributeGroupTransformer. */ class AttributeGroupTransformer implements DataTransformerInterface { private ObjectManager $manager; - /** - * @param ObjectManager $manager - */ public function __construct(ObjectManager $manager) { $this->manager = $manager; @@ -27,20 +23,16 @@ public function __construct(ObjectManager $manager) /** * @param AttributeGroup|null $value - * @return int|string */ public function transform(mixed $value): int|string { if (!$value instanceof AttributeGroup) { return ''; } + return $value->getId(); } - /** - * @param mixed $value - * @return null|AttributeGroup - */ public function reverseTransform(mixed $value): ?AttributeGroup { if (!$value) { @@ -56,10 +48,7 @@ public function reverseTransform(mixed $value): ?AttributeGroup // causes a validation error // this message is not shown to the user // see the invalid_message option - throw new TransformationFailedException(sprintf( - 'A attribute-group with id "%s" does not exist!', - $value - )); + throw new TransformationFailedException(sprintf('A attribute-group with id "%s" does not exist!', $value)); } return $attributeGroup; diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/DocumentCollectionTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/DocumentCollectionTransformer.php index 28fe6359..ffb7103f 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/DocumentCollectionTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/DocumentCollectionTransformer.php @@ -7,15 +7,8 @@ use Doctrine\Persistence\ObjectManager; use RZ\Roadiz\CoreBundle\Entity\Document; -/** - * @package RZ\Roadiz\CoreBundle\Form\DataTransformer - */ class DocumentCollectionTransformer extends EntityCollectionTransformer { - /** - * @param ObjectManager $manager - * @param bool $asCollection - */ public function __construct(ObjectManager $manager, bool $asCollection = false) { parent::__construct($manager, Document::class, $asCollection); diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/EntityCollectionTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/EntityCollectionTransformer.php index bee48792..6d5abccc 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/EntityCollectionTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/EntityCollectionTransformer.php @@ -10,9 +10,6 @@ use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; -/** - * @package RZ\Roadiz\CoreBundle\Form\DataTransformer - */ class EntityCollectionTransformer implements DataTransformerInterface { protected bool $asCollection; @@ -23,9 +20,7 @@ class EntityCollectionTransformer implements DataTransformerInterface private string $classname; /** - * @param ObjectManager $manager * @param class-string $classname - * @param bool $asCollection */ public function __construct(ObjectManager $manager, string $classname, bool $asCollection = false) { @@ -36,7 +31,6 @@ public function __construct(ObjectManager $manager, string $classname, bool $asC /** * @param iterable|mixed|null $value - * @return string|array */ public function transform(mixed $value): string|array { @@ -51,11 +45,13 @@ public function transform(mixed $value): string|array if ($this->asCollection) { return $ids; } + return implode(',', $ids); } /** * @param string|array|null $value + * * @return array|ArrayCollection */ public function reverseTransform(mixed $value): array|ArrayCollection @@ -64,6 +60,7 @@ public function reverseTransform(mixed $value): array|ArrayCollection if ($this->asCollection) { return new ArrayCollection(); } + return []; } @@ -82,11 +79,7 @@ public function reverseTransform(mixed $value): array|ArrayCollection ->find($entityId) ; if (null === $entity) { - throw new TransformationFailedException(sprintf( - 'A %s with id "%s" does not exist!', - $this->classname, - $entityId - )); + throw new TransformationFailedException(sprintf('A %s with id "%s" does not exist!', $this->classname, $entityId)); } $entities[] = $entity; @@ -94,6 +87,7 @@ public function reverseTransform(mixed $value): array|ArrayCollection if ($this->asCollection) { return new ArrayCollection($entities); } + return $entities; } } diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/ExplorerProviderItemTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/ExplorerProviderItemTransformer.php index f94a7863..bc88ff0e 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/ExplorerProviderItemTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/ExplorerProviderItemTransformer.php @@ -16,24 +16,16 @@ class ExplorerProviderItemTransformer implements DataTransformerInterface protected bool $multiple; protected bool $useCollection; - /** - * @param ExplorerProviderInterface $explorerProvider - * @param bool $multiple - * @param bool $useCollection - */ public function __construct( ExplorerProviderInterface $explorerProvider, bool $multiple = true, - bool $useCollection = false + bool $useCollection = false, ) { $this->explorerProvider = $explorerProvider; $this->multiple = $multiple; $this->useCollection = $useCollection; } - /** - * @inheritDoc - */ public function transform(mixed $value): array|string { if (!empty($value) && $this->explorerProvider->supports($value)) { @@ -41,6 +33,7 @@ public function transform(mixed $value): array|string if (!$item instanceof ExplorerItemInterface) { throw new TransformationFailedException('Cannot transform model to ExplorerItem.'); } + return [$item]; } elseif (!empty($value) && is_iterable($value)) { $idArray = []; @@ -58,12 +51,10 @@ public function transform(mixed $value): array|string return array_filter($idArray); } + return ''; } - /** - * @inheritDoc - */ public function reverseTransform(mixed $value): mixed { if (empty($value)) { @@ -89,8 +80,10 @@ public function reverseTransform(mixed $value): mixed if ($this->useCollection) { return new ArrayCollection(array_filter($originals)); } + return array_filter($originals); } + return array_filter($originals)[0] ?? null; } } diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/FolderCollectionTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/FolderCollectionTransformer.php index a234bcac..98e11644 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/FolderCollectionTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/FolderCollectionTransformer.php @@ -7,15 +7,8 @@ use Doctrine\Persistence\ObjectManager; use RZ\Roadiz\CoreBundle\Entity\Folder; -/** - * @package RZ\Roadiz\CoreBundle\Form\DataTransformer - */ class FolderCollectionTransformer extends EntityCollectionTransformer { - /** - * @param ObjectManager $manager - * @param bool $asCollection - */ public function __construct(ObjectManager $manager, bool $asCollection = false) { parent::__construct($manager, Folder::class, $asCollection); diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/JoinDataTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/JoinDataTransformer.php index 5259300a..18ea79c9 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/JoinDataTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/JoinDataTransformer.php @@ -11,9 +11,6 @@ class JoinDataTransformer implements DataTransformerInterface { - /** - * @var NodeTypeField - */ private NodeTypeField $nodeTypeField; private ManagerRegistry $managerRegistry; /** @@ -22,14 +19,12 @@ class JoinDataTransformer implements DataTransformerInterface private string $entityClassname; /** - * @param NodeTypeField $nodeTypeField - * @param ManagerRegistry $managerRegistry * @param class-string $entityClassname */ public function __construct( NodeTypeField $nodeTypeField, ManagerRegistry $managerRegistry, - string $entityClassname + string $entityClassname, ) { $this->nodeTypeField = $nodeTypeField; $this->entityClassname = $entityClassname; @@ -37,8 +32,7 @@ public function __construct( } /** - * @param mixed $value - * @return array JoinDataTransformer must always return an array for view data. + * @return array joinDataTransformer must always return an array for view data */ public function transform(mixed $value): array { @@ -46,8 +40,8 @@ public function transform(mixed $value): array * If model is already an PersistableInterface */ if ( - !empty($value) && - $value instanceof PersistableInterface + !empty($value) + && $value instanceof PersistableInterface ) { return [$value->getId()]; } elseif (!empty($value) && is_iterable($value)) { @@ -60,15 +54,16 @@ public function transform(mixed $value): array $idArray[] = $entity->getId(); } } + return $idArray; } elseif (!empty($value)) { return [$value]; } + return []; } /** - * @param mixed $value * @return array|object|null */ public function reverseTransform(mixed $value): mixed @@ -85,6 +80,7 @@ public function reverseTransform(mixed $value): mixed return array_search($a->getId(), $value) - array_search($b->getId(), $value); }); + return $unorderedEntities; } if ($this->nodeTypeField->isManyToOne()) { @@ -92,6 +88,7 @@ public function reverseTransform(mixed $value): mixed 'id' => $value, ]); } + return null; } } diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/NodeTypeTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/NodeTypeTransformer.php index afe915d9..730255ad 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/NodeTypeTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/NodeTypeTransformer.php @@ -20,20 +20,16 @@ public function __construct(ObjectManager $manager) /** * @param NodeType|null $value - * @return int|string */ public function transform(mixed $value): int|string { if (!$value instanceof NodeType) { return ''; } + return $value->getId(); } - /** - * @param mixed $value - * @return null|NodeType - */ public function reverseTransform(mixed $value): ?NodeType { if (!$value) { @@ -49,10 +45,7 @@ public function reverseTransform(mixed $value): ?NodeType // causes a validation error // this message is not shown to the user // see the invalid_message option - throw new TransformationFailedException(sprintf( - 'A node-type with id "%s" does not exist!', - $value - )); + throw new TransformationFailedException(sprintf('A node-type with id "%s" does not exist!', $value)); } return $nodeType; diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/PersistableTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/PersistableTransformer.php index 28a272c3..f859df1a 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/PersistableTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/PersistableTransformer.php @@ -20,7 +20,6 @@ class PersistableTransformer implements DataTransformerInterface private EntityManagerInterface $entityManager; /** - * @param EntityManagerInterface $entityManager * @param class-string $doctrineEntity */ public function __construct(EntityManagerInterface $entityManager, string $doctrineEntity) @@ -39,6 +38,7 @@ public function transform(mixed $value): mixed if ($value instanceof PersistableInterface) { return $value->getId(); } + return null; } @@ -47,8 +47,9 @@ public function reverseTransform(mixed $value): ?array if (null === $value) { return null; } + return $this->entityManager->getRepository($this->doctrineEntity)->findBy([ - 'id' => $value + 'id' => $value, ]); } } diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/ProviderDataTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/ProviderDataTransformer.php index 205f4102..0da320a2 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/ProviderDataTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/ProviderDataTransformer.php @@ -13,20 +13,12 @@ class ProviderDataTransformer implements DataTransformerInterface protected NodeTypeField $nodeTypeField; protected ExplorerProviderInterface $provider; - /** - * @param NodeTypeField $nodeTypeField - * @param ExplorerProviderInterface $provider - */ public function __construct(NodeTypeField $nodeTypeField, ExplorerProviderInterface $provider) { $this->nodeTypeField = $nodeTypeField; $this->provider = $provider; } - /** - * @param mixed $value - * @return array|null - */ public function transform(mixed $value): ?array { if (null === $value) { @@ -39,23 +31,19 @@ public function transform(mixed $value): ?array $value = array_filter($value); - if (count($value) === 0) { + if (0 === count($value)) { return null; } return $this->provider->getItemsById($value); } - /** - * @param mixed $value - * @return mixed - */ public function reverseTransform(mixed $value): mixed { if ( - is_array($value) && - $this->nodeTypeField->isSingleProvider() && - isset($value[0]) + is_array($value) + && $this->nodeTypeField->isSingleProvider() + && isset($value[0]) ) { return $value[0]; } diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/ReversePersistableTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/ReversePersistableTransformer.php index 11f6c497..8cb1111a 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/ReversePersistableTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/ReversePersistableTransformer.php @@ -17,13 +17,9 @@ class ReversePersistableTransformer implements DataTransformerInterface * @var class-string */ protected string $doctrineEntity; - /** - * @var EntityManagerInterface - */ private EntityManagerInterface $entityManager; /** - * @param EntityManagerInterface $entityManager * @param class-string $doctrineEntity */ public function __construct(EntityManagerInterface $entityManager, string $doctrineEntity) @@ -37,8 +33,9 @@ public function transform(mixed $value): ?array if (null === $value) { return null; } + return $this->entityManager->getRepository($this->doctrineEntity)->findBy([ - 'id' => $value + 'id' => $value, ]); } @@ -52,6 +49,7 @@ public function reverseTransform(mixed $value): mixed if ($value instanceof PersistableInterface) { return $value->getId(); } + return null; } } diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/TagTranslationDocumentsTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/TagTranslationDocumentsTransformer.php index ad9b53f9..9277340b 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/TagTranslationDocumentsTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/TagTranslationDocumentsTransformer.php @@ -13,18 +13,13 @@ use Symfony\Component\Form\Exception\TransformationFailedException; /** - * Class TagTranslationDocumentsTransformer - * @package RZ\Roadiz\CoreBundle\Form\DataTransformer + * Class TagTranslationDocumentsTransformer. */ class TagTranslationDocumentsTransformer implements DataTransformerInterface { private ObjectManager $manager; private TagTranslation $tagTranslation; - /** - * @param ObjectManager $manager - * @param TagTranslation $tagTranslation - */ public function __construct(ObjectManager $manager, TagTranslation $tagTranslation) { $this->manager = $manager; @@ -36,6 +31,7 @@ public function __construct(ObjectManager $manager, TagTranslation $tagTranslati * to Document entities for displaying in document VueJS component. * * @param TagTranslationDocuments[]|null $value + * * @return Document[] */ public function transform(mixed $value): array @@ -53,7 +49,6 @@ public function transform(mixed $value): array /** * @param array $value - * @return ArrayCollection */ public function reverseTransform(mixed $value): ArrayCollection { @@ -69,10 +64,7 @@ public function reverseTransform(mixed $value): ArrayCollection ->find($documentId) ; if (null === $document) { - throw new TransformationFailedException(sprintf( - 'A document with id "%s" does not exist!', - $documentId - )); + throw new TransformationFailedException(sprintf('A document with id "%s" does not exist!', $documentId)); } $ttd = new TagTranslationDocuments($this->tagTranslation, $document); @@ -80,7 +72,7 @@ public function reverseTransform(mixed $value): ArrayCollection $this->manager->persist($ttd); $documents->add($ttd); - $position++; + ++$position; } return $documents; diff --git a/lib/RoadizCoreBundle/src/Form/DataTransformer/TranslationTransformer.php b/lib/RoadizCoreBundle/src/Form/DataTransformer/TranslationTransformer.php index a28baf6b..4291fb24 100644 --- a/lib/RoadizCoreBundle/src/Form/DataTransformer/TranslationTransformer.php +++ b/lib/RoadizCoreBundle/src/Form/DataTransformer/TranslationTransformer.php @@ -21,20 +21,16 @@ public function __construct(ManagerRegistry $managerRegistry) /** * @param Translation|null $value - * @return int|string */ public function transform(mixed $value): int|string { if (!($value instanceof PersistableInterface)) { return ''; } + return $value->getId(); } - /** - * @param mixed $value - * @return null|Translation - */ public function reverseTransform(mixed $value): ?Translation { if (!$value) { @@ -51,10 +47,7 @@ public function reverseTransform(mixed $value): ?Translation // causes a validation error // this message is not shown to the user // see the invalid_message option - throw new TransformationFailedException(sprintf( - 'A translation with id "%s" does not exist!', - $value - )); + throw new TransformationFailedException(sprintf('A translation with id "%s" does not exist!', $value)); } return $translation; diff --git a/lib/RoadizCoreBundle/src/Form/DocumentCollectionType.php b/lib/RoadizCoreBundle/src/Form/DocumentCollectionType.php index be057e78..0d28ccd1 100644 --- a/lib/RoadizCoreBundle/src/Form/DocumentCollectionType.php +++ b/lib/RoadizCoreBundle/src/Form/DocumentCollectionType.php @@ -5,8 +5,8 @@ namespace RZ\Roadiz\CoreBundle\Form; use Doctrine\Persistence\ManagerRegistry; -use RZ\Roadiz\CoreBundle\Form\DataTransformer\DocumentCollectionTransformer; use RZ\Roadiz\CoreBundle\Entity\Document; +use RZ\Roadiz\CoreBundle\Form\DataTransformer\DocumentCollectionTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; @@ -16,17 +16,11 @@ class DocumentCollectionType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addModelTransformer(new DocumentCollectionTransformer( @@ -35,9 +29,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void )); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -49,17 +40,11 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'documents'; diff --git a/lib/RoadizCoreBundle/src/Form/EnumerationType.php b/lib/RoadizCoreBundle/src/Form/EnumerationType.php index d97578a1..783d1d58 100644 --- a/lib/RoadizCoreBundle/src/Form/EnumerationType.php +++ b/lib/RoadizCoreBundle/src/Form/EnumerationType.php @@ -15,9 +15,6 @@ */ class EnumerationType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -36,6 +33,7 @@ public function configureOptions(OptionsResolver $resolver): void $value = trim($value); $choices[$value] = $value; } + return $choices; }); @@ -43,6 +41,7 @@ public function configureOptions(OptionsResolver $resolver): void if ('' !== $options['nodeTypeField']->getPlaceholder()) { $placeholder = $options['nodeTypeField']->getPlaceholder(); } + return $placeholder; }); @@ -50,16 +49,12 @@ public function configureOptions(OptionsResolver $resolver): void return $options['nodeTypeField']->isExpanded(); }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'enumeration'; diff --git a/lib/RoadizCoreBundle/src/Form/Error/FormErrorSerializer.php b/lib/RoadizCoreBundle/src/Form/Error/FormErrorSerializer.php index 4837bdc5..4e4add2f 100644 --- a/lib/RoadizCoreBundle/src/Form/Error/FormErrorSerializer.php +++ b/lib/RoadizCoreBundle/src/Form/Error/FormErrorSerializer.php @@ -34,9 +34,9 @@ public function getErrorsAsArray(FormInterface $form): array } if (is_object($cause)) { if ($cause instanceof \Exception) { - $errors[$errorFieldName . '_cause_message'] = $cause->getMessage(); + $errors[$errorFieldName.'_cause_message'] = $cause->getMessage(); } - $errors[$errorFieldName . '_cause'] = get_class($cause); + $errors[$errorFieldName.'_cause'] = get_class($cause); } } } @@ -48,6 +48,7 @@ public function getErrorsAsArray(FormInterface $form): array $errors[$key] = $err; } } + return $errors; } } diff --git a/lib/RoadizCoreBundle/src/Form/ExplorerProviderItemType.php b/lib/RoadizCoreBundle/src/Form/ExplorerProviderItemType.php index 335438af..d8fb8708 100644 --- a/lib/RoadizCoreBundle/src/Form/ExplorerProviderItemType.php +++ b/lib/RoadizCoreBundle/src/Form/ExplorerProviderItemType.php @@ -4,8 +4,8 @@ namespace RZ\Roadiz\CoreBundle\Form; -use RZ\Roadiz\CoreBundle\Form\DataTransformer\ExplorerProviderItemTransformer; use RZ\Roadiz\CoreBundle\Explorer\ExplorerProviderInterface; +use RZ\Roadiz\CoreBundle\Form\DataTransformer\ExplorerProviderItemTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\FormBuilderInterface; @@ -13,15 +13,8 @@ use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\OptionsResolver; -/** - * @package RZ\Roadiz\CoreBundle\Form - */ class ExplorerProviderItemType extends AbstractType { - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addModelTransformer(new ExplorerProviderItemTransformer( @@ -33,10 +26,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void /** * Pass data to form twig template. - * - * @param FormView $view - * @param FormInterface $form - * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options): void { @@ -48,24 +37,18 @@ public function buildView(FormView $view, FormInterface $form, array $options): if ($options['min_length'] > 0) { $view->vars['attr']['data-min-length'] = $options['min_length']; } - if ($options['asMultiple'] === false) { + if (false === $options['asMultiple']) { $view->vars['attr']['data-max-length'] = 1; } $view->vars['provider_class'] = get_class($options['explorerProvider']); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'explorer_provider'; } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -85,9 +68,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('useCollection', ['bool']); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return HiddenType::class; diff --git a/lib/RoadizCoreBundle/src/Form/ExtendedBooleanType.php b/lib/RoadizCoreBundle/src/Form/ExtendedBooleanType.php index 8bacddc1..bcf6fc81 100644 --- a/lib/RoadizCoreBundle/src/Form/ExtendedBooleanType.php +++ b/lib/RoadizCoreBundle/src/Form/ExtendedBooleanType.php @@ -13,9 +13,6 @@ */ class ExtendedBooleanType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -28,16 +25,12 @@ public function configureOptions(OptionsResolver $resolver): void 'expanded' => true, ]); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'extendedboolean'; diff --git a/lib/RoadizCoreBundle/src/Form/GroupsType.php b/lib/RoadizCoreBundle/src/Form/GroupsType.php index 06cbaa8d..2374cb10 100644 --- a/lib/RoadizCoreBundle/src/Form/GroupsType.php +++ b/lib/RoadizCoreBundle/src/Form/GroupsType.php @@ -23,21 +23,14 @@ class GroupsType extends AbstractType protected AuthorizationCheckerInterface $authorizationChecker; protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - * @param AuthorizationCheckerInterface $authorizationChecker - */ public function __construct( ManagerRegistry $managerRegistry, - AuthorizationCheckerInterface $authorizationChecker + AuthorizationCheckerInterface $authorizationChecker, ) { $this->authorizationChecker = $authorizationChecker; $this->managerRegistry = $managerRegistry; } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addModelTransformer(new CallbackTransformer(function ($modelToForm) { @@ -45,25 +38,24 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if ($modelToForm instanceof Collection) { $modelToForm = $modelToForm->toArray(); } + return array_map(function (Group $group) { return $group->getId(); }, $modelToForm); } + return null; }, function ($formToModels) { - if (null === $formToModels || (is_array($formToModels) && count($formToModels) === 0)) { + if (null === $formToModels || (is_array($formToModels) && 0 === count($formToModels))) { return []; } + return $this->managerRegistry->getRepository(Group::class)->findBy([ - 'id' => $formToModels + 'id' => $formToModels, ]); })); } - - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([]); @@ -80,19 +72,16 @@ public function configureOptions(OptionsResolver $resolver): void $choices[$group->getName()] = $group->getId(); } } + return $choices; }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'groups'; diff --git a/lib/RoadizCoreBundle/src/Form/HoneypotType.php b/lib/RoadizCoreBundle/src/Form/HoneypotType.php index 215128f8..4ddc0b3f 100644 --- a/lib/RoadizCoreBundle/src/Form/HoneypotType.php +++ b/lib/RoadizCoreBundle/src/Form/HoneypotType.php @@ -16,17 +16,11 @@ class HoneypotType extends AbstractType { - /** - * @inheritDoc - */ public function getParent(): ?string { return TextType::class; } - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); @@ -34,26 +28,20 @@ public function buildView(FormView $view, FormInterface $form, array $options): $view->vars['attr'] = [ 'autocomplete' => 'nope', 'tabindex' => -1, - 'style' => 'position: fixed; left: -100vw; top: -100vh;' + 'style' => 'position: fixed; left: -100vw; top: -100vh;', ]; } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'label' => false, 'required' => false, - 'mapped' => false, - 'data' => '', + 'mapped' => false, + 'data' => '', ]); } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { diff --git a/lib/RoadizCoreBundle/src/Form/JsonType.php b/lib/RoadizCoreBundle/src/Form/JsonType.php index 6350208f..3d0cb1d4 100644 --- a/lib/RoadizCoreBundle/src/Form/JsonType.php +++ b/lib/RoadizCoreBundle/src/Form/JsonType.php @@ -16,24 +16,16 @@ */ class JsonType extends AbstractType { - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextareaType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'json'; } - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); @@ -46,8 +38,8 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefaults([ 'required' => false, 'constraints' => [ - new ValidJson() - ] + new ValidJson(), + ], ]); } } diff --git a/lib/RoadizCoreBundle/src/Form/LoginRequestForm.php b/lib/RoadizCoreBundle/src/Form/LoginRequestForm.php index 7d7ccf99..4b91cb0c 100644 --- a/lib/RoadizCoreBundle/src/Form/LoginRequestForm.php +++ b/lib/RoadizCoreBundle/src/Form/LoginRequestForm.php @@ -26,9 +26,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'login_request'; diff --git a/lib/RoadizCoreBundle/src/Form/LoginResetForm.php b/lib/RoadizCoreBundle/src/Form/LoginResetForm.php index d9bfc73e..830b31ce 100644 --- a/lib/RoadizCoreBundle/src/Form/LoginResetForm.php +++ b/lib/RoadizCoreBundle/src/Form/LoginResetForm.php @@ -12,9 +12,6 @@ class LoginResetForm extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('token', HiddenType::class, [ @@ -34,17 +31,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'login_reset'; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired([ diff --git a/lib/RoadizCoreBundle/src/Form/MarkdownType.php b/lib/RoadizCoreBundle/src/Form/MarkdownType.php index f2d90190..c93dcf1a 100644 --- a/lib/RoadizCoreBundle/src/Form/MarkdownType.php +++ b/lib/RoadizCoreBundle/src/Form/MarkdownType.php @@ -15,24 +15,16 @@ */ class MarkdownType extends AbstractType { - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextareaType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'markdown'; } - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); diff --git a/lib/RoadizCoreBundle/src/Form/MultipleEnumerationType.php b/lib/RoadizCoreBundle/src/Form/MultipleEnumerationType.php index aefdecf2..54dc6920 100644 --- a/lib/RoadizCoreBundle/src/Form/MultipleEnumerationType.php +++ b/lib/RoadizCoreBundle/src/Form/MultipleEnumerationType.php @@ -15,9 +15,6 @@ */ class MultipleEnumerationType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -32,6 +29,7 @@ public function configureOptions(OptionsResolver $resolver): void if ('' !== $options['nodeTypeField']->getPlaceholder()) { $placeholder = $options['nodeTypeField']->getPlaceholder(); } + return $placeholder; }); @@ -42,6 +40,7 @@ public function configureOptions(OptionsResolver $resolver): void $value = trim($value); $choices[$value] = $value; } + return $choices; }); @@ -49,16 +48,12 @@ public function configureOptions(OptionsResolver $resolver): void return $options['nodeTypeField']->isExpanded(); }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'enumeration'; diff --git a/lib/RoadizCoreBundle/src/Form/NodeStatesType.php b/lib/RoadizCoreBundle/src/Form/NodeStatesType.php index 50c2cbac..79b24cec 100644 --- a/lib/RoadizCoreBundle/src/Form/NodeStatesType.php +++ b/lib/RoadizCoreBundle/src/Form/NodeStatesType.php @@ -14,9 +14,6 @@ */ class NodeStatesType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $choices = []; @@ -31,16 +28,12 @@ public function configureOptions(OptionsResolver $resolver): void 'placeholder' => 'ignore', ]); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'node_statuses'; diff --git a/lib/RoadizCoreBundle/src/Form/NodeTypesType.php b/lib/RoadizCoreBundle/src/Form/NodeTypesType.php index 6c340b31..4c98d70d 100644 --- a/lib/RoadizCoreBundle/src/Form/NodeTypesType.php +++ b/lib/RoadizCoreBundle/src/Form/NodeTypesType.php @@ -18,17 +18,11 @@ class NodeTypesType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -37,7 +31,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('showInvisible', ['boolean']); $resolver->setNormalizer('choices', function (Options $options, $choices) { $criteria = []; - if ($options['showInvisible'] === false) { + if (false === $options['showInvisible']) { $criteria['visible'] = true; } $nodeTypes = $this->managerRegistry->getRepository(NodeType::class)->findBy($criteria); @@ -51,16 +45,12 @@ public function configureOptions(OptionsResolver $resolver): void return $choices; }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'node_types'; diff --git a/lib/RoadizCoreBundle/src/Form/NodesType.php b/lib/RoadizCoreBundle/src/Form/NodesType.php index e3d450d5..bfbe9e0e 100644 --- a/lib/RoadizCoreBundle/src/Form/NodesType.php +++ b/lib/RoadizCoreBundle/src/Form/NodesType.php @@ -23,9 +23,6 @@ class NodesType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; @@ -40,20 +37,22 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if (!is_array($mixedEntities)) { return [$mixedEntities]; } + return $mixedEntities; }, function ($mixedIds) use ($options) { /** @var NodeRepository $repository */ $repository = $this->managerRegistry ->getRepository(Node::class) ->setDisplayingAllNodesStatuses(true); - if (\is_array($mixedIds) && count($mixedIds) === 0) { + if (\is_array($mixedIds) && 0 === count($mixedIds)) { return []; } elseif (\is_array($mixedIds)) { - if ($options['multiple'] === false) { + if (false === $options['multiple']) { return $repository->findOneBy(['id' => $mixedIds]); } + return $repository->findBy(['id' => $mixedIds]); - } elseif ($options['multiple'] === true) { + } elseif (true === $options['multiple']) { return []; } else { return $repository->findOneById($mixedIds); @@ -61,11 +60,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void })); } - /** - * {@inheritdoc} - * - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -76,13 +70,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('multiple', ['boolean']); } - /** - * {@inheritdoc} - * - * @param FormView $view - * @param FormInterface $form - * @param array $options - */ public function finishView(FormView $view, FormInterface $form, array $options): void { parent::finishView($view, $form, $options); @@ -94,17 +81,12 @@ public function finishView(FormView $view, FormInterface $form, array $options): $view->vars['data'] = $options['nodes']; } } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return HiddenType::class; } - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'nodes'; diff --git a/lib/RoadizCoreBundle/src/Form/RealmChoiceType.php b/lib/RoadizCoreBundle/src/Form/RealmChoiceType.php index a92877b4..337f5e57 100644 --- a/lib/RoadizCoreBundle/src/Form/RealmChoiceType.php +++ b/lib/RoadizCoreBundle/src/Form/RealmChoiceType.php @@ -16,9 +16,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) { } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -36,17 +33,11 @@ public function configureOptions(OptionsResolver $resolver): void }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'realms'; diff --git a/lib/RoadizCoreBundle/src/Form/RealmNodeType.php b/lib/RoadizCoreBundle/src/Form/RealmNodeType.php index 44fcf645..9fcf76b1 100644 --- a/lib/RoadizCoreBundle/src/Form/RealmNodeType.php +++ b/lib/RoadizCoreBundle/src/Form/RealmNodeType.php @@ -25,10 +25,10 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'help' => 'realm_node.inheritanceType.help', 'required' => true, 'choices' => [ - 'realm_node.' . RealmInterface::INHERITANCE_ROOT => RealmInterface::INHERITANCE_ROOT, - 'realm_node.' . RealmInterface::INHERITANCE_AUTO => RealmInterface::INHERITANCE_AUTO, - 'realm_node.' . RealmInterface::INHERITANCE_NONE => RealmInterface::INHERITANCE_NONE, - ] + 'realm_node.'.RealmInterface::INHERITANCE_ROOT => RealmInterface::INHERITANCE_ROOT, + 'realm_node.'.RealmInterface::INHERITANCE_AUTO => RealmInterface::INHERITANCE_AUTO, + 'realm_node.'.RealmInterface::INHERITANCE_NONE => RealmInterface::INHERITANCE_NONE, + ], ]); } diff --git a/lib/RoadizCoreBundle/src/Form/RealmType.php b/lib/RoadizCoreBundle/src/Form/RealmType.php index def44935..f76007c8 100644 --- a/lib/RoadizCoreBundle/src/Form/RealmType.php +++ b/lib/RoadizCoreBundle/src/Form/RealmType.php @@ -27,19 +27,19 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'help' => 'realm.type.help', 'required' => true, 'choices' => [ - 'realm.' . RealmInterface::TYPE_PLAIN_PASSWORD => RealmInterface::TYPE_PLAIN_PASSWORD, - 'realm.' . RealmInterface::TYPE_ROLE => RealmInterface::TYPE_ROLE, - 'realm.' . RealmInterface::TYPE_USER => RealmInterface::TYPE_USER, - ] + 'realm.'.RealmInterface::TYPE_PLAIN_PASSWORD => RealmInterface::TYPE_PLAIN_PASSWORD, + 'realm.'.RealmInterface::TYPE_ROLE => RealmInterface::TYPE_ROLE, + 'realm.'.RealmInterface::TYPE_USER => RealmInterface::TYPE_USER, + ], ])->add('behaviour', ChoiceType::class, [ 'label' => 'realm.behaviour', 'help' => 'realm.behaviour.help', 'required' => true, 'choices' => [ - 'realm.behaviour_' . RealmInterface::BEHAVIOUR_NONE => RealmInterface::BEHAVIOUR_NONE, - 'realm.behaviour_' . RealmInterface::BEHAVIOUR_DENY => RealmInterface::BEHAVIOUR_DENY, - 'realm.behaviour_' . RealmInterface::BEHAVIOUR_HIDE_BLOCKS => RealmInterface::BEHAVIOUR_HIDE_BLOCKS, - ] + 'realm.behaviour_'.RealmInterface::BEHAVIOUR_NONE => RealmInterface::BEHAVIOUR_NONE, + 'realm.behaviour_'.RealmInterface::BEHAVIOUR_DENY => RealmInterface::BEHAVIOUR_DENY, + 'realm.behaviour_'.RealmInterface::BEHAVIOUR_HIDE_BLOCKS => RealmInterface::BEHAVIOUR_HIDE_BLOCKS, + ], ])->add('plainPassword', TextType::class, [ 'label' => 'realm.plainPassword', 'help' => 'realm.plainPassword.help', @@ -68,7 +68,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefault('data_class', Realm::class); $resolver->setDefault('constraints', [ new UniqueEntity(['name']), - new UniqueEntity(['serializationGroup']) + new UniqueEntity(['serializationGroup']), ]); } } diff --git a/lib/RoadizCoreBundle/src/Form/RecaptchaType.php b/lib/RoadizCoreBundle/src/Form/RecaptchaType.php index a44912b7..cb0706e7 100644 --- a/lib/RoadizCoreBundle/src/Form/RecaptchaType.php +++ b/lib/RoadizCoreBundle/src/Form/RecaptchaType.php @@ -11,19 +11,18 @@ use Symfony\Component\OptionsResolver\OptionsResolver; /** - * This class creates recaptcha element + * This class creates recaptcha element. * * @author Nikolay Georgiev + * * @since 1.0 */ class RecaptchaType extends AbstractType { /** - * (non-PHPdoc) + * (non-PHPdoc). + * * @see \Symfony\Component\Form\AbstractType::buildView() - * @param FormView $view - * @param FormInterface $form - * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options): void { @@ -32,13 +31,12 @@ public function buildView(FormView $view, FormInterface $form, array $options): /** * @see \Symfony\Component\Form\AbstractType::configureOptions() - * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'configs' => [ - 'publicKey' => '' + 'publicKey' => '', ], ]); } diff --git a/lib/RoadizCoreBundle/src/Form/RoleEntityType.php b/lib/RoadizCoreBundle/src/Form/RoleEntityType.php index 0ac24b40..d49c28e3 100644 --- a/lib/RoadizCoreBundle/src/Form/RoleEntityType.php +++ b/lib/RoadizCoreBundle/src/Form/RoleEntityType.php @@ -6,23 +6,20 @@ use Doctrine\Persistence\ManagerRegistry; use RZ\Roadiz\CoreBundle\Entity\Role; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; -use Symfony\Bundle\SecurityBundle\Security; final class RoleEntityType extends AbstractType { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly Security $security + private readonly Security $security, ) { } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -44,21 +41,16 @@ public function configureOptions(OptionsResolver $resolver): void $choices[] = $role; } } + return $choices; }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'role_entity'; diff --git a/lib/RoadizCoreBundle/src/Form/RolesType.php b/lib/RoadizCoreBundle/src/Form/RolesType.php index be9cfecf..f022aba2 100644 --- a/lib/RoadizCoreBundle/src/Form/RolesType.php +++ b/lib/RoadizCoreBundle/src/Form/RolesType.php @@ -22,21 +22,14 @@ class RolesType extends AbstractType protected ManagerRegistry $managerRegistry; protected AuthorizationCheckerInterface $authorizationChecker; - /** - * @param ManagerRegistry $managerRegistry - * @param AuthorizationCheckerInterface $authorizationChecker - */ public function __construct( ManagerRegistry $managerRegistry, - AuthorizationCheckerInterface $authorizationChecker + AuthorizationCheckerInterface $authorizationChecker, ) { $this->authorizationChecker = $authorizationChecker; $this->managerRegistry = $managerRegistry; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -56,25 +49,22 @@ public function configureOptions(OptionsResolver $resolver): void /** @var Role $role */ foreach ($roles as $role) { if ( - $this->authorizationChecker->isGranted($role->getRole()) && - !$options['roles']->contains($role) + $this->authorizationChecker->isGranted($role->getRole()) + && !$options['roles']->contains($role) ) { $choices[$role->getRole()] = $role->getId(); } } + return $choices; }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'roles'; diff --git a/lib/RoadizCoreBundle/src/Form/SeparatorType.php b/lib/RoadizCoreBundle/src/Form/SeparatorType.php index f3c05734..4b2dd1e5 100644 --- a/lib/RoadizCoreBundle/src/Form/SeparatorType.php +++ b/lib/RoadizCoreBundle/src/Form/SeparatorType.php @@ -12,18 +12,13 @@ */ class SeparatorType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ - 'required' => false + 'required' => false, ]); } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'separator'; diff --git a/lib/RoadizCoreBundle/src/Form/SettingDocumentType.php b/lib/RoadizCoreBundle/src/Form/SettingDocumentType.php index ce4ddd9f..14ccf073 100644 --- a/lib/RoadizCoreBundle/src/Form/SettingDocumentType.php +++ b/lib/RoadizCoreBundle/src/Form/SettingDocumentType.php @@ -21,24 +21,16 @@ class SettingDocumentType extends AbstractType protected AbstractDocumentFactory $documentFactory; protected FilesystemOperator $documentsStorage; - /** - * @param ManagerRegistry $managerRegistry - * @param AbstractDocumentFactory $documentFactory - * @param FilesystemOperator $documentsStorage - */ public function __construct( ManagerRegistry $managerRegistry, AbstractDocumentFactory $documentFactory, - FilesystemOperator $documentsStorage + FilesystemOperator $documentsStorage, ) { $this->documentFactory = $documentFactory; $this->managerRegistry = $managerRegistry; $this->documentsStorage = $documentsStorage; } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addModelTransformer(new CallbackTransformer( @@ -52,6 +44,7 @@ function ($value) { return new File($this->documentsStorage->publicUrl($document->getMountPath()), false); } } + return null; }, function ($file) { @@ -67,14 +60,12 @@ function ($file) { return $document->getId(); } } + return null; } )); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return FileType::class; diff --git a/lib/RoadizCoreBundle/src/Form/SettingGroupType.php b/lib/RoadizCoreBundle/src/Form/SettingGroupType.php index da3b5412..dac0481c 100644 --- a/lib/RoadizCoreBundle/src/Form/SettingGroupType.php +++ b/lib/RoadizCoreBundle/src/Form/SettingGroupType.php @@ -20,40 +20,34 @@ class SettingGroupType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addModelTransformer(new CallbackTransformer( - function (SettingGroup $settingGroup = null) { + function (?SettingGroup $settingGroup = null) { if (null !== $settingGroup) { // transform the array to a string return $settingGroup->getId(); } + return null; }, function ($id) { if (null !== $id) { $manager = $this->managerRegistry->getManagerForClass(SettingGroup::class); + return $manager->find(SettingGroup::class, $id); } + return null; } )); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -70,19 +64,16 @@ public function configureOptions(OptionsResolver $resolver): void foreach ($groups as $group) { $choices[$group->getName()] = $group->getId(); } + return $choices; }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'setting_groups'; diff --git a/lib/RoadizCoreBundle/src/Form/SettingType.php b/lib/RoadizCoreBundle/src/Form/SettingType.php index 56392a67..d9254856 100644 --- a/lib/RoadizCoreBundle/src/Form/SettingType.php +++ b/lib/RoadizCoreBundle/src/Form/SettingType.php @@ -21,20 +21,14 @@ class SettingType extends AbstractType { protected SettingTypeResolver $settingTypeResolver; - /** - * @param SettingTypeResolver $settingTypeResolver - */ public function __construct(SettingTypeResolver $settingTypeResolver) { $this->settingTypeResolver = $settingTypeResolver; } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options): void { - if ($options['shortEdit'] === false) { + if (false === $options['shortEdit']) { $builder ->add('name', TextType::class, [ 'empty_data' => '', @@ -73,7 +67,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $form = $event->getForm(); if ($setting instanceof Setting) { - if ($setting->getType() === AbstractField::DOCUMENTS_T) { + if (AbstractField::DOCUMENTS_T === $setting->getType()) { $form->add( 'value', SettingDocumentType::class, @@ -98,9 +92,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void }); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', Setting::class); @@ -119,12 +110,13 @@ protected function getFormOptionsForSetting(Setting $setting, bool $shortEdit = $values = array_map(function ($item) { return trim($item); }, $values); + return [ 'label' => $label, 'placeholder' => 'choose.value', 'required' => false, 'choices' => array_combine($values, $values), - 'multiple' => $setting->getType() === AbstractField::MULTIPLE_T + 'multiple' => AbstractField::MULTIPLE_T === $setting->getType(), ]; case AbstractField::EMAIL_T: return [ @@ -132,7 +124,7 @@ protected function getFormOptionsForSetting(Setting $setting, bool $shortEdit = 'required' => false, 'constraints' => [ new Email(), - ] + ], ]; case AbstractField::DATETIME_T: return [ diff --git a/lib/RoadizCoreBundle/src/Form/SettingTypeResolver.php b/lib/RoadizCoreBundle/src/Form/SettingTypeResolver.php index 4043b72e..b4c44bf9 100644 --- a/lib/RoadizCoreBundle/src/Form/SettingTypeResolver.php +++ b/lib/RoadizCoreBundle/src/Form/SettingTypeResolver.php @@ -41,7 +41,6 @@ class SettingTypeResolver ]; /** - * @param Setting $setting * @return class-string */ public function getSettingType(Setting $setting): string diff --git a/lib/RoadizCoreBundle/src/Form/TagTranslationDocumentType.php b/lib/RoadizCoreBundle/src/Form/TagTranslationDocumentType.php index bc82c33f..d5a32888 100644 --- a/lib/RoadizCoreBundle/src/Form/TagTranslationDocumentType.php +++ b/lib/RoadizCoreBundle/src/Form/TagTranslationDocumentType.php @@ -5,9 +5,9 @@ namespace RZ\Roadiz\CoreBundle\Form; use Doctrine\Persistence\ManagerRegistry; -use RZ\Roadiz\CoreBundle\Form\DataTransformer\TagTranslationDocumentsTransformer; use RZ\Roadiz\CoreBundle\Entity\TagTranslation; use RZ\Roadiz\CoreBundle\Entity\TagTranslationDocuments; +use RZ\Roadiz\CoreBundle\Form\DataTransformer\TagTranslationDocumentsTransformer; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\FormBuilderInterface; @@ -15,25 +15,15 @@ use Symfony\Component\Form\FormEvents; use Symfony\Component\OptionsResolver\OptionsResolver; -/** - * @package RZ\Roadiz\CoreBundle\Form\NodeSource - */ class TagTranslationDocumentType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener( @@ -46,9 +36,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void )); } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -62,17 +49,11 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('tagTranslation', [TagTranslation::class]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'documents'; } - /** - * @inheritDoc - */ public function getParent(): ?string { return CollectionType::class; @@ -80,8 +61,6 @@ public function getParent(): ?string /** * Delete existing document association. - * - * @param FormEvent $event */ public function onPostSubmit(FormEvent $event): void { diff --git a/lib/RoadizCoreBundle/src/Form/TagsType.php b/lib/RoadizCoreBundle/src/Form/TagsType.php index 2af4cb3c..e2a7b6a5 100644 --- a/lib/RoadizCoreBundle/src/Form/TagsType.php +++ b/lib/RoadizCoreBundle/src/Form/TagsType.php @@ -16,9 +16,6 @@ */ class TagsType extends AbstractType { - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); @@ -28,8 +25,6 @@ public function buildView(FormView $view, FormInterface $form, array $options): /** * Set every tags s default choices values. - * - * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver): void { @@ -39,16 +34,9 @@ public function configureOptions(OptionsResolver $resolver): void 'entry_type' => HiddenType::class, 'label' => 'list.tags.to_link', 'help' => 'use.new_or_existing.tags_with_hierarchy', - ]); + ]); } - /** - * {@inheritdoc} - * - * @param FormView $view - * @param FormInterface $form - * @param array $options - */ public function finishView(FormView $view, FormInterface $form, array $options): void { parent::finishView($view, $form, $options); @@ -59,17 +47,11 @@ public function finishView(FormView $view, FormInterface $form, array $options): $view->vars['data'] = $form->getData(); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return CollectionType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'tags'; diff --git a/lib/RoadizCoreBundle/src/Form/ThemesType.php b/lib/RoadizCoreBundle/src/Form/ThemesType.php index e47a6590..5256b841 100644 --- a/lib/RoadizCoreBundle/src/Form/ThemesType.php +++ b/lib/RoadizCoreBundle/src/Form/ThemesType.php @@ -14,9 +14,6 @@ */ class ThemesType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -32,21 +29,16 @@ public function configureOptions(OptionsResolver $resolver): void $callable = [$class, 'getThemeName']; $value[call_user_func($callable)] = $class; } + return $value; }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'classname'; diff --git a/lib/RoadizCoreBundle/src/Form/TranslationsType.php b/lib/RoadizCoreBundle/src/Form/TranslationsType.php index 5d444401..fa35b363 100644 --- a/lib/RoadizCoreBundle/src/Form/TranslationsType.php +++ b/lib/RoadizCoreBundle/src/Form/TranslationsType.php @@ -18,17 +18,11 @@ class TranslationsType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([]); @@ -48,16 +42,11 @@ public function configureOptions(OptionsResolver $resolver): void }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'translations'; diff --git a/lib/RoadizCoreBundle/src/Form/UrlAliasType.php b/lib/RoadizCoreBundle/src/Form/UrlAliasType.php index 70d9113a..e44f558a 100644 --- a/lib/RoadizCoreBundle/src/Form/UrlAliasType.php +++ b/lib/RoadizCoreBundle/src/Form/UrlAliasType.php @@ -16,17 +16,11 @@ class UrlAliasType extends AbstractType { private ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('alias', TextType::class, [ @@ -46,9 +40,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', UrlAlias::class); diff --git a/lib/RoadizCoreBundle/src/Form/UserCollectionType.php b/lib/RoadizCoreBundle/src/Form/UserCollectionType.php index e372ff50..b2df226f 100644 --- a/lib/RoadizCoreBundle/src/Form/UserCollectionType.php +++ b/lib/RoadizCoreBundle/src/Form/UserCollectionType.php @@ -23,9 +23,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->addModelTransformer(new CollectionToArrayTransformer()); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -43,17 +40,11 @@ public function configureOptions(OptionsResolver $resolver): void }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'user_collection'; diff --git a/lib/RoadizCoreBundle/src/Form/UsersType.php b/lib/RoadizCoreBundle/src/Form/UsersType.php index dcbcdcdb..fe325550 100644 --- a/lib/RoadizCoreBundle/src/Form/UsersType.php +++ b/lib/RoadizCoreBundle/src/Form/UsersType.php @@ -20,17 +20,11 @@ class UsersType extends AbstractType { private ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -50,19 +44,16 @@ public function configureOptions(OptionsResolver $resolver): void $choices[$user->getUserName()] = $user->getId(); } } + return $choices; }); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'users'; diff --git a/lib/RoadizCoreBundle/src/Form/WebhookType.php b/lib/RoadizCoreBundle/src/Form/WebhookType.php index 44eaf33e..6bea0879 100644 --- a/lib/RoadizCoreBundle/src/Form/WebhookType.php +++ b/lib/RoadizCoreBundle/src/Form/WebhookType.php @@ -20,9 +20,6 @@ class WebhookType extends AbstractType { private array $webhookMessageTypes; - /** - * @param array $webhookMessageTypes - */ public function __construct(array $webhookMessageTypes) { $this->webhookMessageTypes = $webhookMessageTypes; @@ -33,7 +30,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->add('messageType', ChoiceType::class, [ 'required' => true, 'label' => 'webhooks.messageType', - 'choices' => $this->webhookMessageTypes + 'choices' => $this->webhookMessageTypes, ])->add('description', TextType::class, [ 'required' => true, 'label' => 'webhooks.description', @@ -54,7 +51,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'required' => false, 'label' => 'webhooks.rootNode', 'help' => 'webhooks.rootNode.help', - 'multiple' => false + 'multiple' => false, ]); $builder->get('payload')->addModelTransformer(new CallbackTransformer(function (?array $model) { diff --git a/lib/RoadizCoreBundle/src/Form/WebhooksChoiceType.php b/lib/RoadizCoreBundle/src/Form/WebhooksChoiceType.php index 822dea13..41cab8a2 100644 --- a/lib/RoadizCoreBundle/src/Form/WebhooksChoiceType.php +++ b/lib/RoadizCoreBundle/src/Form/WebhooksChoiceType.php @@ -17,15 +17,10 @@ class WebhooksChoiceType extends ChoiceType { private ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - * @param ChoiceListFactoryInterface|null $choiceListFactory - * @param TranslatorInterface|null $translator - */ public function __construct( ManagerRegistry $managerRegistry, - ChoiceListFactoryInterface $choiceListFactory = null, - ?TranslatorInterface $translator = null + ?ChoiceListFactoryInterface $choiceListFactory = null, + ?TranslatorInterface $translator = null, ) { parent::__construct($choiceListFactory, $translator); $this->managerRegistry = $managerRegistry; @@ -38,11 +33,13 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if (null === $webhook) { return null; } + return $webhook->getId(); }, function (?string $id) { if (null === $id) { return null; } + return $this->managerRegistry->getRepository(Webhook::class)->find($id); })); } diff --git a/lib/RoadizCoreBundle/src/Form/YamlType.php b/lib/RoadizCoreBundle/src/Form/YamlType.php index 668ddbed..c4983245 100644 --- a/lib/RoadizCoreBundle/src/Form/YamlType.php +++ b/lib/RoadizCoreBundle/src/Form/YamlType.php @@ -16,25 +16,16 @@ */ class YamlType extends AbstractType { - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextareaType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'yaml'; } - /** - * @inheritDoc - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); @@ -47,8 +38,8 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefaults([ 'required' => false, 'constraints' => [ - new ValidYaml() - ] + new ValidYaml(), + ], ]); } } diff --git a/lib/RoadizCoreBundle/src/Importer/AttributeImporter.php b/lib/RoadizCoreBundle/src/Importer/AttributeImporter.php index a3c96fcb..321cf976 100644 --- a/lib/RoadizCoreBundle/src/Importer/AttributeImporter.php +++ b/lib/RoadizCoreBundle/src/Importer/AttributeImporter.php @@ -15,22 +15,16 @@ public function __construct(private readonly SerializerInterface $serializer) { } - /** - * @inheritDoc - */ public function supports(string $entityClass): bool { - return $entityClass === Attribute::class || $entityClass === 'array<' . Attribute::class . '>'; + return Attribute::class === $entityClass || $entityClass === 'array<'.Attribute::class.'>'; } - /** - * @inheritDoc - */ public function import(string $serializedData): bool { $this->serializer->deserialize( $serializedData, - 'array<' . Attribute::class . '>', + 'array<'.Attribute::class.'>', 'json', DeserializationContext::create() ->setAttribute(TypedObjectConstructorInterface::PERSIST_NEW_OBJECTS, true) diff --git a/lib/RoadizCoreBundle/src/Importer/ChainImporter.php b/lib/RoadizCoreBundle/src/Importer/ChainImporter.php index e975f723..0b5bfa44 100644 --- a/lib/RoadizCoreBundle/src/Importer/ChainImporter.php +++ b/lib/RoadizCoreBundle/src/Importer/ChainImporter.php @@ -16,20 +16,13 @@ public function __construct(array $importers = []) $this->importers = $importers; } - /** - * @param EntityImporterInterface $entityImporter - * - * @return ChainImporter - */ public function addImporter(EntityImporterInterface $entityImporter): self { $this->importers[] = $entityImporter; + return $this; } - /** - * @inheritDoc - */ public function supports(string $entityClass): bool { foreach ($this->importers as $importer) { @@ -41,18 +34,11 @@ public function supports(string $entityClass): bool return false; } - /** - * @inheritDoc - */ public function import(string $serializedData): bool { throw new \RuntimeException('You cannot call import method on ChainImporter, but importWithType method'); } - - /** - * @inheritDoc - */ public function importWithType(string $serializedData, string $entityClass): bool { foreach ($this->importers as $importer) { @@ -60,6 +46,7 @@ public function importWithType(string $serializedData, string $entityClass): boo return $importer->import($serializedData); } } + return false; } } diff --git a/lib/RoadizCoreBundle/src/Importer/EntityImporterInterface.php b/lib/RoadizCoreBundle/src/Importer/EntityImporterInterface.php index cf176773..0cf7108a 100644 --- a/lib/RoadizCoreBundle/src/Importer/EntityImporterInterface.php +++ b/lib/RoadizCoreBundle/src/Importer/EntityImporterInterface.php @@ -6,17 +6,7 @@ interface EntityImporterInterface { - /** - * @param string $entityClass - * - * @return bool - */ public function supports(string $entityClass): bool; - /** - * @param string $serializedData - * - * @return bool - */ public function import(string $serializedData): bool; } diff --git a/lib/RoadizCoreBundle/src/Importer/GroupsImporter.php b/lib/RoadizCoreBundle/src/Importer/GroupsImporter.php index a25934dc..19a3b211 100644 --- a/lib/RoadizCoreBundle/src/Importer/GroupsImporter.php +++ b/lib/RoadizCoreBundle/src/Importer/GroupsImporter.php @@ -13,35 +13,27 @@ class GroupsImporter implements EntityImporterInterface { protected SerializerInterface $serializer; - /** - * @param SerializerInterface $serializer - */ public function __construct(SerializerInterface $serializer) { $this->serializer = $serializer; } - /** - * @inheritDoc - */ public function supports(string $entityClass): bool { - return $entityClass === Group::class; + return Group::class === $entityClass; } - /** - * @inheritDoc - */ public function import(string $serializedData): bool { $this->serializer->deserialize( $serializedData, - 'array<' . Group::class . '>', + 'array<'.Group::class.'>', 'json', DeserializationContext::create() ->setAttribute(TypedObjectConstructorInterface::PERSIST_NEW_OBJECTS, true) ->setAttribute(TypedObjectConstructorInterface::FLUSH_NEW_OBJECTS, true) ); + return true; } } diff --git a/lib/RoadizCoreBundle/src/Importer/NodeTypesImporter.php b/lib/RoadizCoreBundle/src/Importer/NodeTypesImporter.php index 0a8c4077..aa720244 100644 --- a/lib/RoadizCoreBundle/src/Importer/NodeTypesImporter.php +++ b/lib/RoadizCoreBundle/src/Importer/NodeTypesImporter.php @@ -12,18 +12,15 @@ class NodeTypesImporter implements EntityImporterInterface { public function __construct( - protected SerializerInterface $serializer + protected SerializerInterface $serializer, ) { } public function supports(string $entityClass): bool { - return $entityClass === NodeType::class; + return NodeType::class === $entityClass; } - /** - * @inheritDoc - */ public function import(string $serializedData): bool { $this->serializer->deserialize( diff --git a/lib/RoadizCoreBundle/src/Importer/RolesImporter.php b/lib/RoadizCoreBundle/src/Importer/RolesImporter.php index ecdd5389..e46bd970 100644 --- a/lib/RoadizCoreBundle/src/Importer/RolesImporter.php +++ b/lib/RoadizCoreBundle/src/Importer/RolesImporter.php @@ -13,30 +13,21 @@ class RolesImporter implements EntityImporterInterface { protected SerializerInterface $serializer; - /** - * @param SerializerInterface $serializer - */ public function __construct(SerializerInterface $serializer) { $this->serializer = $serializer; } - /** - * @inheritDoc - */ public function supports(string $entityClass): bool { - return $entityClass === Role::class; + return Role::class === $entityClass; } - /** - * @inheritDoc - */ public function import(string $serializedData): bool { $this->serializer->deserialize( $serializedData, - 'array<' . Role::class . '>', + 'array<'.Role::class.'>', 'json', DeserializationContext::create() ->setAttribute(TypedObjectConstructorInterface::PERSIST_NEW_OBJECTS, true) diff --git a/lib/RoadizCoreBundle/src/Importer/SettingsImporter.php b/lib/RoadizCoreBundle/src/Importer/SettingsImporter.php index 41ed59c0..211acb3f 100644 --- a/lib/RoadizCoreBundle/src/Importer/SettingsImporter.php +++ b/lib/RoadizCoreBundle/src/Importer/SettingsImporter.php @@ -17,32 +17,22 @@ class SettingsImporter implements EntityImporterInterface private ManagerRegistry $managerRegistry; private SerializerInterface $serializer; - /** - * @param ManagerRegistry $managerRegistry - * @param SerializerInterface $serializer - */ public function __construct(ManagerRegistry $managerRegistry, SerializerInterface $serializer) { $this->managerRegistry = $managerRegistry; $this->serializer = $serializer; } - /** - * @inheritDoc - */ public function supports(string $entityClass): bool { - return $entityClass === Setting::class; + return Setting::class === $entityClass; } - /** - * @inheritDoc - */ public function import(string $serializedData): bool { $settings = $this->serializer->deserialize( $serializedData, - 'array<' . Setting::class . '>', + 'array<'.Setting::class.'>', 'json', DeserializationContext::create() ->setAttribute(TypedObjectConstructorInterface::PERSIST_NEW_OBJECTS, true) diff --git a/lib/RoadizCoreBundle/src/Importer/TagsImporter.php b/lib/RoadizCoreBundle/src/Importer/TagsImporter.php index 7f902f76..3d163924 100644 --- a/lib/RoadizCoreBundle/src/Importer/TagsImporter.php +++ b/lib/RoadizCoreBundle/src/Importer/TagsImporter.php @@ -14,25 +14,16 @@ class TagsImporter implements EntityImporterInterface { protected SerializerInterface $serializer; - /** - * @param SerializerInterface $serializer - */ public function __construct(SerializerInterface $serializer) { $this->serializer = $serializer; } - /** - * @inheritDoc - */ public function supports(string $entityClass): bool { - return $entityClass === Tag::class; + return Tag::class === $entityClass; } - /** - * @inheritDoc - */ public function import(string $serializedData): bool { $this->serializer->deserialize( diff --git a/lib/RoadizCoreBundle/src/ListManager/AbstractEntityListManager.php b/lib/RoadizCoreBundle/src/ListManager/AbstractEntityListManager.php index 20e2fe0d..78588ae6 100644 --- a/lib/RoadizCoreBundle/src/ListManager/AbstractEntityListManager.php +++ b/lib/RoadizCoreBundle/src/ListManager/AbstractEntityListManager.php @@ -33,18 +33,17 @@ public function __construct(protected readonly ?Request $request = null) public function setAllowRequestSorting(bool $allowRequestSorting): self { $this->allowRequestSorting = $allowRequestSorting; + return $this; } public function setAllowRequestSearching(bool $allowRequestSearching): self { $this->allowRequestSearching = $allowRequestSearching; + return $this; } - /** - * @return bool - */ public function isDisplayingNotPublishedNodes(): bool { return $this->displayNotPublishedNodes; @@ -53,12 +52,10 @@ public function isDisplayingNotPublishedNodes(): bool public function setDisplayingNotPublishedNodes(bool $displayNotPublishedNodes): self { $this->displayNotPublishedNodes = $displayNotPublishedNodes; + return $this; } - /** - * @return bool - */ public function isDisplayingAllNodesStatuses(): bool { return $this->displayAllNodesStatuses; @@ -71,12 +68,10 @@ public function isDisplayingAllNodesStatuses(): bool public function setDisplayingAllNodesStatuses(bool $displayAllNodesStatuses): self { $this->displayAllNodesStatuses = $displayAllNodesStatuses; + return $this; } - /** - * @inheritDoc - */ public function setPage(int $page): self { $this->currentPage = $page > 0 ? $page : 1; @@ -84,9 +79,6 @@ public function setPage(int $page): self return $this; } - /** - * @return int - */ protected function getPage(): int { return $this->currentPage; @@ -95,6 +87,7 @@ protected function getPage(): int public function enablePagination(): self { $this->pagination = true; + return $this; } @@ -106,9 +99,6 @@ public function disablePagination(): self return $this; } - /** - * @inheritDoc - */ public function getAssignation(): array { $assign = [ @@ -161,9 +151,6 @@ protected function getQueryString(): array return $this->queryArray ?? []; } - /** - * @return int - */ protected function getItemPerPage(): int { return $this->itemPerPage; @@ -179,9 +166,6 @@ public function setItemPerPage(int $itemPerPage): self return $this; } - /** - * @return int - */ public function getPageCount(): int { return (int) ceil($this->getItemCount() / $this->getItemPerPage()); @@ -194,6 +178,7 @@ protected function handleRequestQuery(bool $disabled): void * Disable pagination and paginator */ $this->disablePagination(); + return; } @@ -206,11 +191,11 @@ protected function handleRequestQuery(bool $disabled): void $page = $this->request->query->get('page'); if ( - $this->allowRequestSorting && - \is_string($field) && - $field !== "" && - \is_string($ordering) && - \in_array(strtolower($ordering), ['asc', 'desc']) + $this->allowRequestSorting + && \is_string($field) + && '' !== $field + && \is_string($ordering) + && \in_array(strtolower($ordering), ['asc', 'desc']) ) { $this->handleOrderingParam($field, $ordering); $this->queryArray['field'] = $field; @@ -218,24 +203,24 @@ protected function handleRequestQuery(bool $disabled): void } if ( - $this->allowRequestSearching && - \is_string($search) && - $search !== "" + $this->allowRequestSearching + && \is_string($search) + && '' !== $search ) { $this->handleSearchParam($search); $this->queryArray['search'] = $search; } if ( - \is_numeric($itemPerPage) && - ((int) $itemPerPage) > 0 + \is_numeric($itemPerPage) + && ((int) $itemPerPage) > 0 ) { $this->setItemPerPage((int) $itemPerPage); } if ( - \is_numeric($page) && - ((int) $page) > 1 + \is_numeric($page) + && ((int) $page) > 1 ) { $this->setPage((int) $page); } else { @@ -256,7 +241,7 @@ protected function handleOrderingParam(string $field, string $ordering): void protected function validateOrderingFieldName(string $field): void { // check if field is a valid name without any SQL injection - if (\preg_match('/^[a-zA-Z0-9_.]+$/', $field) !== 1) { + if (1 !== \preg_match('/^[a-zA-Z0-9_.]+$/', $field)) { throw new \InvalidArgumentException('Field name is not valid.'); } } diff --git a/lib/RoadizCoreBundle/src/ListManager/EntityListManager.php b/lib/RoadizCoreBundle/src/ListManager/EntityListManager.php index 5d98d517..3f8254bc 100644 --- a/lib/RoadizCoreBundle/src/ListManager/EntityListManager.php +++ b/lib/RoadizCoreBundle/src/ListManager/EntityListManager.php @@ -30,36 +30,28 @@ class EntityListManager extends AbstractEntityListManager protected ?TranslationInterface $translation = null; /** - * @param Request|null $request - * @param ObjectManager $entityManager * @param class-string $entityName - * @param array $filteringArray - * @param array $orderingArray */ public function __construct( ?Request $request, protected readonly ObjectManager $entityManager, protected readonly string $entityName, protected array $filteringArray = [], - protected array $orderingArray = [] + protected array $orderingArray = [], ) { parent::__construct($request); $this->assignation = []; } - /** - * @return TranslationInterface|null - */ public function getTranslation(): ?TranslationInterface { return $this->translation; } /** - * @param TranslationInterface|null $translation * @return $this */ - public function setTranslation(TranslationInterface $translation = null): self + public function setTranslation(?TranslationInterface $translation = null): self { $this->translation = $translation; @@ -70,59 +62,59 @@ public function setTranslation(TranslationInterface $translation = null): self * Handle request to find filter to apply to entity listing. * * @param bool $disabled Disable pagination and filtering over GET params - * @return void + * * @throws \ReflectionException */ public function handle(bool $disabled = false): void { // transform the key chroot in parent if (array_key_exists('chroot', $this->filteringArray)) { - if ($this->filteringArray["chroot"] instanceof Node) { + if ($this->filteringArray['chroot'] instanceof Node) { /** @var NodeRepository $nodeRepo */ $nodeRepo = $this->entityManager ->getRepository(Node::class) ->setDisplayingNotPublishedNodes($this->isDisplayingNotPublishedNodes()) ->setDisplayingAllNodesStatuses($this->isDisplayingAllNodesStatuses()); - $ids = $nodeRepo->findAllOffspringIdByNode($this->filteringArray["chroot"]); // get all offspringId + $ids = $nodeRepo->findAllOffspringIdByNode($this->filteringArray['chroot']); // get all offspringId if (array_key_exists('parent', $this->filteringArray)) { // test if parent key exist - if (is_array($this->filteringArray["parent"])) { + if (is_array($this->filteringArray['parent'])) { // test if multiple parent id if ( - count(array_intersect($this->filteringArray["parent"], $ids)) - != count($this->filteringArray["parent"]) + count(array_intersect($this->filteringArray['parent'], $ids)) + != count($this->filteringArray['parent']) ) { // test if all parent are in the chroot - $this->filteringArray["parent"] = -1; // -1 for make the search return [] + $this->filteringArray['parent'] = -1; // -1 for make the search return [] } } else { - if ($this->filteringArray["parent"] instanceof Node) { + if ($this->filteringArray['parent'] instanceof Node) { // make transform all id in int - $parent = $this->filteringArray["parent"]->getId(); + $parent = $this->filteringArray['parent']->getId(); } else { - $parent = (int) $this->filteringArray["parent"]; + $parent = (int) $this->filteringArray['parent']; } if (!in_array($parent, $ids, true)) { - $this->filteringArray["parent"] = -1; + $this->filteringArray['parent'] = -1; } } } else { - $this->filteringArray["parent"] = $ids; + $this->filteringArray['parent'] = $ids; } } - unset($this->filteringArray["chroot"]); // remove placeholder + unset($this->filteringArray['chroot']); // remove placeholder } $this->handleRequestQuery($disabled); $this->createPaginator(); if ( - $this->allowRequestSearching && - false === $disabled && - null !== $this->request + $this->allowRequestSearching + && false === $disabled + && null !== $this->request ) { $search = $this->request->query->get('search'); - if (\is_string($search) && $search !== "") { + if (\is_string($search) && '' !== $search) { $this->paginator->setSearchPattern($search); } } @@ -132,11 +124,10 @@ protected function handleOrderingParam(string $field, string $ordering): void { $this->validateOrderingFieldName($field); $this->orderingArray = [ - $field => $ordering + $field => $ordering, ]; } - /** * @throws \ReflectionException */ @@ -144,7 +135,7 @@ protected function createPaginator(): void { $reflectionClass = new \ReflectionClass($this->entityName); - if ($this->entityName === Node::class) { + if (Node::class === $this->entityName) { // @phpstan-ignore-next-line $this->paginator = new NodePaginator( $this->entityManager, @@ -154,8 +145,8 @@ protected function createPaginator(): void ); $this->paginator->setTranslation($this->translation); } elseif ( - $this->entityName === NodesSources::class || - $reflectionClass->isSubclassOf(NodesSources::class) + NodesSources::class === $this->entityName + || $reflectionClass->isSubclassOf(NodesSources::class) ) { // @phpstan-ignore-next-line $this->paginator = new NodesSourcesPaginator( @@ -178,14 +169,11 @@ protected function createPaginator(): void $this->paginator->setDisplayingAllNodesStatuses($this->isDisplayingAllNodesStatuses()); } - /** - * @return int - */ public function getItemCount(): int { if ( - $this->pagination === true && - null !== $this->paginator + true === $this->pagination + && null !== $this->paginator ) { return $this->paginator->getTotalCount(); } @@ -193,14 +181,11 @@ public function getItemCount(): int return 0; } - /** - * @return int - */ public function getPageCount(): int { if ( - $this->pagination === true && - null !== $this->paginator + true === $this->pagination + && null !== $this->paginator ) { return $this->paginator->getPageCount(); } @@ -215,8 +200,9 @@ public function getPageCount(): int */ public function getEntities(): array { - if ($this->pagination === true && null !== $this->paginator) { + if (true === $this->pagination && null !== $this->paginator) { $this->paginator->setItemsPerPage($this->getItemPerPage()); + return $this->paginator->findByAtPage($this->orderingArray, $this->currentPage); } else { $repository = $this->entityManager->getRepository($this->entityName); @@ -224,6 +210,7 @@ public function getEntities(): array $repository->setDisplayingNotPublishedNodes($this->isDisplayingNotPublishedNodes()); $repository->setDisplayingAllNodesStatuses($this->isDisplayingAllNodesStatuses()); } + return $repository->findBy( $this->filteringArray, $this->orderingArray, diff --git a/lib/RoadizCoreBundle/src/ListManager/EntityListManagerInterface.php b/lib/RoadizCoreBundle/src/ListManager/EntityListManagerInterface.php index 3b20dd2e..43f8bb5d 100644 --- a/lib/RoadizCoreBundle/src/ListManager/EntityListManagerInterface.php +++ b/lib/RoadizCoreBundle/src/ListManager/EntityListManagerInterface.php @@ -9,39 +9,24 @@ interface EntityListManagerInterface public const ITEM_PER_PAGE = 20; /** - * @param bool $allowRequestSorting * @return $this */ public function setAllowRequestSorting(bool $allowRequestSorting): self; /** - * @param bool $allowRequestSearching * @return $this */ public function setAllowRequestSearching(bool $allowRequestSearching): self; - /** - * @return bool - */ public function isDisplayingNotPublishedNodes(): bool; - /** - * @param bool $displayNotPublishedNodes - * @return EntityListManagerInterface - */ public function setDisplayingNotPublishedNodes(bool $displayNotPublishedNodes): self; - /** - * @return bool - */ public function isDisplayingAllNodesStatuses(): bool; /** * Switch repository to disable any security on Node status. To use ONLY in order to * view deleted and archived nodes. - * - * @param bool $displayAllNodesStatuses - * @return EntityListManagerInterface */ public function setDisplayingAllNodesStatuses(bool $displayAllNodesStatuses): self; @@ -49,22 +34,14 @@ public function setDisplayingAllNodesStatuses(bool $displayAllNodesStatuses): se * Handle request to find filter to apply to entity listing. * * @param bool $disabled Disable pagination and filtering over GET params - * @return void */ public function handle(bool $disabled = false): void; /** * Configure a custom current page. - * - * @param int $page - * - * @return EntityListManagerInterface */ public function setPage(int $page): self; - /** - * @return EntityListManagerInterface - */ public function disablePagination(): self; /** @@ -84,34 +61,20 @@ public function disablePagination(): self; * * previousPageQuery [string] * * previousQueryArray [array] * * nextQueryArray [array] - * - * @return array */ public function getAssignation(): array; - /** - * @return int - */ public function getItemCount(): int; - /** - * @return int - */ public function getPageCount(): int; /** * Return filtered entities. - * - * @return array */ public function getEntities(): array; /** * Configure a custom item count per page. - * - * @param int $itemPerPage - * - * @return EntityListManagerInterface */ public function setItemPerPage(int $itemPerPage): self; } diff --git a/lib/RoadizCoreBundle/src/ListManager/NodePaginator.php b/lib/RoadizCoreBundle/src/ListManager/NodePaginator.php index 3cf1c226..eb451ac6 100644 --- a/lib/RoadizCoreBundle/src/ListManager/NodePaginator.php +++ b/lib/RoadizCoreBundle/src/ListManager/NodePaginator.php @@ -26,9 +26,10 @@ public function getTranslation(): ?TranslationInterface return $this->translation; } - public function setTranslation(TranslationInterface $translation = null): self + public function setTranslation(?TranslationInterface $translation = null): self { $this->translation = $translation; + return $this; } @@ -48,6 +49,7 @@ public function findByAtPage(array $order = [], int $page = 1): array $this->getTranslation() ); } + return $repository->findBy( $this->criteria, $order, diff --git a/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoListManager.php b/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoListManager.php index 1e642ed8..55d8a426 100644 --- a/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoListManager.php +++ b/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoListManager.php @@ -30,8 +30,9 @@ protected function createPaginator(): void */ public function getEntities(): array { - if ($this->pagination === true && null !== $this->paginator) { + if (true === $this->pagination && null !== $this->paginator) { $this->paginator->setItemsPerPage($this->getItemPerPage()); + // @phpstan-ignore-next-line return $this->paginator->findByAtPage($this->orderingArray, $this->currentPage); } else { @@ -40,6 +41,7 @@ public function getEntities(): array $repository->setDisplayingNotPublishedNodes($this->isDisplayingNotPublishedNodes()); $repository->setDisplayingAllNodesStatuses($this->isDisplayingAllNodesStatuses()); } + return $repository->findByAsNodeTreeDto( $this->filteringArray, $this->orderingArray, diff --git a/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoPaginator.php b/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoPaginator.php index f418515b..6a61fac6 100644 --- a/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoPaginator.php +++ b/lib/RoadizCoreBundle/src/ListManager/NodeTreeDtoPaginator.php @@ -14,7 +14,6 @@ * A paginator class to filter node entities with limit and search. * * This class add some translation and security filters - * */ #[Exclude] class NodeTreeDtoPaginator extends Paginator @@ -26,15 +25,14 @@ public function getTranslation(): ?TranslationInterface return $this->translation; } - public function setTranslation(TranslationInterface $translation = null): self + public function setTranslation(?TranslationInterface $translation = null): self { $this->translation = $translation; + return $this; } /** - * @param array $order - * @param int $page * @return array */ public function findByAtPage(array $order = [], int $page = 1): array @@ -82,6 +80,7 @@ protected function getRepository(): NodeRepository $repository = $this->em->getRepository(Node::class); $repository->setDisplayingNotPublishedNodes($this->isDisplayingNotPublishedNodes()); $repository->setDisplayingAllNodesStatuses($this->isDisplayingAllNodesStatuses()); + return $repository; } } diff --git a/lib/RoadizCoreBundle/src/ListManager/NodesSourcesPaginator.php b/lib/RoadizCoreBundle/src/ListManager/NodesSourcesPaginator.php index b5f677b3..c7150223 100644 --- a/lib/RoadizCoreBundle/src/ListManager/NodesSourcesPaginator.php +++ b/lib/RoadizCoreBundle/src/ListManager/NodesSourcesPaginator.php @@ -18,9 +18,6 @@ #[Exclude] class NodesSourcesPaginator extends Paginator { - /** - * {@inheritdoc} - */ public function getTotalCount(): int { if (null === $this->totalCount) { @@ -54,6 +51,7 @@ protected function getRepository(): NodesSourcesRepository $repository = $this->em->getRepository($this->entityName); $repository->setDisplayingNotPublishedNodes($this->isDisplayingNotPublishedNodes()); $repository->setDisplayingAllNodesStatuses($this->isDisplayingAllNodesStatuses()); + return $repository; } } diff --git a/lib/RoadizCoreBundle/src/ListManager/Paginator.php b/lib/RoadizCoreBundle/src/ListManager/Paginator.php index 0e961eb6..1e087cea 100644 --- a/lib/RoadizCoreBundle/src/ListManager/Paginator.php +++ b/lib/RoadizCoreBundle/src/ListManager/Paginator.php @@ -29,49 +29,37 @@ class Paginator protected bool $displayAllNodesStatuses; /** - * @param ObjectManager $em * @param class-string $entityName - * @param int $itemsPerPage - * @param array $criteria */ public function __construct( protected readonly ObjectManager $em, protected readonly string $entityName, protected int $itemsPerPage = 10, - protected readonly array $criteria = [] + protected readonly array $criteria = [], ) { $this->displayNotPublishedNodes = false; $this->displayAllNodesStatuses = false; if (empty($this->entityName)) { - throw new \RuntimeException("Entity name could not be empty", 1); + throw new \RuntimeException('Entity name could not be empty', 1); } if ($this->itemsPerPage < 1) { - throw new \RuntimeException("Items par page could not be lesser than 1.", 1); + throw new \RuntimeException('Items par page could not be lesser than 1.', 1); } } - /** - * @return bool - */ public function isDisplayingNotPublishedNodes(): bool { return $this->displayNotPublishedNodes; } - /** - * @param bool $displayNonPublishedNodes - * @return Paginator - */ public function setDisplayingNotPublishedNodes(bool $displayNonPublishedNodes): Paginator { $this->displayNotPublishedNodes = $displayNonPublishedNodes; + return $this; } - /** - * @return bool - */ public function isDisplayingAllNodesStatuses(): bool { return $this->displayAllNodesStatuses; @@ -81,26 +69,21 @@ public function isDisplayingAllNodesStatuses(): bool * Switch repository to disable any security on Node status. To use ONLY in order to * view deleted and archived nodes. * - * @param bool $displayAllNodesStatuses * @return $this */ public function setDisplayingAllNodesStatuses(bool $displayAllNodesStatuses): Paginator { $this->displayAllNodesStatuses = $displayAllNodesStatuses; + return $this; } - /** - * @return string|null - */ public function getSearchPattern(): ?string { return $this->searchPattern; } /** - * @param string|null $searchPattern - * * @return $this */ public function setSearchPattern(?string $searchPattern): Paginator @@ -112,8 +95,6 @@ public function setSearchPattern(?string $searchPattern): Paginator /** * Return total entities count for given criteria. - * - * @return int */ public function getTotalCount(): int { @@ -134,8 +115,8 @@ public function getTotalCount(): int $qb = $this->getSearchQueryBuilder($alias); $qb->select($qb->expr()->countDistinct($alias)); try { - return (int)$qb->getQuery()->getSingleScalarResult(); - } catch (NoResultException | NonUniqueResultException $e) { + return (int) $qb->getQuery()->getSingleScalarResult(); + } catch (NoResultException|NonUniqueResultException $e) { return 0; } } @@ -148,8 +129,6 @@ public function getTotalCount(): int /** * Return page count according to criteria. - * - * @return int */ public function getPageCount(): int { @@ -159,9 +138,6 @@ public function getPageCount(): int /** * Return entities filtered for current page. * - * @param array $order - * @param int $page - * * @return array */ public function findByAtPage(array $order = [], int $page = 1): array @@ -182,10 +158,8 @@ public function findByAtPage(array $order = [], int $page = 1): array /** * Use a search query to paginate instead of a findBy. * - * @param array $order - * @param int $page - * * @return array + * * @throws \Exception */ public function searchByAtPage(array $order = [], int $page = 1): array @@ -211,15 +185,13 @@ public function searchByAtPage(array $order = [], int $page = 1): array ->setFirstResult($this->getItemsPerPage() * ($page - 1)); foreach ($order as $key => $value) { - $qb->addOrderBy($alias . '.' . $key, $value); + $qb->addOrderBy($alias.'.'.$key, $value); } return $qb->getQuery()->getResult(); } /** - * @param int $itemsPerPage - * * @return $this */ public function setItemsPerPage(int $itemsPerPage): self @@ -228,9 +200,7 @@ public function setItemsPerPage(int $itemsPerPage): self return $this; } - /** - * @return int - */ + public function getItemsPerPage(): int { return $this->itemsPerPage; @@ -239,18 +209,19 @@ public function getItemsPerPage(): int protected function getSearchQueryBuilder(string $alias): QueryBuilder { $searchableFields = $this->getSearchableFields(); - if (count($searchableFields) === 0) { + if (0 === count($searchableFields)) { throw new \RuntimeException('Entity has no searchable field.'); } $qb = $this->getRepository()->createQueryBuilder($alias); $orX = []; foreach ($this->getSearchableFields() as $field) { $orX[] = $qb->expr()->like( - 'LOWER(' . $alias . '.' . $field . ')', - $qb->expr()->literal('%' . \mb_strtolower($this->searchPattern) . '%') + 'LOWER('.$alias.'.'.$field.')', + $qb->expr()->literal('%'.\mb_strtolower($this->searchPattern).'%') ); } $qb->andWhere($qb->expr()->orX(...$orX)); + return $qb; } @@ -260,6 +231,7 @@ protected function getSearchableFields(): array if (!($metadata instanceof ClassMetadataInfo)) { throw new \RuntimeException('Entity has no metadata.'); } + return EntityRepository::getSearchableColumnsNames($metadata); } @@ -273,6 +245,7 @@ protected function getRepository(): \Doctrine\ORM\EntityRepository $repository->setDisplayingNotPublishedNodes($this->isDisplayingNotPublishedNodes()); $repository->setDisplayingAllNodesStatuses($this->isDisplayingAllNodesStatuses()); } + return $repository; } } diff --git a/lib/RoadizCoreBundle/src/ListManager/QueryBuilderListManager.php b/lib/RoadizCoreBundle/src/ListManager/QueryBuilderListManager.php index 43ac851e..f675a6e8 100644 --- a/lib/RoadizCoreBundle/src/ListManager/QueryBuilderListManager.php +++ b/lib/RoadizCoreBundle/src/ListManager/QueryBuilderListManager.php @@ -14,38 +14,26 @@ class QueryBuilderListManager extends AbstractEntityListManager { protected ?Paginator $paginator = null; /** - * @var null|callable + * @var callable|null */ - protected $searchingCallable = null; + protected $searchingCallable; - /** - * @param Request|null $request - * @param QueryBuilder $queryBuilder - * @param string $identifier - * @param bool $debug - */ public function __construct( ?Request $request, protected readonly QueryBuilder $queryBuilder, protected readonly string $identifier = 'obj', - protected readonly bool $debug = false + protected readonly bool $debug = false, ) { parent::__construct($request); } - /** - * @param callable|null $searchingCallable - * @return QueryBuilderListManager - */ public function setSearchingCallable(?callable $searchingCallable): QueryBuilderListManager { $this->searchingCallable = $searchingCallable; + return $this; } - /** - * @param string $search - */ protected function handleSearchParam(string $search): void { parent::handleSearchParam($search); @@ -69,64 +57,49 @@ protected function handleOrderingParam(string $field, string $ordering): void ); } - /** - * @return Paginator - */ protected function getPaginator(): Paginator { if (null === $this->paginator) { $this->paginator = new Paginator($this->queryBuilder); } + return $this->paginator; } - /** - * @inheritDoc - */ public function setPage(int $page): self { parent::setPage($page); $this->queryBuilder->setFirstResult($this->getItemPerPage() * ($page - 1)); + return $this; } - /** - * @inheritDoc - */ public function setItemPerPage(int $itemPerPage): self { parent::setItemPerPage($itemPerPage); $this->queryBuilder->setMaxResults((int) $itemPerPage); + return $this; } - - /** - * @inheritDoc - */ public function getItemCount(): int { return $this->getPaginator()->count(); } - /** - * @inheritDoc - */ public function getEntities(): array { return $this->getPaginator()->getIterator()->getArrayCopy(); } - /** - * @return array - */ public function getAssignation(): array { if ($this->debug) { return array_merge(parent::getAssignation(), [ - 'dql_query' => $this->queryBuilder->getDQL() + 'dql_query' => $this->queryBuilder->getDQL(), ]); } + return parent::getAssignation(); } } diff --git a/lib/RoadizCoreBundle/src/ListManager/SessionListFilters.php b/lib/RoadizCoreBundle/src/ListManager/SessionListFilters.php index 55c246c7..d3027bf4 100644 --- a/lib/RoadizCoreBundle/src/ListManager/SessionListFilters.php +++ b/lib/RoadizCoreBundle/src/ListManager/SessionListFilters.php @@ -12,15 +12,12 @@ class SessionListFilters { public function __construct( private readonly string $sessionIdentifier, - private readonly int $defaultItemsParPage = 20 + private readonly int $defaultItemsParPage = 20, ) { } /** * Handle item_per_page filter form session or from request query. - * - * @param Request $request - * @param EntityListManagerInterface $listManager */ public function handleItemPerPage(Request $request, EntityListManagerInterface $listManager): void { @@ -28,11 +25,11 @@ public function handleItemPerPage(Request $request, EntityListManagerInterface $ * Check if item_per_page is available from session */ if ( - $request->hasSession() && - $request->getSession()->has($this->sessionIdentifier) && - $request->getSession()->get($this->sessionIdentifier) > 0 && - (!$request->query->has('item_per_page') || - $request->query->get('item_per_page') < 1) + $request->hasSession() + && $request->getSession()->has($this->sessionIdentifier) + && $request->getSession()->get($this->sessionIdentifier) > 0 + && (!$request->query->has('item_per_page') + || $request->query->get('item_per_page') < 1) ) { /* * Item count is in session @@ -40,8 +37,8 @@ public function handleItemPerPage(Request $request, EntityListManagerInterface $ $request->query->set('item_per_page', intval($request->getSession()->get($this->sessionIdentifier))); $listManager->setItemPerPage(intval($request->getSession()->get($this->sessionIdentifier))); } elseif ( - $request->query->has('item_per_page') && - $request->query->get('item_per_page') > 0 + $request->query->has('item_per_page') + && $request->query->get('item_per_page') > 0 ) { /* * Item count is in query, save it in session diff --git a/lib/RoadizCoreBundle/src/ListManager/TagListManager.php b/lib/RoadizCoreBundle/src/ListManager/TagListManager.php index 59568ffa..a0d290e3 100644 --- a/lib/RoadizCoreBundle/src/ListManager/TagListManager.php +++ b/lib/RoadizCoreBundle/src/ListManager/TagListManager.php @@ -18,28 +18,22 @@ #[Exclude] class TagListManager extends EntityListManager { - /** - * @param Request|null $request - * @param ObjectManager $entityManager - * @param array $preFilters - * @param array $preOrdering - */ public function __construct( ?Request $request, ObjectManager $entityManager, array $preFilters = [], - array $preOrdering = [] + array $preOrdering = [], ) { parent::__construct($request, $entityManager, Tag::class, $preFilters, $preOrdering); } /** - * @return array + * @return array|array */ public function getEntities(): array { try { - if ($this->searchPattern != '') { + if ('' != $this->searchPattern) { return $this->entityManager ->getRepository(TagTranslation::class) ->searchBy($this->searchPattern, $this->filteringArray, $this->orderingArray); diff --git a/lib/RoadizCoreBundle/src/Logger/DoctrineHandler.php b/lib/RoadizCoreBundle/src/Logger/DoctrineHandler.php index 99c540fd..7f775fbc 100644 --- a/lib/RoadizCoreBundle/src/Logger/DoctrineHandler.php +++ b/lib/RoadizCoreBundle/src/Logger/DoctrineHandler.php @@ -30,7 +30,7 @@ public function __construct( private readonly RequestStack $requestStack, private readonly DocumentUrlGeneratorInterface $documentUrlGenerator, $level = Logger::INFO, - $bubble = true + $bubble = true, ) { parent::__construct($level, $bubble); } @@ -40,11 +40,12 @@ protected function getThumbnailSourcePath(?DocumentInterface $thumbnail): ?strin if (null === $thumbnail || $thumbnail->isPrivate()) { return null; } + return $this->documentUrlGenerator ->setDocument($thumbnail) ->setOptions([ - "fit" => "150x150", - "quality" => 70, + 'fit' => '150x150', + 'quality' => 70, ]) ->getUrl(); } @@ -109,9 +110,6 @@ protected function populateForNodesSources(NodesSources $value, Log $log, array } } - /** - * @param array $record - */ public function write(array $record): void { try { @@ -135,7 +133,7 @@ public function write(array $record): void $this->populateForNode($value, $log, $data); } elseif ($value instanceof NodesSources) { $this->populateForNodesSources($value, $log, $data); - } elseif ($key === 'entity' && $value instanceof PersistableInterface) { + } elseif ('entity' === $key && $value instanceof PersistableInterface) { $log->setEntityClass(get_class($value)); $log->setEntityId($value->getId()); @@ -145,7 +143,7 @@ public function write(array $record): void $data = array_merge( $data, [ - 'entity_title' => $value->{$method}() + 'entity_title' => $value->{$method}(), ] ); break; @@ -157,7 +155,7 @@ public function write(array $record): void $data, [ 'exception_class' => get_class($value), - 'message' => $value->getMessage() + 'message' => $value->getMessage(), ] ); } @@ -170,7 +168,7 @@ public function write(array $record): void ] ); } - if ($key === 'request' && \is_array($value)) { + if ('request' === $key && \is_array($value)) { $data = array_merge( $data, $value @@ -202,7 +200,7 @@ public function write(array $record): void 'user_email' => $user->getEmail(), 'user_public_name' => $user->getPublicName(), 'user_picture_url' => $user->getPictureUrl(), - 'user_id' => $user->getId() + 'user_id' => $user->getId(), ] ); } else { diff --git a/lib/RoadizCoreBundle/src/Logger/Entity/Log.php b/lib/RoadizCoreBundle/src/Logger/Entity/Log.php index 8dbdf02f..8da1875c 100644 --- a/lib/RoadizCoreBundle/src/Logger/Entity/Log.php +++ b/lib/RoadizCoreBundle/src/Logger/Entity/Log.php @@ -16,19 +16,19 @@ #[ ORM\Entity(repositoryClass: LogRepository::class), - ORM\Table(name: "log"), - ORM\Index(columns: ["datetime"]), - ORM\Index(columns: ["entity_class"]), - ORM\Index(columns: ["entity_class", "entity_id"]), - ORM\Index(columns: ["entity_class", "datetime"], name: "log_entity_class_datetime"), - ORM\Index(columns: ["entity_class", "entity_id", "datetime"], name: "log_entity_class_id_datetime"), - ORM\Index(columns: ["username", "datetime"], name: "log_username_datetime"), - ORM\Index(columns: ["user_id", "datetime"], name: "log_user_datetime"), - ORM\Index(columns: ["level", "datetime"], name: "log_level_datetime"), - ORM\Index(columns: ["channel", "datetime"], name: "log_channel_datetime"), - ORM\Index(columns: ["level"]), - ORM\Index(columns: ["username"]), - ORM\Index(columns: ["channel"]), + ORM\Table(name: 'log'), + ORM\Index(columns: ['datetime']), + ORM\Index(columns: ['entity_class']), + ORM\Index(columns: ['entity_class', 'entity_id']), + ORM\Index(columns: ['entity_class', 'datetime'], name: 'log_entity_class_datetime'), + ORM\Index(columns: ['entity_class', 'entity_id', 'datetime'], name: 'log_entity_class_id_datetime'), + ORM\Index(columns: ['username', 'datetime'], name: 'log_username_datetime'), + ORM\Index(columns: ['user_id', 'datetime'], name: 'log_user_datetime'), + ORM\Index(columns: ['level', 'datetime'], name: 'log_level_datetime'), + ORM\Index(columns: ['channel', 'datetime'], name: 'log_channel_datetime'), + ORM\Index(columns: ['level']), + ORM\Index(columns: ['username']), + ORM\Index(columns: ['channel']), ORM\HasLifecycleCallbacks ] class Log extends AbstractEntity @@ -82,9 +82,6 @@ class Log extends AbstractEntity // @phpstan-ignore-next-line protected ?string $entityClass = null; - /** - * @var string|int|null - */ #[ORM\Column(name: 'entity_id', type: 'string', length: 36, unique: false, nullable: true)] #[SymfonySerializer\Groups(['log'])] #[Serializer\Groups(['log'])] @@ -98,59 +95,41 @@ class Log extends AbstractEntity protected ?array $additionalData = null; /** - * @param int $level - * @param string $message - * * @throws \Exception */ public function __construct(int $level, string $message) { $this->level = $level; $this->message = $message; - $this->datetime = new \DateTime("now"); + $this->datetime = new \DateTime('now'); } - /** - * @return int|string|null - */ public function getUserId(): int|string|null { return $this->userId; } - /** - * @param int|string|null $userId - * @return Log - */ public function setUserId(int|string|null $userId): Log { $this->userId = $userId; + return $this; } - /** - * @param User $user - * - * @return Log - */ public function setUser(User $user): Log { $this->userId = $user->getId(); $this->username = $user->getUsername(); + return $this; } - /** - * @return string|null - */ public function getUsername(): ?string { return $this->username; } /** - * @param string|null $username - * * @return Log */ public function setUsername(?string $username) @@ -160,25 +139,16 @@ public function setUsername(?string $username) return $this; } - /** - * @return string - */ public function getMessage(): string { return $this->message; } - /** - * @return int - */ public function getLevel(): int { return $this->level; } - /** - * @return \DateTime - */ public function getDatetime(): \DateTime { return $this->datetime; @@ -187,7 +157,6 @@ public function getDatetime(): \DateTime /** * BC setter. * - * @param NodesSources|null $nodeSource * @return $this */ public function setNodeSource(?NodesSources $nodeSource): Log @@ -196,40 +165,27 @@ public function setNodeSource(?NodesSources $nodeSource): Log $this->entityClass = NodesSources::class; $this->entityId = $nodeSource->getId(); } + return $this; } - /** - * @return string|null - */ public function getClientIp(): ?string { return $this->clientIp; } - /** - * @param string|null $clientIp - * @return Log - */ public function setClientIp(?string $clientIp): Log { $this->clientIp = $clientIp; + return $this; } - /** - * @return array|null - */ public function getAdditionalData(): ?array { return $this->additionalData; } - /** - * @param array|null $additionalData - * - * @return Log - */ public function setAdditionalData(?array $additionalData): Log { $this->additionalData = $additionalData; @@ -237,19 +193,11 @@ public function setAdditionalData(?array $additionalData): Log return $this; } - /** - * @return string|null - */ public function getChannel(): ?string { return $this->channel; } - /** - * @param string|null $channel - * - * @return Log - */ public function setChannel(?string $channel): Log { $this->channel = $channel; @@ -267,35 +215,29 @@ public function getEntityClass(): ?string /** * @param class-string|null $entityClass - * @return Log */ public function setEntityClass(?string $entityClass): Log { $this->entityClass = $entityClass; + return $this; } - /** - * @return int|string|null - */ public function getEntityId(): int|string|null { return $this->entityId; } - /** - * @param int|string|null $entityId - * @return Log - */ public function setEntityId(int|string|null $entityId): Log { $this->entityId = $entityId; + return $this; } #[ORM\PrePersist] public function prePersist(): void { - $this->datetime = new \DateTime("now"); + $this->datetime = new \DateTime('now'); } } diff --git a/lib/RoadizCoreBundle/src/Mailer/ContactFormManager.php b/lib/RoadizCoreBundle/src/Mailer/ContactFormManager.php index 2476885d..6d6b6fcf 100644 --- a/lib/RoadizCoreBundle/src/Mailer/ContactFormManager.php +++ b/lib/RoadizCoreBundle/src/Mailer/ContactFormManager.php @@ -38,7 +38,7 @@ use Twig\Environment; /** - * @internal Use ContactFormManagerFactory to create a new instance. + * @internal use ContactFormManagerFactory to create a new instance */ final class ContactFormManager extends EmailManager { @@ -74,7 +74,7 @@ public function __construct( private readonly FormFactoryInterface $formFactory, private readonly FormErrorSerializerInterface $formErrorSerializer, private readonly ?string $recaptchaPrivateKey, - private readonly ?string $recaptchaPublicKey + private readonly ?string $recaptchaPublicKey, ) { parent::__construct($requestStack, $translator, $templating, $mailer, $settingsBag, $documentUrlGenerator); @@ -100,40 +100,33 @@ public function __construct( )); } - /** - * @return string - */ public function getFormName(): string { return $this->formName; } /** - * Use this method BEFORE withDefaultFields() - * - * @param string $formName - * @return ContactFormManager + * Use this method BEFORE withDefaultFields(). */ public function setFormName(string $formName): ContactFormManager { $this->formName = $formName; + return $this; } /** - * Use this method BEFORE withDefaultFields() + * Use this method BEFORE withDefaultFields(). * * @return $this */ public function disableCsrfProtection(): self { $this->options['csrf_protection'] = false; + return $this; } - /** - * @return FormInterface - */ public function getForm(): FormInterface { return $this->form; @@ -144,8 +137,8 @@ public function getForm(): FormInterface * * Use this method BEFORE withDefaultFields() * - * @param bool $emailStrictMode * @see https://symfony.com/doc/4.4/reference/constraints/Email.html#strict + * * @return $this */ public function setEmailStrictMode(bool $emailStrictMode = true): self @@ -154,9 +147,7 @@ public function setEmailStrictMode(bool $emailStrictMode = true): self return $this; } - /** - * @return bool - */ + public function isEmailStrictMode(): bool { return $this->emailStrictMode; @@ -165,7 +156,6 @@ public function isEmailStrictMode(): bool /** * Adds email, name and message fields with their constraints. * - * @param bool $useHoneypot * @return $this */ public function withDefaultFields(bool $useHoneypot = true): self @@ -179,7 +169,7 @@ public function withDefaultFields(bool $useHoneypot = true): self 'message' => 'email.not.valid', 'mode' => $this->isEmailStrictMode() ? Email::VALIDATION_MODE_STRICT : - Email::VALIDATION_MODE_HTML5 + Email::VALIDATION_MODE_HTML5, ]), ], ]) @@ -207,21 +197,20 @@ public function withDefaultFields(bool $useHoneypot = true): self } /** - * Use this method AFTER withDefaultFields() + * Use this method AFTER withDefaultFields(). * - * @param string $honeypotName * @return $this */ public function withHoneypot(string $honeypotName = 'eml'): self { $this->getFormBuilder()->add($honeypotName, HoneypotType::class); + return $this; } /** - * Use this method AFTER withDefaultFields() + * Use this method AFTER withDefaultFields(). * - * @param string $consentDescription * @return $this */ public function withUserConsent(string $consentDescription = 'contact_form.user_consent'): self @@ -235,12 +224,10 @@ public function withUserConsent(string $consentDescription = 'contact_form.user_ ]), ], ]); + return $this; } - /** - * @return FormBuilderInterface - */ public function getFormBuilder(): FormBuilderInterface { if (null === $this->formBuilder) { @@ -248,6 +235,7 @@ public function getFormBuilder(): FormBuilderInterface ->createNamedBuilder($this->getFormName(), FormType::class, null, $this->options) ->setMethod($this->method); } + return $this->formBuilder; } @@ -265,16 +253,14 @@ public function getFormBuilder(): FormBuilderInterface * * If you are using API REST POST form, use 'g-recaptcha-response' name * to enable Validator to get challenge value. - * - * @return ContactFormManager */ public function withGoogleRecaptcha( string $name = 'recaptcha', - string $validatorFieldName = Recaptcha::FORM_NAME + string $validatorFieldName = Recaptcha::FORM_NAME, ): self { if ( - !empty($this->recaptchaPublicKey) && - !empty($this->recaptchaPrivateKey) + !empty($this->recaptchaPublicKey) + && !empty($this->recaptchaPrivateKey) ) { $this->getFormBuilder()->add($name, RecaptchaType::class, [ 'label' => false, @@ -296,8 +282,6 @@ public function withGoogleRecaptcha( /** * Handle custom form validation and send it as an email. * - * @param callable|null $onValid - * @return Response|null * @throws \Exception */ public function handle(?callable $onValid = null): ?Response @@ -308,10 +292,10 @@ public function handle(?callable $onValid = null): ?Response } $this->form = $this->getFormBuilder()->getForm(); $this->form->handleRequest($request); - $returnJson = $request->isXmlHttpRequest() || - $request->getRequestFormat() === 'json' || - (count($request->getAcceptableContentTypes()) === 1 && $request->getAcceptableContentTypes()[0] === 'application/json') || - ($request->attributes->has('_format') && $request->attributes->get('_format') === 'json'); + $returnJson = $request->isXmlHttpRequest() + || 'json' === $request->getRequestFormat() + || (1 === count($request->getAcceptableContentTypes()) && 'application/json' === $request->getAcceptableContentTypes()[0]) + || ($request->attributes->has('_format') && 'json' === $request->attributes->get('_format')); if ($this->form->isSubmitted()) { if ($this->form->isValid()) { @@ -333,7 +317,8 @@ public function handle(?callable $onValid = null): ?Response ->add('confirm', $this->translator->trans($this->successMessage)); } - $this->redirectUrl = $this->redirectUrl !== null ? $this->redirectUrl : $request->getUri(); + $this->redirectUrl = null !== $this->redirectUrl ? $this->redirectUrl : $request->getUri(); + return new RedirectResponse($this->redirectUrl); } } catch (BadFormRequestException $e) { @@ -358,6 +343,7 @@ public function handle(?callable $onValid = null): ?Response 'errors' => (string) $this->form->getErrors(), 'errorsPerForm' => $errorPerForm, ]; + /* * BC: Still return 200 if form is not valid for Ajax forms */ @@ -367,6 +353,7 @@ public function handle(?callable $onValid = null): ?Response ); } } + return null; } @@ -382,20 +369,20 @@ protected function handleFiles(): void */ foreach ($request->files as $files) { /** - * @var string $name + * @var string $name * @var UploadedFile|array $uploadedFile */ foreach ($files as $name => $uploadedFile) { if (null !== $uploadedFile) { if (is_array($uploadedFile)) { /** - * @var string $singleName + * @var string $singleName * @var UploadedFile|array $singleUploadedFile */ foreach ($uploadedFile as $singleName => $singleUploadedFile) { if (is_array($singleUploadedFile)) { /** - * @var string $singleName2 + * @var string $singleName2 * @var UploadedFile $singleUploadedFile2 */ foreach ($singleUploadedFile as $singleName2 => $singleUploadedFile2) { @@ -414,24 +401,18 @@ protected function handleFiles(): void } /** - * @param string $name - * @param UploadedFile $uploadedFile * @return $this + * * @throws BadFormRequestException */ protected function addUploadedFile(string $name, UploadedFile $uploadedFile): ContactFormManager { if ( - !$uploadedFile->isValid() || - !in_array($uploadedFile->getMimeType(), $this->allowedMimeTypes) || - $uploadedFile->getSize() > $this->maxFileSize + !$uploadedFile->isValid() + || !in_array($uploadedFile->getMimeType(), $this->allowedMimeTypes) + || $uploadedFile->getSize() > $this->maxFileSize ) { - throw new BadFormRequestException( - $this->translator->trans('file.not.accepted'), - Response::HTTP_FORBIDDEN, - 'danger', - $name - ); + throw new BadFormRequestException($this->translator->trans('file.not.accepted'), Response::HTTP_FORBIDDEN, 'danger', $name); } else { $this->uploadedFiles[$name] = $uploadedFile; } @@ -439,29 +420,24 @@ protected function addUploadedFile(string $name, UploadedFile $uploadedFile): Co return $this; } - /** - * @param array $formData - * @return string|null - */ protected function findEmailData(array $formData): ?string { foreach ($formData as $key => $value) { if ( - (new UnicodeString($key))->containsAny('email') && - is_string($value) && - filter_var($value, FILTER_VALIDATE_EMAIL) + (new UnicodeString($key))->containsAny('email') + && is_string($value) + && filter_var($value, FILTER_VALIDATE_EMAIL) ) { return $value; } elseif (is_array($value) && null !== $email = $this->findEmailData($value)) { return $email; } } + return null; } /** - * @param FormInterface $form - * * @throws \Exception */ protected function handleFormData(FormInterface $form): void @@ -478,14 +454,14 @@ protected function handleFormData(FormInterface $form): void } /** - * @var string $key + * @var string $key * @var UploadedFile $uploadedFile */ foreach ($this->uploadedFiles as $key => $uploadedFile) { $fields[] = [ 'name' => strip_tags((string) $key), - 'value' => (strip_tags($uploadedFile->getClientOriginalName()) . - ' [' . $uploadedFile->guessExtension() . ']'), + 'value' => (strip_tags($uploadedFile->getClientOriginalName()). + ' ['.$uploadedFile->guessExtension().']'), ]; } /* @@ -517,26 +493,22 @@ protected function isFieldPrivate(FormInterface $form): bool $key = $form->getName(); $privateFieldNames = [ Recaptcha::FORM_NAME, - 'recaptcha' + 'recaptcha', ]; + return - is_string($key) && - (\mb_substr($key, 0, 1) === '_' || \in_array($key, $privateFieldNames)) + is_string($key) + && ('_' === \mb_substr($key, 0, 1) || \in_array($key, $privateFieldNames)) ; } - /** - * @param FormInterface $form - * @param array $fields - * @return array - */ protected function flattenFormData(FormInterface $form, array $fields): array { /** @var FormInterface $formItem */ foreach ($form as $formItem) { $key = $formItem->getName(); $value = $formItem->getData(); - $displayName = $formItem->getConfig()->getOption("label") ?? + $displayName = $formItem->getConfig()->getOption('label') ?? (is_numeric($key) ? null : strip_tags(trim((string) $key))); if ($this->isFieldPrivate($formItem) || $value instanceof UploadedFile) { @@ -566,17 +538,15 @@ protected function flattenFormData(FormInterface $form, array $fields): array return $fields; } - /** * Send contact form data by email. * - * @return void * @throws \RuntimeException */ public function send(): void { if (empty($this->assignation)) { - throw new \RuntimeException("Can’t send a contact form without data."); + throw new \RuntimeException('Can’t send a contact form without data.'); } $this->message = $this->createMessage(); @@ -601,7 +571,7 @@ public function send(): void } /** - * @return null|array
+ * @return array
|null */ public function getReceiver(): ?array { @@ -609,13 +579,12 @@ public function getReceiver(): ?array throw new \InvalidArgumentException('Main "email_sender" is not configured for this website.'); } $defaultReceivers = [new Address($this->settingsBag->get('email_sender'))]; + return parent::getReceiver() ?? $defaultReceivers; } /** * Gets the value of redirectUrl. - * - * @return string|null */ public function getRedirectUrl(): ?string { @@ -626,8 +595,6 @@ public function getRedirectUrl(): ?string * Sets the value of redirectUrl. * * @param string|null $redirectUrl Redirect url - * - * @return self */ public function setRedirectUrl(?string $redirectUrl): self { @@ -638,8 +605,6 @@ public function setRedirectUrl(?string $redirectUrl): self /** * Gets the value of maxFileSize. - * - * @return int */ public function getMaxFileSize(): int { @@ -650,8 +615,6 @@ public function getMaxFileSize(): int * Sets the value of maxFileSize. * * @param int $maxFileSize the max file size - * - * @return self */ public function setMaxFileSize($maxFileSize): self { @@ -662,8 +625,6 @@ public function setMaxFileSize($maxFileSize): self /** * Gets the value of allowedMimeTypes. - * - * @return array */ public function getAllowedMimeTypes(): array { @@ -674,8 +635,6 @@ public function getAllowedMimeTypes(): array * Sets the value of allowedMimeTypes. * * @param array $allowedMimeTypes the allowed mime types - * - * @return self */ public function setAllowedMimeTypes(array $allowedMimeTypes): self { @@ -684,17 +643,12 @@ public function setAllowedMimeTypes(array $allowedMimeTypes): self return $this; } - /** - * @return array - */ public function getOptions(): array { return $this->options; } /** - * @param array $options - * * @return $this */ public function setOptions(array $options): self @@ -704,21 +658,18 @@ public function setOptions(array $options): self return $this; } - /** - * @return bool - */ public function useRealResponseCode(): bool { return $this->useRealResponseCode; } /** - * @param bool $useRealResponseCode Return a real 400 response if form is not valid. - * @return ContactFormManager + * @param bool $useRealResponseCode return a real 400 response if form is not valid */ public function setUseRealResponseCode(bool $useRealResponseCode): ContactFormManager { $this->useRealResponseCode = $useRealResponseCode; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Mailer/ContactFormManagerFactory.php b/lib/RoadizCoreBundle/src/Mailer/ContactFormManagerFactory.php index 53a146a0..9f62a3d7 100644 --- a/lib/RoadizCoreBundle/src/Mailer/ContactFormManagerFactory.php +++ b/lib/RoadizCoreBundle/src/Mailer/ContactFormManagerFactory.php @@ -25,7 +25,7 @@ public function __construct( private readonly FormFactoryInterface $formFactory, private readonly FormErrorSerializerInterface $formErrorSerializer, private readonly ?string $recaptchaPrivateKey, - private readonly ?string $recaptchaPublicKey + private readonly ?string $recaptchaPublicKey, ) { } diff --git a/lib/RoadizCoreBundle/src/Mailer/EmailManager.php b/lib/RoadizCoreBundle/src/Mailer/EmailManager.php index 540a7d9e..fc147533 100644 --- a/lib/RoadizCoreBundle/src/Mailer/EmailManager.php +++ b/lib/RoadizCoreBundle/src/Mailer/EmailManager.php @@ -22,16 +22,16 @@ use Twig\Error\SyntaxError; /** - * @internal Use EmailManagerFactory to create a new instance. + * @internal use EmailManagerFactory to create a new instance */ class EmailManager { protected ?string $subject = null; protected ?string $emailTitle = null; protected ?string $emailType = null; - /** @var Address[]|null */ + /** @var Address[]|null */ protected ?array $receiver = null; - /** @var Address[]|null */ + /** @var Address[]|null */ protected ?array $sender = null; protected ?Address $origin = null; protected string $successMessage = 'email.successfully.sent'; @@ -43,7 +43,6 @@ class EmailManager protected ?Email $message; /** @var File[] */ protected array $files = []; - /** @var array */ protected array $resources = []; /* @@ -56,18 +55,17 @@ public function __construct( protected readonly Environment $templating, protected readonly MailerInterface $mailer, protected readonly Settings $settingsBag, - protected readonly DocumentUrlGeneratorInterface $documentUrlGenerator + protected readonly DocumentUrlGeneratorInterface $documentUrlGenerator, ) { $this->assignation = []; $this->message = null; /* * Sets a default CSS for emails. */ - $this->emailStylesheet = dirname(__DIR__) . '/../css/transactionalStyles.css'; + $this->emailStylesheet = dirname(__DIR__).'/../css/transactionalStyles.css'; } /** - * @return string * @throws LoaderError * @throws RuntimeError * @throws SyntaxError @@ -78,7 +76,6 @@ public function renderHtmlEmailBody(): string } /** - * @return string * @throws LoaderError * @throws RuntimeError * @throws SyntaxError @@ -102,7 +99,6 @@ public function renderHtmlEmailBodyWithCss(): string } /** - * @return string * @throws LoaderError * @throws RuntimeError * @throws SyntaxError @@ -131,7 +127,6 @@ public function appendWebsiteIcon(): static } /** - * @return Email * @throws LoaderError * @throws RuntimeError * @throws SyntaxError @@ -168,7 +163,6 @@ public function createMessage(): Email /** * Send email. * - * @return void * @throws TransportExceptionInterface * @throws LoaderError * @throws RuntimeError @@ -177,7 +171,7 @@ public function createMessage(): Email public function send(): void { if (empty($this->assignation)) { - throw new \RuntimeException("Can’t send a contact form without data."); + throw new \RuntimeException('Can’t send a contact form without data.'); } if (null === $this->message) { @@ -199,46 +193,40 @@ public function send(): void $this->mailer->send($this->message); } - /** - * @return null|string - */ public function getSubject(): ?string { return null !== $this->subject ? trim(strip_tags($this->subject)) : null; } /** - * @param null|string $subject * @return $this */ public function setSubject(?string $subject): static { $this->subject = $subject; + return $this; } - /** - * @return null|string - */ public function getEmailTitle(): ?string { return null !== $this->emailTitle ? trim(strip_tags($this->emailTitle)) : null; } /** - * @param null|string $emailTitle * @return $this */ public function setEmailTitle(?string $emailTitle): static { $this->emailTitle = $emailTitle; + return $this; } /** * Message destination email(s). * - * @return null|Address[] + * @return Address[]|null */ public function getReceiver(): ?array { @@ -247,8 +235,6 @@ public function getReceiver(): ?array /** * Return only one email as string. - * - * @return null|string */ public function getReceiverEmail(): ?string { @@ -265,6 +251,7 @@ public function getReceiverEmail(): ?string * @param Address|string|array|array
$receiver the receiver * * @return $this + * * @throws \Exception */ public function setReceiver(mixed $receiver): static @@ -294,7 +281,7 @@ public function setReceiver(mixed $receiver): static * * This email will be used as ReplyTo: and ReturnPath: * - * @return null|Address[] + * @return Address[]|null */ public function getSender(): ?array { @@ -303,8 +290,6 @@ public function getSender(): ?array /** * Return only one email as string. - * - * @return null|string */ public function getSenderEmail(): ?string { @@ -319,7 +304,9 @@ public function getSenderEmail(): ?string * Sets the value of sender. * * @param Address|string|array|array $sender + * * @return $this + * * @throws \Exception */ public function setSender(mixed $sender): static @@ -346,123 +333,96 @@ public function setSender(mixed $sender): static return $this; } - /** - * @return string - */ public function getSuccessMessage(): string { return $this->successMessage; } /** - * @param string $successMessage * @return $this */ public function setSuccessMessage(string $successMessage): static { $this->successMessage = $successMessage; + return $this; } - /** - * @return string - */ public function getFailMessage(): string { return $this->failMessage; } /** - * @param string $failMessage * @return $this */ public function setFailMessage(string $failMessage): static { $this->failMessage = $failMessage; + return $this; } - /** - * @return TranslatorInterface - */ public function getTranslator(): TranslatorInterface { return $this->translator; } - /** - * @return Environment - */ public function getTemplating(): Environment { return $this->templating; } - /** - * @return MailerInterface - */ public function getMailer(): MailerInterface { return $this->mailer; } - /** - * @return string|null - */ public function getEmailTemplate(): ?string { return $this->emailTemplate; } /** - * @param string|null $emailTemplate * @return $this */ public function setEmailTemplate(?string $emailTemplate = null): static { $this->emailTemplate = $emailTemplate; + return $this; } - /** - * @return string|null - */ public function getEmailPlainTextTemplate(): ?string { return $this->emailPlainTextTemplate; } /** - * @param string|null $emailPlainTextTemplate * @return $this */ public function setEmailPlainTextTemplate(?string $emailPlainTextTemplate = null): static { $this->emailPlainTextTemplate = $emailPlainTextTemplate; + return $this; } - /** - * @return string|null - */ public function getEmailStylesheet(): ?string { return $this->emailStylesheet; } /** - * @param string|null $emailStylesheet * @return $this */ public function setEmailStylesheet(?string $emailStylesheet = null): static { $this->emailStylesheet = $emailStylesheet; + return $this; } - /** - * @return Request - */ public function getRequest(): Request { return $this->requestStack->getMainRequest(); @@ -473,8 +433,6 @@ public function getRequest(): Request * * This must be an email address with a know * domain name to be validated on your SMTP server. - * - * @return null|Address */ public function getOrigin(): ?Address { @@ -484,52 +442,47 @@ public function getOrigin(): ?Address $defaultSender = $this->settingsBag->get('email_sender'); $defaultSenderName = $this->settingsBag->get('site_name', '') ?? ''; } + return $this->origin ?? new Address($defaultSender, $defaultSenderName); } /** - * @param string $origin * @return $this */ public function setOrigin(string $origin): static { $this->origin = new Address($origin); + return $this; } - /** - * @return array - */ public function getAssignation(): array { return $this->assignation; } /** - * @param array $assignation * @return $this */ public function setAssignation(array $assignation): static { $this->assignation = $assignation; + return $this; } - /** - * @return null|string - */ public function getEmailType(): ?string { return $this->emailType; } /** - * @param null|string $emailType * @return $this */ public function setEmailType(?string $emailType): static { $this->emailType = $emailType; + return $this; } @@ -543,11 +496,13 @@ public function getFiles(): array /** * @param File[] $files + * * @return $this */ public function setFiles(array $files): static { $this->files = $files; + return $this; } @@ -561,13 +516,13 @@ public function getResources(): array /** * @param resource $resource - * @param string $filename - * @param string $mimeType + * * @return $this */ public function addResource($resource, string $filename, string $mimeType): static { $this->resources[] = [$resource, $filename, $mimeType]; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Mailer/EmailManagerFactory.php b/lib/RoadizCoreBundle/src/Mailer/EmailManagerFactory.php index 3227946e..1a91ecba 100644 --- a/lib/RoadizCoreBundle/src/Mailer/EmailManagerFactory.php +++ b/lib/RoadizCoreBundle/src/Mailer/EmailManagerFactory.php @@ -19,7 +19,7 @@ public function __construct( private readonly Environment $templating, private readonly MailerInterface $mailer, private readonly Settings $settingsBag, - private readonly DocumentUrlGeneratorInterface $documentUrlGenerator + private readonly DocumentUrlGeneratorInterface $documentUrlGenerator, ) { } diff --git a/lib/RoadizCoreBundle/src/Message/ApplyRealmNodeInheritanceMessage.php b/lib/RoadizCoreBundle/src/Message/ApplyRealmNodeInheritanceMessage.php index f00d994c..61c1f9b7 100644 --- a/lib/RoadizCoreBundle/src/Message/ApplyRealmNodeInheritanceMessage.php +++ b/lib/RoadizCoreBundle/src/Message/ApplyRealmNodeInheritanceMessage.php @@ -8,21 +8,15 @@ final class ApplyRealmNodeInheritanceMessage implements AsyncMessage { public function __construct( private readonly int|string|null $nodeId, - private readonly int|string|null $realmId + private readonly int|string|null $realmId, ) { } - /** - * @return int|string|null - */ public function getNodeId(): int|string|null { return $this->nodeId; } - /** - * @return int|string|null - */ public function getRealmId(): int|string|null { return $this->realmId; diff --git a/lib/RoadizCoreBundle/src/Message/CleanRealmNodeInheritanceMessage.php b/lib/RoadizCoreBundle/src/Message/CleanRealmNodeInheritanceMessage.php index 107e5b76..58e84bb4 100644 --- a/lib/RoadizCoreBundle/src/Message/CleanRealmNodeInheritanceMessage.php +++ b/lib/RoadizCoreBundle/src/Message/CleanRealmNodeInheritanceMessage.php @@ -8,21 +8,15 @@ final class CleanRealmNodeInheritanceMessage implements AsyncMessage { public function __construct( private readonly int|string|null $nodeId, - private readonly int|string|null $realmId + private readonly int|string|null $realmId, ) { } - /** - * @return int|string|null - */ public function getNodeId(): int|string|null { return $this->nodeId; } - /** - * @return int|string|null - */ public function getRealmId(): int|string|null { return $this->realmId; diff --git a/lib/RoadizCoreBundle/src/Message/DeleteNodeTypeMessage.php b/lib/RoadizCoreBundle/src/Message/DeleteNodeTypeMessage.php index ca7566d8..74850340 100644 --- a/lib/RoadizCoreBundle/src/Message/DeleteNodeTypeMessage.php +++ b/lib/RoadizCoreBundle/src/Message/DeleteNodeTypeMessage.php @@ -10,9 +10,6 @@ public function __construct(private readonly int|string|null $nodeTypeId) { } - /** - * @return int|string|null - */ public function getNodeTypeId(): int|string|null { return $this->nodeTypeId; diff --git a/lib/RoadizCoreBundle/src/Message/GuzzleRequestMessage.php b/lib/RoadizCoreBundle/src/Message/GuzzleRequestMessage.php index 65bb93f7..59de00fe 100644 --- a/lib/RoadizCoreBundle/src/Message/GuzzleRequestMessage.php +++ b/lib/RoadizCoreBundle/src/Message/GuzzleRequestMessage.php @@ -10,31 +10,21 @@ final class GuzzleRequestMessage implements AsyncMessage, HttpRequestMessage { private array $options; - /** - * @param RequestInterface $request - * @param array $options - */ public function __construct( private readonly RequestInterface $request, - array $options = [] + array $options = [], ) { $this->options = array_merge([ 'debug' => false, - 'timeout' => 3 + 'timeout' => 3, ], $options); } - /** - * @return RequestInterface - */ public function getRequest(): RequestInterface { return $this->request; } - /** - * @return array - */ public function getOptions(): array { return $this->options; diff --git a/lib/RoadizCoreBundle/src/Message/Handler/ApplyRealmNodeInheritanceMessageHandler.php b/lib/RoadizCoreBundle/src/Message/Handler/ApplyRealmNodeInheritanceMessageHandler.php index 2cad5a4c..a028d088 100644 --- a/lib/RoadizCoreBundle/src/Message/Handler/ApplyRealmNodeInheritanceMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Message/Handler/ApplyRealmNodeInheritanceMessageHandler.php @@ -10,8 +10,8 @@ use RZ\Roadiz\CoreBundle\Entity\RealmNode; use RZ\Roadiz\CoreBundle\Message\ApplyRealmNodeInheritanceMessage; use RZ\Roadiz\CoreBundle\Model\RealmInterface; -use Symfony\Component\Messenger\Attribute\AsMessageHandler; use RZ\Roadiz\CoreBundle\Node\NodeOffspringResolverInterface; +use Symfony\Component\Messenger\Attribute\AsMessageHandler; use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException; #[AsMessageHandler] @@ -19,13 +19,13 @@ final class ApplyRealmNodeInheritanceMessageHandler { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly NodeOffspringResolverInterface $nodeOffspringResolver + private readonly NodeOffspringResolverInterface $nodeOffspringResolver, ) { } public function __invoke(ApplyRealmNodeInheritanceMessage $message): void { - if ($message->getRealmId() === null) { + if (null === $message->getRealmId()) { return; } $node = $this->managerRegistry->getRepository(Node::class)->find($message->getNodeId()); @@ -46,7 +46,7 @@ public function __invoke(ApplyRealmNodeInheritanceMessage $message): void /* * Do not propagate if realm node inheritance type is not ROOT */ - if (null === $realmNode || $realmNode->getInheritanceType() !== RealmInterface::INHERITANCE_ROOT) { + if (null === $realmNode || RealmInterface::INHERITANCE_ROOT !== $realmNode->getInheritanceType()) { return; } diff --git a/lib/RoadizCoreBundle/src/Message/Handler/CleanRealmNodeInheritanceMessageHandler.php b/lib/RoadizCoreBundle/src/Message/Handler/CleanRealmNodeInheritanceMessageHandler.php index c0cb7895..ab327a2b 100644 --- a/lib/RoadizCoreBundle/src/Message/Handler/CleanRealmNodeInheritanceMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Message/Handler/CleanRealmNodeInheritanceMessageHandler.php @@ -9,8 +9,8 @@ use RZ\Roadiz\CoreBundle\Entity\Realm; use RZ\Roadiz\CoreBundle\Entity\RealmNode; use RZ\Roadiz\CoreBundle\Message\CleanRealmNodeInheritanceMessage; -use Symfony\Component\Messenger\Attribute\AsMessageHandler; use RZ\Roadiz\CoreBundle\Node\NodeOffspringResolverInterface; +use Symfony\Component\Messenger\Attribute\AsMessageHandler; use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException; #[AsMessageHandler] @@ -18,13 +18,13 @@ final class CleanRealmNodeInheritanceMessageHandler { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly NodeOffspringResolverInterface $nodeOffspringResolver + private readonly NodeOffspringResolverInterface $nodeOffspringResolver, ) { } public function __invoke(CleanRealmNodeInheritanceMessage $message): void { - if ($message->getRealmId() === null) { + if (null === $message->getRealmId()) { return; } $node = $this->managerRegistry->getRepository(Node::class)->find($message->getNodeId()); diff --git a/lib/RoadizCoreBundle/src/Message/Handler/DeleteNodeTypeMessageHandler.php b/lib/RoadizCoreBundle/src/Message/Handler/DeleteNodeTypeMessageHandler.php index abde1303..5b396cbf 100644 --- a/lib/RoadizCoreBundle/src/Message/Handler/DeleteNodeTypeMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Message/Handler/DeleteNodeTypeMessageHandler.php @@ -23,7 +23,7 @@ final class DeleteNodeTypeMessageHandler public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly HandlerFactoryInterface $handlerFactory, - private readonly MessageBusInterface $messageBus + private readonly MessageBusInterface $messageBus, ) { } @@ -44,7 +44,7 @@ public function __invoke(DeleteNodeTypeMessage $message): void $handler->deleteWithAssociations(); $this->messageBus->dispatch( - (new Envelope(new UpdateDoctrineSchemaMessage())) + new Envelope(new UpdateDoctrineSchemaMessage()) ); $this->managerRegistry->getManager()->clear(); } diff --git a/lib/RoadizCoreBundle/src/Message/Handler/HttpRequestMessageHandler.php b/lib/RoadizCoreBundle/src/Message/Handler/HttpRequestMessageHandler.php index c354d37d..6f309792 100644 --- a/lib/RoadizCoreBundle/src/Message/Handler/HttpRequestMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Message/Handler/HttpRequestMessageHandler.php @@ -15,7 +15,7 @@ final class HttpRequestMessageHandler { public function __construct( - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } diff --git a/lib/RoadizCoreBundle/src/Message/Handler/PurgeReverseProxyCacheMessageHandler.php b/lib/RoadizCoreBundle/src/Message/Handler/PurgeReverseProxyCacheMessageHandler.php index 76ec8101..56a2840a 100644 --- a/lib/RoadizCoreBundle/src/Message/Handler/PurgeReverseProxyCacheMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Message/Handler/PurgeReverseProxyCacheMessageHandler.php @@ -25,7 +25,7 @@ public function __construct( private readonly MessageBusInterface $bus, private readonly UrlGeneratorInterface $urlGenerator, private readonly ReverseProxyCacheLocator $reverseProxyCacheLocator, - private readonly ManagerRegistry $managerRegistry + private readonly ManagerRegistry $managerRegistry, ) { } @@ -57,35 +57,30 @@ public function __invoke(PurgeReverseProxyCacheMessage $message): void } /** - * @param string $path - * * @return \GuzzleHttp\Psr7\Request[] */ - protected function createPurgeRequests(string $path = "/"): array + protected function createPurgeRequests(string $path = '/'): array { $requests = []; foreach ($this->reverseProxyCacheLocator->getFrontends() as $frontend) { $requests[$frontend->getName()] = new \GuzzleHttp\Psr7\Request( Request::METHOD_PURGE, - 'http://' . $frontend->getHost() . $path, + 'http://'.$frontend->getHost().$path, [ - 'Host' => $frontend->getDomainName() + 'Host' => $frontend->getDomainName(), ] ); } + return $requests; } - /** - * @param \GuzzleHttp\Psr7\Request $request - * @return void - */ protected function sendRequest(\GuzzleHttp\Psr7\Request $request): void { try { $this->bus->dispatch(new Envelope(new GuzzleRequestMessage($request, [ 'debug' => false, - 'timeout' => 3 + 'timeout' => 3, ]))); } catch (NoHandlerForMessageException $exception) { throw new UnrecoverableMessageHandlingException($exception->getMessage(), 0, $exception); diff --git a/lib/RoadizCoreBundle/src/Message/Handler/SearchRealmNodeInheritanceMessageHandler.php b/lib/RoadizCoreBundle/src/Message/Handler/SearchRealmNodeInheritanceMessageHandler.php index 56daa1dc..966af980 100644 --- a/lib/RoadizCoreBundle/src/Message/Handler/SearchRealmNodeInheritanceMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Message/Handler/SearchRealmNodeInheritanceMessageHandler.php @@ -26,7 +26,7 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly HandlerFactoryInterface $handlerFactory, private readonly MessageBusInterface $bus, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } @@ -47,7 +47,7 @@ private function clearAnyExistingRealmNodes(Node $node): void /** @var RealmNode[] $autoRealmNodes */ $autoRealmNodes = $this->managerRegistry->getRepository(RealmNode::class)->findBy([ 'node' => $node, - 'inheritanceType' => RealmInterface::INHERITANCE_AUTO + 'inheritanceType' => RealmInterface::INHERITANCE_AUTO, ]); /* @@ -68,7 +68,7 @@ private function applyRootRealmNodes(Node $node): void $nodeHandler = $this->handlerFactory->getHandler($node); $parents = $nodeHandler->getParents(); - if (count($parents) === 0) { + if (0 === count($parents)) { return; } diff --git a/lib/RoadizCoreBundle/src/Message/Handler/UpdateNodeTypeSchemaMessageHandler.php b/lib/RoadizCoreBundle/src/Message/Handler/UpdateNodeTypeSchemaMessageHandler.php index 6aeb47a6..95eb172a 100644 --- a/lib/RoadizCoreBundle/src/Message/Handler/UpdateNodeTypeSchemaMessageHandler.php +++ b/lib/RoadizCoreBundle/src/Message/Handler/UpdateNodeTypeSchemaMessageHandler.php @@ -21,7 +21,7 @@ final class UpdateNodeTypeSchemaMessageHandler public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly HandlerFactoryInterface $handlerFactory, - private readonly MessageBusInterface $messageBus + private readonly MessageBusInterface $messageBus, ) { } @@ -39,7 +39,7 @@ public function __invoke(UpdateNodeTypeSchemaMessage $message): void $this->managerRegistry->getManager()->clear(); $this->messageBus->dispatch( - (new Envelope(new UpdateDoctrineSchemaMessage())) + new Envelope(new UpdateDoctrineSchemaMessage()) ); } } diff --git a/lib/RoadizCoreBundle/src/Message/HttpRequestMessage.php b/lib/RoadizCoreBundle/src/Message/HttpRequestMessage.php index 1e021314..485601d4 100644 --- a/lib/RoadizCoreBundle/src/Message/HttpRequestMessage.php +++ b/lib/RoadizCoreBundle/src/Message/HttpRequestMessage.php @@ -9,5 +9,6 @@ interface HttpRequestMessage { public function getRequest(): RequestInterface; + public function getOptions(): array; } diff --git a/lib/RoadizCoreBundle/src/Message/PurgeReverseProxyCacheMessage.php b/lib/RoadizCoreBundle/src/Message/PurgeReverseProxyCacheMessage.php index d8a47f51..2faf65ca 100644 --- a/lib/RoadizCoreBundle/src/Message/PurgeReverseProxyCacheMessage.php +++ b/lib/RoadizCoreBundle/src/Message/PurgeReverseProxyCacheMessage.php @@ -10,9 +10,6 @@ public function __construct(private readonly int|string|null $nodeSourceId) { } - /** - * @return int|string|null - */ public function getNodeSourceId(): int|string|null { return $this->nodeSourceId; diff --git a/lib/RoadizCoreBundle/src/Message/SearchRealmNodeInheritanceMessage.php b/lib/RoadizCoreBundle/src/Message/SearchRealmNodeInheritanceMessage.php index a1a634f2..d49e163d 100644 --- a/lib/RoadizCoreBundle/src/Message/SearchRealmNodeInheritanceMessage.php +++ b/lib/RoadizCoreBundle/src/Message/SearchRealmNodeInheritanceMessage.php @@ -10,9 +10,6 @@ public function __construct(private readonly int|string|null $nodeId) { } - /** - * @return int|string|null - */ public function getNodeId(): int|string|null { return $this->nodeId; diff --git a/lib/RoadizCoreBundle/src/Message/UpdateNodeTypeSchemaMessage.php b/lib/RoadizCoreBundle/src/Message/UpdateNodeTypeSchemaMessage.php index 33b36324..e7236e3c 100644 --- a/lib/RoadizCoreBundle/src/Message/UpdateNodeTypeSchemaMessage.php +++ b/lib/RoadizCoreBundle/src/Message/UpdateNodeTypeSchemaMessage.php @@ -13,9 +13,6 @@ public function __construct(private readonly int|string|null $nodeTypeId) { } - /** - * @return int|string|null - */ public function getNodeTypeId(): int|string|null { return $this->nodeTypeId; diff --git a/lib/RoadizCoreBundle/src/Model/AttributableInterface.php b/lib/RoadizCoreBundle/src/Model/AttributableInterface.php index 6024140c..50effd46 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributableInterface.php +++ b/lib/RoadizCoreBundle/src/Model/AttributableInterface.php @@ -10,42 +10,29 @@ interface AttributableInterface extends PersistableInterface { - /** - * @return Collection - */ public function getAttributeValues(): Collection; /** - * @param TranslationInterface $translation - * * @return Collection */ public function getAttributesValuesForTranslation(TranslationInterface $translation): Collection; /** - * @param TranslationInterface $translation - * * @return Collection */ public function getAttributesValuesTranslations(TranslationInterface $translation): Collection; /** - * @param Collection $attributes - * * @return $this */ public function setAttributeValues(Collection $attributes): static; /** - * @param AttributeValueInterface $attribute - * * @return $this */ public function addAttributeValue(AttributeValueInterface $attribute): static; /** - * @param AttributeValueInterface $attribute - * * @return $this */ public function removeAttributeValue(AttributeValueInterface $attribute): static; diff --git a/lib/RoadizCoreBundle/src/Model/AttributableTrait.php b/lib/RoadizCoreBundle/src/Model/AttributableTrait.php index ec5ebbf5..0196631f 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributableTrait.php +++ b/lib/RoadizCoreBundle/src/Model/AttributableTrait.php @@ -18,8 +18,6 @@ public function getAttributeValues(): Collection } /** - * @param TranslationInterface $translation - * * @return Collection */ public function getAttributesValuesForTranslation(TranslationInterface $translation): Collection @@ -31,13 +29,12 @@ public function getAttributesValuesForTranslation(TranslationInterface $translat return true; } } + return false; }); } /** - * @param TranslationInterface $translation - * * @return Collection */ public function getAttributesValuesTranslations(TranslationInterface $translation): Collection @@ -51,29 +48,28 @@ public function getAttributesValuesTranslations(TranslationInterface $translatio return $attributeValueTranslation; } } + return null; }) ->filter(function (?AttributeValueTranslationInterface $attributeValueTranslation) { return null !== $attributeValueTranslation; }) ; + return $values; // phpstan does not understand return type after filtering } /** - * @param Collection $attributes - * * @return $this */ public function setAttributeValues(Collection $attributes): static { $this->attributeValues = $attributes; + return $this; } /** - * @param AttributeValueInterface $attribute - * * @return $this */ public function addAttributeValue(AttributeValueInterface $attribute): static @@ -81,13 +77,11 @@ public function addAttributeValue(AttributeValueInterface $attribute): static if (!$this->getAttributeValues()->contains($attribute)) { $this->getAttributeValues()->add($attribute); } + return $this; } - /** - * @param AttributeValueInterface $attribute - * * @return $this */ public function removeAttributeValue(AttributeValueInterface $attribute): static @@ -95,6 +89,7 @@ public function removeAttributeValue(AttributeValueInterface $attribute): static if ($this->getAttributeValues()->contains($attribute)) { $this->getAttributeValues()->removeElement($attribute); } + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeGroupInterface.php b/lib/RoadizCoreBundle/src/Model/AttributeGroupInterface.php index 18081048..77deb630 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeGroupInterface.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeGroupInterface.php @@ -11,15 +11,20 @@ interface AttributeGroupInterface extends PersistableInterface { public function getName(): ?string; + public function getTranslatedName(TranslationInterface $translation): ?string; + public function setName(string $name): self; public function getCanonicalName(): ?string; + public function setCanonicalName(string $canonicalName): self; public function getAttributes(): Collection; + public function setAttributes(Collection $attributes): self; public function getAttributeGroupTranslations(): Collection; + public function setAttributeGroupTranslations(Collection $attributeGroupTranslations): self; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeGroupTrait.php b/lib/RoadizCoreBundle/src/Model/AttributeGroupTrait.php index 398d03d5..99bd65ef 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeGroupTrait.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeGroupTrait.php @@ -5,21 +5,18 @@ namespace RZ\Roadiz\CoreBundle\Model; use Doctrine\Common\Collections\Collection; -use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; -use RZ\Roadiz\Utils\StringHandler; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; +use RZ\Roadiz\Utils\StringHandler; use Symfony\Component\Validator\Constraints as Assert; -/** - * @package RZ\Roadiz\CoreBundle\Model - */ trait AttributeGroupTrait { #[ - ORM\Column(name: "canonical_name", type: "string", length: 255, unique: true, nullable: false), - Serializer\Groups(["attribute_group", "attribute", "node", "nodes_sources"]), - Serializer\Type("string"), + ORM\Column(name: 'canonical_name', type: 'string', length: 255, unique: true, nullable: false), + Serializer\Groups(['attribute_group', 'attribute', 'node', 'nodes_sources']), + Serializer\Type('string'), Assert\NotNull(), Assert\Length(max: 255), Assert\NotBlank() @@ -30,8 +27,8 @@ trait AttributeGroupTrait * @var Collection */ #[ - ORM\OneToMany(mappedBy: "group", targetEntity: AttributeInterface::class), - Serializer\Groups(["attribute_group"]), + ORM\OneToMany(mappedBy: 'group', targetEntity: AttributeInterface::class), + Serializer\Groups(['attribute_group']), Serializer\Type("ArrayCollection") ] protected Collection $attributes; @@ -41,14 +38,14 @@ trait AttributeGroupTrait */ #[ ORM\OneToMany( - mappedBy: "attributeGroup", + mappedBy: 'attributeGroup', targetEntity: AttributeGroupTranslationInterface::class, - cascade: ["all"], + cascade: ['all'], orphanRemoval: true ), - Serializer\Groups(["attribute_group", "attribute", "node", "nodes_sources"]), + Serializer\Groups(['attribute_group', 'attribute', 'node', 'nodes_sources']), Serializer\Type("ArrayCollection"), - Serializer\Accessor(getter: "getAttributeGroupTranslations", setter: "setAttributeGroupTranslations") + Serializer\Accessor(getter: 'getAttributeGroupTranslations', setter: 'setAttributeGroupTranslations') ] protected Collection $attributeGroupTranslations; @@ -57,6 +54,7 @@ public function getName(): ?string if ($this->getAttributeGroupTranslations()->first()) { return $this->getAttributeGroupTranslations()->first()->getName(); } + return $this->getCanonicalName(); } @@ -71,24 +69,27 @@ function (AttributeGroupTranslationInterface $attributeGroupTranslation) use ($t if ($attributeGroupTranslation->getTranslation() === $translation) { return true; } + return false; } ); - if ($attributeGroupTranslation->count() > 0 && $attributeGroupTranslation->first()->getName() !== '') { + if ($attributeGroupTranslation->count() > 0 && '' !== $attributeGroupTranslation->first()->getName()) { return $attributeGroupTranslation->first()->getName(); } + return $this->getCanonicalName(); } public function setName(?string $name): self { - if ($this->getAttributeGroupTranslations()->count() === 0) { + if (0 === $this->getAttributeGroupTranslations()->count()) { $this->getAttributeGroupTranslations()->add( $this->createAttributeGroupTranslation()->setName($name) ); } $this->canonicalName = StringHandler::slugify($name ?? ''); + return $this; } @@ -98,12 +99,12 @@ public function getCanonicalName(): ?string } /** - * @param string|null $canonicalName * @return $this */ public function setCanonicalName(?string $canonicalName): self { $this->canonicalName = StringHandler::slugify($canonicalName ?? ''); + return $this; } @@ -113,12 +114,12 @@ public function getAttributes(): Collection } /** - * @param Collection $attributes * @return $this */ public function setAttributes(Collection $attributes): self { $this->attributes = $attributes; + return $this; } @@ -128,7 +129,6 @@ public function getAttributeGroupTranslations(): Collection } /** - * @param Collection $attributeGroupTranslations * @return $this */ public function setAttributeGroupTranslations(Collection $attributeGroupTranslations): self @@ -138,11 +138,11 @@ public function setAttributeGroupTranslations(Collection $attributeGroupTranslat foreach ($this->attributeGroupTranslations as $attributeGroupTranslation) { $attributeGroupTranslation->setAttributeGroup($this); } + return $this; } /** - * @param AttributeGroupTranslationInterface $attributeGroupTranslation * @return $this */ public function addAttributeGroupTranslation(AttributeGroupTranslationInterface $attributeGroupTranslation): self @@ -151,11 +151,11 @@ public function addAttributeGroupTranslation(AttributeGroupTranslationInterface $this->getAttributeGroupTranslations()->add($attributeGroupTranslation); $attributeGroupTranslation->setAttributeGroup($this); } + return $this; } /** - * @param AttributeGroupTranslationInterface $attributeGroupTranslation * @return $this */ public function removeAttributeGroupTranslation(AttributeGroupTranslationInterface $attributeGroupTranslation): self @@ -163,6 +163,7 @@ public function removeAttributeGroupTranslation(AttributeGroupTranslationInterfa if ($this->getAttributeGroupTranslations()->contains($attributeGroupTranslation)) { $this->getAttributeGroupTranslations()->removeElement($attributeGroupTranslation); } + return $this; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationInterface.php b/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationInterface.php index 9371733a..02160d1b 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationInterface.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationInterface.php @@ -9,39 +9,24 @@ interface AttributeGroupTranslationInterface extends PersistableInterface { - /** - * @return string - */ public function getName(): string; /** - * @param string $value - * - * @return mixed + * @return $this */ - public function setName(string $value); + public function setName(string $value): self; /** - * @param TranslationInterface $translation - * - * @return mixed + * @return $this */ - public function setTranslation(TranslationInterface $translation); + public function setTranslation(TranslationInterface $translation): self; - /** - * @return TranslationInterface|null - */ public function getTranslation(): ?TranslationInterface; - /** - * @return AttributeGroupInterface - */ public function getAttributeGroup(): AttributeGroupInterface; /** - * @param AttributeGroupInterface $attributeGroup - * - * @return mixed + * @return $this */ - public function setAttributeGroup(AttributeGroupInterface $attributeGroup); + public function setAttributeGroup(AttributeGroupInterface $attributeGroup): self; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationTrait.php b/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationTrait.php index 34ec8324..b76f0cc6 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationTrait.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeGroupTranslationTrait.php @@ -13,53 +13,50 @@ trait AttributeGroupTranslationTrait { #[ ORM\ManyToOne(targetEntity: "RZ\Roadiz\Core\AbstractEntities\TranslationInterface"), - ORM\JoinColumn(name: "translation_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), - Serializer\Groups(["attribute_group", "attribute", "node", "nodes_sources"]), + ORM\JoinColumn(name: 'translation_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), + Serializer\Groups(['attribute_group', 'attribute', 'node', 'nodes_sources']), Serializer\Type("RZ\Roadiz\Core\AbstractEntities\TranslationInterface"), - Serializer\Accessor(getter: "getTranslation", setter: "setTranslation") + Serializer\Accessor(getter: 'getTranslation', setter: 'setTranslation') ] protected TranslationInterface $translation; #[ - ORM\Column(type: "string", length: 255, unique: false, nullable: false), - Serializer\Groups(["attribute_group", "attribute", "node", "nodes_sources"]), - Serializer\Type("string"), + ORM\Column(type: 'string', length: 255, unique: false, nullable: false), + Serializer\Groups(['attribute_group', 'attribute', 'node', 'nodes_sources']), + Serializer\Type('string'), Assert\Length(max: 255) ] protected string $name = ''; #[ - ORM\ManyToOne(targetEntity: AttributeGroupInterface::class, cascade: ["persist"], inversedBy: "attributeGroupTranslations"), - ORM\JoinColumn(name: "attribute_group_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), + ORM\ManyToOne(targetEntity: AttributeGroupInterface::class, cascade: ['persist'], inversedBy: 'attributeGroupTranslations'), + ORM\JoinColumn(name: 'attribute_group_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), Serializer\Exclude ] protected AttributeGroupInterface $attributeGroup; - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string $value - * @return self + * @return $this */ - public function setName(string $value) + public function setName(string $value): self { $this->name = $value; + return $this; } /** - * @param TranslationInterface $translation - * @return self + * @return $this */ - public function setTranslation(TranslationInterface $translation) + public function setTranslation(TranslationInterface $translation): self { $this->translation = $translation; + return $this; } @@ -68,21 +65,18 @@ public function getTranslation(): TranslationInterface return $this->translation; } - /** - * @return AttributeGroupInterface - */ public function getAttributeGroup(): AttributeGroupInterface { return $this->attributeGroup; } /** - * @param AttributeGroupInterface $attributeGroup - * @return self + * @return $this */ - public function setAttributeGroup(AttributeGroupInterface $attributeGroup) + public function setAttributeGroup(AttributeGroupInterface $attributeGroup): self { $this->attributeGroup = $attributeGroup; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeInterface.php b/lib/RoadizCoreBundle/src/Model/AttributeInterface.php index 1da81a62..56ca21c6 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeInterface.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeInterface.php @@ -53,27 +53,17 @@ interface AttributeInterface extends PersistableInterface */ public const DATE_T = 22; /** - * ISO Country + * ISO Country. */ public const COUNTRY_T = 25; - /** - * @return string - */ public function getCode(): string; /** - * @param string $code - * * @return $this */ public function setCode(string $code): self; - /** - * @param TranslationInterface|null $translation - * - * @return string - */ public function getLabelOrCode(?TranslationInterface $translation = null): string; /** @@ -89,135 +79,68 @@ public function getAttributeTranslations(): Collection; public function setAttributeTranslations(Collection $attributeTranslations): self; /** - * @param AttributeTranslationInterface $attributeTranslation - * * @return $this */ public function addAttributeTranslation(AttributeTranslationInterface $attributeTranslation): self; /** - * @param AttributeTranslationInterface $attributeTranslation - * * @return $this */ public function removeAttributeTranslation(AttributeTranslationInterface $attributeTranslation): self; - /** - * @return bool - */ public function isSearchable(): bool; - /** - * @param bool $searchable - */ public function setSearchable(bool $searchable): self; - /** - * @param TranslationInterface $translation - * - * @return array|null - */ public function getOptions(TranslationInterface $translation): ?array; - /** - * @return int - */ public function getType(): int; - /** - * @return string|null - */ public function getColor(): ?string; public function getWeight(): int; - /** - * @param string|null $color - */ public function setColor(?string $color): self; - /** - * @return AttributeGroupInterface|null - */ public function getGroup(): ?AttributeGroupInterface; /** - * @param AttributeGroupInterface|null $group * @return $this */ public function setGroup(?AttributeGroupInterface $group): self; - /** - * @return Collection - */ public function getDocuments(): Collection; /** - * @param int $type * @return $this */ public function setType(int $type): self; - /** - * @return bool - */ public function isString(): bool; - /** - * @return bool - */ public function isDate(): bool; - /** - * @return bool - */ public function isDateTime(): bool; - /** - * @return bool - */ public function isBoolean(): bool; - /** - * @return bool - */ public function isInteger(): bool; - /** - * @return bool - */ public function isDecimal(): bool; - /** - * @return bool - */ public function isPercent(): bool; - /** - * @return bool - */ public function isEmail(): bool; - /** - * @return bool - */ public function isColor(): bool; - /** - * @return bool - */ public function isColour(): bool; - /** - * @return bool - */ public function isEnum(): bool; - /** - * @return bool - */ public function isCountry(): bool; public function getDefaultRealm(): ?RealmInterface; + public function setDefaultRealm(?RealmInterface $defaultRealm): self; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeTrait.php b/lib/RoadizCoreBundle/src/Model/AttributeTrait.php index bb52d5e3..a8a7833d 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeTrait.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeTrait.php @@ -5,22 +5,22 @@ namespace RZ\Roadiz\CoreBundle\Model; use Doctrine\Common\Collections\Collection; +use Doctrine\ORM\Mapping as ORM; +use JMS\Serializer\Annotation as Serializer; use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; use RZ\Roadiz\CoreBundle\Entity\AttributeGroup; use RZ\Roadiz\CoreBundle\Entity\AttributeTranslation; use RZ\Roadiz\Utils\StringHandler; -use Doctrine\ORM\Mapping as ORM; -use JMS\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation as SymfonySerializer; use Symfony\Component\Validator\Constraints as Assert; trait AttributeTrait { #[ - ORM\Column(type: "string", length: 255, unique: true, nullable: false), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - SymfonySerializer\Groups(["attribute", "node", "nodes_sources"]), - Serializer\Type("string"), + ORM\Column(type: 'string', length: 255, unique: true, nullable: false), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + SymfonySerializer\Groups(['attribute', 'node', 'nodes_sources']), + Serializer\Type('string'), Assert\NotNull(), Assert\NotBlank(), Assert\Length(max: 255) @@ -28,26 +28,26 @@ trait AttributeTrait protected string $code = ''; #[ - ORM\Column(type: "boolean", unique: false, nullable: false, options: ["default" => false]), - Serializer\Groups(["attribute"]), - SymfonySerializer\Groups(["attribute"]), - Serializer\Type("boolean") + ORM\Column(type: 'boolean', unique: false, nullable: false, options: ['default' => false]), + Serializer\Groups(['attribute']), + SymfonySerializer\Groups(['attribute']), + Serializer\Type('boolean') ] protected bool $searchable = false; #[ - ORM\Column(type: "integer", unique: false, nullable: false), - Serializer\Groups(["attribute"]), - SymfonySerializer\Groups(["attribute"]), - Serializer\Type("integer") + ORM\Column(type: 'integer', unique: false, nullable: false), + Serializer\Groups(['attribute']), + SymfonySerializer\Groups(['attribute']), + Serializer\Type('integer') ] protected int $type = AttributeInterface::STRING_T; #[ - ORM\Column(type: "string", length: 7, unique: false, nullable: true), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - SymfonySerializer\Groups(["attribute", "node", "nodes_sources"]), - Serializer\Type("string"), + ORM\Column(type: 'string', length: 7, unique: false, nullable: true), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + SymfonySerializer\Groups(['attribute', 'node', 'nodes_sources']), + Serializer\Type('string'), Assert\Length(max: 7) ] protected ?string $color = null; @@ -55,32 +55,32 @@ trait AttributeTrait #[ ORM\ManyToOne( targetEntity: AttributeGroupInterface::class, - cascade: ["persist", "merge"], - fetch: "EAGER", - inversedBy: "attributes" + cascade: ['persist', 'merge'], + fetch: 'EAGER', + inversedBy: 'attributes' ), - ORM\JoinColumn(name: "group_id", onDelete: "SET NULL"), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - SymfonySerializer\Groups(["attribute", "node", "nodes_sources"]), + ORM\JoinColumn(name: 'group_id', onDelete: 'SET NULL'), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + SymfonySerializer\Groups(['attribute', 'node', 'nodes_sources']), Serializer\Type(AttributeGroup::class) ] protected ?AttributeGroupInterface $group = null; /** - * @var Collection + * @var Collection */ #[ ORM\OneToMany( - mappedBy: "attribute", + mappedBy: 'attribute', targetEntity: AttributeTranslationInterface::class, - cascade: ["all"], - fetch: "EAGER", + cascade: ['all'], + fetch: 'EAGER', orphanRemoval: true ), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - SymfonySerializer\Groups(["attribute", "node", "nodes_sources"]), - Serializer\Type("ArrayCollection<" . AttributeTranslation::class . ">"), - Serializer\Accessor(getter: "getAttributeTranslations", setter: "setAttributeTranslations") + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + SymfonySerializer\Groups(['attribute', 'node', 'nodes_sources']), + Serializer\Type('ArrayCollection<'.AttributeTranslation::class.'>'), + Serializer\Accessor(getter: 'getAttributeTranslations', setter: 'setAttributeTranslations') ] protected Collection $attributeTranslations; @@ -89,10 +89,10 @@ trait AttributeTrait */ #[ ORM\OneToMany( - mappedBy: "attribute", + mappedBy: 'attribute', targetEntity: AttributeValueInterface::class, - cascade: ["persist", "remove"], - fetch: "EXTRA_LAZY", + cascade: ['persist', 'remove'], + fetch: 'EXTRA_LAZY', orphanRemoval: true ), Serializer\Exclude, @@ -100,106 +100,81 @@ trait AttributeTrait ] protected Collection $attributeValues; - /** - * @return string - */ public function getCode(): string { return $this->code; } /** - * @param string|null $code - * * @return $this */ public function setCode(?string $code): self { $this->code = StringHandler::slugify($code ?? ''); + return $this; } - /** - * @return int - */ public function getType(): int { return $this->type; } /** - * @param int $type - * * @return $this */ public function setType(int $type): self { $this->type = $type; + return $this; } - /** - * @return string|null - */ public function getColor(): ?string { return $this->color; } /** - * @param string|null $color - * * @return $this */ public function setColor(?string $color): self { $this->color = $color; + return $this; } - /** - * @return AttributeGroupInterface|null - */ public function getGroup(): ?AttributeGroupInterface { return $this->group; } /** - * @param AttributeGroupInterface|null $group - * * @return $this */ public function setGroup(?AttributeGroupInterface $group): self { $this->group = $group; + return $this; } - /** - * @return bool - */ public function isSearchable(): bool { return (bool) $this->searchable; } /** - * @param bool $searchable - * * @return $this */ public function setSearchable(bool $searchable): self { $this->searchable = $searchable; + return $this; } - /** - * @param TranslationInterface|null $translation - * - * @return string - */ public function getLabelOrCode(?TranslationInterface $translation = null): string { if (null !== $translation) { @@ -210,8 +185,8 @@ function (AttributeTranslationInterface $attributeTranslation) use ($translation ); if ( - $attributeTranslation->first() && - $attributeTranslation->first()->getLabel() !== '' + $attributeTranslation->first() + && '' !== $attributeTranslation->first()->getLabel() ) { return $attributeTranslation->first()->getLabel(); } @@ -220,11 +195,6 @@ function (AttributeTranslationInterface $attributeTranslation) use ($translation return $this->getCode(); } - /** - * @param TranslationInterface $translation - * - * @return array|null - */ public function getOptions(TranslationInterface $translation): ?array { $attributeTranslation = $this->getAttributeTranslations()->filter( @@ -248,8 +218,6 @@ public function getAttributeTranslations(): Collection } /** - * @param Collection $attributeTranslations - * * @return $this */ public function setAttributeTranslations(Collection $attributeTranslations): self @@ -259,12 +227,11 @@ public function setAttributeTranslations(Collection $attributeTranslations): sel foreach ($this->attributeTranslations as $attributeTranslation) { $attributeTranslation->setAttribute($this); } + return $this; } /** - * @param AttributeTranslationInterface $attributeTranslation - * * @return $this */ public function addAttributeTranslation(AttributeTranslationInterface $attributeTranslation): self @@ -273,12 +240,11 @@ public function addAttributeTranslation(AttributeTranslationInterface $attribute $this->getAttributeTranslations()->add($attributeTranslation); $attributeTranslation->setAttribute($this); } + return $this; } /** - * @param AttributeTranslationInterface $attributeTranslation - * * @return $this */ public function removeAttributeTranslation(AttributeTranslationInterface $attributeTranslation): self @@ -286,52 +252,53 @@ public function removeAttributeTranslation(AttributeTranslationInterface $attrib if ($this->getAttributeTranslations()->contains($attributeTranslation)) { $this->getAttributeTranslations()->removeElement($attributeTranslation); } + return $this; } public function isString(): bool { - return $this->getType() === AttributeInterface::STRING_T; + return AttributeInterface::STRING_T === $this->getType(); } public function isDate(): bool { - return $this->getType() === AttributeInterface::DATE_T; + return AttributeInterface::DATE_T === $this->getType(); } public function isDateTime(): bool { - return $this->getType() === AttributeInterface::DATETIME_T; + return AttributeInterface::DATETIME_T === $this->getType(); } public function isBoolean(): bool { - return $this->getType() === AttributeInterface::BOOLEAN_T; + return AttributeInterface::BOOLEAN_T === $this->getType(); } public function isInteger(): bool { - return $this->getType() === AttributeInterface::INTEGER_T; + return AttributeInterface::INTEGER_T === $this->getType(); } public function isDecimal(): bool { - return $this->getType() === AttributeInterface::DECIMAL_T; + return AttributeInterface::DECIMAL_T === $this->getType(); } public function isPercent(): bool { - return $this->getType() === AttributeInterface::PERCENT_T; + return AttributeInterface::PERCENT_T === $this->getType(); } public function isEmail(): bool { - return $this->getType() === AttributeInterface::EMAIL_T; + return AttributeInterface::EMAIL_T === $this->getType(); } public function isColor(): bool { - return $this->getType() === AttributeInterface::COLOUR_T; + return AttributeInterface::COLOUR_T === $this->getType(); } public function isColour(): bool @@ -341,28 +308,28 @@ public function isColour(): bool public function isEnum(): bool { - return $this->getType() === AttributeInterface::ENUM_T; + return AttributeInterface::ENUM_T === $this->getType(); } public function isCountry(): bool { - return $this->getType() === AttributeInterface::COUNTRY_T; + return AttributeInterface::COUNTRY_T === $this->getType(); } public function getTypeLabel(): string { return match ($this->getType()) { - AttributeInterface::DATETIME_T => 'attributes.form.type.datetime', - AttributeInterface::BOOLEAN_T => 'attributes.form.type.boolean', - AttributeInterface::INTEGER_T => 'attributes.form.type.integer', - AttributeInterface::DECIMAL_T => 'attributes.form.type.decimal', - AttributeInterface::PERCENT_T => 'attributes.form.type.percent', - AttributeInterface::EMAIL_T => 'attributes.form.type.email', - AttributeInterface::COLOUR_T => 'attributes.form.type.colour', - AttributeInterface::ENUM_T => 'attributes.form.type.enum', - AttributeInterface::DATE_T => 'attributes.form.type.date', - AttributeInterface::COUNTRY_T => 'attributes.form.type.country', - default => 'attributes.form.type.string', + AttributeInterface::DATETIME_T => 'attributes.form.type.datetime', + AttributeInterface::BOOLEAN_T => 'attributes.form.type.boolean', + AttributeInterface::INTEGER_T => 'attributes.form.type.integer', + AttributeInterface::DECIMAL_T => 'attributes.form.type.decimal', + AttributeInterface::PERCENT_T => 'attributes.form.type.percent', + AttributeInterface::EMAIL_T => 'attributes.form.type.email', + AttributeInterface::COLOUR_T => 'attributes.form.type.colour', + AttributeInterface::ENUM_T => 'attributes.form.type.enum', + AttributeInterface::DATE_T => 'attributes.form.type.date', + AttributeInterface::COUNTRY_T => 'attributes.form.type.country', + default => 'attributes.form.type.string', }; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeTranslationInterface.php b/lib/RoadizCoreBundle/src/Model/AttributeTranslationInterface.php index c96ce5ba..730e8850 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeTranslationInterface.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeTranslationInterface.php @@ -9,52 +9,31 @@ interface AttributeTranslationInterface extends PersistableInterface { - /** - * @return string|null - */ public function getLabel(): ?string; /** - * @param string|null $label - * - * @return mixed + * @return $this */ - public function setLabel(?string $label); + public function setLabel(?string $label): self; /** - * @param TranslationInterface $translation - * - * @return mixed + * @return $this */ - public function setTranslation(TranslationInterface $translation); + public function setTranslation(TranslationInterface $translation): self; - /** - * @return TranslationInterface|null - */ public function getTranslation(): ?TranslationInterface; - /** - * @return AttributeInterface - */ public function getAttribute(): AttributeInterface; /** - * @param AttributeInterface $attribute - * - * @return mixed + * @return $this */ - public function setAttribute(AttributeInterface $attribute); - + public function setAttribute(AttributeInterface $attribute): self; - /** - * @return array|null - */ public function getOptions(): ?array; /** - * @param array|null $options - * - * @return mixed + * @return $this */ - public function setOptions(?array $options); + public function setOptions(?array $options): self; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeTranslationTrait.php b/lib/RoadizCoreBundle/src/Model/AttributeTranslationTrait.php index 9926436f..24866495 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeTranslationTrait.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeTranslationTrait.php @@ -13,17 +13,17 @@ trait AttributeTranslationTrait { #[ ORM\ManyToOne(targetEntity: TranslationInterface::class), - ORM\JoinColumn(name: "translation_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), - Serializer\Groups(["attribute", "node", "nodes_sources"]), + ORM\JoinColumn(name: 'translation_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), Serializer\Type("RZ\Roadiz\Core\AbstractEntities\TranslationInterface"), - Serializer\Accessor(getter: "getTranslation", setter: "setTranslation") + Serializer\Accessor(getter: 'getTranslation', setter: 'setTranslation') ] protected TranslationInterface $translation; #[ - ORM\Column(type: "string", length: 250, unique: false, nullable: false), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - Serializer\Type("string"), + ORM\Column(type: 'string', length: 250, unique: false, nullable: false), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + Serializer\Type('string'), Assert\Length(max: 250) ] protected string $label = ''; @@ -32,45 +32,41 @@ trait AttributeTranslationTrait * @var array|null */ #[ - ORM\Column(type: "simple_array", unique: false, nullable: true), - Serializer\Groups(["attribute"]), - Serializer\Type("array") + ORM\Column(type: 'simple_array', unique: false, nullable: true), + Serializer\Groups(['attribute']), + Serializer\Type('array') ] protected ?array $options = []; #[ - ORM\ManyToOne(targetEntity: AttributeInterface::class, cascade: ["persist"], inversedBy: "attributeTranslations"), - ORM\JoinColumn(name: "attribute_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), + ORM\ManyToOne(targetEntity: AttributeInterface::class, cascade: ['persist'], inversedBy: 'attributeTranslations'), + ORM\JoinColumn(name: 'attribute_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), Serializer\Exclude ] protected AttributeInterface $attribute; - /** - * @return string|null - */ public function getLabel(): ?string { return $this->label; } /** - * @param string|null $label - * * @return $this */ - public function setLabel(?string $label) + public function setLabel(?string $label): self { $this->label = null !== $label ? trim($label) : null; + return $this; } /** - * @param TranslationInterface $translation * @return $this */ - public function setTranslation(TranslationInterface $translation) + public function setTranslation(TranslationInterface $translation): self { $this->translation = $translation; + return $this; } @@ -79,25 +75,21 @@ public function getTranslation(): TranslationInterface return $this->translation; } - /** - * @return AttributeInterface - */ public function getAttribute(): AttributeInterface { return $this->attribute; } /** - * @param AttributeInterface $attribute * @return $this */ - public function setAttribute(AttributeInterface $attribute) + public function setAttribute(AttributeInterface $attribute): self { $this->attribute = $attribute; + return $this; } - /** * @return array|null */ @@ -111,9 +103,10 @@ public function getOptions(): ?array * * @return $this */ - public function setOptions(?array $options) + public function setOptions(?array $options): self { $this->options = $options; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeValueInterface.php b/lib/RoadizCoreBundle/src/Model/AttributeValueInterface.php index aab86a8c..9c7061db 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeValueInterface.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeValueInterface.php @@ -12,23 +12,19 @@ interface AttributeValueInterface extends PositionedInterface, PersistableInterface { public function getRealm(): ?RealmInterface; - public function setRealm(?RealmInterface $realm): self; /** - * @return AttributeInterface|null + * @return $this */ + public function setRealm(?RealmInterface $realm): self; + public function getAttribute(): ?AttributeInterface; /** - * @param AttributeInterface $attribute - * - * @return mixed + * @return $this */ - public function setAttribute(AttributeInterface $attribute); + public function setAttribute(AttributeInterface $attribute): self; - /** - * @return int - */ public function getType(): int; /** @@ -36,29 +32,19 @@ public function getType(): int; */ public function getAttributeValueTranslations(): Collection; - /** - * @param TranslationInterface $translation - * - * @return AttributeValueTranslationInterface|null - */ public function getAttributeValueTranslation(TranslationInterface $translation): ?AttributeValueTranslationInterface; /** * @param Collection $attributeValueTranslations * - * @return mixed + * @return $this */ - public function setAttributeValueTranslations(Collection $attributeValueTranslations); + public function setAttributeValueTranslations(Collection $attributeValueTranslations): self; - /** - * @return AttributableInterface|null - */ public function getAttributable(): ?AttributableInterface; /** - * @param AttributableInterface|null $attributable - * - * @return mixed + * @return $this */ - public function setAttributable(?AttributableInterface $attributable); + public function setAttributable(?AttributableInterface $attributable): self; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeValueTrait.php b/lib/RoadizCoreBundle/src/Model/AttributeValueTrait.php index ef154cfc..47f9f39e 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeValueTrait.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeValueTrait.php @@ -4,38 +4,38 @@ namespace RZ\Roadiz\CoreBundle\Model; +use ApiPlatform\Doctrine\Orm\Filter as BaseFilter; use ApiPlatform\Metadata\ApiFilter; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; -use ApiPlatform\Doctrine\Orm\Filter as BaseFilter; trait AttributeValueTrait { #[ - ORM\ManyToOne(targetEntity: AttributeInterface::class, fetch: "EAGER", inversedBy: "attributeValues"), - ORM\JoinColumn(name: "attribute_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), - Serializer\Groups(["attribute", "node", "nodes_sources"]), + ORM\ManyToOne(targetEntity: AttributeInterface::class, fetch: 'EAGER', inversedBy: 'attributeValues'), + ORM\JoinColumn(name: 'attribute_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), Serializer\Type("RZ\Roadiz\CoreBundle\Entity\Attribute"), ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "attribute.id" => "exact", - "attribute.code" => "exact", - "attribute.color" => "exact", - "attribute.type" => "exact", - "attribute.group" => "exact", - "attribute.group.canonicalName" => "exact", + 'attribute.id' => 'exact', + 'attribute.code' => 'exact', + 'attribute.color' => 'exact', + 'attribute.type' => 'exact', + 'attribute.group' => 'exact', + 'attribute.group.canonicalName' => 'exact', ]), ApiFilter(BaseFilter\BooleanFilter::class, properties: [ - "attribute.visible", - "attribute.searchable" + 'attribute.visible', + 'attribute.searchable', ]), ApiFilter(BaseFilter\ExistsFilter::class, properties: [ - "attribute.color", - "attribute.group" + 'attribute.color', + 'attribute.group', ]), ApiFilter(BaseFilter\OrderFilter::class, properties: [ - "attribute.weight" => "DESC", + 'attribute.weight' => 'DESC', ]) ] protected AttributeInterface $attribute; @@ -45,48 +45,39 @@ trait AttributeValueTrait */ #[ ORM\OneToMany( - mappedBy: "attributeValue", + mappedBy: 'attributeValue', targetEntity: AttributeValueTranslationInterface::class, - cascade: ["persist", "remove"], - fetch: "EAGER", + cascade: ['persist', 'remove'], + fetch: 'EAGER', orphanRemoval: true ), - Serializer\Groups(["attribute", "node", "nodes_sources"]), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), Serializer\Type("ArrayCollection"), - Serializer\Accessor(getter: "getAttributeValueTranslations", setter: "setAttributeValueTranslations"), + Serializer\Accessor(getter: 'getAttributeValueTranslations', setter: 'setAttributeValueTranslations'), ApiFilter(BaseFilter\SearchFilter::class, properties: [ - "attributeValueTranslations.value" => "partial", + 'attributeValueTranslations.value' => 'partial', ]), ApiFilter(BaseFilter\RangeFilter::class, properties: [ - "attributeValueTranslations.value", + 'attributeValueTranslations.value', ]), ApiFilter(BaseFilter\ExistsFilter::class, properties: [ - "attributeValueTranslations.value", + 'attributeValueTranslations.value', ]), ] protected Collection $attributeValueTranslations; - /** - * @return AttributeInterface|null - */ public function getAttribute(): ?AttributeInterface { return $this->attribute; } - /** - * @param AttributeInterface $attribute - * @return self - */ - public function setAttribute(AttributeInterface $attribute) + public function setAttribute(AttributeInterface $attribute): self { $this->attribute = $attribute; + return $this; } - /** - * @return int - */ public function getType(): int { return $this->getAttribute()->getType(); @@ -101,25 +92,19 @@ public function getAttributeValueTranslations(): Collection } /** - * @param Collection $attributeValueTranslations - * * @return static */ - public function setAttributeValueTranslations(Collection $attributeValueTranslations) + public function setAttributeValueTranslations(Collection $attributeValueTranslations): self { $this->attributeValueTranslations = $attributeValueTranslations; /** @var AttributeValueTranslationInterface $attributeValueTranslation */ foreach ($this->attributeValueTranslations as $attributeValueTranslation) { $attributeValueTranslation->setAttributeValue($this); } + return $this; } - /** - * @param TranslationInterface $translation - * - * @return AttributeValueTranslationInterface|null - */ public function getAttributeValueTranslation(TranslationInterface $translation): ?AttributeValueTranslationInterface { return $this->getAttributeValueTranslations() @@ -127,14 +112,12 @@ public function getAttributeValueTranslation(TranslationInterface $translation): if ($attributeValueTranslation->getTranslation() === $translation) { return true; } + return false; }) ->first() ?: null; } - /** - * @return AttributeValueTranslationInterface|null - */ public function getAttributeValueDefaultTranslation(): ?AttributeValueTranslationInterface { return $this->getAttributeValueTranslations() diff --git a/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationInterface.php b/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationInterface.php index c0ad7e74..cb0938fb 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationInterface.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationInterface.php @@ -9,44 +9,26 @@ interface AttributeValueTranslationInterface extends PersistableInterface { - /** - * @return mixed - */ - public function getValue(); + public function getValue(): mixed; /** - * @param mixed $value - * - * @return mixed + * @return $this */ - public function setValue($value); + public function setValue(mixed $value): self; /** - * @param TranslationInterface $translation - * - * @return mixed + * @return $this */ - public function setTranslation(TranslationInterface $translation); + public function setTranslation(TranslationInterface $translation): self; - /** - * @return TranslationInterface|null - */ public function getTranslation(): ?TranslationInterface; - /** - * @return AttributeInterface|null - */ public function getAttribute(): ?AttributeInterface; - /** - * @return AttributeValueInterface - */ public function getAttributeValue(): AttributeValueInterface; /** - * @param AttributeValueInterface $attributeValue - * - * @return mixed + * @return $this */ - public function setAttributeValue(AttributeValueInterface $attributeValue); + public function setAttributeValue(AttributeValueInterface $attributeValue): self; } diff --git a/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationTrait.php b/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationTrait.php index 57cb8ae2..06d2a060 100644 --- a/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationTrait.php +++ b/lib/RoadizCoreBundle/src/Model/AttributeValueTranslationTrait.php @@ -4,39 +4,38 @@ namespace RZ\Roadiz\CoreBundle\Model; -use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation as Serializer; +use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; use Symfony\Component\Validator\Constraints as Assert; trait AttributeValueTranslationTrait { #[ ORM\ManyToOne(targetEntity: TranslationInterface::class), - ORM\JoinColumn(name: "translation_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), - Serializer\Groups(["attribute", "node", "nodes_sources"]), + ORM\JoinColumn(name: 'translation_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), Serializer\Type("RZ\Roadiz\Core\AbstractEntities\TranslationInterface"), - Serializer\Accessor(getter: "getTranslation", setter: "setTranslation") + Serializer\Accessor(getter: 'getTranslation', setter: 'setTranslation') ] protected TranslationInterface $translation; #[ - ORM\Column(type: "string", length: 255, unique: false, nullable: true), - Serializer\Groups(["attribute", "node", "nodes_sources"]), - Serializer\Type("string"), + ORM\Column(type: 'string', length: 255, unique: false, nullable: true), + Serializer\Groups(['attribute', 'node', 'nodes_sources']), + Serializer\Type('string'), Assert\Length(max: 255) ] protected ?string $value = null; #[ - ORM\ManyToOne(targetEntity: AttributeValueInterface::class, cascade: ["persist"], inversedBy: "attributeValueTranslations"), - ORM\JoinColumn(name: "attribute_value", referencedColumnName: "id", nullable: false, onDelete: "CASCADE"), + ORM\ManyToOne(targetEntity: AttributeValueInterface::class, cascade: ['persist'], inversedBy: 'attributeValueTranslations'), + ORM\JoinColumn(name: 'attribute_value', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE'), Serializer\Exclude ] protected AttributeValueInterface $attributeValue; /** - * @return bool|\DateTime|float|int|string|null * @throws \Exception */ public function getValue(): bool|\DateTime|float|int|string|null @@ -44,6 +43,7 @@ public function getValue(): bool|\DateTime|float|int|string|null if (null === $this->value) { return null; } + return match ($this->getAttributeValue()->getType()) { AttributeInterface::DECIMAL_T => (float) $this->value, AttributeInterface::INTEGER_T => (int) $this->value, @@ -56,9 +56,9 @@ public function getValue(): bool|\DateTime|float|int|string|null /** * @param mixed|null $value * - * @return self + * @return $this */ - public function setValue(mixed $value) + public function setValue(mixed $value): self { if (null === $value) { $this->value = null; @@ -69,6 +69,7 @@ public function setValue(mixed $value) throw new \InvalidArgumentException('Email is not valid'); } $this->value = (string) $value; + return $this; case AttributeInterface::DATETIME_T: case AttributeInterface::DATE_T: @@ -77,20 +78,22 @@ public function setValue(mixed $value) } else { $this->value = (string) $value; } + return $this; default: $this->value = (string) $value; + return $this; } } /** - * @param TranslationInterface $translation - * @return self + * @return $this */ - public function setTranslation(TranslationInterface $translation) + public function setTranslation(TranslationInterface $translation): self { $this->translation = $translation; + return $this; } @@ -99,21 +102,18 @@ public function getTranslation(): TranslationInterface return $this->translation; } - /** - * @return AttributeValueInterface - */ public function getAttributeValue(): AttributeValueInterface { return $this->attributeValue; } /** - * @param AttributeValueInterface $attributeValue - * @return self + * @return $this */ - public function setAttributeValue(AttributeValueInterface $attributeValue) + public function setAttributeValue(AttributeValueInterface $attributeValue): self { $this->attributeValue = $attributeValue; + return $this; } diff --git a/lib/RoadizCoreBundle/src/Model/NodeTreeDto.php b/lib/RoadizCoreBundle/src/Model/NodeTreeDto.php index c07d1053..2bcacd9e 100644 --- a/lib/RoadizCoreBundle/src/Model/NodeTreeDto.php +++ b/lib/RoadizCoreBundle/src/Model/NodeTreeDto.php @@ -106,36 +106,24 @@ public function isLocked(): bool return $this->locked; } - /** - * @return bool - */ public function isPublished(): bool { - return ($this->status === Node::PUBLISHED); + return Node::PUBLISHED === $this->status; } - /** - * @return bool - */ public function isPending(): bool { - return ($this->status === Node::PENDING); + return Node::PENDING === $this->status; } - /** - * @return bool - */ public function isDraft(): bool { - return ($this->status === Node::DRAFT); + return Node::DRAFT === $this->status; } - /** - * @return bool - */ public function isDeleted(): bool { - return ($this->status === Node::DELETED); + return Node::DELETED === $this->status; } public function getNodeType(): NodeTypeInterface diff --git a/lib/RoadizCoreBundle/src/Model/RealmInterface.php b/lib/RoadizCoreBundle/src/Model/RealmInterface.php index 6518eca8..f6322078 100644 --- a/lib/RoadizCoreBundle/src/Model/RealmInterface.php +++ b/lib/RoadizCoreBundle/src/Model/RealmInterface.php @@ -33,20 +33,24 @@ interface RealmInterface extends PersistableInterface public function getType(): string; /** - * @return string * @see https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml */ public function getAuthenticationScheme(): string; /** - * @return string * @see https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/WWW-Authenticate */ public function getChallenge(): string; + public function getBehaviour(): string; + public function getName(): string; + public function getPlainPassword(): ?string; + public function getRole(): ?string; + public function getUsers(): Collection; + public function getSerializationGroup(): ?string; } diff --git a/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolver.php b/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolver.php index 88976779..229b10c1 100644 --- a/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolver.php +++ b/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolver.php @@ -17,18 +17,17 @@ final class CachedNodeOffspringResolver implements CachedNodeOffspringResolverIn { public function __construct( private readonly CacheItemPoolInterface $cache, - private readonly ManagerRegistry $managerRegistry + private readonly ManagerRegistry $managerRegistry, ) { } /** - * @inheritDoc * @throws InvalidArgumentException * @throws CacheException */ public function getAllOffspringIds(NodeInterface $ancestor): array { - $cacheItem = $this->cache->getItem(self::CACHE_PREFIX . $ancestor->getId()); + $cacheItem = $this->cache->getItem(self::CACHE_PREFIX.$ancestor->getId()); if (!$cacheItem->isHit()) { $nodeRepository = $this->managerRegistry->getRepository(Node::class); $offspringIds = $nodeRepository->findAllOffspringIdByNode($ancestor); @@ -36,13 +35,14 @@ public function getAllOffspringIds(NodeInterface $ancestor): array $cacheItem->expiresAfter(300); if ($cacheItem instanceof ItemInterface && $this->cache instanceof TagAwareCacheInterface) { $cacheItem->tag(array_map(function (int $nodeId) { - return self::CACHE_TAG_PREFIX . $nodeId; + return self::CACHE_TAG_PREFIX.$nodeId; }, $offspringIds)); } $this->cache->save($cacheItem); } else { $offspringIds = $cacheItem->get(); } + return $offspringIds; } @@ -51,18 +51,18 @@ public function getAllOffspringIds(NodeInterface $ancestor): array */ public function purgeOffspringCache(NodeInterface $node): void { - $this->cache->deleteItem(self::CACHE_PREFIX . $node->getId()); + $this->cache->deleteItem(self::CACHE_PREFIX.$node->getId()); if ($this->cache instanceof TagAwareCacheInterface) { /* * If cache pool supports tags, we can invalidate all nodes at once. */ - $this->cache->invalidateTags([self::CACHE_TAG_PREFIX . $node->getId()]); + $this->cache->invalidateTags([self::CACHE_TAG_PREFIX.$node->getId()]); } elseif ($node instanceof Node) { $ancestorsId = $this->managerRegistry ->getRepository(Node::class) ->findAllParentsIdByNode($node); foreach ($ancestorsId as $ancestorId) { - $this->cache->deleteItem(self::CACHE_PREFIX . $ancestorId); + $this->cache->deleteItem(self::CACHE_PREFIX.$ancestorId); } } } diff --git a/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolverInterface.php b/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolverInterface.php index 6786db09..424c0290 100644 --- a/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolverInterface.php +++ b/lib/RoadizCoreBundle/src/Node/CachedNodeOffspringResolverInterface.php @@ -10,5 +10,6 @@ interface CachedNodeOffspringResolverInterface extends NodeOffspringResolverInte { public const CACHE_PREFIX = 'node_offspring_ids_'; public const CACHE_TAG_PREFIX = 'node_'; + public function purgeOffspringCache(NodeInterface $node): void; } diff --git a/lib/RoadizCoreBundle/src/Node/NodeDuplicator.php b/lib/RoadizCoreBundle/src/Node/NodeDuplicator.php index f1b6c5a6..2ff12929 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeDuplicator.php +++ b/lib/RoadizCoreBundle/src/Node/NodeDuplicator.php @@ -21,14 +21,12 @@ final class NodeDuplicator public function __construct( private readonly Node $originalNode, private readonly ObjectManager $objectManager, - private readonly NodeNamePolicyInterface $nodeNamePolicy + private readonly NodeNamePolicyInterface $nodeNamePolicy, ) { } /** * Warning this method flush entityManager at its end. - * - * @return Node */ public function duplicate(): Node { @@ -45,7 +43,7 @@ public function duplicate(): Node $this->objectManager->clear(); } - if ($parent !== null) { + if (null !== $parent) { /** @var Node $parent */ $parent = $this->objectManager->find(Node::class, $parent->getId()); $node->setParent($parent); @@ -62,9 +60,6 @@ public function duplicate(): Node /** * Warning, do not do any FLUSH here to preserve transactional integrity. - * - * @param Node $node - * @return Node */ private function doDuplicate(Node &$node): Node { @@ -123,8 +118,6 @@ private function doDuplicate(Node &$node): Node * Duplicate Node to Node relationship. * * Warning, do not do any FLUSH here to preserve transactional integrity. - * - * @param Node $node */ private function doDuplicateNodeRelations(Node $node): void { diff --git a/lib/RoadizCoreBundle/src/Node/NodeFactory.php b/lib/RoadizCoreBundle/src/Node/NodeFactory.php index 1cbc852b..f38a4d16 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeFactory.php +++ b/lib/RoadizCoreBundle/src/Node/NodeFactory.php @@ -19,7 +19,7 @@ final class NodeFactory { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly NodeNamePolicyInterface $nodeNamePolicy + private readonly NodeNamePolicyInterface $nodeNamePolicy, ) { } @@ -28,21 +28,21 @@ public function create( ?NodeTypeInterface $type = null, ?TranslationInterface $translation = null, ?Node $node = null, - ?Node $parent = null + ?Node $parent = null, ): Node { /** @var NodeRepository $repository */ $repository = $this->managerRegistry->getRepository(Node::class) ->setDisplayingAllNodesStatuses(true); - if ($node === null && $type === null) { + if (null === $node && null === $type) { throw new \RuntimeException('Cannot create node from null NodeType and null Node.'); } - if ($translation === null) { + if (null === $translation) { $translation = $this->managerRegistry->getRepository(Translation::class)->findDefault(); } - if ($node === null) { + if (null === $node) { $node = new Node(); $node->setNodeType($type); } @@ -90,7 +90,7 @@ public function createWithUrlAlias( ?NodeTypeInterface $type = null, ?TranslationInterface $translation = null, ?Node $node = null, - ?Node $parent = null + ?Node $parent = null, ): Node { $node = $this->create($title, $type, $translation, $node, $parent); $nodeSource = $node->getNodeSources()->first(); diff --git a/lib/RoadizCoreBundle/src/Node/NodeMover.php b/lib/RoadizCoreBundle/src/Node/NodeMover.php index 8deaff0d..c302ae6f 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeMover.php +++ b/lib/RoadizCoreBundle/src/Node/NodeMover.php @@ -9,16 +9,15 @@ use Psr\Cache\CacheItemPoolInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; +use RZ\Roadiz\Core\Handlers\HandlerFactoryInterface; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\Roadiz\CoreBundle\Entity\Redirection; -use RZ\Roadiz\Core\Handlers\HandlerFactoryInterface; use RZ\Roadiz\CoreBundle\EntityHandler\NodeHandler; -use RZ\Roadiz\CoreBundle\Event\Redirection\PostCreatedRedirectionEvent; use RZ\Roadiz\CoreBundle\Event\Redirection\PostUpdatedRedirectionEvent; +use RZ\Roadiz\CoreBundle\Node\Exception\SameNodeUrlException; use RZ\Roadiz\CoreBundle\Repository\EntityRepository; use RZ\Roadiz\CoreBundle\Routing\NodeRouter; -use RZ\Roadiz\CoreBundle\Node\Exception\SameNodeUrlException; use Symfony\Cmf\Component\Routing\RouteObjectInterface; use Symfony\Component\Cache\ResettableInterface; use Symfony\Component\HttpFoundation\Response; @@ -35,21 +34,13 @@ class NodeMover protected CacheItemPoolInterface $cacheAdapter; protected LoggerInterface $logger; - /** - * @param ManagerRegistry $managerRegistry - * @param UrlGeneratorInterface $urlGenerator - * @param HandlerFactoryInterface $handlerFactory - * @param EventDispatcherInterface $dispatcher - * @param CacheItemPoolInterface $cacheAdapter - * @param LoggerInterface|null $logger - */ public function __construct( ManagerRegistry $managerRegistry, UrlGeneratorInterface $urlGenerator, HandlerFactoryInterface $handlerFactory, EventDispatcherInterface $dispatcher, CacheItemPoolInterface $cacheAdapter, - ?LoggerInterface $logger = null + ?LoggerInterface $logger = null, ) { $this->urlGenerator = $urlGenerator; $this->logger = $logger ?? new NullLogger(); @@ -65,28 +56,21 @@ private function getManager(): ObjectManager if (null === $manager) { throw new \RuntimeException('No manager was found during transtyping.'); } + return $manager; } /** * Warning: this method DOES NOT flush entity manager. - * - * @param Node $node - * @param Node|null $parentNode - * @param float $position - * @param bool $force - * @param bool $cleanPosition - * - * @return Node */ public function move( Node $node, ?Node $parentNode, float $position, bool $force = false, - bool $cleanPosition = true + bool $cleanPosition = true, ): Node { - if ($node->isLocked() && $force === false) { + if ($node->isLocked() && false === $force) { throw new BadRequestHttpException('Locked node cannot be moved.'); } @@ -111,11 +95,6 @@ public function move( return $node; } - /** - * @param Node $node - * - * @return array - */ public function getNodeSourcesUrls(Node $node): array { $paths = []; @@ -133,18 +112,14 @@ public function getNodeSourcesUrls(Node $node): array } $paths[$nodeSource->getTranslation()->getLocale()] = $url; $this->logger->debug( - 'Redirect ' . $nodeSource->getId() . ' ' . $nodeSource->getTranslation()->getLocale() . ': ' . $url + 'Redirect '.$nodeSource->getId().' '.$nodeSource->getTranslation()->getLocale().': '.$url ); $lastUrl = $url; } + return $paths; } - /** - * @param Node $node - * @param array $previousPaths - * @param bool $permanently - */ public function redirectAll(Node $node, array $previousPaths, bool $permanently = true): void { if (count($previousPaths) > 0) { @@ -163,17 +138,12 @@ public function redirectAll(Node $node, array $previousPaths, bool $permanently /** * Warning: this method DOES NOT flush entity manager. - * - * @param NodesSources $nodeSource - * @param string $previousPath - * @param bool $permanently - * - * @return NodesSources */ protected function redirect(NodesSources $nodeSource, string $previousPath, bool $permanently = true): NodesSources { - if (empty($previousPath) || $previousPath === '/') { - $this->logger->warning('Cannot redirect empty or root path: ' . $nodeSource->getTitle()); + if (empty($previousPath) || '/' === $previousPath) { + $this->logger->warning('Cannot redirect empty or root path: '.$nodeSource->getTitle()); + return $nodeSource; } @@ -181,7 +151,7 @@ protected function redirect(NodesSources $nodeSource, string $previousPath, bool RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ RouteObjectInterface::ROUTE_OBJECT => $nodeSource, - NodeRouter::NO_CACHE_PARAMETER => true // do not use nodeSourceUrl cache provider + NodeRouter::NO_CACHE_PARAMETER => true, // do not use nodeSourceUrl cache provider ] ); diff --git a/lib/RoadizCoreBundle/src/Node/NodeNameChecker.php b/lib/RoadizCoreBundle/src/Node/NodeNameChecker.php index b9b54d77..06b05297 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeNameChecker.php +++ b/lib/RoadizCoreBundle/src/Node/NodeNameChecker.php @@ -18,10 +18,6 @@ class NodeNameChecker implements NodeNamePolicyInterface protected bool $useTypedSuffix; private ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - * @param bool $useTypedSuffix - */ public function __construct(ManagerRegistry $managerRegistry, bool $useTypedSuffix = false) { $this->useTypedSuffix = $useTypedSuffix; @@ -31,25 +27,28 @@ public function __construct(ManagerRegistry $managerRegistry, bool $useTypedSuff public function getCanonicalNodeName(NodesSources $nodeSource): string { $nodeTypeSuffix = StringHandler::slugify($nodeSource->getNodeTypeName()); - if ($nodeSource->getTitle() !== '') { + if ('' !== $nodeSource->getTitle()) { $title = StringHandler::slugify($nodeSource->getTitle()); if ($nodeSource->isReachable() || !$this->useTypedSuffix) { // truncate title to 250 chars if needed if (\mb_strlen($title) > self::MAX_LENGTH) { $title = \mb_substr($title, 0, self::MAX_LENGTH); } + return $title; } // truncate title if title + suffix + 1 exceed 250 chars if ((\mb_strlen($title) + \mb_strlen($nodeTypeSuffix) + 1) > self::MAX_LENGTH) { $title = \mb_substr($title, 0, self::MAX_LENGTH - (\mb_strlen($nodeTypeSuffix) + 1)); } + return sprintf( '%s-%s', $title, $nodeTypeSuffix, ); } + return sprintf( '%s-%s', $nodeTypeSuffix, @@ -102,13 +101,12 @@ public function getDatestampedNodeName(NodesSources $nodeSource): string /** * Test if current node name is suffixed with a 13 chars Unique ID (uniqid()). * - * @param string $canonicalNodeName Node name without uniqid after. - * @param string $nodeName Node name to test - * @return bool + * @param string $canonicalNodeName node name without uniqid after + * @param string $nodeName Node name to test */ public function isNodeNameWithUniqId(string $canonicalNodeName, string $nodeName): bool { - $pattern = '#^' . preg_quote($canonicalNodeName) . '\-[0-9a-z]{13}$#'; + $pattern = '#^'.preg_quote($canonicalNodeName).'\-[0-9a-z]{13}$#'; $returnState = preg_match_all($pattern, $nodeName); if (1 === $returnState) { @@ -118,25 +116,18 @@ public function isNodeNameWithUniqId(string $canonicalNodeName, string $nodeName return false; } - /** - * @param string $nodeName - * - * @return bool - */ public function isNodeNameValid(string $nodeName): bool { - if (preg_match('#^[a-zA-Z0-9\-]+$#', $nodeName) === 1) { + if (1 === preg_match('#^[a-zA-Z0-9\-]+$#', $nodeName)) { return true; } + return false; } /** * Test if node’s name is already used as a name or an url-alias. * - * @param string $nodeName - * - * @return bool * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ @@ -151,11 +142,12 @@ public function isNodeNameAlreadyUsed(string $nodeName): bool ->setDisplayingNotPublishedNodes(true); if ( - false === $urlAliasRepo->exists($nodeName) && - false === $nodeRepo->exists($nodeName) + false === $urlAliasRepo->exists($nodeName) + && false === $nodeRepo->exists($nodeName) ) { return false; } + return true; } } diff --git a/lib/RoadizCoreBundle/src/Node/NodeNamePolicyFactory.php b/lib/RoadizCoreBundle/src/Node/NodeNamePolicyFactory.php index 2eefaa2a..684bf003 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeNamePolicyFactory.php +++ b/lib/RoadizCoreBundle/src/Node/NodeNamePolicyFactory.php @@ -10,7 +10,7 @@ final class NodeNamePolicyFactory { public function __construct( private readonly ManagerRegistry $registry, - private readonly bool $useTypedNodeNames + private readonly bool $useTypedNodeNames, ) { } diff --git a/lib/RoadizCoreBundle/src/Node/NodeNamePolicyInterface.php b/lib/RoadizCoreBundle/src/Node/NodeNamePolicyInterface.php index 14a5572d..4c85ab4d 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeNamePolicyInterface.php +++ b/lib/RoadizCoreBundle/src/Node/NodeNamePolicyInterface.php @@ -9,20 +9,17 @@ interface NodeNamePolicyInterface { /** - * @param NodesSources $nodeSource - * @return string Return a canonical node name built against a NS title and node-type. + * @return string return a canonical node name built against a NS title and node-type */ public function getCanonicalNodeName(NodesSources $nodeSource): string; /** - * @param NodesSources $nodeSource - * @return string Return a canonical node' name built against a NS title, node-type and a unique suffix. + * @return string return a canonical node' name built against a NS title, node-type and a unique suffix */ public function getSafeNodeName(NodesSources $nodeSource): string; /** - * @param NodesSources $nodeSource - * @return string Return a canonical node' name built against a NS title, node-type and a date suffix. + * @return string return a canonical node' name built against a NS title, node-type and a date suffix */ public function getDatestampedNodeName(NodesSources $nodeSource): string; diff --git a/lib/RoadizCoreBundle/src/Node/NodeOffspringResolverInterface.php b/lib/RoadizCoreBundle/src/Node/NodeOffspringResolverInterface.php index 92405b14..b7556630 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeOffspringResolverInterface.php +++ b/lib/RoadizCoreBundle/src/Node/NodeOffspringResolverInterface.php @@ -9,7 +9,6 @@ interface NodeOffspringResolverInterface { /** - * @param NodeInterface $ancestor * @return array */ public function getAllOffspringIds(NodeInterface $ancestor): array; diff --git a/lib/RoadizCoreBundle/src/Node/NodeTranslator.php b/lib/RoadizCoreBundle/src/Node/NodeTranslator.php index be1d63ca..47358786 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeTranslator.php +++ b/lib/RoadizCoreBundle/src/Node/NodeTranslator.php @@ -15,7 +15,7 @@ final class NodeTranslator { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly EventDispatcherInterface $dispatcher + private readonly EventDispatcherInterface $dispatcher, ) { } @@ -23,7 +23,7 @@ public function translateNode( ?Translation $sourceTranslation, Translation $destinationTranslation, Node $node, - bool $translateChildren = false + bool $translateChildren = false, ): Node { $this->translateSingleNode($sourceTranslation, $destinationTranslation, $node); @@ -40,7 +40,7 @@ public function translateNode( private function translateSingleNode( ?Translation $sourceTranslation, Translation $destinationTranslation, - Node $node + Node $node, ): NodesSources { /** @var NodesSources|null $existing */ $existing = $this->managerRegistry diff --git a/lib/RoadizCoreBundle/src/Node/NodeTranstyper.php b/lib/RoadizCoreBundle/src/Node/NodeTranstyper.php index 2109757e..16663f74 100644 --- a/lib/RoadizCoreBundle/src/Node/NodeTranstyper.php +++ b/lib/RoadizCoreBundle/src/Node/NodeTranstyper.php @@ -26,13 +26,9 @@ final class NodeTranstyper private ManagerRegistry $managerRegistry; private LoggerInterface $logger; - /** - * @param ManagerRegistry $managerRegistry - * @param LoggerInterface|null $logger - */ public function __construct( ManagerRegistry $managerRegistry, - ?LoggerInterface $logger = null + ?LoggerInterface $logger = null, ) { $this->logger = $logger ?? new NullLogger(); $this->managerRegistry = $managerRegistry; @@ -44,24 +40,23 @@ private function getManager(): ObjectManager if (null === $manager) { throw new \RuntimeException('No manager was found during trans-typing.'); } + return $manager; } /** - * @param NodeTypeFieldInterface $oldField - * @param NodeTypeInterface $destinationNodeType - * * @return NodeTypeField|null */ private function getMatchingNodeTypeField( NodeTypeFieldInterface $oldField, - NodeTypeInterface $destinationNodeType + NodeTypeInterface $destinationNodeType, ): ?NodeTypeFieldInterface { $criteria = Criteria::create(); $criteria->andWhere(Criteria::expr()->eq('name', $oldField->getName())) ->andWhere(Criteria::expr()->eq('type', $oldField->getType())) ->setMaxResults(1); $field = $destinationNodeType->getFields()->matching($criteria)->first(); + return $field ? $field : null; } @@ -69,13 +64,8 @@ private function getMatchingNodeTypeField( * Warning, this method DOES NOT flush entityManager at the end. * * Trans-typing SHOULD be executed in one single transaction - * @see https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/transactions-and-concurrency.html * - * @param Node $node - * @param NodeTypeInterface $destinationNodeType - * @param bool $mock - * - * @return Node + * @see https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/transactions-and-concurrency.html */ public function transtype(Node $node, NodeTypeInterface $destinationNodeType, bool $mock = true): Node { @@ -118,6 +108,7 @@ public function transtype(Node $node, NodeTypeInterface $destinationNodeType, bo foreach ($existingSources as $existingSource) { $existingRedirections[$existingSource->getTranslation()->getLocale()] = array_map(function (Redirection $redirection) { $this->managerRegistry->getManager()->detach($redirection); + return $redirection; }, $existingSource->getRedirections()->toArray()); } @@ -135,17 +126,14 @@ public function transtype(Node $node, NodeTypeInterface $destinationNodeType, bo $fieldAssociations, $existingRedirections ); - $this->logger->debug('Transtyped: ' . $existingSource->getTranslation()->getLocale()); + $this->logger->debug('Transtyped: '.$existingSource->getTranslation()->getLocale()); } $node->setNodeType($destinationNodeType); + return $node; } - /** - * @param Node $node - * @param array $sources - */ protected function removeOldSources(Node $node, array &$sources): void { /** @var NodesSources $existingSource */ @@ -162,13 +150,7 @@ protected function removeOldSources(Node $node, array &$sources): void /** * Warning, this method DO NOT flush entityManager at the end. * - * @param Node $node - * @param NodesSources $existingSource - * @param TranslationInterface $translation * @param class-string $sourceClass - * @param array $fieldAssociations - * @param array $existingRedirections - * @return NodesSources */ protected function doTranstypeSingleSource( Node $node, @@ -176,7 +158,7 @@ protected function doTranstypeSingleSource( TranslationInterface $translation, string $sourceClass, array &$fieldAssociations, - array &$existingRedirections + array &$existingRedirections, ): NodesSources { /** @var NodesSources $source */ $source = new $sourceClass($node, $translation); @@ -196,7 +178,7 @@ protected function doTranstypeSingleSource( $setter = $oldField->getSetterName(); $getter = $oldField->getGetterName(); $source->$setter($existingSource->$getter()); - } elseif ($oldField->getType() === AbstractField::DOCUMENTS_T) { + } elseif (AbstractField::DOCUMENTS_T === $oldField->getType()) { /* * Copy documents. */ @@ -243,14 +225,13 @@ protected function doTranstypeSingleSource( /** * Warning, this method flushes entityManager. * - * @param NodeTypeInterface $nodeType - * @throws \InvalidArgumentException If mock fails due to Source class not existing. + * @throws \InvalidArgumentException if mock fails due to Source class not existing */ protected function mockTranstype(NodeTypeInterface $nodeType): void { $sourceClass = $nodeType->getSourceEntityFullQualifiedClassName(); if (!class_exists($sourceClass)) { - throw new \InvalidArgumentException($sourceClass . ' node-source class does not exist.'); + throw new \InvalidArgumentException($sourceClass.' node-source class does not exist.'); } $uniqueId = uniqid(); /* @@ -260,18 +241,18 @@ protected function mockTranstype(NodeTypeInterface $nodeType): void */ $node = new Node(); $node->setNodeType($nodeType); - $node->setNodeName('testing_before_transtype' . $uniqueId); + $node->setNodeName('testing_before_transtype'.$uniqueId); $this->getManager()->persist($node); $translation = new Translation(); $translation->setAvailable(true); $translation->setLocale(\mb_substr($uniqueId, 0, 10)); - $translation->setName('test' . $uniqueId); + $translation->setName('test'.$uniqueId); $this->getManager()->persist($translation); /** @var NodesSources $testSource */ $testSource = new $sourceClass($node, $translation); - $testSource->setTitle('testing_before_transtype' . $uniqueId); + $testSource->setTitle('testing_before_transtype'.$uniqueId); $this->getManager()->persist($testSource); $this->getManager()->flush(); diff --git a/lib/RoadizCoreBundle/src/Node/UniqueNodeGenerator.php b/lib/RoadizCoreBundle/src/Node/UniqueNodeGenerator.php index 483a6ed0..bffd2578 100644 --- a/lib/RoadizCoreBundle/src/Node/UniqueNodeGenerator.php +++ b/lib/RoadizCoreBundle/src/Node/UniqueNodeGenerator.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\CoreBundle\Node; -use DateTime; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; use Doctrine\Persistence\ManagerRegistry; @@ -33,24 +32,16 @@ public function __construct( * Generate a node with a unique name. * * This method flush entity-manager by default. - * - * @param NodeType $nodeType - * @param TranslationInterface $translation - * @param Node|null $parent - * @param Tag|null $tag - * @param bool $pushToTop - * @param bool $flush - * @return NodesSources */ public function generate( NodeType $nodeType, TranslationInterface $translation, - Node $parent = null, - Tag $tag = null, + ?Node $parent = null, + ?Tag $tag = null, bool $pushToTop = false, - bool $flush = true + bool $flush = true, ): NodesSources { - $name = $nodeType->getDisplayName() . " " . uniqid(); + $name = $nodeType->getDisplayName().' '.uniqid(); $node = new Node(); $node->setNodeType($nodeType); $node->setTtl($nodeType->getDefaultTtl()); @@ -67,12 +58,12 @@ public function generate( $node->setPosition(0.5); } - /** @var class-string $sourceClass */ # phpstan hint - $sourceClass = NodeType::getGeneratedEntitiesNamespace() . "\\" . $nodeType->getSourceEntityClassName(); + /** @var class-string $sourceClass */ // phpstan hint + $sourceClass = NodeType::getGeneratedEntitiesNamespace().'\\'.$nodeType->getSourceEntityClassName(); $source = new $sourceClass($node, $translation); $source->setTitle($name); - $source->setPublishedAt(new DateTime()); + $source->setPublishedAt(new \DateTime()); $node->setNodeName($this->nodeNamePolicy->getCanonicalNodeName($source)); $manager = $this->managerRegistry->getManagerForClass(Node::class); @@ -90,9 +81,6 @@ public function generate( /** * Try to generate a unique node from request variables. * - * @param Request $request - * - * @return NodesSources * @throws ORMException * @throws OptimisticLockException */ @@ -100,7 +88,7 @@ public function generateFromRequest(Request $request): NodesSources { $pushToTop = false; - if ($request->get('pushTop') == 1) { + if (1 == $request->get('pushTop')) { $pushToTop = true; } @@ -117,7 +105,7 @@ public function generateFromRequest(Request $request): NodesSources ->getRepository(Node::class) ->find((int) $request->get('parentNodeId')); if (null === $parent || !$this->security->isGranted(NodeVoter::CREATE, $parent)) { - throw new BadRequestHttpException("Parent node does not exist."); + throw new BadRequestHttpException('Parent node does not exist.'); } } else { if (!$this->security->isGranted(NodeVoter::CREATE_AT_ROOT)) { @@ -128,7 +116,7 @@ public function generateFromRequest(Request $request): NodesSources $nodeTypeId = $request->get('nodeTypeId'); if (!is_numeric($nodeTypeId) || $nodeTypeId < 1) { - throw new BadRequestHttpException("No node-type ID has been given."); + throw new BadRequestHttpException('No node-type ID has been given.'); } /** @var NodeType|null $nodeType */ @@ -137,7 +125,7 @@ public function generateFromRequest(Request $request): NodesSources ->find((int) $nodeTypeId); if (null === $nodeType) { - throw new BadRequestHttpException("Node-type does not exist."); + throw new BadRequestHttpException('Node-type does not exist.'); } if ($request->get('translationId') > 0) { diff --git a/lib/RoadizCoreBundle/src/Node/UniversalDataDuplicator.php b/lib/RoadizCoreBundle/src/Node/UniversalDataDuplicator.php index 0f8c9803..51fc176b 100644 --- a/lib/RoadizCoreBundle/src/Node/UniversalDataDuplicator.php +++ b/lib/RoadizCoreBundle/src/Node/UniversalDataDuplicator.php @@ -25,8 +25,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) * * **Be careful, this method does not flush.** * - * @param NodesSources $source - * @return bool * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException * @throws \Doctrine\ORM\ORMException @@ -72,6 +70,7 @@ public function duplicateUniversalContents(NodesSources $source): bool } } } + return true; } } @@ -80,9 +79,6 @@ public function duplicateUniversalContents(NodesSources $source): bool } /** - * @param NodesSources $source - * - * @return bool * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ @@ -102,13 +98,13 @@ private function hasDefaultTranslation(NodesSources $source): bool 'translation' => $defaultTranslation, ]); - return $sourceCount === 1; + return 1 === $sourceCount; } protected function duplicateNonVirtualField( NodesSources $universalSource, NodesSources $destSource, - NodeTypeFieldInterface $field + NodeTypeFieldInterface $field, ): void { $getter = $field->getGetterName(); $setter = $field->getSetterName(); @@ -119,7 +115,7 @@ protected function duplicateNonVirtualField( protected function duplicateDocumentsField( NodesSources $universalSource, NodesSources $destSource, - NodeTypeFieldInterface $field + NodeTypeFieldInterface $field, ): void { $newDocuments = $this->managerRegistry ->getRepository(NodesSourcesDocuments::class) @@ -147,7 +143,7 @@ protected function duplicateDocumentsField( foreach ($newDocuments as $newDocument) { $nsDoc = new NodesSourcesDocuments($destSource, $newDocument->getDocument(), $field); $nsDoc->setPosition($position); - $position++; + ++$position; $manager->persist($nsDoc); } diff --git a/lib/RoadizCoreBundle/src/NodeType/ApiResourceGenerator.php b/lib/RoadizCoreBundle/src/NodeType/ApiResourceGenerator.php index 6506c450..6d4d845c 100644 --- a/lib/RoadizCoreBundle/src/NodeType/ApiResourceGenerator.php +++ b/lib/RoadizCoreBundle/src/NodeType/ApiResourceGenerator.php @@ -7,7 +7,6 @@ use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\GetCollection; use Doctrine\Inflector\InflectorFactory; -use LogicException; use Psr\Log\LoggerInterface; use RZ\Roadiz\Contracts\NodeType\NodeTypeInterface; use RZ\Roadiz\CoreBundle\Api\Controller\GetWebResponseByPathController; @@ -19,29 +18,25 @@ final class ApiResourceGenerator { /** - * @param ApiResourceOperationNameGenerator $apiResourceOperationNameGenerator - * @param string $apiResourcesDir - * @param LoggerInterface $logger * @param class-string $webResponseClass */ public function __construct( private readonly ApiResourceOperationNameGenerator $apiResourceOperationNameGenerator, private readonly string $apiResourcesDir, private readonly LoggerInterface $logger, - private readonly string $webResponseClass + private readonly string $webResponseClass, ) { } /** - * @param NodeTypeInterface $nodeType - * @return string|null Generated resource file path or null if nothing done. + * @return string|null generated resource file path or null if nothing done */ public function generate(NodeTypeInterface $nodeType): ?string { $filesystem = new Filesystem(); if (!$filesystem->exists($this->apiResourcesDir)) { - throw new LogicException($this->apiResourcesDir . ' folder does not exist.'); + throw new \LogicException($this->apiResourcesDir.' folder does not exist.'); } $resourcePath = $this->getResourcePath($nodeType); @@ -54,8 +49,8 @@ public function generate(NodeTypeInterface $nodeType): ?string 'resources' => [ $this->webResponseClass => [ 'operations' => [], - ] - ] + ], + ], ], 7) ); } @@ -78,6 +73,7 @@ public function generate(NodeTypeInterface $nodeType): ?string 'file' => $resourcePath, ]); \clearstatcache(true, $resourcePath); + return $resourcePath; } else { return null; @@ -89,7 +85,7 @@ public function remove(NodeTypeInterface $nodeType): void $filesystem = new Filesystem(); if (!$filesystem->exists($this->apiResourcesDir)) { - throw new LogicException($this->apiResourcesDir . ' folder does not exist.'); + throw new \LogicException($this->apiResourcesDir.' folder does not exist.'); } $resourcePath = $this->getResourcePath($nodeType); @@ -118,7 +114,7 @@ public function remove(NodeTypeInterface $nodeType): void public function getResourcePath(NodeTypeInterface $nodeType): string { - return $this->apiResourcesDir . '/' . (new UnicodeString($nodeType->getName())) + return $this->apiResourcesDir.'/'.(new UnicodeString($nodeType->getName())) ->lower() ->prepend('ns') ->append('.yml') @@ -127,7 +123,7 @@ public function getResourcePath(NodeTypeInterface $nodeType): string protected function getWebResponseResourcePath(): string { - return $this->apiResourcesDir . '/web_response.yml'; + return $this->apiResourcesDir.'/web_response.yml'; } protected function getResourceName(string $nodeTypeName): string @@ -141,7 +137,8 @@ protected function getResourceName(string $nodeTypeName): string protected function getResourceUriPrefix(NodeTypeInterface $nodeType): string { $pluralNodeTypeName = InflectorFactory::create()->build()->pluralize($nodeType->getName()); - return '/' . $this->getResourceName($pluralNodeTypeName); + + return '/'.$this->getResourceName($pluralNodeTypeName); } protected function getApiResourceDefinition(NodeTypeInterface $nodeType): array @@ -157,10 +154,10 @@ protected function getApiResourceDefinition(NodeTypeInterface $nodeType): array 'types' => [$nodeType->getName()], 'operations' => [ ...$this->getCollectionOperations($nodeType), - ...$this->getItemOperations($nodeType) + ...$this->getItemOperations($nodeType), ], - ] - ] + ], + ], ]; } @@ -176,7 +173,7 @@ protected function addWebResponseResourceOperation(NodeTypeInterface $nodeType, 'resources' => [ $this->webResponseClass => [ 'operations' => [], - ] + ], ], ]; } @@ -213,13 +210,13 @@ protected function addWebResponseResourceOperation(NodeTypeInterface $nodeType, 'web_response', 'walker', 'children', - ] - ] + ], + ], ], 'openapiContext' => [ 'tags' => ['WebResponse'], - 'summary' => 'Get a ' . $nodeType->getName() . ' by its path wrapped in a WebResponse object', - 'description' => 'Get a ' . $nodeType->getName() . ' by its path wrapped in a WebResponse', + 'summary' => 'Get a '.$nodeType->getName().' by its path wrapped in a WebResponse object', + 'description' => 'Get a '.$nodeType->getName().' by its path wrapped in a WebResponse', 'parameters' => [ [ 'type' => 'string', @@ -230,12 +227,13 @@ protected function addWebResponseResourceOperation(NodeTypeInterface $nodeType, 'schema' => [ 'type' => 'string', ], - ] - ] - ] + ], + ], + ], ]; $webResponseResource['resources'][$this->webResponseClass]['operations'] = $operations; + return $webResponseResource; } @@ -261,6 +259,7 @@ protected function removeWebResponseResourceOperation(NodeTypeInterface $nodeTyp unset($operations[$getByPathOperationName]); $webResponseResource['resources'][$this->webResponseClass]['operations'] = array_filter($operations); + return $webResponseResource; } @@ -269,15 +268,15 @@ protected function getCollectionOperations(NodeTypeInterface $nodeType): array $operations = []; if ($nodeType->isReachable()) { $groups = [ - "nodes_sources_base", - "nodes_sources_default", - "urls", - "tag_base", - "translation_base", - "document_display", - "document_thumbnails", - "document_display_sources", - ...$this->getGroupedFieldsSerializationGroups($nodeType) + 'nodes_sources_base', + 'nodes_sources_default', + 'urls', + 'tag_base', + 'translation_base', + 'document_display', + 'document_thumbnails', + 'document_display_sources', + ...$this->getGroupedFieldsSerializationGroups($nodeType), ]; $collectionOperationName = $this->apiResourceOperationNameGenerator->generate( @@ -293,9 +292,9 @@ protected function getCollectionOperations(NodeTypeInterface $nodeType): array 'shortName' => $nodeType->getName(), 'normalizationContext' => [ 'enable_max_depth' => true, - 'groups' => array_values(array_filter(array_unique($groups))) + 'groups' => array_values(array_filter(array_unique($groups))), ], - ] + ], ] ); } @@ -311,7 +310,7 @@ protected function getCollectionOperations(NodeTypeInterface $nodeType): array 'method' => 'GET', 'class' => GetCollection::class, 'shortName' => $nodeType->getName(), - 'uriTemplate' => $this->getResourceUriPrefix($nodeType) . '/archives', + 'uriTemplate' => $this->getResourceUriPrefix($nodeType).'/archives', 'extraProperties' => [ 'archive_enabled' => true, ], @@ -321,25 +320,26 @@ protected function getCollectionOperations(NodeTypeInterface $nodeType): array $nodeType->getName() ), ], - ] + ], ] ); } + return $operations; } protected function getItemOperationSerializationGroups(NodeTypeInterface $nodeType): array { return [ - "nodes_sources", - "node_listing", - "urls", - "tag_base", - "translation_base", - "document_display", - "document_thumbnails", - "document_display_sources", - ...$this->getGroupedFieldsSerializationGroups($nodeType) + 'nodes_sources', + 'node_listing', + 'urls', + 'tag_base', + 'translation_base', + 'document_display', + 'document_thumbnails', + 'document_display_sources', + ...$this->getGroupedFieldsSerializationGroups($nodeType), ]; } @@ -350,15 +350,16 @@ protected function getItemOperations(NodeTypeInterface $nodeType): array $nodeType->getSourceEntityFullQualifiedClassName(), 'get' ); + return [ $itemOperationName => [ 'method' => 'GET', 'class' => Get::class, 'shortName' => $nodeType->getName(), 'normalizationContext' => [ - 'groups' => array_values(array_filter(array_unique($groups))) + 'groups' => array_values(array_filter(array_unique($groups))), ], - ] + ], ]; } @@ -375,6 +376,7 @@ protected function getGroupedFieldsSerializationGroups(NodeTypeInterface $nodeTy ; } } + return $groups; } } diff --git a/lib/RoadizCoreBundle/src/NodeType/DefaultValuesResolver.php b/lib/RoadizCoreBundle/src/NodeType/DefaultValuesResolver.php index 28739dd7..acb9faf6 100644 --- a/lib/RoadizCoreBundle/src/NodeType/DefaultValuesResolver.php +++ b/lib/RoadizCoreBundle/src/NodeType/DefaultValuesResolver.php @@ -14,7 +14,7 @@ final class DefaultValuesResolver implements DefaultValuesResolverInterface { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly string $inheritanceType + private readonly string $inheritanceType, ) { } @@ -24,7 +24,7 @@ public function getDefaultValuesAmongAllFields(NodeTypeFieldInterface $field): a * With joined inheritance, we can use current field default values because * SQL field won't be shared between all node types. */ - if ($this->inheritanceType === Configuration::INHERITANCE_TYPE_JOINED) { + if (Configuration::INHERITANCE_TYPE_JOINED === $this->inheritanceType) { return array_map('trim', explode(',', $field->getDefaultValues() ?? '')); } else { /* @@ -39,6 +39,7 @@ public function getDefaultValuesAmongAllFields(NodeTypeFieldInterface $field): a foreach ($nodeTypeFields as $nodeTypeField) { $defaultValues = array_merge($defaultValues, array_map('trim', explode(',', $nodeTypeField->getDefaultValues() ?? ''))); } + return $defaultValues; } } diff --git a/lib/RoadizCoreBundle/src/NodeType/NodeTypeResolver.php b/lib/RoadizCoreBundle/src/NodeType/NodeTypeResolver.php index 687fa7b9..78e85527 100644 --- a/lib/RoadizCoreBundle/src/NodeType/NodeTypeResolver.php +++ b/lib/RoadizCoreBundle/src/NodeType/NodeTypeResolver.php @@ -16,23 +16,23 @@ public function __construct(private readonly CacheItemPoolInterface $cacheAdapte } /** - * @param NodeTypeFieldInterface $field * @return array */ protected function getNodeTypeList(NodeTypeFieldInterface $field): array { $nodeTypesNames = array_map('trim', explode(',', $field->getDefaultValues() ?? '')); + return array_filter($nodeTypesNames); } /** - * @param NodeTypeInterface $nodeType * @return array + * * @throws InvalidArgumentException */ public function getChildrenNodeTypeList(NodeTypeInterface $nodeType): array { - $cacheKey = 'children_' . $nodeType->getName(); + $cacheKey = 'children_'.$nodeType->getName(); $cacheItem = $this->cacheAdapter->getItem($cacheKey); if ($cacheItem->isHit()) { diff --git a/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewBarSubscriber.php b/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewBarSubscriber.php index a3ab4354..42d894eb 100644 --- a/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewBarSubscriber.php +++ b/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewBarSubscriber.php @@ -16,29 +16,21 @@ public function __construct(private readonly PreviewResolverInterface $previewRe { } - /** - * @return array - */ public static function getSubscribedEvents(): array { return [ - KernelEvents::RESPONSE => ['onKernelResponse', -128] + KernelEvents::RESPONSE => ['onKernelResponse', -128], ]; } - /** - * @param ResponseEvent $event - * - * @return bool - */ protected function supports(ResponseEvent $event): bool { $response = $event->getResponse(); if ( - $this->previewResolver->isPreview() && - $event->isMainRequest() && - $response->getStatusCode() === Response::HTTP_OK && - str_contains($response->headers->get('Content-Type'), 'text/html') + $this->previewResolver->isPreview() + && $event->isMainRequest() + && Response::HTTP_OK === $response->getStatusCode() + && str_contains($response->headers->get('Content-Type'), 'text/html') ) { return true; } @@ -46,27 +38,24 @@ protected function supports(ResponseEvent $event): bool return false; } - /** - * @param ResponseEvent $event - */ public function onKernelResponse(ResponseEvent $event): void { if ($this->supports($event)) { $response = $event->getResponse(); $content = $response->getContent(); if ( - is_string($content) && - str_contains($content, '') && - str_contains($content, '') + is_string($content) + && str_contains($content, '') + && str_contains($content, '') ) { $content = str_replace( '', - "", + '', $content ); $content = str_replace( '', - "
Preview
", + '
Preview
', $content ); $response->setContent($content); diff --git a/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewModeSubscriber.php b/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewModeSubscriber.php index 82540443..b2390efe 100644 --- a/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewModeSubscriber.php +++ b/lib/RoadizCoreBundle/src/Preview/EventSubscriber/PreviewModeSubscriber.php @@ -19,13 +19,10 @@ final class PreviewModeSubscriber implements EventSubscriberInterface public function __construct( private readonly PreviewResolverInterface $previewResolver, - private readonly Security $security + private readonly Security $security, ) { } - /** - * @return array - */ public static function getSubscribedEvents(): array { return [ @@ -36,24 +33,18 @@ public static function getSubscribedEvents(): array ]; } - /** - * @return bool - */ protected function supports(): bool { return $this->previewResolver->isPreview(); } - /** - * @param RequestEvent $event - */ public function onKernelRequest(RequestEvent $event): void { $request = $event->getRequest(); if ( - $event->isMainRequest() && - $request->query->has(self::QUERY_PARAM_NAME) && - \in_array( + $event->isMainRequest() + && $request->query->has(self::QUERY_PARAM_NAME) + && \in_array( $request->query->get(self::QUERY_PARAM_NAME, 0), ['true', true, '1', 1, 'on', 'yes', 'y'], true @@ -68,7 +59,6 @@ public function onKernelRequest(RequestEvent $event): void * You MUST check here is user can use preview mode BEFORE going * any further into your app logic. * - * @param ControllerEvent $event * @throws PreviewNotAllowedException */ public function onControllerMatched(ControllerEvent $event): void @@ -82,8 +72,6 @@ public function onControllerMatched(ControllerEvent $event): void /** * Enforce cache disabling. - * - * @param ResponseEvent $event */ public function onResponse(ResponseEvent $event): void { diff --git a/lib/RoadizCoreBundle/src/Preview/Exception/PreviewNotAllowedException.php b/lib/RoadizCoreBundle/src/Preview/Exception/PreviewNotAllowedException.php index 07da1c7b..d4b325e4 100644 --- a/lib/RoadizCoreBundle/src/Preview/Exception/PreviewNotAllowedException.php +++ b/lib/RoadizCoreBundle/src/Preview/Exception/PreviewNotAllowedException.php @@ -12,7 +12,7 @@ */ class PreviewNotAllowedException extends AccessDeniedHttpException { - public function __construct(string $message = "You are not allowed to use preview mode.") + public function __construct(string $message = 'You are not allowed to use preview mode.') { parent::__construct($message); } diff --git a/lib/RoadizCoreBundle/src/Preview/PreviewResolverInterface.php b/lib/RoadizCoreBundle/src/Preview/PreviewResolverInterface.php index 9347ab52..ec133317 100644 --- a/lib/RoadizCoreBundle/src/Preview/PreviewResolverInterface.php +++ b/lib/RoadizCoreBundle/src/Preview/PreviewResolverInterface.php @@ -7,5 +7,6 @@ interface PreviewResolverInterface { public function isPreview(): bool; + public function getRequiredRole(): string; } diff --git a/lib/RoadizCoreBundle/src/Preview/RequestPreviewRevolver.php b/lib/RoadizCoreBundle/src/Preview/RequestPreviewRevolver.php index 46ff3646..1cd5fbf3 100644 --- a/lib/RoadizCoreBundle/src/Preview/RequestPreviewRevolver.php +++ b/lib/RoadizCoreBundle/src/Preview/RequestPreviewRevolver.php @@ -8,26 +8,22 @@ /** * BC Preview resolver to check Request-time then Kernel boot-time preview param. - * - * @package RZ\Roadiz\CoreBundle\Preview */ final class RequestPreviewRevolver implements PreviewResolverInterface { public function __construct( private readonly RequestStack $requestStack, - private readonly string $requiredRole + private readonly string $requiredRole, ) { } - /** - * @return bool - */ public function isPreview(): bool { $request = $this->requestStack->getMainRequest(); if (null === $request) { return false; } + return $request->attributes->getBoolean('preview'); } diff --git a/lib/RoadizCoreBundle/src/Preview/User/PreviewUser.php b/lib/RoadizCoreBundle/src/Preview/User/PreviewUser.php index 5d3fc9e1..a7fd7c01 100644 --- a/lib/RoadizCoreBundle/src/Preview/User/PreviewUser.php +++ b/lib/RoadizCoreBundle/src/Preview/User/PreviewUser.php @@ -11,51 +11,32 @@ class PreviewUser implements UserInterface protected string $username; protected array $roles = []; - /** - * @param string $username - * @param array $roles - */ public function __construct(string $username, array $roles) { $this->username = $username; $this->roles = $roles; } - /** - * @inheritDoc - */ public function getRoles(): array { return $this->roles; } - /** - * @inheritDoc - */ public function getPassword(): string { throw new \BadMethodCallException('Preview user does not have a password'); } - /** - * @inheritDoc - */ public function getSalt(): string { throw new \BadMethodCallException('Preview user does not have a password salt'); } - /** - * @inheritDoc - */ public function eraseCredentials(): void { throw new \BadMethodCallException('Preview user cannot erase its credentials'); } - /** - * @inheritDoc - */ public function getUsername(): string { return $this->username; diff --git a/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProvider.php b/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProvider.php index 9184f8ef..dbd3cc7d 100644 --- a/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProvider.php +++ b/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProvider.php @@ -5,27 +5,26 @@ namespace RZ\Roadiz\CoreBundle\Preview\User; use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface; -use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Bundle\SecurityBundle\Security; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\User\UserInterface; final class PreviewUserProvider implements PreviewUserProviderInterface { public function __construct( private readonly PreviewResolverInterface $previewResolver, - private readonly Security $security + private readonly Security $security, ) { } public function createFromSecurity(): UserInterface { if (!$this->security->isGranted($this->previewResolver->getRequiredRole())) { - throw new AccessDeniedException( - 'Cannot create a preview user proxy from a user that is not allowed to preview.' - ); + throw new AccessDeniedException('Cannot create a preview user proxy from a user that is not allowed to preview.'); } + return new PreviewUser($this->security->getUser()->getUserIdentifier(), [ - $this->previewResolver->getRequiredRole() + $this->previewResolver->getRequiredRole(), ]); } } diff --git a/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProviderInterface.php b/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProviderInterface.php index 7aff0210..c34d2628 100644 --- a/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProviderInterface.php +++ b/lib/RoadizCoreBundle/src/Preview/User/PreviewUserProviderInterface.php @@ -10,7 +10,6 @@ interface PreviewUserProviderInterface { /** - * @return UserInterface * @throws AccessDeniedException If original user is not allowed to preview */ public function createFromSecurity(): UserInterface; diff --git a/lib/RoadizCoreBundle/src/Realm/RealmResolver.php b/lib/RoadizCoreBundle/src/Realm/RealmResolver.php index d900db6b..b4a578cf 100644 --- a/lib/RoadizCoreBundle/src/Realm/RealmResolver.php +++ b/lib/RoadizCoreBundle/src/Realm/RealmResolver.php @@ -10,8 +10,8 @@ use RZ\Roadiz\CoreBundle\Entity\Realm; use RZ\Roadiz\CoreBundle\Model\RealmInterface; use RZ\Roadiz\CoreBundle\Security\Authorization\Voter\RealmVoter; -use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Symfony\Bundle\SecurityBundle\Security; +use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Symfony\Component\String\Slugger\AsciiSlugger; final class RealmResolver implements RealmResolverInterface @@ -19,7 +19,7 @@ final class RealmResolver implements RealmResolverInterface public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly Security $security, - private readonly CacheItemPoolInterface $cache + private readonly CacheItemPoolInterface $cache, ) { } @@ -28,6 +28,7 @@ public function getRealms(?Node $node): array if (null === $node) { return []; } + return $this->managerRegistry->getRepository(Realm::class)->findByNode($node); } @@ -36,6 +37,7 @@ public function getRealmsWithSerializationGroup(?Node $node): array if (null === $node) { return []; } + return $this->managerRegistry->getRepository(Realm::class)->findByNodeWithSerializationGroup($node); } @@ -47,10 +49,7 @@ public function isGranted(RealmInterface $realm): bool public function denyUnlessGranted(RealmInterface $realm): void { if (!$this->isGranted($realm)) { - throw new UnauthorizedHttpException( - $realm->getChallenge(), - 'WebResponse was denied by Realm authorization, check Www-Authenticate header' - ); + throw new UnauthorizedHttpException($realm->getChallenge(), 'WebResponse was denied by Realm authorization, check Www-Authenticate header'); } } @@ -63,25 +62,27 @@ private function getUserCacheKey(): string public function getGrantedRealms(): array { - $cacheItem = $this->cache->getItem('granted_realms_' . $this->getUserCacheKey()); + $cacheItem = $this->cache->getItem('granted_realms_'.$this->getUserCacheKey()); if (!$cacheItem->isHit()) { $allRealms = $this->managerRegistry->getRepository(Realm::class)->findBy([]); - $cacheItem->set(array_filter($allRealms, fn(RealmInterface $realm) => $this->isGranted($realm))); + $cacheItem->set(array_filter($allRealms, fn (RealmInterface $realm) => $this->isGranted($realm))); $cacheItem->expiresAfter(new \DateInterval('PT1H')); $this->cache->save($cacheItem); } + return $cacheItem->get(); } public function getDeniedRealms(): array { - $cacheItem = $this->cache->getItem('denied_realms_' . $this->getUserCacheKey()); + $cacheItem = $this->cache->getItem('denied_realms_'.$this->getUserCacheKey()); if (!$cacheItem->isHit()) { $allRealms = $this->managerRegistry->getRepository(Realm::class)->findBy([]); - $cacheItem->set(array_filter($allRealms, fn(RealmInterface $realm) => !$this->isGranted($realm))); + $cacheItem->set(array_filter($allRealms, fn (RealmInterface $realm) => !$this->isGranted($realm))); $cacheItem->expiresAfter(new \DateInterval('PT1H')); $this->cache->save($cacheItem); } + return $cacheItem->get(); } @@ -94,6 +95,7 @@ public function hasRealms(): bool $cacheItem->expiresAfter(new \DateInterval('PT2H')); $this->cache->save($cacheItem); } + return $cacheItem->get(); } @@ -106,6 +108,7 @@ public function hasRealmsWithSerializationGroup(): bool $cacheItem->expiresAfter(new \DateInterval('PT2H')); $this->cache->save($cacheItem); } + return $cacheItem->get(); } } diff --git a/lib/RoadizCoreBundle/src/Realm/RealmResolverInterface.php b/lib/RoadizCoreBundle/src/Realm/RealmResolverInterface.php index 0124db98..5c5527bd 100644 --- a/lib/RoadizCoreBundle/src/Realm/RealmResolverInterface.php +++ b/lib/RoadizCoreBundle/src/Realm/RealmResolverInterface.php @@ -14,36 +14,36 @@ interface RealmResolverInterface * @return bool Does current application has realms? */ public function hasRealms(): bool; + /** * @return bool Does current application has realms with serialization groups? */ public function hasRealmsWithSerializationGroup(): bool; + /** - * @param Node|null $node * @return RealmInterface[] */ public function getRealms(?Node $node): array; + /** - * @param Node|null $node * @return RealmInterface[] */ public function getRealmsWithSerializationGroup(?Node $node): array; + public function isGranted(RealmInterface $realm): bool; /** - * @param RealmInterface $realm - * @return void * @throws UnauthorizedHttpException */ public function denyUnlessGranted(RealmInterface $realm): void; /** - * @return RealmInterface[] Return all realms granted to current user. + * @return RealmInterface[] return all realms granted to current user */ public function getGrantedRealms(): array; /** - * @return RealmInterface[] Return all realms denied from current user. + * @return RealmInterface[] return all realms denied from current user */ public function getDeniedRealms(): array; } diff --git a/lib/RoadizCoreBundle/src/Repository/AttributeDocumentsRepository.php b/lib/RoadizCoreBundle/src/Repository/AttributeDocumentsRepository.php index eeeae623..8f5249a4 100644 --- a/lib/RoadizCoreBundle/src/Repository/AttributeDocumentsRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/AttributeDocumentsRepository.php @@ -16,15 +16,12 @@ final class AttributeDocumentsRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, AttributeDocuments::class, $dispatcher); } /** - * @param AttributeInterface $attribute - * - * @return int * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ diff --git a/lib/RoadizCoreBundle/src/Repository/AttributeGroupRepository.php b/lib/RoadizCoreBundle/src/Repository/AttributeGroupRepository.php index 45dd1b0c..1b5fa338 100644 --- a/lib/RoadizCoreBundle/src/Repository/AttributeGroupRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/AttributeGroupRepository.php @@ -15,7 +15,7 @@ final class AttributeGroupRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, AttributeGroup::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/AttributeGroupTranslationRepository.php b/lib/RoadizCoreBundle/src/Repository/AttributeGroupTranslationRepository.php index 00f6e0b1..84898526 100644 --- a/lib/RoadizCoreBundle/src/Repository/AttributeGroupTranslationRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/AttributeGroupTranslationRepository.php @@ -16,7 +16,7 @@ final class AttributeGroupTranslationRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, AttributeGroupTranslation::class, $dispatcher); } @@ -24,6 +24,7 @@ public function __construct( public function findOneByNameAndLocale(string $name, string $locale): ?AttributeGroupTranslationInterface { $qb = $this->createQueryBuilder('agt'); + return $qb->innerJoin('agt.translation', 't') ->andWhere($qb->expr()->eq('t.locale', ':locale')) ->andWhere($qb->expr()->eq('agt.name', ':name')) diff --git a/lib/RoadizCoreBundle/src/Repository/AttributeRepository.php b/lib/RoadizCoreBundle/src/Repository/AttributeRepository.php index 111e992f..235a5b23 100644 --- a/lib/RoadizCoreBundle/src/Repository/AttributeRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/AttributeRepository.php @@ -15,7 +15,7 @@ final class AttributeRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Attribute::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/AttributeTranslationRepository.php b/lib/RoadizCoreBundle/src/Repository/AttributeTranslationRepository.php index 0fcb735a..d77825f6 100644 --- a/lib/RoadizCoreBundle/src/Repository/AttributeTranslationRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/AttributeTranslationRepository.php @@ -15,7 +15,7 @@ final class AttributeTranslationRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, AttributeTranslation::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/AttributeValueRepository.php b/lib/RoadizCoreBundle/src/Repository/AttributeValueRepository.php index c49f0774..9e784a9a 100644 --- a/lib/RoadizCoreBundle/src/Repository/AttributeValueRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/AttributeValueRepository.php @@ -17,19 +17,17 @@ final class AttributeValueRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, AttributeValue::class, $dispatcher); } /** - * @param AttributableInterface $attributable - * @param bool $orderByWeight * @return array */ public function findByAttributable( AttributableInterface $attributable, - bool $orderByWeight = false + bool $orderByWeight = false, ): array { $qb = $this->createQueryBuilder('av'); $qb = $qb->addSelect('avt') @@ -61,17 +59,12 @@ public function findByAttributable( ->getResult(); } - /** - * @param AttributableInterface $attributable - * @param TranslationInterface $translation - * - * @return array - */ public function findByAttributableAndTranslation( AttributableInterface $attributable, - TranslationInterface $translation + TranslationInterface $translation, ): array { $qb = $this->createQueryBuilder('av'); + return $qb->addSelect('avt') ->addSelect('a') ->addSelect('at') @@ -90,7 +83,7 @@ public function findByAttributableAndTranslation( ->addOrderBy('av.position', 'ASC') ->setParameters([ 'attributable' => $attributable, - 'translation' => $translation + 'translation' => $translation, ]) ->setCacheable(true) ->getQuery() diff --git a/lib/RoadizCoreBundle/src/Repository/AttributeValueTranslationRepository.php b/lib/RoadizCoreBundle/src/Repository/AttributeValueTranslationRepository.php index 553db03c..f28c87b0 100644 --- a/lib/RoadizCoreBundle/src/Repository/AttributeValueTranslationRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/AttributeValueTranslationRepository.php @@ -15,7 +15,7 @@ final class AttributeValueTranslationRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, AttributeValueTranslation::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/CustomFormAnswerRepository.php b/lib/RoadizCoreBundle/src/Repository/CustomFormAnswerRepository.php index 36870df2..a245e703 100644 --- a/lib/RoadizCoreBundle/src/Repository/CustomFormAnswerRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/CustomFormAnswerRepository.php @@ -17,7 +17,7 @@ final class CustomFormAnswerRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, CustomFormAnswer::class, $dispatcher); } @@ -25,13 +25,12 @@ public function __construct( protected function getCustomFormSubmittedBeforeQueryBuilder(): QueryBuilder { $qb = $this->createQueryBuilder('cfa'); + return $qb->andWhere($qb->expr()->eq('cfa.customForm', ':customForm')) ->andWhere($qb->expr()->lte('cfa.submittedAt', ':submittedAt')); } /** - * @param CustomForm $customForm - * @param \DateTime $submittedAt * @return Paginator */ public function findByCustomFormSubmittedBefore(CustomForm $customForm, \DateTime $submittedAt): Paginator @@ -39,13 +38,11 @@ public function findByCustomFormSubmittedBefore(CustomForm $customForm, \DateTim $qb = $this->getCustomFormSubmittedBeforeQueryBuilder() ->setParameter(':customForm', $customForm) ->setParameter(':submittedAt', $submittedAt); + return new Paginator($qb->getQuery()); } /** - * @param CustomForm $customForm - * @param \DateTime $submittedAt - * @return int * @throws NoResultException * @throws NonUniqueResultException */ @@ -55,6 +52,7 @@ public function deleteByCustomFormSubmittedBefore(CustomForm $customForm, \DateT ->delete() ->setParameter(':customForm', $customForm) ->setParameter(':submittedAt', $submittedAt); + return (int) $qb->getQuery()->getSingleScalarResult(); } } diff --git a/lib/RoadizCoreBundle/src/Repository/CustomFormFieldAttributeRepository.php b/lib/RoadizCoreBundle/src/Repository/CustomFormFieldAttributeRepository.php index f89b32bd..979f8aed 100644 --- a/lib/RoadizCoreBundle/src/Repository/CustomFormFieldAttributeRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/CustomFormFieldAttributeRepository.php @@ -15,7 +15,7 @@ final class CustomFormFieldAttributeRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, CustomFormFieldAttribute::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/CustomFormFieldRepository.php b/lib/RoadizCoreBundle/src/Repository/CustomFormFieldRepository.php index 117fe365..64765383 100644 --- a/lib/RoadizCoreBundle/src/Repository/CustomFormFieldRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/CustomFormFieldRepository.php @@ -16,7 +16,7 @@ final class CustomFormFieldRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, CustomFormField::class, $dispatcher); } @@ -29,6 +29,7 @@ public function findDistinctGroupNamesInCustomForm(CustomForm $customForm): arra ->setParameter('customForm', $customForm); $result = $qb->getQuery()->getResult(); + return array_map(fn (array $row) => $row['groupName'], $result); } } diff --git a/lib/RoadizCoreBundle/src/Repository/CustomFormRepository.php b/lib/RoadizCoreBundle/src/Repository/CustomFormRepository.php index 62df6b92..6cf99b68 100644 --- a/lib/RoadizCoreBundle/src/Repository/CustomFormRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/CustomFormRepository.php @@ -17,7 +17,7 @@ final class CustomFormRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, CustomForm::class, $dispatcher); } @@ -28,15 +28,15 @@ public function __construct( public function findAllWithRetentionTime(): array { $qb = $this->createQueryBuilder('cf'); + return $qb->andWhere($qb->expr()->isNotNull('cf.retentionTime')) ->getQuery() ->getResult(); } /** - * @param Node $node - * @param NodeTypeFieldInterface $field * @return CustomForm[] + * * @deprecated Use findByNodeAndFieldName instead */ public function findByNodeAndField(Node $node, NodeTypeFieldInterface $field): array @@ -53,8 +53,6 @@ public function findByNodeAndField(Node $node, NodeTypeFieldInterface $field): a } /** - * @param Node $node - * @param string $fieldName * @return CustomForm[] */ public function findByNodeAndFieldName(Node $node, string $fieldName): array diff --git a/lib/RoadizCoreBundle/src/Repository/DocumentRepository.php b/lib/RoadizCoreBundle/src/Repository/DocumentRepository.php index 12f69b71..216edd00 100644 --- a/lib/RoadizCoreBundle/src/Repository/DocumentRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/DocumentRepository.php @@ -11,29 +11,30 @@ use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\Tools\Pagination\Paginator; use Doctrine\Persistence\ManagerRegistry; -use RZ\Roadiz\CoreBundle\Entity\CustomFormFieldAttribute; -use RZ\Roadiz\Documents\Repository\DocumentRepositoryInterface; use RZ\Roadiz\Contracts\NodeType\NodeTypeFieldInterface; use RZ\Roadiz\Core\AbstractEntities\AbstractField; use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; use RZ\Roadiz\CoreBundle\Doctrine\ORM\SimpleQueryBuilder; use RZ\Roadiz\CoreBundle\Entity\CustomForm; +use RZ\Roadiz\CoreBundle\Entity\CustomFormFieldAttribute; use RZ\Roadiz\CoreBundle\Entity\Document; use RZ\Roadiz\CoreBundle\Entity\DocumentTranslation; use RZ\Roadiz\CoreBundle\Entity\Folder; use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\Roadiz\CoreBundle\Entity\Setting; +use RZ\Roadiz\Documents\Repository\DocumentRepositoryInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * @extends EntityRepository + * * @implements DocumentRepositoryInterface */ final class DocumentRepository extends EntityRepository implements DocumentRepositoryInterface { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Document::class, $dispatcher); } @@ -41,8 +42,6 @@ public function __construct( /** * Get a document with its translation id. * - * @param int $id - * @return Document|null * @throws NonUniqueResultException */ public function findOneByDocumentTranslationId(int $id): ?Document @@ -60,6 +59,7 @@ public function findOneByDocumentTranslationId(int $id): ?Document protected function getCustomFormSubmittedBeforeQueryBuilder(): QueryBuilder { $qb = $this->createQueryBuilder('d'); + return $qb->innerJoin('d.customFormFieldAttributes', 'cffa') ->innerJoin('cffa.customFormAnswer', 'cfa') ->andWhere($qb->expr()->eq('cfa.customForm', ':customForm')) @@ -67,8 +67,6 @@ protected function getCustomFormSubmittedBeforeQueryBuilder(): QueryBuilder } /** - * @param CustomForm $customForm - * @param \DateTime $submittedAt * @return array */ public function findByCustomFormSubmittedBefore(CustomForm $customForm, \DateTime $submittedAt): array @@ -76,15 +74,12 @@ public function findByCustomFormSubmittedBefore(CustomForm $customForm, \DateTim $qb = $this->getCustomFormSubmittedBeforeQueryBuilder() ->setParameter(':customForm', $customForm) ->setParameter(':submittedAt', $submittedAt); + return $qb->getQuery()->getResult(); } /** * Add a folder filtering to queryBuilder. - * - * @param array $criteria - * @param QueryBuilder $qb - * @param string $prefix */ protected function filterByFolder(array &$criteria, QueryBuilder $qb, string $prefix = 'd'): void { @@ -100,12 +95,12 @@ protected function filterByFolder(array &$criteria, QueryBuilder $qb, string $pr /* * Do not filter if folder array is empty. */ - if (count($criteria['folders']) === 0) { + if (0 === count($criteria['folders'])) { return; } if ( - in_array("folderExclusive", array_keys($criteria)) - && $criteria["folderExclusive"] === true + in_array('folderExclusive', array_keys($criteria)) + && true === $criteria['folderExclusive'] ) { // To get an exclusive folder filter // we need to filter against each folder id @@ -113,16 +108,16 @@ protected function filterByFolder(array &$criteria, QueryBuilder $qb, string $pr // with AND operator foreach ($criteria['folders'] as $index => $folder) { if (null !== $folder && $folder instanceof Folder) { - $alias = 'fd' . $index; - $qb->innerJoin($prefix . '.folders', $alias); - $qb->andWhere($qb->expr()->eq($alias . '.id', $folder->getId())); + $alias = 'fd'.$index; + $qb->innerJoin($prefix.'.folders', $alias); + $qb->andWhere($qb->expr()->eq($alias.'.id', $folder->getId())); } } - unset($criteria["folderExclusive"]); + unset($criteria['folderExclusive']); unset($criteria['folders']); } else { $qb->innerJoin( - $prefix . '.folders', + $prefix.'.folders', 'fd', 'WITH', 'fd.id IN (:folders)' @@ -130,7 +125,7 @@ protected function filterByFolder(array &$criteria, QueryBuilder $qb, string $pr } } else { $qb->innerJoin( - $prefix . '.folders', + $prefix.'.folders', 'fd', 'WITH', 'fd.id = :folders' @@ -140,7 +135,7 @@ protected function filterByFolder(array &$criteria, QueryBuilder $qb, string $pr } /** - * Reimplementing findBy features… with extra things + * Reimplementing findBy features… with extra things. * * * key => array('<=', $value) * * key => array('<', $value) @@ -155,9 +150,6 @@ protected function filterByFolder(array &$criteria, QueryBuilder $qb, string $pr * * * `translation => $object` * * `translation.locale => 'fr_FR'` - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void { @@ -166,7 +158,7 @@ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void * Reimplementing findBy features… */ foreach ($criteria as $key => $value) { - if ($key == "folders" || $key == "folderExclusive") { + if ('folders' == $key || 'folderExclusive' == $key) { continue; } @@ -190,7 +182,7 @@ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void */ $prefix = 'dt.'; $key = str_replace('documentTranslations.', '', $key); - } elseif ($key == 'translation') { + } elseif ('translation' == $key) { $prefix = 'dt.'; } @@ -201,18 +193,16 @@ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void /** * Create a Criteria object from a search pattern and additional fields. * - * @param string $pattern Search pattern - * @param QueryBuilder $qb QueryBuilder to pass - * @param array $criteria Additional criteria - * @param string $alias SQL query table alias - * - * @return QueryBuilder + * @param string $pattern Search pattern + * @param QueryBuilder $qb QueryBuilder to pass + * @param array $criteria Additional criteria + * @param string $alias SQL query table alias */ protected function createSearchBy( string $pattern, QueryBuilder $qb, array &$criteria = [], - string $alias = "obj" + string $alias = 'obj', ): QueryBuilder { $this->filterByFolder($criteria, $qb, $alias); $this->applyFilterByFolder($criteria, $qb); @@ -221,15 +211,15 @@ protected function createSearchBy( /* * Search in translations */ - $qb->leftJoin($alias . '.documentTranslations', 'dt'); + $qb->leftJoin($alias.'.documentTranslations', 'dt'); $criteriaFields = []; foreach (self::getSearchableColumnsNames($this->_em->getClassMetadata(DocumentTranslation::class)) as $field) { - $criteriaFields[$field] = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $criteriaFields[$field] = '%'.strip_tags(\mb_strtolower($pattern)).'%'; } foreach ($criteriaFields as $key => $value) { - $fullKey = sprintf('LOWER(%s)', 'dt.' . $key); + $fullKey = sprintf('LOWER(%s)', 'dt.'.$key); $qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value))); } @@ -238,9 +228,6 @@ protected function createSearchBy( /** * Bind parameters to generated query. - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): void { @@ -249,7 +236,7 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo */ $simpleQB = new SimpleQueryBuilder($qb); foreach ($criteria as $key => $value) { - if ($key == "folders" || $key == "folderExclusive") { + if ('folders' == $key || 'folderExclusive' == $key) { continue; } $simpleQB->bindValue($key, $value); @@ -257,10 +244,7 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo } /** - * Bind tag parameter to final query - * - * @param array $criteria - * @param QueryBuilder $qb + * Bind tag parameter to final query. */ protected function applyFilterByFolder(array &$criteria, QueryBuilder $qb): void { @@ -274,19 +258,16 @@ protected function applyFilterByFolder(array &$criteria, QueryBuilder $qb): void } elseif (is_integer($criteria['folders'])) { $qb->setParameter('folders', (int) $criteria['folders']); } - unset($criteria["folders"]); + unset($criteria['folders']); } } /** - * Bind translation parameter to final query - * - * @param QueryBuilder $qb - * @param null|TranslationInterface $translation + * Bind translation parameter to final query. */ protected function applyTranslationByFolder( QueryBuilder $qb, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): void { if (null !== $translation) { $qb->setParameter('translation', $translation); @@ -295,35 +276,27 @@ protected function applyTranslationByFolder( /** * Restrict documents to their copyright valid datetime range or null. - * - * @param QueryBuilder $qb - * @param string $alias - * @return QueryBuilder */ public function alterQueryBuilderWithCopyrightLimitations(QueryBuilder $qb, string $alias = 'd'): QueryBuilder { return $qb->andWhere($qb->expr()->orX( - $qb->expr()->isNull($alias . '.copyrightValidSince'), - $qb->expr()->lte($alias . '.copyrightValidSince', ':now') + $qb->expr()->isNull($alias.'.copyrightValidSince'), + $qb->expr()->lte($alias.'.copyrightValidSince', ':now') ))->andWhere($qb->expr()->orX( - $qb->expr()->isNull($alias . '.copyrightValidUntil'), - $qb->expr()->gte($alias . '.copyrightValidUntil', ':now') + $qb->expr()->isNull($alias.'.copyrightValidUntil'), + $qb->expr()->gte($alias.'.copyrightValidUntil', ':now') ))->setParameter(':now', new \DateTime()); } /** * Create filters according to any translation criteria OR argument. - * - * @param array $criteria - * @param QueryBuilder $qb - * @param TranslationInterface|null $translation */ - protected function filterByTranslation(array &$criteria, QueryBuilder $qb, TranslationInterface $translation = null): void + protected function filterByTranslation(array &$criteria, QueryBuilder $qb, ?TranslationInterface $translation = null): void { if ( - isset($criteria['translation']) || - isset($criteria['translation.locale']) || - isset($criteria['translation.id']) + isset($criteria['translation']) + || isset($criteria['translation.locale']) + || isset($criteria['translation.id']) ) { $qb->leftJoin('d.documentTranslations', 'dt'); $qb->leftJoin('dt.translation', 't'); @@ -356,21 +329,13 @@ protected function filterByTranslation(array &$criteria, QueryBuilder $qb, Trans /** * This method allows to pre-filter Documents with a given translation. - * - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset - * @param TranslationInterface|null $translation - * - * @return QueryBuilder */ protected function getContextualQueryWithTranslation( array &$criteria, - array $orderBy = null, + ?array $orderBy = null, ?int $limit = null, ?int $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): QueryBuilder { $qb = $this->createQueryBuilder('d'); $qb->andWhere($qb->expr()->eq('d.raw', ':raw')) @@ -386,7 +351,7 @@ protected function getContextualQueryWithTranslation( // Add ordering if (null !== $orderBy) { foreach ($orderBy as $key => $value) { - $qb->addOrderBy('d.' . $key, $value); + $qb->addOrderBy('d.'.$key, $value); } } @@ -402,37 +367,28 @@ protected function getContextualQueryWithTranslation( /** * This method allows to pre-filter Documents with a given translation. - * - * @param array $criteria - * @param TranslationInterface|null $translation - * - * @return QueryBuilder */ protected function getCountContextualQueryWithTranslation( array &$criteria, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): QueryBuilder { $qb = $this->getContextualQueryWithTranslation($criteria, null, null, null, $translation); + return $qb->select($qb->expr()->countDistinct('d.id')); } /** * Just like the findBy method but with relational criteria. * - * @param array $criteria - * @param array|null $orderBy * @param int|null $limit * @param int|null $offset - * @param TranslationInterface|null $translation - * - * @return array */ public function findBy( array $criteria, - array $orderBy = null, + ?array $orderBy = null, $limit = null, $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): array { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -449,8 +405,8 @@ public function findBy( $this->dispatchQueryEvent($query); if ( - null !== $limit && - null !== $offset + null !== $limit + && null !== $offset ) { /* * We need to use Doctrine paginator @@ -465,17 +421,12 @@ public function findBy( /** * Just like the findOneBy method but with relational criteria. * - * @param array $criteria - * @param array|null $orderBy - * @param TranslationInterface|null $translation - * - * @return Document|null - * @throws \Doctrine\ORM\NonUniqueResultException + * @throws NonUniqueResultException */ public function findOneBy( array $criteria, ?array $orderBy = null, - ?TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): ?Document { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -498,18 +449,17 @@ public function findOneBy( * Just like the countBy method but with relational criteria. * * @param Criteria|mixed|array $criteria - * @param TranslationInterface|null $translation * - * @return int * @throws NonUniqueResultException * @throws NoResultException */ public function countBy( mixed $criteria, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): int { if ($criteria instanceof Criteria) { $collection = $this->matching($criteria); + return $collection->count(); } elseif (\is_array($criteria)) { $query = $this->getCountContextualQueryWithTranslation( @@ -523,18 +473,16 @@ public function countBy( return (int) $query->getQuery()->getSingleScalarResult(); } + return 0; } /** - * @param NodesSources|int $nodeSource - * @param TranslationInterface|int $translation - * @return Document|null * @throws NonUniqueResultException */ public function findOneDisplayableByNodeSource( NodesSources|int $nodeSource, - TranslationInterface|int $translation + TranslationInterface|int $translation, ): ?Document { $qb = $this->createQueryBuilder('d'); $qb->addSelect('dt') @@ -553,14 +501,13 @@ public function findOneDisplayableByNodeSource( } /** - * @param NodesSources $nodeSource - * @param NodeTypeFieldInterface $field * @return array + * * @deprecated Use findByNodeSourceAndFieldName instead */ public function findByNodeSourceAndField( NodesSources $nodeSource, - NodeTypeFieldInterface $field + NodeTypeFieldInterface $field, ): array { $qb = $this->createQueryBuilder('d'); $qb->addSelect('dt') @@ -579,13 +526,11 @@ public function findByNodeSourceAndField( } /** - * @param NodesSources $nodeSource - * @param string $fieldName * @return array */ public function findByNodeSourceAndFieldName( NodesSources $nodeSource, - string $fieldName + string $fieldName, ): array { $qb = $this->createQueryBuilder('d'); $qb->addSelect('dt') @@ -679,9 +624,6 @@ protected function getAllDocumentsIdUsedInCustomFormAnswers(): array return $idArray; } - /** - * @return QueryBuilder - */ public function getAllUnusedQueryBuilder(): QueryBuilder { $qb1 = $this->createQueryBuilder('d1'); @@ -727,6 +669,7 @@ public function getAllUnusedQueryBuilder(): QueryBuilder public function findAllWithoutFileHash(): array { $qb = $this->createQueryBuilder('d'); + return $qb->andWhere($qb->expr()->isNull('d.fileHash')) ->getQuery() ->getResult(); @@ -742,7 +685,6 @@ public function getDuplicatesQueryBuilder(): QueryBuilder ->andHaving($qb->expr()->gt($qb->expr()->count('d2.fileHash'), 1)) ->andHaving($qb->expr()->gt($qb->expr()->count('d2.fileHashAlgorithm'), 1)); - $qb2 = $this->createQueryBuilder('d'); $qb2->andWhere($qb2->expr()->in('d.fileHash', $qb->getDQL())) ->setParameter(':raw', false) diff --git a/lib/RoadizCoreBundle/src/Repository/DocumentTranslationRepository.php b/lib/RoadizCoreBundle/src/Repository/DocumentTranslationRepository.php index c6a6906f..5f4d60ea 100644 --- a/lib/RoadizCoreBundle/src/Repository/DocumentTranslationRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/DocumentTranslationRepository.php @@ -16,14 +16,12 @@ final class DocumentTranslationRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, DocumentTranslation::class, $dispatcher); } /** - * @param int $id - * @return DocumentTranslation|null * @throws NonUniqueResultException */ public function findOneWithDocument(int $id): ?DocumentTranslation diff --git a/lib/RoadizCoreBundle/src/Repository/EntityRepository.php b/lib/RoadizCoreBundle/src/Repository/EntityRepository.php index f99e398c..84ad5bc7 100644 --- a/lib/RoadizCoreBundle/src/Repository/EntityRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/EntityRepository.php @@ -27,19 +27,18 @@ /** * @template TEntityClass of object + * * @extends ServiceEntityRepository */ abstract class EntityRepository extends ServiceEntityRepository { /** - * @param ManagerRegistry $registry * @param class-string $entityClass - * @param EventDispatcherInterface $dispatcher */ public function __construct( ManagerRegistry $registry, string $entityClass, - protected readonly EventDispatcherInterface $dispatcher + protected readonly EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, $entityClass); } @@ -75,7 +74,6 @@ public function __construct( public const NODETYPE_ALIAS = 'nt'; /** - * @param QueryBuilder $qb * @param class-string $entityClass */ protected function dispatchQueryBuilderEvent(QueryBuilder $qb, string $entityClass): void @@ -85,10 +83,6 @@ protected function dispatchQueryBuilderEvent(QueryBuilder $qb, string $entityCla } /** - * @param QueryBuilder $qb - * @param string $property - * @param mixed $value - * * @return Event */ protected function dispatchQueryBuilderBuildEvent(QueryBuilder $qb, string $property, mixed $value): object @@ -104,8 +98,6 @@ protected function dispatchQueryBuilderBuildEvent(QueryBuilder $qb, string $prop } /** - * @param Query $query - * * @return Event */ protected function dispatchQueryEvent(Query $query): object @@ -118,10 +110,6 @@ protected function dispatchQueryEvent(Query $query): object } /** - * @param QueryBuilder $qb - * @param string $property - * @param mixed $value - * * @return Event */ protected function dispatchQueryBuilderApplyEvent(QueryBuilder $qb, string $property, mixed $value): object @@ -136,13 +124,6 @@ protected function dispatchQueryBuilderApplyEvent(QueryBuilder $qb, string $prop )); } - /** - * - * @param array $criteria - * @param QueryBuilder $qb - * @param string $alias - * @return QueryBuilder - */ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string $alias): QueryBuilder { $simpleQB = new SimpleQueryBuilder($qb); @@ -154,17 +135,13 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string $event = $this->dispatchQueryBuilderBuildEvent($qb, $key, $value); if (!$event->isPropagationStopped()) { - $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $alias . '.', $key)); + $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $alias.'.', $key)); } } return $qb; } - /** - * @param array $criteria - * @param QueryBuilder $qb - */ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): void { $simpleQB = new SimpleQueryBuilder($qb); @@ -176,14 +153,6 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo } } - /** - * @param QueryBuilder $qb - * @param string $name - * @param string $key - * @param mixed $value - * - * @return Query\Expr\Func - */ protected function directExprIn(QueryBuilder $qb, string $name, string $key, mixed $value): Query\Expr\Func { $newValue = []; @@ -205,34 +174,30 @@ protected function directExprIn(QueryBuilder $qb, string $name, string $key, mix * Count entities using a Criteria object or a simple filter array. * * @param Criteria|mixed|array $criteria or array - * - * @return int */ public function countBy(mixed $criteria): int { if ($criteria instanceof Criteria) { $collection = $this->matching($criteria); + return $collection->count(); } elseif (is_array($criteria)) { $qb = $this->createQueryBuilder(static::DEFAULT_ALIAS); - $qb->select($qb->expr()->countDistinct(static::DEFAULT_ALIAS . '.id')); + $qb->select($qb->expr()->countDistinct(static::DEFAULT_ALIAS.'.id')); $qb = $this->prepareComparisons($criteria, $qb, static::DEFAULT_ALIAS); $this->dispatchQueryBuilderEvent($qb, $this->getEntityName()); $this->applyFilterByCriteria($criteria, $qb); try { return (int) $qb->getQuery()->getSingleScalarResult(); - } catch (NoResultException | NonUniqueResultException $e) { + } catch (NoResultException|NonUniqueResultException $e) { return 0; } } + return 0; } - /** - * @param ClassMetadataInfo $metadata - * @return array - */ public static function getSearchableColumnsNames(ClassMetadataInfo $metadata): array { /* @@ -244,15 +209,15 @@ public static function getSearchableColumnsNames(ClassMetadataInfo $metadata): a $field = $metadata->getFieldName($col); $type = $metadata->getTypeOfField($field); if ( - in_array($type, ['string', 'text']) && - !in_array($field, [ + in_array($type, ['string', 'text']) + && !in_array($field, [ 'color', 'folder', 'childrenOrder', 'childrenOrderDirection', 'password', 'token', - 'confirmationToken' + 'confirmationToken', ]) ) { $criteriaFields[] = $field; @@ -264,24 +229,19 @@ public static function getSearchableColumnsNames(ClassMetadataInfo $metadata): a /** * Create a LIKE comparison with entity texts colunms. - * - * @param string $pattern - * @param QueryBuilder $qb - * @param string $alias - * @return QueryBuilder */ protected function classicLikeComparison( string $pattern, QueryBuilder $qb, - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): QueryBuilder { $criteriaFields = []; foreach (static::getSearchableColumnsNames($this->getClassMetadata()) as $field) { - $criteriaFields[$field] = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $criteriaFields[$field] = '%'.strip_tags(\mb_strtolower($pattern)).'%'; } foreach ($criteriaFields as $key => $value) { - $fullKey = sprintf('LOWER(%s)', $alias . '.' . $key); + $fullKey = sprintf('LOWER(%s)', $alias.'.'.$key); $qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value))); } @@ -291,17 +251,16 @@ protected function classicLikeComparison( /** * Create a Criteria object from a search pattern and additional fields. * - * @param string $pattern Search pattern - * @param QueryBuilder $qb QueryBuilder to pass - * @param array $criteria Additional criteria - * @param string $alias SQL query table alias - * @return QueryBuilder + * @param string $pattern Search pattern + * @param QueryBuilder $qb QueryBuilder to pass + * @param array $criteria Additional criteria + * @param string $alias SQL query table alias */ protected function createSearchBy( string $pattern, QueryBuilder $qb, array &$criteria = [], - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): QueryBuilder { $this->classicLikeComparison($pattern, $qb, $alias); $this->prepareComparisons($criteria, $qb, $alias); @@ -310,14 +269,11 @@ protected function createSearchBy( } /** - * @param string $pattern Search pattern - * @param array $criteria Additional criteria - * @param array $orders - * @param int|null $limit - * @param int|null $offset - * @param string $alias + * @param string $pattern Search pattern + * @param array $criteria Additional criteria * * @return array + * * @throws \Exception */ public function searchBy( @@ -326,7 +282,7 @@ public function searchBy( array $orders = [], ?int $limit = null, ?int $offset = null, - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): array { $qb = $this->createQueryBuilder($alias); $qb = $this->createSearchBy($pattern, $qb, $criteria, $alias); @@ -334,18 +290,18 @@ public function searchBy( // Add ordering foreach ($orders as $key => $value) { if ( - (\str_starts_with($key, 'node.') || \str_starts_with($key, static::NODE_ALIAS . '.')) && - $this->hasJoinedNode($qb, $alias) + (\str_starts_with($key, 'node.') || \str_starts_with($key, static::NODE_ALIAS.'.')) + && $this->hasJoinedNode($qb, $alias) ) { - $key = preg_replace('#^node\.#', static::NODE_ALIAS . '.', $key); + $key = preg_replace('#^node\.#', static::NODE_ALIAS.'.', $key); $qb->addOrderBy($key, $value); } elseif ( - \str_starts_with($key, static::NODESSOURCES_ALIAS . '.') && - $this->hasJoinedNodesSources($qb, $alias) + \str_starts_with($key, static::NODESSOURCES_ALIAS.'.') + && $this->hasJoinedNodesSources($qb, $alias) ) { $qb->addOrderBy($key, $value); } else { - $qb->addOrderBy($alias . '.' . $key, $value); + $qb->addOrderBy($alias.'.'.$key, $value); } } if (null !== $offset) { @@ -361,8 +317,8 @@ public function searchBy( $this->dispatchQueryEvent($query); if ( - null !== $limit && - null !== $offset + null !== $limit + && null !== $offset ) { /* * We need to use Doctrine paginator @@ -375,14 +331,13 @@ public function searchBy( } /** - * @param string $pattern Search pattern - * @param array $criteria Additional criteria - * @return int + * @param string $pattern Search pattern + * @param array $criteria Additional criteria */ public function countSearchBy(string $pattern, array $criteria = []): int { $qb = $this->createQueryBuilder(static::DEFAULT_ALIAS); - $qb->select($qb->expr()->countDistinct(static::DEFAULT_ALIAS . '.id')); + $qb->select($qb->expr()->countDistinct(static::DEFAULT_ALIAS.'.id')); $qb = $this->createSearchBy($pattern, $qb, $criteria); $this->dispatchQueryBuilderEvent($qb, $this->getEntityName()); @@ -390,16 +345,11 @@ public function countSearchBy(string $pattern, array $criteria = []): int try { return (int) $qb->getQuery()->getSingleScalarResult(); - } catch (NoResultException | NonUniqueResultException $e) { + } catch (NoResultException|NonUniqueResultException $e) { return 0; } } - /** - * @param array $criteria - * @param QueryBuilder $qb - * @param string $nodeAlias - */ protected function buildTagFiltering(array &$criteria, QueryBuilder $qb, string $nodeAlias = 'n'): void { if (key_exists('tags', $criteria)) { @@ -414,33 +364,33 @@ protected function buildTagFiltering(array &$criteria, QueryBuilder $qb, string /* * Do not filter if tag array is empty. */ - if (count($criteria['tags']) === 0) { + if (0 === count($criteria['tags'])) { return; } if ( - in_array("tagExclusive", array_keys($criteria)) - && $criteria["tagExclusive"] === true + in_array('tagExclusive', array_keys($criteria)) + && true === $criteria['tagExclusive'] ) { // To get an exclusive tag filter // we need to filter against each tag id // and to inner join with a different alias for each tag // with AND operator /** - * @var int $index + * @var int $index * @var Tag|null $tag Tag can be null if not found */ foreach ($criteria['tags'] as $index => $tag) { if ($tag instanceof Tag) { - $alias = 'ntg_' . $index; - $qb->innerJoin($nodeAlias . '.nodesTags', $alias); - $qb->andWhere($qb->expr()->eq($alias . '.tag', $tag->getId())); + $alias = 'ntg_'.$index; + $qb->innerJoin($nodeAlias.'.nodesTags', $alias); + $qb->andWhere($qb->expr()->eq($alias.'.tag', $tag->getId())); } } - unset($criteria["tagExclusive"]); + unset($criteria['tagExclusive']); unset($criteria['tags']); } else { $qb->innerJoin( - $nodeAlias . '.nodesTags', + $nodeAlias.'.nodesTags', 'ntg_0', 'WITH', 'ntg_0.tag IN (:tags)' @@ -448,7 +398,7 @@ protected function buildTagFiltering(array &$criteria, QueryBuilder $qb, string } } else { $qb->innerJoin( - $nodeAlias . '.nodesTags', + $nodeAlias.'.nodesTags', 'ntg_0', 'WITH', 'ntg_0.tag = :tags' @@ -458,10 +408,7 @@ protected function buildTagFiltering(array &$criteria, QueryBuilder $qb, string } /** - * Bind tag parameters to final query - * - * @param array $criteria - * @param QueryBuilder $qb + * Bind tag parameters to final query. */ protected function applyFilterByTag(array &$criteria, QueryBuilder $qb): void { @@ -481,10 +428,6 @@ protected function applyFilterByTag(array &$criteria, QueryBuilder $qb): void /** * Ensure that node table is joined only once. - * - * @param QueryBuilder $qb - * @param string $alias - * @return bool */ protected function hasJoinedNode(QueryBuilder $qb, string $alias): bool { @@ -493,10 +436,6 @@ protected function hasJoinedNode(QueryBuilder $qb, string $alias): bool /** * Ensure that nodes_sources table is joined only once. - * - * @param QueryBuilder $qb - * @param string $alias - * @return bool */ protected function hasJoinedNodesSources(QueryBuilder $qb, string $alias): bool { @@ -505,29 +444,19 @@ protected function hasJoinedNodesSources(QueryBuilder $qb, string $alias): bool /** * Ensure that nodes_sources table is joined only once. - * - * @param QueryBuilder $qb - * @param string $alias - * @return bool */ protected function hasJoinedNodeType(QueryBuilder $qb, string $alias): bool { return $this->joinExists($qb, $alias, static::NODETYPE_ALIAS); } - /** - * @param QueryBuilder $qb - * @param string $rootAlias - * @param string $joinAlias - * @return bool - */ protected function joinExists(QueryBuilder $qb, string $rootAlias, string $joinAlias): bool { if (isset($qb->getDQLPart('join')[$rootAlias])) { foreach ($qb->getDQLPart('join')[$rootAlias] as $join) { if ( - $join instanceof Join && - $join->getAlias() === $joinAlias + $join instanceof Join + && $join->getAlias() === $joinAlias ) { return true; } diff --git a/lib/RoadizCoreBundle/src/Repository/FolderRepository.php b/lib/RoadizCoreBundle/src/Repository/FolderRepository.php index c4a0f64a..a748e433 100644 --- a/lib/RoadizCoreBundle/src/Repository/FolderRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/FolderRepository.php @@ -25,7 +25,7 @@ final class FolderRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Folder::class, $dispatcher); } @@ -33,10 +33,6 @@ public function __construct( /** * Find a folder according to the given path or create it. * - * @param string $folderPath - * @param TranslationInterface|null $translation - * - * @return Folder|null * @throws ORMException * @throws OptimisticLockException */ @@ -46,7 +42,7 @@ public function findOrCreateByPath(string $folderPath, ?TranslationInterface $tr $folders = explode('/', $folderPath); $folders = array_filter($folders); - if (count($folders) === 0) { + if (0 === count($folders)) { return null; } @@ -92,9 +88,6 @@ public function findOrCreateByPath(string $folderPath, ?TranslationInterface $tr /** * Find a folder according to the given path. * - * @param string $folderPath - * - * @return Folder|null * @throws NonUniqueResultException */ public function findByPath(string $folderPath): ?Folder @@ -108,12 +101,7 @@ public function findByPath(string $folderPath): ?Folder return $this->findOneByFolderName($folderName); } - /** - * @param Folder $folder - * @param TranslationInterface|null $translation - * @return array - */ - public function findAllChildrenFromFolder(Folder $folder, TranslationInterface $translation = null): array + public function findAllChildrenFromFolder(Folder $folder, ?TranslationInterface $translation = null): array { $ids = $this->findAllChildrenIdFromFolder($folder); if (count($ids) > 0) { @@ -128,19 +116,17 @@ public function findAllChildrenFromFolder(Folder $folder, TranslationInterface $ ->andWhere($qb->expr()->eq('tf.translation', ':translation')) ->setParameter(':translation', $translation); } + return $qb->getQuery()->getResult(); } + return []; } /** - * @param string $folderName - * @param TranslationInterface|null $translation - * - * @return Folder|null * @throws NonUniqueResultException */ - public function findOneByFolderName(string $folderName, TranslationInterface $translation = null): ?Folder + public function findOneByFolderName(string $folderName, ?TranslationInterface $translation = null): ?Folder { $qb = $this->createQueryBuilder('f'); $qb->addSelect('f') @@ -158,10 +144,6 @@ public function findOneByFolderName(string $folderName, TranslationInterface $tr return $qb->getQuery()->getOneOrNullResult(); } - /** - * @param Folder $folder - * @return array - */ public function findAllChildrenIdFromFolder(Folder $folder): array { $idsArray = $this->findChildrenIdFromFolder($folder); @@ -174,10 +156,6 @@ public function findAllChildrenIdFromFolder(Folder $folder): array return $idsArray; } - /** - * @param Folder $folder - * @return array - */ public function findChildrenIdFromFolder(Folder $folder): array { $qb = $this->createQueryBuilder('f'); @@ -191,17 +169,16 @@ public function findChildrenIdFromFolder(Folder $folder): array /** * Create a Criteria object from a search pattern and additionnal fields. * - * @param string $pattern Search pattern - * @param QueryBuilder $qb QueryBuilder to pass - * @param array $criteria Additional criteria - * @param string $alias SQL query table alias - * @return QueryBuilder + * @param string $pattern Search pattern + * @param QueryBuilder $qb QueryBuilder to pass + * @param array $criteria Additional criteria + * @param string $alias SQL query table alias */ protected function createSearchBy( string $pattern, QueryBuilder $qb, array &$criteria = [], - string $alias = "obj" + string $alias = 'obj', ): QueryBuilder { $this->classicLikeComparison($pattern, $qb, $alias); @@ -212,11 +189,11 @@ protected function createSearchBy( $criteriaFields = []; foreach (self::getSearchableColumnsNames($this->_em->getClassMetadata(FolderTranslation::class)) as $field) { - $criteriaFields[$field] = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $criteriaFields[$field] = '%'.strip_tags(\mb_strtolower($pattern)).'%'; } foreach ($criteriaFields as $key => $value) { - $fullKey = sprintf('LOWER(%s)', 'tf.' . $key); + $fullKey = sprintf('LOWER(%s)', 'tf.'.$key); $qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value))); } @@ -224,14 +201,10 @@ protected function createSearchBy( } /** - * @param string $pattern - * @param array $criteria - * @param string $alias - * @return int * @throws \Doctrine\ORM\NoResultException * @throws NonUniqueResultException */ - public function countSearchBy(string $pattern, array $criteria = [], string $alias = "obj"): int + public function countSearchBy(string $pattern, array $criteria = [], string $alias = 'obj'): int { $qb = $this->createQueryBuilder($alias); $qb->select($qb->expr()->countDistinct($alias)); @@ -240,12 +213,7 @@ public function countSearchBy(string $pattern, array $criteria = [], string $ali return (int) $qb->getQuery()->getSingleScalarResult(); } - /** - * @param Document $document - * @param TranslationInterface|null $translation - * @return array - */ - public function findByDocumentAndTranslation(Document $document, TranslationInterface $translation = null): array + public function findByDocumentAndTranslation(Document $document, ?TranslationInterface $translation = null): array { $qb = $this->createQueryBuilder('f'); $qb->innerJoin('f.documents', 'd') @@ -266,12 +234,7 @@ public function findByDocumentAndTranslation(Document $document, TranslationInte return $qb->getQuery()->getResult(); } - /** - * @param Folder|null $parent - * @param TranslationInterface|null $translation - * @return array - */ - public function findByParentAndTranslation(Folder $parent = null, TranslationInterface $translation = null): array + public function findByParentAndTranslation(?Folder $parent = null, ?TranslationInterface $translation = null): array { $qb = $this->createQueryBuilder('f'); $qb->addOrderBy('f.position', 'ASC'); diff --git a/lib/RoadizCoreBundle/src/Repository/FolderTranslationRepository.php b/lib/RoadizCoreBundle/src/Repository/FolderTranslationRepository.php index 3b78c003..692df669 100644 --- a/lib/RoadizCoreBundle/src/Repository/FolderTranslationRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/FolderTranslationRepository.php @@ -15,7 +15,7 @@ final class FolderTranslationRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, FolderTranslation::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/GroupRepository.php b/lib/RoadizCoreBundle/src/Repository/GroupRepository.php index 557e0166..55c4b44c 100644 --- a/lib/RoadizCoreBundle/src/Repository/GroupRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/GroupRepository.php @@ -14,13 +14,14 @@ * @method Group|null findOneBy(array $criteria, array $orderBy = null) * @method Group[] findAll() * @method Group[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class GroupRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Group::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/LogRepository.php b/lib/RoadizCoreBundle/src/Repository/LogRepository.php index 3419bca8..a8bc0bde 100644 --- a/lib/RoadizCoreBundle/src/Repository/LogRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/LogRepository.php @@ -20,16 +20,13 @@ final class LogRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Log::class, $dispatcher); } /** * Find the latest Log with NodesSources. - * - * @param int $maxResult - * @return Paginator */ public function findLatestByNodesSources(int $maxResult = 5): Paginator { @@ -62,6 +59,7 @@ public function findLatestByNodesSources(int $maxResult = 5): Paginator public function findByNode(Node $node): array { $qb = $this->getAllRelatedToNodeQueryBuilder($node); + return $qb->getQuery()->getResult(); } @@ -85,6 +83,7 @@ public function getAllRelatedToNodeQueryBuilder(Node $node): QueryBuilder $qb->setParameter('nodeSourceId', $node->getNodeSources()->map(function (NodesSources $ns) { return $ns->getId(); })->toArray()); + return $qb; } } diff --git a/lib/RoadizCoreBundle/src/Repository/NodeRepository.php b/lib/RoadizCoreBundle/src/Repository/NodeRepository.php index 0e8ad202..bf0dbaba 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodeRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodeRepository.php @@ -37,16 +37,12 @@ public function __construct( ManagerRegistry $registry, PreviewResolverInterface $previewResolver, EventDispatcherInterface $dispatcher, - Security $security + Security $security, ) { parent::__construct($registry, Node::class, $previewResolver, $dispatcher, $security); } /** - * @param QueryBuilder $qb - * @param string $property - * @param mixed $value - * * @return Event */ protected function dispatchQueryBuilderBuildEvent(QueryBuilder $qb, string $property, mixed $value): object @@ -58,10 +54,6 @@ protected function dispatchQueryBuilderBuildEvent(QueryBuilder $qb, string $prop } /** - * @param QueryBuilder $qb - * @param string $property - * @param mixed $value - * * @return Event */ protected function dispatchQueryBuilderApplyEvent(QueryBuilder $qb, string $property, mixed $value): object @@ -76,15 +68,13 @@ protected function dispatchQueryBuilderApplyEvent(QueryBuilder $qb, string $prop * Just like the countBy method but with relational criteria. * * @param Criteria|mixed|array $criteria - * @param TranslationInterface|null $translation * - * @return int * @throws NonUniqueResultException - * @throws \Doctrine\ORM\NoResultException + * @throws NoResultException */ public function countBy( mixed $criteria, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): int { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select($qb->expr()->countDistinct(self::NODE_ALIAS)); @@ -111,26 +101,22 @@ public function countBy( /** * Create filters according to any translation criteria OR argument. - * - * @param array $criteria - * @param QueryBuilder $qb - * @param TranslationInterface|null $translation */ protected function filterByTranslation( array $criteria, QueryBuilder $qb, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): void { if ( - isset($criteria['translation']) || - isset($criteria['translation.locale']) || - isset($criteria['translation.id']) || - isset($criteria['translation.available']) + isset($criteria['translation']) + || isset($criteria['translation.locale']) + || isset($criteria['translation.id']) + || isset($criteria['translation.available']) ) { if (!$this->hasJoinedNodesSources($qb, self::NODE_ALIAS)) { - $qb->innerJoin(self::NODE_ALIAS . '.nodeSources', self::NODESSOURCES_ALIAS); + $qb->innerJoin(self::NODE_ALIAS.'.nodeSources', self::NODESSOURCES_ALIAS); } - $qb->innerJoin(self::NODESSOURCES_ALIAS . '.translation', self::TRANSLATION_ALIAS); + $qb->innerJoin(self::NODESSOURCES_ALIAS.'.translation', self::TRANSLATION_ALIAS); } else { if (null !== $translation) { /* @@ -140,7 +126,7 @@ protected function filterByTranslation( 'n.nodeSources', self::NODESSOURCES_ALIAS, 'WITH', - self::NODESSOURCES_ALIAS . '.translation = :translation' + self::NODESSOURCES_ALIAS.'.translation = :translation' ); } else { /* @@ -148,7 +134,7 @@ protected function filterByTranslation( * nodes with only one translation which is not the default one. */ if (!$this->hasJoinedNodesSources($qb, self::NODE_ALIAS)) { - $qb->innerJoin(self::NODE_ALIAS . '.nodeSources', self::NODESSOURCES_ALIAS); + $qb->innerJoin(self::NODE_ALIAS.'.nodeSources', self::NODESSOURCES_ALIAS); } } } @@ -156,9 +142,6 @@ protected function filterByTranslation( /** * Add a tag filtering to queryBuilder. - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function filterByTag(array &$criteria, QueryBuilder $qb): void { @@ -183,9 +166,6 @@ protected function filterByTag(array &$criteria, QueryBuilder $qb): void * * * `translation => $object` * * `translation.locale => 'fr_FR'` - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void { @@ -194,7 +174,7 @@ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void * Reimplementing findBy features… */ foreach ($criteria as $key => $value) { - if ($key == "tags" || $key == "tagExclusive") { + if ('tags' == $key || 'tagExclusive' == $key) { continue; } /* @@ -208,7 +188,7 @@ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void * compute prefix for * filtering node, and sources relation fields */ - $prefix = self::NODE_ALIAS . '.'; + $prefix = self::NODE_ALIAS.'.'; // Dots are forbidden in field definitions $baseKey = $simpleQB->getParameterKey($key); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $prefix, $key, $baseKey)); @@ -218,9 +198,6 @@ protected function filterByCriteria(array &$criteria, QueryBuilder $qb): void /** * Bind parameters to generated query. - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): void { @@ -229,7 +206,7 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo */ $simpleQB = new SimpleQueryBuilder($qb); foreach ($criteria as $key => $value) { - if ($key == "tags" || $key == "tagExclusive") { + if ('tags' == $key || 'tagExclusive' == $key) { continue; } @@ -242,13 +219,10 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo /** * Bind translation parameter to final query. - * - * @param QueryBuilder $qb - * @param TranslationInterface|null $translation */ protected function applyTranslationByTag( QueryBuilder $qb, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): void { if (null !== $translation) { $qb->setParameter('translation', $translation); @@ -280,19 +254,17 @@ protected function applyTranslationByTag( * * `tags => [$tag1, $tag2]` * * `tags => [$tag1, $tag2], tagExclusive => true` * - * @param array $criteria - * @param array|null $orderBy * @param int|null $limit * @param int|null $offset - * @param TranslationInterface|null $translation + * * @return array */ public function findBy( array $criteria, - array $orderBy = null, + ?array $orderBy = null, $limit = null, $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): array { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -312,8 +284,8 @@ public function findBy( $this->dispatchQueryEvent($query); if ( - null !== $limit && - null !== $offset + null !== $limit + && null !== $offset ) { /* * We need to use Doctrine paginator @@ -325,21 +297,15 @@ public function findBy( } } - /** - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset - * @param TranslationInterface|null $translation * @return array */ public function findByAsNodeTreeDto( array $criteria, - array $orderBy = null, + ?array $orderBy = null, ?int $limit = null, ?int $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): array { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -365,14 +331,11 @@ public function findByAsNodeTreeDto( } /** - * @param string $pattern Search pattern - * @param array $criteria Additional criteria - * @param array $orders - * @param int|null $limit - * @param int|null $offset - * @param string $alias + * @param string $pattern Search pattern + * @param array $criteria Additional criteria * * @return array + * * @psalm-return array */ public function searchByAsNodeTreeDto( @@ -381,7 +344,7 @@ public function searchByAsNodeTreeDto( array $orders = [], ?int $limit = null, ?int $offset = null, - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): array { $qb = $this->createQueryBuilder($alias); $qb = $this->createSearchBy($pattern, $qb, $criteria, $alias); @@ -389,18 +352,18 @@ public function searchByAsNodeTreeDto( // Add ordering foreach ($orders as $key => $value) { if ( - (\str_starts_with($key, 'node.') || \str_starts_with($key, static::NODE_ALIAS . '.')) && - $this->hasJoinedNode($qb, $alias) + (\str_starts_with($key, 'node.') || \str_starts_with($key, static::NODE_ALIAS.'.')) + && $this->hasJoinedNode($qb, $alias) ) { - $key = preg_replace('#^node\.#', static::NODE_ALIAS . '.', $key); + $key = preg_replace('#^node\.#', static::NODE_ALIAS.'.', $key); $qb->addOrderBy($key, $value); } elseif ( - \str_starts_with($key, static::NODESSOURCES_ALIAS . '.') && - $this->hasJoinedNodesSources($qb, $alias) + \str_starts_with($key, static::NODESSOURCES_ALIAS.'.') + && $this->hasJoinedNodesSources($qb, $alias) ) { $qb->addOrderBy($key, $value); } else { - $qb->addOrderBy($alias . '.' . $key, $value); + $qb->addOrderBy($alias.'.'.$key, $value); } } if (null !== $offset) { @@ -424,10 +387,10 @@ public function searchByAsNodeTreeDto( protected function alterQueryBuilderAsNodeTreeDto(QueryBuilder $qb): QueryBuilder { if (!$this->hasJoinedNodeType($qb, self::NODE_ALIAS)) { - $qb->innerJoin(self::NODE_ALIAS . '.nodeType', self::NODETYPE_ALIAS); + $qb->innerJoin(self::NODE_ALIAS.'.nodeType', self::NODETYPE_ALIAS); } if (!$this->hasJoinedNodesSources($qb, self::NODE_ALIAS)) { - $qb->innerJoin(self::NODE_ALIAS . '.nodeSources', self::NODESSOURCES_ALIAS); + $qb->innerJoin(self::NODE_ALIAS.'.nodeSources', self::NODESSOURCES_ALIAS); } $qb->select(sprintf( @@ -486,20 +449,13 @@ protected function alterQueryBuilderAsNodeTreeDto(QueryBuilder $qb): QueryBuilde * not a Backend user and if authorizationChecker is defined. * * This method allows to pre-filter Nodes with a given translation. - * - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset - * @param TranslationInterface|null $translation - * @return QueryBuilder */ protected function getContextualQueryWithTranslation( array &$criteria, - array $orderBy = null, + ?array $orderBy = null, ?int $limit = null, ?int $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): QueryBuilder { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->addSelect(self::NODESSOURCES_ALIAS); @@ -515,15 +471,15 @@ protected function getContextualQueryWithTranslation( // Add ordering if (null !== $orderBy) { foreach ($orderBy as $key => $value) { - if (str_starts_with($key, self::NODESSOURCES_ALIAS . '.')) { + if (str_starts_with($key, self::NODESSOURCES_ALIAS.'.')) { $qb->addOrderBy($key, $value); - } elseif (str_starts_with($key, self::NODETYPE_ALIAS . '.')) { + } elseif (str_starts_with($key, self::NODETYPE_ALIAS.'.')) { if (!$this->hasJoinedNodeType($qb, self::NODE_ALIAS)) { - $qb->innerJoin(self::NODE_ALIAS . '.nodeType', self::NODETYPE_ALIAS); + $qb->innerJoin(self::NODE_ALIAS.'.nodeType', self::NODETYPE_ALIAS); } $qb->addOrderBy($key, $value); } else { - $qb->addOrderBy(self::NODE_ALIAS . '.' . $key, $value); + $qb->addOrderBy(self::NODE_ALIAS.'.'.$key, $value); } } } @@ -544,14 +500,11 @@ protected function getContextualQueryWithTranslation( * If no translation nor authorizationChecker is given, the vanilla `findOneBy` * method will be called instead. * - * @param array $criteria - * @param TranslationInterface|null $translation - * @return null|Node * @throws NonUniqueResultException */ public function findOneByWithTranslation( array $criteria, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): ?Node { return $this->findOneBy( $criteria, @@ -563,16 +516,12 @@ public function findOneByWithTranslation( /** * Just like the findOneBy method but with relational criteria. * - * @param array $criteria - * @param array|null $orderBy - * @param TranslationInterface|null $translation - * @return null|Node * @throws NonUniqueResultException */ public function findOneBy( array $criteria, ?array $orderBy = null, - ?TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): ?Node { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -597,14 +546,11 @@ public function findOneBy( /** * Find one Node with its Id and a given translation. * - * @param int $nodeId - * @param TranslationInterface $translation - * @return null|Node * @throws NonUniqueResultException */ public function findWithTranslation( int $nodeId, - TranslationInterface $translation + TranslationInterface $translation, ): ?Node { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns') @@ -624,12 +570,10 @@ public function findWithTranslation( /** * Find one Node with its Id and the default translation. * - * @param int $nodeId - * @return null|Node * @throws NonUniqueResultException */ public function findWithDefaultTranslation( - int $nodeId + int $nodeId, ): ?Node { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns') @@ -650,16 +594,13 @@ public function findWithDefaultTranslation( /** * Find one Node with its nodeName and a given translation. * - * @param string $nodeName - * @param TranslationInterface $translation - * - * @return null|Node * @throws NonUniqueResultException + * * @deprecated Use findNodeTypeNameAndSourceIdByIdentifier */ public function findByNodeNameWithTranslation( string $nodeName, - TranslationInterface $translation + TranslationInterface $translation, ): ?Node { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns') @@ -679,18 +620,15 @@ public function findByNodeNameWithTranslation( /** * Find one node using its nodeName and a translation, or a unique URL alias. * - * @param string $identifier - * @param TranslationInterface|null $translation - * @param bool $availableTranslation - * @param bool $allowNonReachableNodes * @return array|null Array with node-type "name" and node-source "id" + * * @throws NonUniqueResultException */ public function findNodeTypeNameAndSourceIdByIdentifier( string $identifier, ?TranslationInterface $translation, bool $availableTranslation = false, - bool $allowNonReachableNodes = true + bool $allowNonReachableNodes = true, ): ?array { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('nt.name, ns.id') @@ -724,20 +662,19 @@ public function findNodeTypeNameAndSourceIdByIdentifier( $query = $qb->getQuery(); $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); $query->setHydrationMode(Query::HYDRATE_ARRAY); + return $query->getOneOrNullResult(); } /** * Find one Node with its nodeName and the default translation. * - * @param string $nodeName - * - * @return null|Node * @throws NonUniqueResultException + * * @deprecated Use findNodeTypeNameAndSourceIdByIdentifier */ public function findByNodeNameWithDefaultTranslation( - string $nodeName + string $nodeName, ): ?Node { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns') @@ -758,12 +695,10 @@ public function findByNodeNameWithDefaultTranslation( /** * Find the Home node with a given translation. * - * @param TranslationInterface|null $translation - * @return null|Node * @throws NonUniqueResultException */ public function findHomeWithTranslation( - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): ?Node { if (null === $translation) { return $this->findHomeWithDefaultTranslation(); @@ -787,7 +722,6 @@ public function findHomeWithTranslation( /** * Find the Home node with the default translation. * - * @return null|Node * @throws NonUniqueResultException */ public function findHomeWithDefaultTranslation(): ?Node @@ -808,25 +742,20 @@ public function findHomeWithDefaultTranslation(): ?Node return $qb->getQuery()->getOneOrNullResult(); } - /** - * @param TranslationInterface $translation - * @param Node|null $parent - * @return array - */ public function findByParentWithTranslation( TranslationInterface $translation, - Node $parent = null + ?Node $parent = null, ): array { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns, ua') ->innerJoin('n.nodeSources', self::NODESSOURCES_ALIAS) - ->leftJoin(self::NODESSOURCES_ALIAS . '.urlAliases', 'ua') + ->leftJoin(self::NODESSOURCES_ALIAS.'.urlAliases', 'ua') ->andWhere($qb->expr()->eq('ns.translation', ':translation')) ->setParameter('translation', $translation) ->addOrderBy('n.position', 'ASC') ->setCacheable(true); - if ($parent === null) { + if (null === $parent) { $qb->andWhere($qb->expr()->isNull('n.parent')); } else { $qb->andWhere($qb->expr()->eq('n.parent', ':parent')) @@ -839,10 +768,9 @@ public function findByParentWithTranslation( } /** - * @param Node|null $parent * @return Node[] */ - public function findByParentWithDefaultTranslation(Node $parent = null): array + public function findByParentWithDefaultTranslation(?Node $parent = null): array { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns') @@ -852,7 +780,7 @@ public function findByParentWithDefaultTranslation(Node $parent = null): array ->addOrderBy('n.position', 'ASC') ->setCacheable(true); - if ($parent === null) { + if (null === $parent) { $qb->andWhere($qb->expr()->isNull('n.parent')); } else { $qb->andWhere($qb->expr()->eq('n.parent', ':parent')) @@ -865,9 +793,6 @@ public function findByParentWithDefaultTranslation(Node $parent = null): array } /** - * @param string $urlAliasAlias - * - * @return null|Node * @throws NonUniqueResultException */ public function findOneWithAliasAndAvailableTranslation(string $urlAliasAlias): ?Node @@ -892,7 +817,6 @@ public function findOneWithAliasAndAvailableTranslation(string $urlAliasAlias): /** * @param string $urlAliasAlias * - * @return null|Node * @throws NonUniqueResultException */ public function findOneWithAlias($urlAliasAlias): ?Node @@ -915,8 +839,7 @@ public function findOneWithAlias($urlAliasAlias): ?Node /** * @param string $nodeName * - * @return bool - * @throws NonUniqueResultException|\Doctrine\ORM\NoResultException + * @throws NonUniqueResultException|NoResultException */ public function exists($nodeName): bool { @@ -931,13 +854,11 @@ public function exists($nodeName): bool } /** - * @param Node $node - * @param NodeTypeFieldInterface $field * @return Node[] */ public function findByNodeAndField( Node $node, - NodeTypeFieldInterface $field + NodeTypeFieldInterface $field, ): array { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select(self::NODE_ALIAS) @@ -955,16 +876,10 @@ public function findByNodeAndField( return $qb->getQuery()->getResult(); } - /** - * @param Node $node - * @param NodeTypeFieldInterface $field - * @param TranslationInterface $translation - * @return array - */ public function findByNodeAndFieldAndTranslation( Node $node, NodeTypeFieldInterface $field, - TranslationInterface $translation + TranslationInterface $translation, ): array { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns') @@ -985,14 +900,9 @@ public function findByNodeAndFieldAndTranslation( return $qb->getQuery()->getResult(); } - /** - * @param Node $node - * @param NodeTypeFieldInterface $field - * @return array - */ public function findByReverseNodeAndField( Node $node, - NodeTypeFieldInterface $field + NodeTypeFieldInterface $field, ): array { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select(self::NODE_ALIAS) @@ -1010,16 +920,10 @@ public function findByReverseNodeAndField( return $qb->getQuery()->getResult(); } - /** - * @param Node $node - * @param NodeTypeFieldInterface $field - * @param TranslationInterface $translation - * @return array - */ public function findByReverseNodeAndFieldAndTranslation( Node $node, NodeTypeFieldInterface $field, - TranslationInterface $translation + TranslationInterface $translation, ): array { $qb = $this->createQueryBuilder(self::NODE_ALIAS); $qb->select('n, ns') @@ -1041,8 +945,8 @@ public function findByReverseNodeAndFieldAndTranslation( } /** - * @param NodeInterface $node * @return array + * * @internal Use NodeOffspringResolverInterface service instead */ public function findAllOffspringIdByNode(NodeInterface $node): array @@ -1060,32 +964,25 @@ public function findAllOffspringIdByNode(NodeInterface $node): array $result = $subQb->getQuery()->getScalarResult(); $in = []; - //For memory optimizations + // For memory optimizations foreach ($result as $item) { $in[] = (int) $item['id']; } } while (!empty($in)); + return $theOffsprings; } /** * Find all node’ parents with criteria and ordering. - * - * @param Node $node - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset - * @param TranslationInterface|null $translation - * @return array|Paginator|null */ public function findAllNodeParentsBy( Node $node, array $criteria, - array $orderBy = null, + ?array $orderBy = null, ?int $limit = null, ?int $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): array|Paginator|null { $parentsId = $this->findAllParentsIdByNode($node); if (count($parentsId) > 0) { @@ -1104,7 +1001,6 @@ public function findAllNodeParentsBy( } /** - * @param Node $node * @return array */ public function findAllParentsIdByNode(Node $node): array @@ -1127,27 +1023,25 @@ public function findAllParentsIdByNode(Node $node): array * @param QueryBuilder $qb QueryBuilder to pass * @param array $criteria Additional criteria * @param string $alias SQL query table alias - * - * @return QueryBuilder */ protected function createSearchBy( string $pattern, QueryBuilder $qb, array &$criteria = [], - string $alias = "obj" + string $alias = 'obj', ): QueryBuilder { $this->classicLikeComparison($pattern, $qb, $alias); /* * Search in translations */ - $qb->innerJoin($alias . '.nodeSources', self::NODESSOURCES_ALIAS); + $qb->innerJoin($alias.'.nodeSources', self::NODESSOURCES_ALIAS); $criteriaFields = []; foreach (self::getSearchableColumnsNames($this->_em->getClassMetadata(NodesSources::class)) as $field) { - $criteriaFields[$field] = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $criteriaFields[$field] = '%'.strip_tags(\mb_strtolower($pattern)).'%'; } foreach ($criteriaFields as $key => $value) { - $fullKey = sprintf('LOWER(%s)', self::NODESSOURCES_ALIAS . '.' . $key); + $fullKey = sprintf('LOWER(%s)', self::NODESSOURCES_ALIAS.'.'.$key); $qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value))); } @@ -1157,21 +1051,21 @@ protected function createSearchBy( if (isset($criteria['tags'])) { if ($criteria['tags'] instanceof PersistableInterface) { $qb->innerJoin( - $alias . '.nodesTags', + $alias.'.nodesTags', 'ntg', Expr\Join::WITH, $qb->expr()->eq('ntg.tag', (int) $criteria['tags']->getId()) ); } elseif (is_array($criteria['tags'])) { $qb->innerJoin( - $alias . '.nodesTags', + $alias.'.nodesTags', 'ntg', Expr\Join::WITH, $qb->expr()->in('ntg.tag', $criteria['tags']) ); } elseif (is_integer($criteria['tags'])) { $qb->innerJoin( - $alias . '.nodesTags', + $alias.'.nodesTags', 'ntg', Expr\Join::WITH, $qb->expr()->eq('ntg.tag', (int) $criteria['tags']) @@ -1201,20 +1095,20 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string if (!$event->isPropagationStopped()) { $baseKey = $simpleQB->getParameterKey($key); - if ($key == 'translation') { + if ('translation' == $key) { if (!$this->hasJoinedNodesSources($qb, $alias)) { - $qb->innerJoin($alias . '.nodeSources', self::NODESSOURCES_ALIAS); + $qb->innerJoin($alias.'.nodeSources', self::NODESSOURCES_ALIAS); } $qb->andWhere($simpleQB->buildExpressionWithoutBinding( $value, - self::NODESSOURCES_ALIAS . '.', + self::NODESSOURCES_ALIAS.'.', $key, $baseKey )); } else { $qb->andWhere($simpleQB->buildExpressionWithoutBinding( $value, - $alias . '.', + $alias.'.', $key, $baseKey )); @@ -1230,12 +1124,10 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string * * Parent can be null for node root * - * @param Node|null $parent - * @return int * @throws NonUniqueResultException * @throws NoResultException */ - public function findLatestPositionInParent(Node $parent = null): int + public function findLatestPositionInParent(?Node $parent = null): int { $qb = $this->createQueryBuilder('n'); $qb->select($qb->expr()->max('n.position')); @@ -1253,14 +1145,12 @@ public function findLatestPositionInParent(Node $parent = null): int /** * Use by UniqueEntity Validator to bypass node status query filtering. * - * @param array $criteria - * @return Node|null * @throws NonUniqueResultException */ public function findOneWithoutSecurity(array $criteria): ?Node { $this->setDisplayingAllNodesStatuses(true); - if (count($criteria) === 1 && !empty($criteria['nodeName'])) { + if (1 === count($criteria) && !empty($criteria['nodeName'])) { /* * Test if nodeName is used as an url-alias too */ @@ -1276,35 +1166,37 @@ public function findOneWithoutSecurity(array $criteria): ?Node ->setParameter('nodeName', $nodeName) ->setMaxResults(1) ->setCacheable(true); - ; + return $qb->getQuery()->getOneOrNullResult(); } + return $this->findOneBy($criteria); } protected function classicLikeComparison( string $pattern, QueryBuilder $qb, - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): QueryBuilder { $qb = parent::classicLikeComparison($pattern, $qb, $alias); $qb - ->leftJoin($alias . '.attributeValues', 'av') + ->leftJoin($alias.'.attributeValues', 'av') ->leftJoin('av.attributeValueTranslations', 'avt') ; - $value = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $value = '%'.strip_tags(\mb_strtolower($pattern)).'%'; $qb->orWhere($qb->expr()->like('LOWER(avt.value)', $qb->expr()->literal($value))); - $qb->orWhere($qb->expr()->like('LOWER(' . $alias . '.nodeName)', $qb->expr()->literal($value))); + $qb->orWhere($qb->expr()->like('LOWER('.$alias.'.nodeName)', $qb->expr()->literal($value))); + return $qb; } /** - * Get previous node from hierarchy + * Get previous node from hierarchy. */ public function findPreviousNode( Node $node, ?array $criteria = null, - ?array $order = null + ?array $order = null, ): ?Node { if ($node->getPosition() <= 1) { return null; @@ -1341,7 +1233,7 @@ public function findPreviousNode( public function findNextNode( Node $node, ?array $criteria = null, - ?array $order = null + ?array $order = null, ): ?Node { if (null === $criteria) { $criteria = []; diff --git a/lib/RoadizCoreBundle/src/Repository/NodeTypeFieldRepository.php b/lib/RoadizCoreBundle/src/Repository/NodeTypeFieldRepository.php index 3e219678..75ad2266 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodeTypeFieldRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodeTypeFieldRepository.php @@ -12,22 +12,17 @@ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** - * @package RZ\Roadiz\CoreBundle\Repository * @extends EntityRepository */ final class NodeTypeFieldRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, NodeTypeField::class, $dispatcher); } - /** - * @param NodeTypeInterface|null $nodeType - * @return array - */ public function findAvailableGroupsForNodeType(?NodeTypeInterface $nodeType): array { if (null === $nodeType) { @@ -44,10 +39,6 @@ public function findAvailableGroupsForNodeType(?NodeTypeInterface $nodeType): ar return $query->getScalarResult(); } - /** - * @param NodeTypeInterface|null $nodeType - * @return array - */ public function findAllNotUniversal(?NodeTypeInterface $nodeType): array { if (null === $nodeType) { @@ -63,10 +54,6 @@ public function findAllNotUniversal(?NodeTypeInterface $nodeType): array return $qb->getQuery()->getResult(); } - /** - * @param NodeTypeInterface|null $nodeType - * @return array - */ public function findAllUniversal(?NodeTypeInterface $nodeType): array { if (null === $nodeType) { @@ -87,9 +74,6 @@ public function findAllUniversal(?NodeTypeInterface $nodeType): array * * Parent can be null for tag root * - * @param NodeTypeInterface|null $nodeType - * - * @return int * @throws NoResultException * @throws NonUniqueResultException */ diff --git a/lib/RoadizCoreBundle/src/Repository/NodeTypeRepository.php b/lib/RoadizCoreBundle/src/Repository/NodeTypeRepository.php index 5b15f4d3..39d5f868 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodeTypeRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodeTypeRepository.php @@ -9,20 +9,17 @@ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** - * @package RZ\Roadiz\CoreBundle\Repository * @extends EntityRepository */ final class NodeTypeRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, NodeType::class, $dispatcher); } - /** - * @return array - */ + public function findAll(): array { $qb = $this->createQueryBuilder('nt'); diff --git a/lib/RoadizCoreBundle/src/Repository/NodesCustomFormsRepository.php b/lib/RoadizCoreBundle/src/Repository/NodesCustomFormsRepository.php index 0164634b..ce7b6b13 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodesCustomFormsRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodesCustomFormsRepository.php @@ -11,24 +11,21 @@ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** - * @package RZ\Roadiz\CoreBundle\Repository * @extends EntityRepository<\RZ\Roadiz\CoreBundle\Entity\NodesCustomForms> */ final class NodesCustomFormsRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, NodesCustomForms::class, $dispatcher); } /** - * @param Node $node - * @param NodeTypeFieldInterface $field - * @return int * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException + * * @deprecated Use getLatestPositionForFieldName instead */ public function getLatestPosition(Node $node, NodeTypeFieldInterface $field): int diff --git a/lib/RoadizCoreBundle/src/Repository/NodesSourcesDocumentsRepository.php b/lib/RoadizCoreBundle/src/Repository/NodesSourcesDocumentsRepository.php index 81ba862a..b357cf49 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodesSourcesDocumentsRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodesSourcesDocumentsRepository.php @@ -19,17 +19,15 @@ final class NodesSourcesDocumentsRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, NodesSourcesDocuments::class, $dispatcher); } /** - * @param NodesSources $nodeSource - * @param NodeTypeFieldInterface $field - * @return int * @throws NoResultException * @throws NonUniqueResultException + * * @deprecated Use getLatestPositionForFieldName instead */ public function getLatestPosition(NodesSources $nodeSource, NodeTypeFieldInterface $field): int diff --git a/lib/RoadizCoreBundle/src/Repository/NodesSourcesRepository.php b/lib/RoadizCoreBundle/src/Repository/NodesSourcesRepository.php index 66aebf8d..17c33f9f 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodesSourcesRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodesSourcesRepository.php @@ -32,7 +32,9 @@ * EntityRepository that implements search engine query with Solr. * * @template T of NodesSources + * * @extends StatusAwareRepository + * * @template-extends StatusAwareRepository */ class NodesSourcesRepository extends StatusAwareRepository @@ -40,11 +42,6 @@ class NodesSourcesRepository extends StatusAwareRepository private ?NodeSourceSearchHandlerInterface $nodeSourceSearchHandler; /** - * @param ManagerRegistry $registry - * @param PreviewResolverInterface $previewResolver - * @param EventDispatcherInterface $dispatcher - * @param Security $security - * @param NodeSourceSearchHandlerInterface|null $nodeSourceSearchHandler * @param class-string $entityClass */ public function __construct( @@ -53,17 +50,13 @@ public function __construct( EventDispatcherInterface $dispatcher, Security $security, ?NodeSourceSearchHandlerInterface $nodeSourceSearchHandler, - string $entityClass = NodesSources::class + string $entityClass = NodesSources::class, ) { parent::__construct($registry, $entityClass, $previewResolver, $dispatcher, $security); $this->nodeSourceSearchHandler = $nodeSourceSearchHandler; } /** - * @param QueryBuilder $qb - * @param string $property - * @param mixed $value - * * @return Event */ protected function dispatchQueryBuilderBuildEvent(QueryBuilder $qb, string $property, mixed $value): object @@ -75,10 +68,6 @@ protected function dispatchQueryBuilderBuildEvent(QueryBuilder $qb, string $prop } /** - * @param QueryBuilder $qb - * @param string $property - * @param mixed $value - * * @return Event */ protected function dispatchQueryBuilderApplyEvent(QueryBuilder $qb, string $property, mixed $value): object @@ -90,8 +79,6 @@ protected function dispatchQueryBuilderApplyEvent(QueryBuilder $qb, string $prop } /** - * @param Query $query - * * @return Event */ protected function dispatchQueryEvent(Query $query): object @@ -104,16 +91,13 @@ protected function dispatchQueryEvent(Query $query): object /** * Add a tag filtering to queryBuilder. - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function filterByTag(array &$criteria, QueryBuilder $qb): void { if (key_exists('tags', $criteria)) { if (!$this->hasJoinedNode($qb, static::NODESSOURCES_ALIAS)) { $qb->innerJoin( - static::NODESSOURCES_ALIAS . '.node', + static::NODESSOURCES_ALIAS.'.node', static::NODE_ALIAS ); } @@ -138,25 +122,23 @@ protected function filterByTag(array &$criteria, QueryBuilder $qb): void * * * `node.published => true` * * `node.nodeName => 'page1'` - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function filterByCriteria( array &$criteria, - QueryBuilder $qb + QueryBuilder $qb, ): void { $simpleQB = new SimpleQueryBuilder($qb); /* * Reimplementing findBy features… */ foreach ($criteria as $key => $value) { - if ($key == "tags" || $key == "tagExclusive") { + if ('tags' == $key || 'tagExclusive' == $key) { continue; } /** * Main QueryBuilder dispatch loop for * custom properties criteria. + * * @var QueryBuilderNodesSourcesBuildEvent $event */ $event = $this->dispatchQueryBuilderBuildEvent($qb, $key, $value); @@ -166,7 +148,7 @@ protected function filterByCriteria( * compute prefix for * filtering node relation fields */ - $prefix = static::NODESSOURCES_ALIAS . '.'; + $prefix = static::NODESSOURCES_ALIAS.'.'; // Dots are forbidden in field definitions $baseKey = $simpleQB->getParameterKey($key); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $prefix, $key, $baseKey)); @@ -176,9 +158,6 @@ protected function filterByCriteria( /** * Bind parameters to generated query. - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): void { @@ -187,7 +166,7 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo */ $simpleQB = new SimpleQueryBuilder($qb); foreach ($criteria as $key => $value) { - if ($key == "tags" || $key == "tagExclusive") { + if ('tags' == $key || 'tagExclusive' == $key) { continue; } @@ -199,20 +178,15 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo } } - - /** - * @param QueryBuilder $qb - * @param string $prefix - * @return QueryBuilder - */ public function alterQueryBuilderWithAuthorizationChecker( QueryBuilder $qb, - string $prefix = EntityRepository::NODESSOURCES_ALIAS + string $prefix = EntityRepository::NODESSOURCES_ALIAS, ): QueryBuilder { if (true === $this->isDisplayingAllNodesStatuses()) { if (!$this->hasJoinedNode($qb, $prefix)) { - $qb->innerJoin($prefix . '.node', static::NODE_ALIAS); + $qb->innerJoin($prefix.'.node', static::NODE_ALIAS); } + return $qb; } @@ -221,36 +195,31 @@ public function alterQueryBuilderWithAuthorizationChecker( * Forbid deleted node for backend user when authorizationChecker not null. */ if (!$this->hasJoinedNode($qb, $prefix)) { - $qb->innerJoin($prefix . '.node', static::NODE_ALIAS); + $qb->innerJoin($prefix.'.node', static::NODE_ALIAS); } - $qb->andWhere($qb->expr()->lte(static::NODE_ALIAS . '.status', Node::PUBLISHED)); + $qb->andWhere($qb->expr()->lte(static::NODE_ALIAS.'.status', Node::PUBLISHED)); } else { /* * Forbid unpublished node for anonymous and not backend users. */ if (!$this->hasJoinedNode($qb, $prefix)) { - $qb->innerJoin($prefix . '.node', static::NODE_ALIAS); + $qb->innerJoin($prefix.'.node', static::NODE_ALIAS); } - $qb->andWhere($qb->expr()->eq(static::NODE_ALIAS . '.status', Node::PUBLISHED)); + $qb->andWhere($qb->expr()->eq(static::NODE_ALIAS.'.status', Node::PUBLISHED)); } + return $qb; } /** * Create a secure query with node.published = true if user is * not a Backend user. - * - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset - * @return QueryBuilder */ protected function getContextualQuery( array &$criteria, - array $orderBy = null, + ?array $orderBy = null, ?int $limit = null, - ?int $offset = null + ?int $offset = null, ): QueryBuilder { $qb = $this->createQueryBuilder(static::NODESSOURCES_ALIAS); $this->alterQueryBuilderWithAuthorizationChecker($qb, static::NODESSOURCES_ALIAS); @@ -266,9 +235,9 @@ protected function getContextualQuery( foreach ($orderBy as $key => $value) { if (\str_contains($key, 'node.')) { $simpleKey = str_replace('node.', '', $key); - $qb->addOrderBy(static::NODE_ALIAS . '.' . $simpleKey, $value); + $qb->addOrderBy(static::NODE_ALIAS.'.'.$simpleKey, $value); } else { - $qb->addOrderBy(static::NODESSOURCES_ALIAS . '.' . $key, $value); + $qb->addOrderBy(static::NODESSOURCES_ALIAS.'.'.$key, $value); } } } @@ -289,7 +258,6 @@ protected function getContextualQuery( * * This method allows to pre-filter Nodes with a given translation. * - * @param array $criteria * @return QueryBuilder */ protected function getCountContextualQuery(array &$criteria) @@ -302,7 +270,7 @@ protected function getCountContextualQuery(array &$criteria) $this->filterByTag($criteria, $qb); $this->filterByCriteria($criteria, $qb); - return $qb->select($qb->expr()->countDistinct(static::NODESSOURCES_ALIAS . '.id')); + return $qb->select($qb->expr()->countDistinct(static::NODESSOURCES_ALIAS.'.id')); } /** @@ -310,9 +278,8 @@ protected function getCountContextualQuery(array &$criteria) * * @param array $criteria * - * @return int * @throws \Doctrine\ORM\NoResultException - * @throws \Doctrine\ORM\NonUniqueResultException + * @throws NonUniqueResultException */ public function countBy(mixed $criteria): int { @@ -350,17 +317,16 @@ public function countBy(mixed $criteria): int * * `tags => [$tag1, $tag2]` * * `tags => [$tag1, $tag2], tagExclusive => true` * - * @param array $criteria - * @param array|null $orderBy * @param int|null $limit * @param int|null $offset + * * @return array */ public function findBy( array $criteria, - array $orderBy = null, + ?array $orderBy = null, $limit = null, - $offset = null + $offset = null, ): array { $qb = $this->getContextualQuery( $criteria, @@ -372,7 +338,7 @@ public function findBy( * Eagerly fetch UrlAliases * to limit SQL query count */ - $qb->leftJoin(static::NODESSOURCES_ALIAS . '.urlAliases', 'ua') + $qb->leftJoin(static::NODESSOURCES_ALIAS.'.urlAliases', 'ua') ->addSelect('ua') ; $qb->setCacheable(true); @@ -383,8 +349,8 @@ public function findBy( $this->dispatchQueryEvent($query); if ( - null !== $limit && - null !== $offset + null !== $limit + && null !== $offset ) { /* * We need to use Doctrine paginator @@ -400,15 +366,11 @@ public function findBy( * A secure findOneBy with which user must be a backend user * to see unpublished nodes. * - * @param array $criteria - * @param array|null $orderBy - * - * @return null|NodesSources - * @throws \Doctrine\ORM\NonUniqueResultException + * @throws NonUniqueResultException */ public function findOneBy( array $criteria, - ?array $orderBy = null + ?array $orderBy = null, ): ?NodesSources { $qb = $this->getContextualQuery( $criteria, @@ -420,7 +382,7 @@ public function findOneBy( * Eagerly fetch UrlAliases * to limit SQL query count */ - $qb->leftJoin(static::NODESSOURCES_ALIAS . '.urlAliases', 'ua') + $qb->leftJoin(static::NODESSOURCES_ALIAS.'.urlAliases', 'ua') ->addSelect('ua') ; $qb->setCacheable(true); @@ -437,7 +399,8 @@ public function findOneBy( * Search nodes sources by using Solr search engine. * * @param string $query Solr query string (for example: `text:Lorem Ipsum`) - * @param int $limit Result number to fetch (default: all) + * @param int $limit Result number to fetch (default: all) + * * @return array> */ public function findBySearchQuery(string $query, int $limit = 25): array @@ -456,11 +419,13 @@ public function findBySearchQuery(string $query, int $limit = 25): array if ($limit > 0) { return $this->nodeSourceSearchHandler->search($query, $arguments, $limit)->getResultItems(); } + return $this->nodeSourceSearchHandler->search($query, $arguments, 999999)->getResultItems(); } catch (SolrServerNotAvailableException $exception) { return []; } } + return []; } @@ -468,9 +433,10 @@ public function findBySearchQuery(string $query, int $limit = 25): array * Search nodes sources by using Solr search engine * and a specific translation. * - * @param string $query Solr query string (for example: `text:Lorem Ipsum`) + * @param string $query Solr query string (for example: `text:Lorem Ipsum`) * @param TranslationInterface $translation Current translation - * @param int $limit + * @param int $limit + * * @return SearchResultsInterface */ public function findBySearchQueryAndTranslation($query, TranslationInterface $translation, $limit = 25) @@ -490,6 +456,7 @@ public function findBySearchQueryAndTranslation($query, TranslationInterface $tr return new SolrSearchResults([], $this->_em); } } + return new SolrSearchResults([], $this->_em); } @@ -497,11 +464,6 @@ public function findBySearchQueryAndTranslation($query, TranslationInterface $tr * Search Nodes-Sources using LIKE condition on title * meta-title, meta-keywords, meta-description. * - * @param string $textQuery - * @param int $limit - * @param array $nodeTypes - * @param bool $onlyVisible - * @param array $additionalCriteria * @return array */ public function findByTextQuery( @@ -509,19 +471,19 @@ public function findByTextQuery( int $limit = 0, array $nodeTypes = [], bool $onlyVisible = false, - array $additionalCriteria = [] + array $additionalCriteria = [], ) { $qb = $this->createQueryBuilder(static::NODESSOURCES_ALIAS); $qb->addSelect(static::NODE_ALIAS) ->addSelect('ua') - ->leftJoin(static::NODESSOURCES_ALIAS . '.urlAliases', 'ua') + ->leftJoin(static::NODESSOURCES_ALIAS.'.urlAliases', 'ua') ->andWhere($qb->expr()->orX( - $qb->expr()->like(static::NODESSOURCES_ALIAS . '.title', ':query'), - $qb->expr()->like(static::NODESSOURCES_ALIAS . '.metaTitle', ':query'), - $qb->expr()->like(static::NODESSOURCES_ALIAS . '.metaDescription', ':query') + $qb->expr()->like(static::NODESSOURCES_ALIAS.'.title', ':query'), + $qb->expr()->like(static::NODESSOURCES_ALIAS.'.metaTitle', ':query'), + $qb->expr()->like(static::NODESSOURCES_ALIAS.'.metaDescription', ':query') )) - ->orderBy(static::NODESSOURCES_ALIAS . '.title', 'ASC') - ->setParameter(':query', '%' . $textQuery . '%'); + ->orderBy(static::NODESSOURCES_ALIAS.'.title', 'ASC') + ->setParameter(':query', '%'.$textQuery.'%'); if ($limit > 0) { $qb->setMaxResults($limit); @@ -555,9 +517,6 @@ public function findByTextQuery( /** * Find latest updated NodesSources using Log table. - * - * @param int $maxResult - * @return Paginator */ public function findByLatestUpdated(int $maxResult = 5): Paginator { @@ -569,7 +528,7 @@ public function findByLatestUpdated(int $maxResult = 5): Paginator $query = $this->createQueryBuilder(static::NODESSOURCES_ALIAS); $query - ->andWhere($query->expr()->in(static::NODESSOURCES_ALIAS . '.id', $subQuery->getQuery()->getDQL())) + ->andWhere($query->expr()->in(static::NODESSOURCES_ALIAS.'.id', $subQuery->getQuery()->getDQL())) ->setParameter(':entityClass', NodesSources::class) ->setMaxResults($maxResult) ; @@ -580,20 +539,19 @@ public function findByLatestUpdated(int $maxResult = 5): Paginator /** * Get node-source parent according to its translation. * - * @param NodesSources $nodeSource - * * @return NodesSources|null - * @throws \Doctrine\ORM\NonUniqueResultException + * + * @throws NonUniqueResultException */ public function findParent(NodesSources $nodeSource) { $qb = $this->createQueryBuilder(static::NODESSOURCES_ALIAS); - $qb->select(static::NODESSOURCES_ALIAS . ', n, ua') - ->innerJoin(static::NODESSOURCES_ALIAS . '.node', static::NODE_ALIAS) + $qb->select(static::NODESSOURCES_ALIAS.', n, ua') + ->innerJoin(static::NODESSOURCES_ALIAS.'.node', static::NODE_ALIAS) ->innerJoin('n.children', 'cn') - ->leftJoin(static::NODESSOURCES_ALIAS . '.urlAliases', 'ua') + ->leftJoin(static::NODESSOURCES_ALIAS.'.urlAliases', 'ua') ->andWhere($qb->expr()->eq('cn.id', ':childNodeId')) - ->andWhere($qb->expr()->eq(static::NODESSOURCES_ALIAS . '.translation', ':translation')) + ->andWhere($qb->expr()->eq(static::NODESSOURCES_ALIAS.'.translation', ':translation')) ->setParameter('childNodeId', $nodeSource->getNode()->getId()) ->setParameter('translation', $nodeSource->getTranslation()) ->setMaxResults(1) @@ -603,8 +561,6 @@ public function findParent(NodesSources $nodeSource) } /** - * @param Node $node - * @param TranslationInterface|null $translation * @return mixed|null */ public function findOneByNodeAndTranslation(Node $node, ?TranslationInterface $translation) @@ -612,13 +568,13 @@ public function findOneByNodeAndTranslation(Node $node, ?TranslationInterface $t $qb = $this->createQueryBuilder(static::NODESSOURCES_ALIAS); $qb->select(static::NODESSOURCES_ALIAS) - ->andWhere($qb->expr()->eq(static::NODESSOURCES_ALIAS . '.node', ':node')) + ->andWhere($qb->expr()->eq(static::NODESSOURCES_ALIAS.'.node', ':node')) ->setMaxResults(1) ->setParameter('node', $node) ->setCacheable(true); if (null !== $translation) { - $qb->andWhere($qb->expr()->eq(static::NODESSOURCES_ALIAS . '.translation', ':translation')) + $qb->andWhere($qb->expr()->eq(static::NODESSOURCES_ALIAS.'.translation', ':translation')) ->setParameter('translation', $translation); } @@ -626,7 +582,7 @@ public function findOneByNodeAndTranslation(Node $node, ?TranslationInterface $t } /** - * @inheritdoc + * {@inheritdoc} * * Extends EntityRepository to make join possible with «node.» prefix. * Required if making search with EntityListManager and filtering by node criteria. @@ -646,23 +602,23 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string $baseKey = $simpleQB->getParameterKey($key); if (\str_contains($key, 'node.nodeType.')) { if (!$this->hasJoinedNode($qb, $alias)) { - $qb->innerJoin($alias . '.node', static::NODE_ALIAS); + $qb->innerJoin($alias.'.node', static::NODE_ALIAS); } if (!$this->hasJoinedNodeType($qb, $alias)) { - $qb->innerJoin(static::NODE_ALIAS . '.nodeType', static::NODETYPE_ALIAS); + $qb->innerJoin(static::NODE_ALIAS.'.nodeType', static::NODETYPE_ALIAS); } - $prefix = static::NODETYPE_ALIAS . '.'; + $prefix = static::NODETYPE_ALIAS.'.'; $simpleKey = str_replace('node.nodeType.', '', $key); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $prefix, $simpleKey, $baseKey)); } elseif (\str_contains($key, 'node.')) { if (!$this->hasJoinedNode($qb, $alias)) { - $qb->innerJoin($alias . '.node', static::NODE_ALIAS); + $qb->innerJoin($alias.'.node', static::NODE_ALIAS); } - $prefix = static::NODE_ALIAS . '.'; + $prefix = static::NODE_ALIAS.'.'; $simpleKey = str_replace('node.', '', $key); $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $prefix, $simpleKey, $baseKey)); } else { - $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $alias . '.', $key, $baseKey)); + $qb->andWhere($simpleQB->buildExpressionWithoutBinding($value, $alias.'.', $key, $baseKey)); } } } @@ -670,14 +626,11 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string return $qb; } - /** - * @inheritDoc - */ protected function createSearchBy( string $pattern, QueryBuilder $qb, array &$criteria = [], - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): QueryBuilder { $qb = parent::createSearchBy($pattern, $qb, $criteria, $alias); $this->alterQueryBuilderWithAuthorizationChecker($qb, $alias); @@ -685,29 +638,23 @@ protected function createSearchBy( return $qb; } - /** - * @inheritDoc - */ public function searchBy( string $pattern, array $criteria = [], array $orders = [], - $limit = null, - $offset = null, - string $alias = EntityRepository::DEFAULT_ALIAS + ?int $limit = null, + ?int $offset = null, + string $alias = EntityRepository::DEFAULT_ALIAS, ): array { return parent::searchBy($pattern, $criteria, $orders, $limit, $offset, static::NODESSOURCES_ALIAS); } /** - * @param NodesSources $nodesSources - * @param NodeTypeFieldInterface $field * @deprecated Use findByNodesSourcesAndFieldNameAndTranslation instead - * @return array|null */ public function findByNodesSourcesAndFieldAndTranslation( NodesSources $nodesSources, - NodeTypeFieldInterface $field + NodeTypeFieldInterface $field, ): ?array { $qb = $this->createQueryBuilder(static::NODESSOURCES_ALIAS); $qb->select('ns, n, ua') @@ -729,15 +676,9 @@ public function findByNodesSourcesAndFieldAndTranslation( return $qb->getQuery()->getResult(); } - /** - * @param NodesSources $nodesSources - * @param string $fieldName - * - * @return array|null - */ public function findByNodesSourcesAndFieldNameAndTranslation( NodesSources $nodesSources, - string $fieldName + string $fieldName, ): ?array { $qb = $this->createQueryBuilder(static::NODESSOURCES_ALIAS); $qb->select('ns, n, ua') @@ -767,14 +708,14 @@ public function findByNode(Node $node): array ->innerJoin('ns.translation', static::TRANSLATION_ALIAS) ->leftJoin('ns.urlAliases', 'ua') ->andWhere($qb->expr()->eq('n.id', ':node')) - ->addOrderBy(static::TRANSLATION_ALIAS . '.defaultTranslation', 'DESC') - ->addOrderBy(static::TRANSLATION_ALIAS . '.locale', 'ASC') + ->addOrderBy(static::TRANSLATION_ALIAS.'.defaultTranslation', 'DESC') + ->addOrderBy(static::TRANSLATION_ALIAS.'.locale', 'ASC') ->setParameter('node', $node) ->setCacheable(true); $this->alterQueryBuilderWithAuthorizationChecker($qb); if (!$this->previewResolver->isPreview()) { - $qb->andWhere($qb->expr()->eq(static::TRANSLATION_ALIAS . '.available', ':available')) + $qb->andWhere($qb->expr()->eq(static::TRANSLATION_ALIAS.'.available', ':available')) ->setParameter('available', true); } @@ -784,31 +725,31 @@ public function findByNode(Node $node): array protected function classicLikeComparison( string $pattern, QueryBuilder $qb, - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): QueryBuilder { $qb = parent::classicLikeComparison($pattern, $qb, $alias); $qb - ->innerJoin($alias . '.node', static::NODE_ALIAS) - ->leftJoin(static::NODE_ALIAS . '.attributeValues', 'av') + ->innerJoin($alias.'.node', static::NODE_ALIAS) + ->leftJoin(static::NODE_ALIAS.'.attributeValues', 'av') ->leftJoin('av.attributeValueTranslations', 'avt') ; - $value = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $value = '%'.strip_tags(\mb_strtolower($pattern)).'%'; $qb->orWhere($qb->expr()->like('LOWER(avt.value)', $qb->expr()->literal($value))); - $qb->orWhere($qb->expr()->like('LOWER(' . static::NODE_ALIAS . '.nodeName)', $qb->expr()->literal($value))); + $qb->orWhere($qb->expr()->like('LOWER('.static::NODE_ALIAS.'.nodeName)', $qb->expr()->literal($value))); + return $qb; } /** * Get every nodeSources parents from direct parent to farthest ancestor. * - * @param NodesSources $nodeSource - * @param array|null $criteria * @return array - * @throws \Doctrine\ORM\NonUniqueResultException + * + * @throws NonUniqueResultException */ public function findParents( NodesSources $nodeSource, - ?array $criteria = null + ?array $criteria = null, ): array { $parentsNodeSources = []; @@ -844,16 +785,15 @@ public function findParents( /** * Get children nodes sources to lock with current translation. * - * @param NodesSources $nodeSource * @param array|null $criteria Additional criteria - * @param array|null $order Non default ordering + * @param array|null $order Non default ordering * * @return Paginator|array */ public function findChildren( NodesSources $nodeSource, - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): Paginator|array { $defaultCriteria = [ 'node.parent' => $nodeSource->getNode(), @@ -881,17 +821,12 @@ public function findChildren( /** * Get first node-source among current node-source children. * - * @param NodesSources|null $nodeSource - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @throws NonUniqueResultException */ public function findFirstChild( ?NodesSources $nodeSource, - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { $defaultCriteria = [ 'node.parent' => $nodeSource?->getNode() ?? null, @@ -922,17 +857,12 @@ public function findFirstChild( /** * Get last node-source among current node-source children. * - * @param NodesSources|null $nodeSource - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @throws NonUniqueResultException */ public function findLastChild( ?NodesSources $nodeSource, - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { $defaultCriteria = [ 'node.parent' => $nodeSource?->getNode() ?? null, @@ -963,59 +893,46 @@ public function findLastChild( /** * Get first node-source in the same parent as current node-source. * - * @param NodesSources $nodeSource - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @throws NonUniqueResultException */ public function findFirstSibling( NodesSources $nodeSource, - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { if (null !== $nodeSource->getParent()) { return $this->findFirstChild($nodeSource->getParent(), $criteria, $order); } + return $this->findFirstChild(null, $criteria, $order); } /** * Get last node-source in the same parent as current node-source. * - * @param NodesSources $nodeSource - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @throws NonUniqueResultException */ public function findLastSibling( NodesSources $nodeSource, - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { if (null !== $nodeSource->getParent()) { return $this->findLastChild($nodeSource->getParent(), $criteria, $order); } + return $this->findLastChild(null, $criteria, $order); } /** * Get previous node-source from hierarchy. * - * @param NodesSources $nodeSource - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @throws NonUniqueResultException */ public function findPrevious( NodesSources $nodeSource, - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { if ($nodeSource->getNode()->getPosition() <= 1) { return null; @@ -1054,17 +971,12 @@ public function findPrevious( /** * Get next node-source from hierarchy. * - * @param NodesSources $nodeSource - * @param array|null $criteria - * @param array|null $order - * - * @return NodesSources|null * @throws NonUniqueResultException */ public function findNext( NodesSources $nodeSource, - array $criteria = null, - array $order = null + ?array $criteria = null, + ?array $order = null, ): ?NodesSources { $defaultCriteria = [ /* diff --git a/lib/RoadizCoreBundle/src/Repository/NodesTagsRepository.php b/lib/RoadizCoreBundle/src/Repository/NodesTagsRepository.php index 540478e0..f9f698f2 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodesTagsRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodesTagsRepository.php @@ -15,7 +15,7 @@ class NodesTagsRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, NodesTags::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/NodesToNodesRepository.php b/lib/RoadizCoreBundle/src/Repository/NodesToNodesRepository.php index edb68b93..ba1cb81e 100644 --- a/lib/RoadizCoreBundle/src/Repository/NodesToNodesRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/NodesToNodesRepository.php @@ -13,24 +13,21 @@ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** - * @package RZ\Roadiz\CoreBundle\Repository * @extends EntityRepository */ final class NodesToNodesRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, NodesToNodes::class, $dispatcher); } /** - * @param Node $node - * @param NodeTypeFieldInterface $field - * @return int * @throws NoResultException * @throws NonUniqueResultException + * * @deprecated Use getLatestPositionForFieldName instead */ public function getLatestPosition(Node $node, NodeTypeFieldInterface $field): int diff --git a/lib/RoadizCoreBundle/src/Repository/PrefixAwareRepository.php b/lib/RoadizCoreBundle/src/Repository/PrefixAwareRepository.php index 2c84a269..e666ee50 100644 --- a/lib/RoadizCoreBundle/src/Repository/PrefixAwareRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/PrefixAwareRepository.php @@ -13,6 +13,7 @@ * Class PrefixAwareRepository for defining join-queries prefixes. * * @template TEntityClass of object + * * @extends EntityRepository */ abstract class PrefixAwareRepository extends EntityRepository @@ -32,17 +33,11 @@ abstract class PrefixAwareRepository extends EntityRepository */ private array $prefixes = []; - /** - * @return array - */ public function getPrefixes(): array { return $this->prefixes; } - /** - * @return string - */ public function getDefaultPrefix(): string { return EntityRepository::DEFAULT_ALIAS; @@ -50,8 +45,9 @@ public function getDefaultPrefix(): string /** * @param string $prefix Ex. 'node' - * @param array $joins Ex. ['n': 'obj.node'] - * @param string $type Ex. 'inner'|'left', default 'left' + * @param array $joins Ex. ['n': 'obj.node'] + * @param string $type Ex. 'inner'|'left', default 'left' + * * @return $this */ public function addPrefix(string $prefix, array $joins, string $type = 'left'): self @@ -63,14 +59,13 @@ public function addPrefix(string $prefix, array $joins, string $type = 'left'): if (!array_key_exists($prefix, $this->prefixes)) { $this->prefixes[$prefix] = [ 'joins' => $joins, - 'type' => $type + 'type' => $type, ]; } return $this; } - protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string $alias): QueryBuilder { $simpleQB = new SimpleQueryBuilder($qb); @@ -91,11 +86,6 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string return $qb; } - /** - * @param QueryBuilder $qb - * @param string $key - * @return array - */ protected function getRealKey(QueryBuilder $qb, string $key): array { $keyParts = explode('.', $key); @@ -116,26 +106,22 @@ protected function getRealKey(QueryBuilder $qb, string $key): array $lastPrefix = $prefix; } + return [ - 'prefix' => $lastPrefix . '.', - 'key' => $keyParts[1] + 'prefix' => $lastPrefix.'.', + 'key' => $keyParts[1], ]; } - throw new \InvalidArgumentException('"' . $keyParts[0] . '" prefix is not known for initiating joined queries.'); + throw new \InvalidArgumentException('"'.$keyParts[0].'" prefix is not known for initiating joined queries.'); } return [ - 'prefix' => $this->getDefaultPrefix() . '.', - 'key' => $key + 'prefix' => $this->getDefaultPrefix().'.', + 'key' => $key, ]; } - /** - * @param QueryBuilder $qb - * @param string $prefix - * @return bool - */ protected function hasJoinedPrefix(QueryBuilder $qb, string $prefix): bool { return $this->joinExists($qb, $this->getDefaultPrefix(), $prefix); @@ -144,18 +130,18 @@ protected function hasJoinedPrefix(QueryBuilder $qb, string $prefix): bool /** * Count entities using a Criteria object or a simple filter array. * - * @param array $criteria - * @param array|null $orderBy * @param int|null $limit * @param int|null $offset + * * @return array + * * @throws \Exception */ public function findBy( array $criteria, - array $orderBy = null, + ?array $orderBy = null, $limit = null, - $offset = null + $offset = null, ): array { $qb = $this->createQueryBuilder($this->getDefaultPrefix()); $qb->select($this->getDefaultPrefix()); @@ -165,7 +151,7 @@ public function findBy( if (null !== $orderBy) { foreach ($orderBy as $key => $value) { $realKey = $this->getRealKey($qb, $key); - $qb->addOrderBy($realKey['prefix'] . $realKey['key'], $value); + $qb->addOrderBy($realKey['prefix'].$realKey['key'], $value); } } if (null !== $offset) { @@ -181,8 +167,8 @@ public function findBy( $this->dispatchQueryEvent($query); if ( - null !== $limit && - null !== $offset + null !== $limit + && null !== $offset ) { /* * We need to use Doctrine paginator @@ -197,16 +183,13 @@ public function findBy( /** * Count entities using a Criteria object or a simple filter array. * - * @param array $criteria - * @param array|null $orderBy - * - * @return object|null * @psalm-return TEntityClass + * * @throws \Doctrine\ORM\NonUniqueResultException */ public function findOneBy( array $criteria, - ?array $orderBy = null + ?array $orderBy = null, ): ?object { $qb = $this->createQueryBuilder($this->getDefaultPrefix()); $qb->select($this->getDefaultPrefix()); @@ -216,7 +199,7 @@ public function findOneBy( if (null !== $orderBy) { foreach ($orderBy as $key => $value) { $realKey = $this->getRealKey($qb, $key); - $qb->addOrderBy($realKey['prefix'] . $realKey['key'], $value); + $qb->addOrderBy($realKey['prefix'].$realKey['key'], $value); } } @@ -230,12 +213,10 @@ public function findOneBy( } /** - * @param string $pattern Search pattern - * @param array $criteria Additional criteria - * @param array $orders - * @param integer $limit - * @param integer $offset - * @param string $alias + * @param string $pattern Search pattern + * @param array $criteria Additional criteria + * @param int $limit + * @param int $offset * * @return array */ @@ -245,7 +226,7 @@ public function searchBy( array $orders = [], $limit = null, $offset = null, - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): array { $qb = $this->createQueryBuilder($alias); $qb->select($alias); @@ -255,7 +236,7 @@ public function searchBy( if (null !== $orders) { foreach ($orders as $key => $value) { $realKey = $this->getRealKey($qb, $key); - $qb->addOrderBy($realKey['prefix'] . $realKey['key'], $value); + $qb->addOrderBy($realKey['prefix'].$realKey['key'], $value); } } @@ -272,8 +253,8 @@ public function searchBy( $this->dispatchQueryEvent($query); if ( - null !== $limit && - null !== $offset + null !== $limit + && null !== $offset ) { /* * We need to use Doctrine paginator @@ -288,7 +269,7 @@ public function searchBy( public function countSearchBy(string $pattern, array $criteria = []): int { $qb = $this->createQueryBuilder($this->getDefaultPrefix()); - $qb->select($qb->expr()->countDistinct($this->getDefaultPrefix() . '.id')); + $qb->select($qb->expr()->countDistinct($this->getDefaultPrefix().'.id')); $qb = $this->createSearchBy($pattern, $qb, $criteria); $this->dispatchQueryBuilderEvent($qb, $this->getEntityName()); @@ -299,32 +280,28 @@ public function countSearchBy(string $pattern, array $criteria = []): int /** * Create a LIKE comparison with entity texts columns. - * - * @param string $pattern - * @param QueryBuilder $qb - * @param string $alias - * @return QueryBuilder */ protected function classicLikeComparison( string $pattern, QueryBuilder $qb, - string $alias = "obj" + string $alias = 'obj', ): QueryBuilder { /* * Get fields needed for a search query */ $criteriaFields = []; foreach (static::getSearchableColumnsNames($this->getClassMetadata()) as $field) { - $criteriaFields[$field] = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $criteriaFields[$field] = '%'.strip_tags(\mb_strtolower($pattern)).'%'; } foreach ($criteriaFields as $key => $value) { if (\is_string($key)) { $realKey = $this->getRealKey($qb, $key); - $fullKey = sprintf('LOWER(%s)', $realKey['prefix'] . $realKey['key']); + $fullKey = sprintf('LOWER(%s)', $realKey['prefix'].$realKey['key']); $qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value))); } } + return $qb; } } diff --git a/lib/RoadizCoreBundle/src/Repository/RealmNodeRepository.php b/lib/RoadizCoreBundle/src/Repository/RealmNodeRepository.php index 4af3e76f..dd587146 100644 --- a/lib/RoadizCoreBundle/src/Repository/RealmNodeRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/RealmNodeRepository.php @@ -13,6 +13,7 @@ * @method RealmNode|null findOneBy(array $criteria, array $orderBy = null) * @method RealmNode[] findAll() * @method RealmNode[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class RealmNodeRepository extends EntityRepository diff --git a/lib/RoadizCoreBundle/src/Repository/RealmRepository.php b/lib/RoadizCoreBundle/src/Repository/RealmRepository.php index 42375537..3be72660 100644 --- a/lib/RoadizCoreBundle/src/Repository/RealmRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/RealmRepository.php @@ -15,6 +15,7 @@ * @method Realm|null findOneBy(array $criteria, array $orderBy = null) * @method Realm[] findAll() * @method Realm[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class RealmRepository extends EntityRepository diff --git a/lib/RoadizCoreBundle/src/Repository/RedirectionRepository.php b/lib/RoadizCoreBundle/src/Repository/RedirectionRepository.php index 24cf7709..bc937791 100644 --- a/lib/RoadizCoreBundle/src/Repository/RedirectionRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/RedirectionRepository.php @@ -14,13 +14,14 @@ * @method Redirection|null findOneBy(array $criteria, array $orderBy = null) * @method Redirection[] findAll() * @method Redirection[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class RedirectionRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Redirection::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/RoleRepository.php b/lib/RoadizCoreBundle/src/Repository/RoleRepository.php index 7a0cb83d..db273a93 100644 --- a/lib/RoadizCoreBundle/src/Repository/RoleRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/RoleRepository.php @@ -6,11 +6,9 @@ use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\NoResultException; -use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; use Doctrine\Persistence\ManagerRegistry; use RZ\Roadiz\CoreBundle\Entity\Role; -use RZ\Roadiz\CoreBundle\Entity\SettingGroup; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** @@ -20,20 +18,19 @@ * @method Role|null findOneBy(array $criteria, array $orderBy = null) * @method Role[] findAll() * @method Role[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class RoleRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Role::class, $dispatcher); } /** - * @param string $roleName - * @return int * @throws NoResultException * @throws NonUniqueResultException */ @@ -50,8 +47,6 @@ public function countByName(string $roleName): int } /** - * @param string $roleName - * @return Role * @throws NonUniqueResultException * @throws ORMException */ @@ -76,8 +71,6 @@ public function findOneByName(string $roleName): Role /** * Get every Role names except for ROLE_SUPERADMIN. - * - * @return array */ public function getAllBasicRoleName(): array { @@ -93,9 +86,7 @@ public function getAllBasicRoleName(): array } /** - * Get every Role names - * - * @return array + * Get every Role names. */ public function getAllRoleName(): array { diff --git a/lib/RoadizCoreBundle/src/Repository/SettingGroupRepository.php b/lib/RoadizCoreBundle/src/Repository/SettingGroupRepository.php index 35be698f..2623d2bf 100644 --- a/lib/RoadizCoreBundle/src/Repository/SettingGroupRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/SettingGroupRepository.php @@ -14,21 +14,19 @@ * @method SettingGroup|null findOneBy(array $criteria, array $orderBy = null) * @method SettingGroup[] findAll() * @method SettingGroup[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class SettingGroupRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, SettingGroup::class, $dispatcher); } /** - * @param string $name - * - * @return bool * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ @@ -42,12 +40,10 @@ public function exists(string $name): bool return (bool) $query->getSingleScalarResult(); } - /** - * @return array - */ public function findAllNames(): array { $query = $this->_em->createQuery('SELECT s.name FROM RZ\Roadiz\CoreBundle\Entity\SettingGroup s'); + return array_map('current', $query->getScalarResult()); } } diff --git a/lib/RoadizCoreBundle/src/Repository/SettingRepository.php b/lib/RoadizCoreBundle/src/Repository/SettingRepository.php index 19483196..680e7d94 100644 --- a/lib/RoadizCoreBundle/src/Repository/SettingRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/SettingRepository.php @@ -16,21 +16,19 @@ * @method Setting|null findOneBy(array $criteria, array $orderBy = null) * @method Setting[] findAll() * @method Setting[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class SettingRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Setting::class, $dispatcher); } /** - * @param string $name - * - * @return mixed * @throws NoResultException * @throws NonUniqueResultException */ @@ -42,15 +40,12 @@ public function getValue(string $name): mixed ->setParameter(':name', $name); $query = $builder->getQuery(); - $query->enableResultCache(3600, 'RZSettingValue_' . $name); + $query->enableResultCache(3600, 'RZSettingValue_'.$name); return $query->getSingleScalarResult(); } /** - * @param string $name - * - * @return bool * @throws NoResultException * @throws NonUniqueResultException */ @@ -62,15 +57,13 @@ public function exists(string $name): bool ->setParameter(':name', $name); $query = $builder->getQuery(); - $query->enableResultCache(3600, 'RZSettingExists_' . $name); + $query->enableResultCache(3600, 'RZSettingExists_'.$name); return (bool) $query->getSingleScalarResult(); } /** - * Get every Setting names - * - * @return array + * Get every Setting names. */ public function findAllNames(): array { diff --git a/lib/RoadizCoreBundle/src/Repository/StatusAwareRepository.php b/lib/RoadizCoreBundle/src/Repository/StatusAwareRepository.php index 4012a2a1..aa96a429 100644 --- a/lib/RoadizCoreBundle/src/Repository/StatusAwareRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/StatusAwareRepository.php @@ -13,6 +13,7 @@ /** * @template TEntityClass of object + * * @extends EntityRepository */ abstract class StatusAwareRepository extends EntityRepository @@ -21,18 +22,14 @@ abstract class StatusAwareRepository extends EntityRepository private bool $displayAllNodesStatuses; /** - * @param ManagerRegistry $registry * @param class-string $entityClass - * @param PreviewResolverInterface $previewResolver - * @param EventDispatcherInterface $dispatcher - * @param Security $security */ public function __construct( ManagerRegistry $registry, string $entityClass, protected readonly PreviewResolverInterface $previewResolver, EventDispatcherInterface $dispatcher, - protected readonly Security $security + protected readonly Security $security, ) { parent::__construct($registry, $entityClass, $dispatcher); @@ -40,28 +37,21 @@ public function __construct( $this->displayAllNodesStatuses = false; } - - /** - * @return bool - */ public function isDisplayingNotPublishedNodes(): bool { return $this->displayNotPublishedNodes; } /** - * @param bool $displayNotPublishedNodes * @return $this */ public function setDisplayingNotPublishedNodes(bool $displayNotPublishedNodes): self { $this->displayNotPublishedNodes = $displayNotPublishedNodes; + return $this; } - /** - * @return bool - */ public function isDisplayingAllNodesStatuses(): bool { return $this->displayAllNodesStatuses; @@ -71,23 +61,18 @@ public function isDisplayingAllNodesStatuses(): bool * Switch repository to disable any security on Node status. To use ONLY in order to * view deleted and archived nodes. * - * @param bool $displayAllNodesStatuses * @return $this */ public function setDisplayingAllNodesStatuses(bool $displayAllNodesStatuses): self { $this->displayAllNodesStatuses = $displayAllNodesStatuses; + return $this; } - /** - * @param QueryBuilder $qb - * @param string $prefix - * @return QueryBuilder - */ public function alterQueryBuilderWithAuthorizationChecker( QueryBuilder $qb, - string $prefix = EntityRepository::NODE_ALIAS + string $prefix = EntityRepository::NODE_ALIAS, ): QueryBuilder { if (true === $this->isDisplayingAllNodesStatuses()) { // do not filter on status @@ -98,9 +83,9 @@ public function alterQueryBuilderWithAuthorizationChecker( * and context. */ if (true === $this->isDisplayingNotPublishedNodes() || $this->previewResolver->isPreview()) { - $qb->andWhere($qb->expr()->lte($prefix . '.status', Node::PUBLISHED)); + $qb->andWhere($qb->expr()->lte($prefix.'.status', Node::PUBLISHED)); } else { - $qb->andWhere($qb->expr()->eq($prefix . '.status', Node::PUBLISHED)); + $qb->andWhere($qb->expr()->eq($prefix.'.status', Node::PUBLISHED)); } return $qb; diff --git a/lib/RoadizCoreBundle/src/Repository/TagRepository.php b/lib/RoadizCoreBundle/src/Repository/TagRepository.php index 4dc6e292..cabdf8e1 100644 --- a/lib/RoadizCoreBundle/src/Repository/TagRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/TagRepository.php @@ -25,22 +25,20 @@ * @method Tag|null findOneByName(string $query) * @method Tag|null find($id, $lockMode = null, $lockVersion = null) * @method Tag[] findAll() + * * @extends EntityRepository */ final class TagRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Tag::class, $dispatcher); } /** * Add a node filtering to queryBuilder. - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function filterByNodes(array &$criteria, QueryBuilder $qb): void { @@ -64,10 +62,7 @@ protected function filterByNodes(array &$criteria, QueryBuilder $qb): void } /** - * Bind node parameter to final query - * - * @param array $criteria - * @param QueryBuilder $qb + * Bind node parameter to final query. */ protected function applyFilterByNodes(array &$criteria, QueryBuilder $qb): void { @@ -75,8 +70,8 @@ protected function applyFilterByNodes(array &$criteria, QueryBuilder $qb): void if ($criteria['nodes'] instanceof Node) { $qb->setParameter('nodes', $criteria['nodes']->getId()); } elseif ( - is_array($criteria['nodes']) || - $criteria['nodes'] instanceof Collection + is_array($criteria['nodes']) + || $criteria['nodes'] instanceof Collection ) { $qb->setParameter('nodes', $criteria['nodes']); } elseif (is_integer($criteria['nodes'])) { @@ -88,9 +83,6 @@ protected function applyFilterByNodes(array &$criteria, QueryBuilder $qb): void /** * Bind parameters to generated query. - * - * @param array $criteria - * @param QueryBuilder $qb */ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): void { @@ -108,20 +100,16 @@ protected function applyFilterByCriteria(array &$criteria, QueryBuilder $qb): vo /** * Create filters according to any translation criteria OR argument. - * - * @param array $criteria - * @param QueryBuilder $qb - * @param TranslationInterface|null $translation */ protected function filterByTranslation( array &$criteria, QueryBuilder $qb, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): void { if ( - isset($criteria['translation']) || - isset($criteria['translation.locale']) || - isset($criteria['translation.id']) + isset($criteria['translation']) + || isset($criteria['translation.locale']) + || isset($criteria['translation.id']) ) { $qb->leftJoin('tg.translatedTags', 'tt'); $qb->leftJoin('tt.translation', static::TRANSLATION_ALIAS); @@ -152,14 +140,11 @@ protected function filterByTranslation( } /** - * Bind translation parameter to final query - * - * @param QueryBuilder $qb - * @param TranslationInterface|null $translation + * Bind translation parameter to final query. */ protected function applyTranslationByTag( QueryBuilder $qb, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): void { if (null !== $translation) { $qb->setParameter('translation', $translation); @@ -168,21 +153,13 @@ protected function applyTranslationByTag( /** * This method allows to pre-filter Nodes with a given translation. - * - * @param array $criteria - * @param array|null $orderBy - * @param int|null $limit - * @param int|null $offset - * @param TranslationInterface|null $translation - * - * @return QueryBuilder */ protected function getContextualQueryWithTranslation( array &$criteria, - array $orderBy = null, + ?array $orderBy = null, ?int $limit = null, ?int $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): QueryBuilder { $qb = $this->createQueryBuilder(EntityRepository::TAG_ALIAS); $qb->addSelect('tt'); @@ -193,7 +170,7 @@ protected function getContextualQueryWithTranslation( // Add ordering if (null !== $orderBy) { foreach ($orderBy as $key => $value) { - $qb->addOrderBy(EntityRepository::TAG_ALIAS . '.' . $key, $value); + $qb->addOrderBy(EntityRepository::TAG_ALIAS.'.'.$key, $value); } } @@ -206,17 +183,13 @@ protected function getContextualQueryWithTranslation( return $qb; } + /** * This method allows to pre-filter Nodes with a given translation. - * - * @param array $criteria - * @param TranslationInterface|null $translation - * - * @return QueryBuilder */ protected function getCountContextualQueryWithTranslation( array &$criteria, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): QueryBuilder { $qb = $this->createQueryBuilder(EntityRepository::TAG_ALIAS); $this->filterByNodes($criteria, $qb); @@ -229,20 +202,18 @@ protected function getCountContextualQueryWithTranslation( /** * Just like the findBy method but with relational criteria. * - * @param array $criteria - * @param array|string[]|null $orderBy - * @param integer|null $limit - * @param integer|null $offset - * @param TranslationInterface|null $translation + * @param array|string[]|null $orderBy + * @param int|null $limit + * @param int|null $offset * * @return array */ public function findBy( array $criteria, - array $orderBy = null, + ?array $orderBy = null, $limit = null, $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): array { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -261,8 +232,8 @@ public function findBy( $this->dispatchQueryEvent($query); if ( - null !== $limit && - null !== $offset + null !== $limit + && null !== $offset ) { /* * We need to use Doctrine paginator @@ -277,20 +248,16 @@ public function findBy( /** * Just like the findBy method but with relational criteria. * - * @param array $criteria - * @param array|string[]|null $orderBy - * @param int|null $limit - * @param int|null $offset - * @param TranslationInterface|null $translation + * @param array|string[]|null $orderBy * * @return array */ public function findByAsTagTreeDto( array $criteria, - array $orderBy = null, + ?array $orderBy = null, ?int $limit = null, ?int $offset = null, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): array { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -340,17 +307,12 @@ protected function alterQueryBuilderAsTagTreeDto(QueryBuilder $qb): QueryBuilder /** * Just like the findOneBy method but with relational criteria. * - * @param array $criteria - * @param array|null $orderBy - * @param TranslationInterface|null $translation - * - * @return Tag|null * @throws NonUniqueResultException */ public function findOneBy( array $criteria, ?array $orderBy = null, - ?TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): ?Tag { $qb = $this->getContextualQueryWithTranslation( $criteria, @@ -375,14 +337,13 @@ public function findOneBy( * Just like the countBy method but with relational criteria. * * @param array $criteria - * @param TranslationInterface|null $translation - * @return int + * * @throws NonUniqueResultException * @throws NoResultException */ public function countBy( mixed $criteria, - TranslationInterface $translation = null + ?TranslationInterface $translation = null, ): int { $query = $this->getCountContextualQueryWithTranslation( $criteria, @@ -399,9 +360,9 @@ public function countBy( /** * @param int $tagId - * @param TranslationInterface $translation * * @return Tag|null + * * @throws NonUniqueResultException */ public function findWithTranslation($tagId, TranslationInterface $translation) @@ -420,7 +381,6 @@ public function findWithTranslation($tagId, TranslationInterface $translation) } /** - * @param TranslationInterface $translation * @return Tag[] */ public function findAllWithTranslation(TranslationInterface $translation) @@ -490,13 +450,11 @@ public function findAllColored() '#ffffff', ]) ; + return $qb->getQuery()->getResult(); } /** - * @param Node $parentNode - * @param TranslationInterface|null $translation - * * @return Tag[] */ public function findAllLinkedToNodeChildren(Node $parentNode, ?TranslationInterface $translation = null) @@ -520,6 +478,7 @@ public function findAllLinkedToNodeChildren(Node $parentNode, ?TranslationInterf ->andWhere($qb->expr()->eq('ns.translation', ':translation')) ->setParameter('translation', $translation); } + return $qb->getQuery() ->setHint(\Doctrine\ORM\Query::HINT_FORCE_PARTIAL_LOAD, true) ->getResult() @@ -527,12 +486,9 @@ public function findAllLinkedToNodeChildren(Node $parentNode, ?TranslationInterf } /** - * @param TranslationInterface $translation - * @param Tag|null $parent - * * @return Tag[] */ - public function findByParentWithTranslation(TranslationInterface $translation, Tag $parent = null) + public function findByParentWithTranslation(TranslationInterface $translation, ?Tag $parent = null) { $qb = $this->createQueryBuilder('t'); $qb->select('t, tt') @@ -553,11 +509,9 @@ public function findByParentWithTranslation(TranslationInterface $translation, T } /** - * @param Tag|null $parent - * * @return Tag[] */ - public function findByParentWithDefaultTranslation(Tag $parent = null) + public function findByParentWithDefaultTranslation(?Tag $parent = null) { $qb = $this->createQueryBuilder('t'); $qb->select('t, tt') @@ -581,10 +535,9 @@ public function findByParentWithDefaultTranslation(Tag $parent = null) /** * Returns only Tags that have children. * - * @param Tag|null $parent * @return Tag[] */ - public function findByParentWithChildrenAndDefaultTranslation(Tag $parent = null) + public function findByParentWithChildrenAndDefaultTranslation(?Tag $parent = null) { $qb = $this->createQueryBuilder('t'); $qb->select('t, tt') @@ -610,44 +563,36 @@ public function findByParentWithChildrenAndDefaultTranslation(Tag $parent = null /** * Create a Criteria object from a search pattern and additional fields. * - * @param string $pattern Search pattern - * @param QueryBuilder $qb QueryBuilder to pass - * @param array $criteria Additional criteria - * @param string $alias SQL query table alias - * - * @return QueryBuilder + * @param string $pattern Search pattern + * @param QueryBuilder $qb QueryBuilder to pass + * @param array $criteria Additional criteria + * @param string $alias SQL query table alias */ protected function createSearchBy( string $pattern, QueryBuilder $qb, array &$criteria = [], - string $alias = EntityRepository::DEFAULT_ALIAS + string $alias = EntityRepository::DEFAULT_ALIAS, ): QueryBuilder { $this->classicLikeComparison($pattern, $qb, $alias); /* * Search in translations */ - $qb->leftJoin($alias . '.translatedTags', 'tt'); + $qb->leftJoin($alias.'.translatedTags', 'tt'); $criteriaFields = []; foreach (self::getSearchableColumnsNames($this->_em->getClassMetadata(TagTranslation::class)) as $field) { - $criteriaFields[$field] = '%' . strip_tags(\mb_strtolower($pattern)) . '%'; + $criteriaFields[$field] = '%'.strip_tags(\mb_strtolower($pattern)).'%'; } foreach ($criteriaFields as $key => $value) { - $fullKey = sprintf('LOWER(%s)', 'tt.' . $key); + $fullKey = sprintf('LOWER(%s)', 'tt.'.$key); $qb->orWhere($qb->expr()->like($fullKey, $qb->expr()->literal($value))); } return $this->prepareComparisons($criteria, $qb, $alias); } - /** - * @param array $criteria - * @param QueryBuilder $qb - * @param string $alias - * @return QueryBuilder - */ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string $alias): QueryBuilder { $simpleQB = new SimpleQueryBuilder($qb); @@ -662,7 +607,7 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string /* * Search in node fields */ - if ($key == 'nodes') { + if ('nodes' == $key) { continue; } @@ -679,13 +624,13 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string /* * Search in translation fields */ - $prefix = static::TRANSLATION_ALIAS . '.'; + $prefix = static::TRANSLATION_ALIAS.'.'; $key = str_replace('translation.', '', $key); } elseif (\str_contains($key, 'nodes.')) { /* * Search in node fields */ - $prefix = static::NODE_ALIAS . '.'; + $prefix = static::NODE_ALIAS.'.'; $key = str_replace('nodes.', '', $key); } elseif (\str_contains($key, 'translatedTag.')) { /* @@ -693,7 +638,7 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string */ $prefix = 'tt.'; $key = str_replace('translatedTag.', '', $key); - } elseif ($key === 'translation') { + } elseif ('translation' === $key) { /* * Search in translation fields */ @@ -709,10 +654,8 @@ protected function prepareComparisons(array &$criteria, QueryBuilder $qb, string /** * Find a tag according to the given path or create it. * - * @param string $tagPath - * @param TranslationInterface|null $translation - * * @return Tag|null + * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException */ @@ -722,7 +665,7 @@ public function findOrCreateByPath(string $tagPath, ?TranslationInterface $trans $tags = explode('/', $tagPath); $tags = array_filter($tags); - if (count($tags) === 0) { + if (0 === count($tags)) { return null; } @@ -780,10 +723,6 @@ public function findOrCreateByPath(string $tagPath, ?TranslationInterface $trans /** * Find a tag according to the given path. - * - * @param string $tagPath - * - * @return Tag|null */ public function findByPath(string $tagPath): ?Tag { @@ -810,12 +749,10 @@ public function findByPath(string $tagPath): ?Tag * * Parent can be null for tag root * - * @param Tag|null $parent - * @return int * @throws NoResultException * @throws NonUniqueResultException */ - public function findLatestPositionInParent(Tag $parent = null): int + public function findLatestPositionInParent(?Tag $parent = null): int { $qb = $this->createQueryBuilder('t'); $qb->select($qb->expr()->max('t.position')); @@ -834,8 +771,8 @@ public function findByNodesSources(NodesSources $nodesSources): array|Paginator { // @phpstan-ignore-next-line return $this->findBy([ - "nodes" => $nodesSources->getNode(), - "translation" => $nodesSources->getTranslation(), + 'nodes' => $nodesSources->getNode(), + 'translation' => $nodesSources->getTranslation(), ], [ 'position' => 'ASC', ]); diff --git a/lib/RoadizCoreBundle/src/Repository/TagTranslationDocumentsRepository.php b/lib/RoadizCoreBundle/src/Repository/TagTranslationDocumentsRepository.php index e693ca4d..f1c233d9 100644 --- a/lib/RoadizCoreBundle/src/Repository/TagTranslationDocumentsRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/TagTranslationDocumentsRepository.php @@ -15,20 +15,23 @@ * @method TagTranslationDocuments|null findOneBy(array $criteria, array $orderBy = null) * @method TagTranslationDocuments[] findAll() * @method TagTranslationDocuments[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class TagTranslationDocumentsRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, TagTranslationDocuments::class, $dispatcher); } + /** * @param TagTranslation $tagTranslation * - * @return integer + * @return int + * * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ diff --git a/lib/RoadizCoreBundle/src/Repository/TagTranslationRepository.php b/lib/RoadizCoreBundle/src/Repository/TagTranslationRepository.php index 1683b98f..a612b924 100644 --- a/lib/RoadizCoreBundle/src/Repository/TagTranslationRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/TagTranslationRepository.php @@ -14,13 +14,14 @@ * @method TagTranslation|null findOneBy(array $criteria, array $orderBy = null) * @method TagTranslation[] findAll() * @method TagTranslation[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class TagTranslationRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, TagTranslation::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Repository/TranslationRepository.php b/lib/RoadizCoreBundle/src/Repository/TranslationRepository.php index 75555f3f..2bcf847a 100644 --- a/lib/RoadizCoreBundle/src/Repository/TranslationRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/TranslationRepository.php @@ -20,13 +20,14 @@ * @method Translation|null findOneBy(array $criteria, array $orderBy = null) * @method Translation[] findAll() * @method Translation[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class TranslationRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Translation::class, $dispatcher); } @@ -37,13 +38,12 @@ public function isLocaleValid(?string $locale): bool return false; } - return preg_match('/^[A-Za-z]{2,4}([_-][A-Za-z]{4})?([_-]([A-Za-z]{2}|[0-9]{3}))?$/', $locale) === 1; + return 1 === preg_match('/^[A-Za-z]{2,4}([_-][A-Za-z]{4})?([_-]([A-Za-z]{2}|[0-9]{3}))?$/', $locale); } /** * Get single default translation. * - * @return TranslationInterface|null * @throws NonUniqueResultException */ public function findDefault(): ?TranslationInterface @@ -83,9 +83,6 @@ public function findAllAvailable(): array } /** - * @param string $locale - * - * @return bool * @throws NonUniqueResultException * @throws NoResultException */ @@ -102,15 +99,13 @@ public function exists(string $locale): bool ->setCacheable(true); $query = $qb->getQuery(); - $query->enableResultCache(120, 'RZTranslationExists-' . $locale); + $query->enableResultCache(120, 'RZTranslationExists-'.$locale); return (bool) $query->getSingleScalarResult(); } /** * Get all available locales. - * - * @return array */ public function getAvailableLocales(): array { @@ -130,8 +125,6 @@ public function getAvailableLocales(): array /** * Get all locales. - * - * @return array */ public function getAllLocales(): array { @@ -149,8 +142,6 @@ public function getAllLocales(): array /** * Get all available locales. - * - * @return array */ public function getAvailableOverrideLocales(): array { @@ -173,8 +164,6 @@ public function getAvailableOverrideLocales(): array /** * Get all available locales. - * - * @return array */ public function getAllOverrideLocales(): array { @@ -196,8 +185,6 @@ public function getAllOverrideLocales(): array /** * Get all available translations by locale. * - * @param string $locale - * * @return TranslationInterface[] */ public function findByLocaleAndAvailable(string $locale): array @@ -206,8 +193,8 @@ public function findByLocaleAndAvailable(string $locale): array return []; } $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); - $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.available', ':available')) - ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.locale', ':locale')) + $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.available', ':available')) + ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.locale', ':locale')) ->setParameter('available', true) ->setParameter('locale', $locale) ->setCacheable(true); @@ -215,7 +202,7 @@ public function findByLocaleAndAvailable(string $locale): array $query = $qb->getQuery(); $query->enableResultCache( 120, - 'RZTranslationAllByLocaleAndAvailable-' . $locale + 'RZTranslationAllByLocaleAndAvailable-'.$locale ); return $query->getResult(); @@ -224,7 +211,6 @@ public function findByLocaleAndAvailable(string $locale): array /** * Get all available translations by overrideLocale. * - * @param string $overrideLocale * @return TranslationInterface[] */ public function findByOverrideLocaleAndAvailable(string $overrideLocale): array @@ -233,8 +219,8 @@ public function findByOverrideLocaleAndAvailable(string $overrideLocale): array return []; } $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); - $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.available', ':available')) - ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.overrideLocale', ':overrideLocale')) + $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.available', ':available')) + ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.overrideLocale', ':overrideLocale')) ->setParameter('available', true) ->setParameter('overrideLocale', $overrideLocale) ->setCacheable(true); @@ -242,7 +228,7 @@ public function findByOverrideLocaleAndAvailable(string $overrideLocale): array $query = $qb->getQuery(); $query->enableResultCache( 120, - 'RZTranslationAllByOverrideAndAvailable-' . $overrideLocale + 'RZTranslationAllByOverrideAndAvailable-'.$overrideLocale ); return $query->getResult(); @@ -251,30 +237,26 @@ public function findByOverrideLocaleAndAvailable(string $overrideLocale): array /** * Get one translation by locale or override locale. * - * @param string $locale - * @param string $alias - * - * @return TranslationInterface|null * @throws NonUniqueResultException */ public function findOneByLocaleOrOverrideLocale( string $locale, - string $alias = TranslationRepository::TRANSLATION_ALIAS + string $alias = TranslationRepository::TRANSLATION_ALIAS, ): ?TranslationInterface { if (!$this->isLocaleValid($locale)) { return null; } $qb = $this->createQueryBuilder($alias); $qb->andWhere($qb->expr()->orX( - $qb->expr()->eq($alias . '.locale', ':locale'), - $qb->expr()->eq($alias . '.overrideLocale', ':locale') + $qb->expr()->eq($alias.'.locale', ':locale'), + $qb->expr()->eq($alias.'.overrideLocale', ':locale') )) ->setParameter('locale', $locale) ->setMaxResults(1) ->setCacheable(true); $query = $qb->getQuery(); - $query->enableResultCache(120, 'findOneByLocaleOrOverrideLocale_' . $locale); + $query->enableResultCache(120, 'findOneByLocaleOrOverrideLocale_'.$locale); return $query->getOneOrNullResult(); } @@ -282,9 +264,6 @@ public function findOneByLocaleOrOverrideLocale( /** * Get one available translation by locale or override locale. * - * @param string $locale - * - * @return TranslationInterface|null * @throws NonUniqueResultException */ public function findOneAvailableByLocaleOrOverrideLocale(string $locale): ?TranslationInterface @@ -294,17 +273,17 @@ public function findOneAvailableByLocaleOrOverrideLocale(string $locale): ?Trans } $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); $qb->andWhere($qb->expr()->orX( - $qb->expr()->eq(self::TRANSLATION_ALIAS . '.locale', ':locale'), - $qb->expr()->eq(self::TRANSLATION_ALIAS . '.overrideLocale', ':locale') + $qb->expr()->eq(self::TRANSLATION_ALIAS.'.locale', ':locale'), + $qb->expr()->eq(self::TRANSLATION_ALIAS.'.overrideLocale', ':locale') )) - ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.available', ':available')) + ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.available', ':available')) ->setParameter('available', true) ->setParameter('locale', $locale) ->setMaxResults(1) ->setCacheable(true); $query = $qb->getQuery(); - $query->enableResultCache(120, 'findOneAvailableByLocaleOrOverrideLocale_' . $locale); + $query->enableResultCache(120, 'findOneAvailableByLocaleOrOverrideLocale_'.$locale); return $query->getOneOrNullResult(); } @@ -312,9 +291,6 @@ public function findOneAvailableByLocaleOrOverrideLocale(string $locale): ?Trans /** * Get one available translation by locale. * - * @param string $locale - * - * @return TranslationInterface|null * @throws NonUniqueResultException */ public function findOneByLocaleAndAvailable(string $locale): ?TranslationInterface @@ -323,15 +299,15 @@ public function findOneByLocaleAndAvailable(string $locale): ?TranslationInterfa return null; } $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); - $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.available', ':available')) - ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.locale', ':locale')) + $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.available', ':available')) + ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.locale', ':locale')) ->setParameter('available', true) ->setParameter('locale', $locale) ->setMaxResults(1) ->setCacheable(true); $query = $qb->getQuery(); - $query->enableResultCache(120, 'RZTranslationOneByLocaleAndAvailable-' . $locale); + $query->enableResultCache(120, 'RZTranslationOneByLocaleAndAvailable-'.$locale); return $query->getOneOrNullResult(); } @@ -339,9 +315,6 @@ public function findOneByLocaleAndAvailable(string $locale): ?TranslationInterfa /** * Get one available translation by overrideLocale. * - * @param string $overrideLocale - * - * @return TranslationInterface|null * @throws NonUniqueResultException */ public function findOneByOverrideLocaleAndAvailable(string $overrideLocale): ?TranslationInterface @@ -350,8 +323,8 @@ public function findOneByOverrideLocaleAndAvailable(string $overrideLocale): ?Tr return null; } $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); - $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.available', ':available')) - ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.overrideLocale', ':overrideLocale')) + $qb->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.available', ':available')) + ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.overrideLocale', ':overrideLocale')) ->setParameter('available', true) ->setParameter('overrideLocale', $overrideLocale) ->setMaxResults(1) @@ -360,21 +333,20 @@ public function findOneByOverrideLocaleAndAvailable(string $overrideLocale): ?Tr $query = $qb->getQuery(); $query->enableResultCache( 120, - 'RZTranslationOneByOverrideAndAvailable-' . $overrideLocale + 'RZTranslationOneByOverrideAndAvailable-'.$overrideLocale ); return $query->getOneOrNullResult(); } /** - * @param Node $node * @return TranslationInterface[] */ public function findAvailableTranslationsForNode(Node $node): array { $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); $qb->innerJoin('t.nodeSources', self::NODESSOURCES_ALIAS) - ->andWhere($qb->expr()->eq(self::NODESSOURCES_ALIAS . '.node', ':node')) + ->andWhere($qb->expr()->eq(self::NODESSOURCES_ALIAS.'.node', ':node')) ->addOrderBy('t.defaultTranslation', 'DESC') ->addOrderBy('t.locale', 'ASC') ->setParameter('node', $node) @@ -384,7 +356,6 @@ public function findAvailableTranslationsForNode(Node $node): array } /** - * @param Tag $tag * @return TranslationInterface[] */ public function findAvailableTranslationsForTag(Tag $tag): array @@ -400,7 +371,6 @@ public function findAvailableTranslationsForTag(Tag $tag): array } /** - * @param Folder $folder * @return TranslationInterface[] */ public function findAvailableTranslationsForFolder(Folder $folder): array @@ -418,15 +388,14 @@ public function findAvailableTranslationsForFolder(Folder $folder): array /** * Find available node translations which are available too. * - * @param Node $node * @return TranslationInterface[] */ public function findStrictlyAvailableTranslationsForNode(Node $node): array { $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); $qb->innerJoin('t.nodeSources', self::NODESSOURCES_ALIAS) - ->andWhere($qb->expr()->eq(self::NODESSOURCES_ALIAS . '.node', ':node')) - ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS . '.available', ':available')) + ->andWhere($qb->expr()->eq(self::NODESSOURCES_ALIAS.'.node', ':node')) + ->andWhere($qb->expr()->eq(self::TRANSLATION_ALIAS.'.available', ':available')) ->addOrderBy('t.defaultTranslation', 'DESC') ->addOrderBy('t.locale', 'ASC') ->setParameter('node', $node) @@ -436,9 +405,7 @@ public function findStrictlyAvailableTranslationsForNode(Node $node): array return $qb->getQuery()->getResult(); } - /** - * @param Node $node * @return TranslationInterface[] */ public function findUnavailableTranslationsForNode(Node $node): array @@ -451,16 +418,12 @@ public function findUnavailableTranslationsForNode(Node $node): array return $qb->getQuery()->getResult(); } - /** - * @param Node $node - * @return array - */ public function findAvailableTranslationIdForNode(Node $node): array { $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); - $qb->select(self::TRANSLATION_ALIAS . '.id') + $qb->select(self::TRANSLATION_ALIAS.'.id') ->innerJoin('t.nodeSources', self::NODESSOURCES_ALIAS) - ->andWhere($qb->expr()->eq(self::NODESSOURCES_ALIAS . '.node', ':node')) + ->andWhere($qb->expr()->eq(self::NODESSOURCES_ALIAS.'.node', ':node')) ->addOrderBy('t.defaultTranslation', 'DESC') ->addOrderBy('t.locale', 'ASC') ->setParameter('node', $node) @@ -469,14 +432,10 @@ public function findAvailableTranslationIdForNode(Node $node): array return array_map('current', $qb->getQuery()->getScalarResult()); } - /** - * @param Node $node - * @return array - */ public function findUnavailableTranslationIdForNode(Node $node): array { $qb = $this->createQueryBuilder(self::TRANSLATION_ALIAS); - $qb->select(self::TRANSLATION_ALIAS . '.id') + $qb->select(self::TRANSLATION_ALIAS.'.id') ->andWhere($qb->expr()->notIn('t.id', ':translationsId')) ->setParameter('translationsId', $this->findAvailableTranslationIdForNode($node)) ->setCacheable(true); diff --git a/lib/RoadizCoreBundle/src/Repository/UrlAliasRepository.php b/lib/RoadizCoreBundle/src/Repository/UrlAliasRepository.php index 86815976..bfef788c 100644 --- a/lib/RoadizCoreBundle/src/Repository/UrlAliasRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/UrlAliasRepository.php @@ -16,13 +16,14 @@ * @method UrlAlias|null findOneBy(array $criteria, array $orderBy = null) * @method UrlAlias[] findAll() * @method UrlAlias[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class UrlAliasRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, UrlAlias::class, $dispatcher); } @@ -30,8 +31,6 @@ public function __construct( /** * Get all url aliases linked to given node. * - * @param int|string|null $nodeId - * * @return iterable */ public function findAllFromNode(int|string|null $nodeId): iterable @@ -50,9 +49,6 @@ public function findAllFromNode(int|string|null $nodeId): iterable } /** - * @param string $alias - * - * @return boolean * @throws NoResultException * @throws NonUniqueResultException */ diff --git a/lib/RoadizCoreBundle/src/Repository/UserLogEntryRepository.php b/lib/RoadizCoreBundle/src/Repository/UserLogEntryRepository.php index a3a3a171..7f672ba8 100644 --- a/lib/RoadizCoreBundle/src/Repository/UserLogEntryRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/UserLogEntryRepository.php @@ -9,7 +9,6 @@ use Doctrine\ORM\NoResultException; use Doctrine\Persistence\ManagerRegistry; use Gedmo\Loggable\Entity\Repository\LogEntryRepository; -use LogicException; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; /** @@ -27,24 +26,22 @@ public function __construct(ManagerRegistry $registry) $manager = $registry->getManagerForClass($entityClass); if (!$manager instanceof \Doctrine\ORM\EntityManagerInterface) { - throw new LogicException(sprintf( - 'Could not find the entity manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this entity’s metadata.', - $entityClass - )); + throw new \LogicException(sprintf('Could not find the entity manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this entity’s metadata.', $entityClass)); } parent::__construct($manager, $manager->getClassMetadata($entityClass)); } /** - * @param \DateTime $dateTime * @return int The number of entries + * * @throws NoResultException * @throws NonUniqueResultException */ public function countAllBeforeLoggedIn(\DateTime $dateTime): int { $qb = $this->createQueryBuilder('l'); + // @phpstan-ignore-next-line return $qb ->select($qb->expr()->countDistinct('l')) @@ -56,12 +53,12 @@ public function countAllBeforeLoggedIn(\DateTime $dateTime): int } /** - * @param \DateTime $dateTime * @return int The number of deleted entries */ public function deleteAllBeforeLoggedIn(\DateTime $dateTime): int { $qb = $this->createQueryBuilder('l'); + return $qb->delete(UserLogEntry::class, 'l') ->where($qb->expr()->lt('l.loggedAt', ':loggedAt')) ->setParameter('loggedAt', $dateTime) @@ -97,7 +94,7 @@ public function deleteAllExceptCount(int $count): int $deleteCount += $deleteQuery->execute([ 'objectId' => $object['objectId'], 'objectClass' => $object['objectClass'], - 'lowestVersion' => $lowestVersion + 'lowestVersion' => $lowestVersion, ]); } } diff --git a/lib/RoadizCoreBundle/src/Repository/UserRepository.php b/lib/RoadizCoreBundle/src/Repository/UserRepository.php index 7ffdc349..6b40b963 100644 --- a/lib/RoadizCoreBundle/src/Repository/UserRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/UserRepository.php @@ -14,13 +14,14 @@ * @method User|null findOneBy(array $criteria, array $orderBy = null) * @method User[] findAll() * @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class UserRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, User::class, $dispatcher); } @@ -28,7 +29,6 @@ public function __construct( /** * @param string $username * - * @return bool * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ @@ -44,8 +44,6 @@ public function usernameExists($username): bool } /** - * @param string $email - * @return bool * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ @@ -64,8 +62,8 @@ public function emailExists(string $email): bool * Find all users that did not logged-in since a number of days, including users that never logged-in using * their creation date. * - * @param int $days * @return User[] + * * @throws \Exception */ public function findAllInactiveSinceDays(int $days): array @@ -78,7 +76,7 @@ public function findAllInactiveSinceDays(int $days): array $qb->expr()->lt('u.createdAt', ':lastLogin') ), $qb->expr()->lt('u.lastLogin', ':lastLogin'), - ))->setParameter('lastLogin', new \DateTimeImmutable('-' . $days . ' days')); + ))->setParameter('lastLogin', new \DateTimeImmutable('-'.$days.' days')); return $qb->getQuery()->getResult(); } diff --git a/lib/RoadizCoreBundle/src/Repository/WebhookRepository.php b/lib/RoadizCoreBundle/src/Repository/WebhookRepository.php index cecbbc79..d9c3724c 100644 --- a/lib/RoadizCoreBundle/src/Repository/WebhookRepository.php +++ b/lib/RoadizCoreBundle/src/Repository/WebhookRepository.php @@ -14,13 +14,14 @@ * @method Webhook|null findOneBy(array $criteria, array $orderBy = null) * @method Webhook[] findAll() * @method Webhook[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + * * @extends EntityRepository */ final class WebhookRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Webhook::class, $dispatcher); } diff --git a/lib/RoadizCoreBundle/src/Routing/ChainResourcePathResolver.php b/lib/RoadizCoreBundle/src/Routing/ChainResourcePathResolver.php index d618ae25..f2782488 100644 --- a/lib/RoadizCoreBundle/src/Routing/ChainResourcePathResolver.php +++ b/lib/RoadizCoreBundle/src/Routing/ChainResourcePathResolver.php @@ -16,19 +16,17 @@ final class ChainResourcePathResolver implements PathResolverInterface public function addPathResolver(PathResolverInterface $pathResolver): ChainResourcePathResolver { $this->pathResolvers[get_class($pathResolver)] = $pathResolver; + return $this; } - /** - * @inheritDoc - */ public function resolvePath( string $path, array $supportedFormatExtensions = ['html'], bool $allowRootPaths = false, - bool $allowNonReachableNodes = true + bool $allowNonReachableNodes = true, ): ResourceInfo { - if (count($this->pathResolvers) === 0) { + if (0 === count($this->pathResolvers)) { throw new ResourceNotFoundException('No PathResolverInterface was registered to resolve path'); } foreach ($this->pathResolvers as $pathResolver) { diff --git a/lib/RoadizCoreBundle/src/Routing/DocumentUrlGenerator.php b/lib/RoadizCoreBundle/src/Routing/DocumentUrlGenerator.php index 005a7cb5..f45a5882 100644 --- a/lib/RoadizCoreBundle/src/Routing/DocumentUrlGenerator.php +++ b/lib/RoadizCoreBundle/src/Routing/DocumentUrlGenerator.php @@ -16,14 +16,11 @@ public function __construct( FilesystemOperator $documentsStorage, UrlHelper $urlHelper, private readonly UrlGeneratorInterface $urlGenerator, - CacheItemPoolInterface $optionsCacheAdapter + CacheItemPoolInterface $optionsCacheAdapter, ) { parent::__construct($documentsStorage, $urlHelper, $optionsCacheAdapter); } - /** - * @return string - */ protected function getRouteName(): string { return 'interventionRequestProcess'; diff --git a/lib/RoadizCoreBundle/src/Routing/DynamicUrlMatcher.php b/lib/RoadizCoreBundle/src/Routing/DynamicUrlMatcher.php index 51d0b61a..e33b7b43 100644 --- a/lib/RoadizCoreBundle/src/Routing/DynamicUrlMatcher.php +++ b/lib/RoadizCoreBundle/src/Routing/DynamicUrlMatcher.php @@ -21,7 +21,7 @@ public function __construct( RequestContext $context, protected readonly PreviewResolverInterface $previewResolver, protected readonly Stopwatch $stopwatch, - protected readonly LoggerInterface $logger + protected readonly LoggerInterface $logger, ) { parent::__construct(new RouteCollection(), $context); } diff --git a/lib/RoadizCoreBundle/src/Routing/NodePathInfo.php b/lib/RoadizCoreBundle/src/Routing/NodePathInfo.php index 30e8710b..7b2e2b6e 100644 --- a/lib/RoadizCoreBundle/src/Routing/NodePathInfo.php +++ b/lib/RoadizCoreBundle/src/Routing/NodePathInfo.php @@ -11,19 +11,11 @@ class NodePathInfo protected bool $isComplete = false; protected bool $containsScheme = false; - /** - * @return string|null - */ public function getPath(): ?string { return $this->path; } - /** - * @param string $path - * - * @return NodePathInfo - */ public function setPath(string $path): NodePathInfo { $this->path = $path; @@ -31,19 +23,11 @@ public function setPath(string $path): NodePathInfo return $this; } - /** - * @return array - */ public function getParameters(): array { return $this->parameters; } - /** - * @param array $parameters - * - * @return NodePathInfo - */ public function setParameters(array $parameters): NodePathInfo { $this->parameters = $parameters; @@ -51,19 +35,11 @@ public function setParameters(array $parameters): NodePathInfo return $this; } - /** - * @return bool - */ public function isComplete(): bool { return $this->isComplete; } - /** - * @param bool $isComplete - * - * @return NodePathInfo - */ public function setComplete(bool $isComplete): NodePathInfo { $this->isComplete = $isComplete; @@ -71,19 +47,11 @@ public function setComplete(bool $isComplete): NodePathInfo return $this; } - /** - * @return bool - */ public function containsScheme(): bool { return $this->containsScheme; } - /** - * @param bool $containsScheme - * - * @return NodePathInfo - */ public function setContainsScheme(bool $containsScheme): NodePathInfo { $this->containsScheme = $containsScheme; @@ -100,11 +68,12 @@ public function serialize(): string 'path' => $this->getPath(), 'parameters' => $this->getParameters(), 'is_complete' => $this->isComplete(), - 'contains_scheme' => $this->containsScheme() + 'contains_scheme' => $this->containsScheme(), ]); if (false === $json) { throw new \RuntimeException('Unable to serialize NodePathInfo'); } + return $json; } @@ -114,7 +83,7 @@ public function __serialize(): array 'path' => $this->getPath(), 'parameters' => $this->getParameters(), 'is_complete' => $this->isComplete(), - 'contains_scheme' => $this->containsScheme() + 'contains_scheme' => $this->containsScheme(), ]; } diff --git a/lib/RoadizCoreBundle/src/Routing/NodeRouteHelper.php b/lib/RoadizCoreBundle/src/Routing/NodeRouteHelper.php index 867dbb17..7d0e949a 100644 --- a/lib/RoadizCoreBundle/src/Routing/NodeRouteHelper.php +++ b/lib/RoadizCoreBundle/src/Routing/NodeRouteHelper.php @@ -19,12 +19,7 @@ final class NodeRouteHelper private ?string $controller = null; /** - * @param NodeInterface $node - * @param Theme|null $theme - * @param PreviewResolverInterface $previewResolver - * @param LoggerInterface $logger * @param class-string $defaultControllerClass - * @param string $defaultControllerNamespace */ public function __construct( private readonly NodeInterface $node, @@ -32,7 +27,7 @@ public function __construct( private readonly PreviewResolverInterface $previewResolver, private readonly LoggerInterface $logger, private readonly string $defaultControllerClass, - private readonly string $defaultControllerNamespace = '\\App\\Controller' + private readonly string $defaultControllerNamespace = '\\App\\Controller', ) { } @@ -47,16 +42,14 @@ public function getController(): ?string if (!$this->node->getNodeType()->isReachable()) { return null; } - $controllerClassName = $this->getControllerNamespace() . '\\' . - StringHandler::classify($this->node->getNodeType()->getName()) . + $controllerClassName = $this->getControllerNamespace().'\\'. + StringHandler::classify($this->node->getNodeType()->getName()). 'Controller'; if (\class_exists($controllerClassName)) { $reflection = new \ReflectionClass($controllerClassName); if (!$reflection->isSubclassOf(AbstractController::class)) { - throw new \InvalidArgumentException( - 'Controller class ' . $controllerClassName . ' must extends ' . AbstractController::class - ); + throw new \InvalidArgumentException('Controller class '.$controllerClassName.' must extends '.AbstractController::class); } // @phpstan-ignore-next-line $this->controller = $controllerClassName; @@ -67,6 +60,7 @@ public function getController(): ?string $this->controller = $this->defaultControllerClass; } } + // @phpstan-ignore-next-line return $this->controller; } @@ -76,8 +70,9 @@ protected function getControllerNamespace(): string $namespace = $this->defaultControllerNamespace; if (null !== $this->theme) { $reflection = new \ReflectionClass($this->theme->getClassName()); - $namespace = $reflection->getNamespaceName() . '\\Controllers'; + $namespace = $reflection->getNamespaceName().'\\Controllers'; } + return $namespace; } @@ -88,20 +83,20 @@ public function getMethod(): string /** * Return FALSE or TRUE if node is viewable. - * - * @return bool */ public function isViewable(): bool { if (!class_exists($this->getController())) { - $this->logger->debug($this->getController() . ' controller does not exist.'); + $this->logger->debug($this->getController().' controller does not exist.'); + return false; } if (!method_exists($this->getController(), $this->getMethod())) { $this->logger->debug( - $this->getController() . ':' . - $this->getMethod() . ' controller method does not exist.' + $this->getController().':'. + $this->getMethod().' controller method does not exist.' ); + return false; } diff --git a/lib/RoadizCoreBundle/src/Routing/NodeRouter.php b/lib/RoadizCoreBundle/src/Routing/NodeRouter.php index 4d839b48..3b5528ac 100644 --- a/lib/RoadizCoreBundle/src/Routing/NodeRouter.php +++ b/lib/RoadizCoreBundle/src/Routing/NodeRouter.php @@ -36,7 +36,7 @@ public function __construct( protected readonly CacheItemPoolInterface $nodeSourceUrlCacheAdapter, RequestContext $context, LoggerInterface $logger, - array $options = [] + array $options = [], ) { parent::__construct( new NullLoader(), @@ -48,9 +48,6 @@ public function __construct( $this->matcher = $matcher; } - /** - * {@inheritdoc} - */ public function getRouteCollection(): RouteCollection { return new RouteCollection(); @@ -58,54 +55,44 @@ public function getRouteCollection(): RouteCollection /** * Gets the UrlMatcher instance associated with this Router. - * - * @return UrlMatcherInterface */ public function getMatcher(): UrlMatcherInterface { return $this->matcher; } - /** - * @return Theme|null - */ public function getTheme(): ?Theme { return $this->theme; } - /** - * @param Theme|null $theme - * @return NodeRouter - */ public function setTheme(?Theme $theme): NodeRouter { $this->theme = $theme; + return $this; } - /** - * @inheritDoc - */ public function getRouteDebugMessage(string $name, array $parameters = []): string { if (RouteObjectInterface::OBJECT_BASED_ROUTE_NAME === $name) { if ( - array_key_exists(RouteObjectInterface::ROUTE_OBJECT, $parameters) && - $parameters[RouteObjectInterface::ROUTE_OBJECT] instanceof NodesSources + array_key_exists(RouteObjectInterface::ROUTE_OBJECT, $parameters) + && $parameters[RouteObjectInterface::ROUTE_OBJECT] instanceof NodesSources ) { $route = $parameters[RouteObjectInterface::ROUTE_OBJECT]; - return '[' . $route->getTranslation()->getLocale() . ']' . - $route->getTitle() . ' - ' . - $route->getNode()->getNodeName() . - '[' . $route->getNode()->getId() . ']'; + + return '['.$route->getTranslation()->getLocale().']'. + $route->getTitle().' - '. + $route->getNode()->getNodeName(). + '['.$route->getNode()->getId().']'; } } + return (string) $name; } /** - * {@inheritdoc} * @throws InvalidArgumentException */ public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string @@ -115,8 +102,8 @@ public function generate(string $name, array $parameters = [], int $referenceTyp } if ( - array_key_exists(RouteObjectInterface::ROUTE_OBJECT, $parameters) && - $parameters[RouteObjectInterface::ROUTE_OBJECT] instanceof NodesSources + array_key_exists(RouteObjectInterface::ROUTE_OBJECT, $parameters) + && $parameters[RouteObjectInterface::ROUTE_OBJECT] instanceof NodesSources ) { $route = $parameters[RouteObjectInterface::ROUTE_OBJECT]; unset($parameters[RouteObjectInterface::ROUTE_OBJECT]); @@ -132,12 +119,12 @@ public function generate(string $name, array $parameters = [], int $referenceTyp $schemeAuthority = trim($parameters['canonicalScheme']); unset($parameters['canonicalScheme']); } else { - $schemeAuthority = $this->getContext()->getScheme() . '://' . $this->getHttpHost(); + $schemeAuthority = $this->getContext()->getScheme().'://'.$this->getHttpHost(); } $noCache = false; if (!empty($parameters[static::NO_CACHE_PARAMETER])) { - $noCache = (bool)($parameters[static::NO_CACHE_PARAMETER]); + $noCache = (bool) $parameters[static::NO_CACHE_PARAMETER]; } $nodePathInfo = $this->getResourcePath($route, $parameters, $noCache); @@ -146,9 +133,10 @@ public function generate(string $name, array $parameters = [], int $referenceTyp * If node path is complete, do not alter path anymore. */ if (true === $nodePathInfo->isComplete()) { - if ($referenceType == self::ABSOLUTE_URL && !$nodePathInfo->containsScheme()) { - return $schemeAuthority . $nodePathInfo->getPath(); + if (self::ABSOLUTE_URL == $referenceType && !$nodePathInfo->containsScheme()) { + return $schemeAuthority.$nodePathInfo->getPath(); } + return $nodePathInfo->getPath(); } @@ -157,9 +145,9 @@ public function generate(string $name, array $parameters = [], int $referenceTyp $matcher = $this->getMatcher(); if ( - isset($parameters['_format']) && - $matcher instanceof NodeUrlMatcher && - in_array($parameters['_format'], $matcher->getSupportedFormatExtensions()) + isset($parameters['_format']) + && $matcher instanceof NodeUrlMatcher + && in_array($parameters['_format'], $matcher->getSupportedFormatExtensions()) ) { unset($parameters['_format']); } @@ -167,51 +155,41 @@ public function generate(string $name, array $parameters = [], int $referenceTyp unset($parameters[static::NO_CACHE_PARAMETER]); } if (count($parameters) > 0) { - $queryString = '?' . http_build_query($parameters); + $queryString = '?'.http_build_query($parameters); } - if ($referenceType == self::ABSOLUTE_URL) { + if (self::ABSOLUTE_URL == $referenceType) { // Absolute path - return $schemeAuthority . $this->getContext()->getBaseUrl() . '/' . $nodePathInfo->getPath() . $queryString; + return $schemeAuthority.$this->getContext()->getBaseUrl().'/'.$nodePathInfo->getPath().$queryString; } // ABSOLUTE_PATH - return $this->getContext()->getBaseUrl() . '/' . $nodePathInfo->getPath() . $queryString; + return $this->getContext()->getBaseUrl().'/'.$nodePathInfo->getPath().$queryString; } /** - * @param NodesSources $source - * @param array $parameters - * @param bool $noCache - * - * @return NodePathInfo - * @throws \Psr\Cache\InvalidArgumentException + * @throws InvalidArgumentException */ protected function getResourcePath( NodesSources $source, array $parameters = [], - bool $noCache = false + bool $noCache = false, ): NodePathInfo { if ($noCache) { $parametersHash = sha1(serialize($parameters)); - $cacheKey = 'ns_url_' . $source->getId() . '_' . $this->getContext()->getHost() . '_' . $parametersHash; + $cacheKey = 'ns_url_'.$source->getId().'_'.$this->getContext()->getHost().'_'.$parametersHash; $cacheItem = $this->nodeSourceUrlCacheAdapter->getItem($cacheKey); if (!$cacheItem->isHit()) { $cacheItem->set($this->getNodesSourcesPath($source, $parameters)); $this->nodeSourceUrlCacheAdapter->save($cacheItem); } + return $cacheItem->get(); } return $this->getNodesSourcesPath($source, $parameters); } - /** - * @param NodesSources $source - * @param array $parameters - * - * @return NodePathInfo - */ protected function getNodesSourcesPath(NodesSources $source, array $parameters = []): NodePathInfo { $event = new NodesSourcesPathGeneratingEvent( @@ -238,6 +216,7 @@ protected function getNodesSourcesPath(NodesSources $source, array $parameters = if (null === $nodePathInfo->getPath()) { throw new InvalidParameterException('NodeSource generated path is null.'); } + return $nodePathInfo; } @@ -245,8 +224,6 @@ protected function getNodesSourcesPath(NodesSources $source, array $parameters = * Returns the HTTP host being requested. * * The port name will be appended to the host if it's non-standard. - * - * @return string */ private function getHttpHost(): string { @@ -254,11 +231,11 @@ private function getHttpHost(): string $port = ''; if ('http' === $scheme && 80 != $this->context->getHttpPort()) { - $port = ':' . $this->context->getHttpPort(); + $port = ':'.$this->context->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) { - $port = ':' . $this->context->getHttpsPort(); + $port = ':'.$this->context->getHttpsPort(); } - return $this->getContext()->getHost() . $port; + return $this->getContext()->getHost().$port; } } diff --git a/lib/RoadizCoreBundle/src/Routing/NodeUrlMatcher.php b/lib/RoadizCoreBundle/src/Routing/NodeUrlMatcher.php index 743e405f..96cee535 100644 --- a/lib/RoadizCoreBundle/src/Routing/NodeUrlMatcher.php +++ b/lib/RoadizCoreBundle/src/Routing/NodeUrlMatcher.php @@ -20,11 +20,6 @@ final class NodeUrlMatcher extends DynamicUrlMatcher implements NodeUrlMatcherInterface { /** - * @param PathResolverInterface $pathResolver - * @param RequestContext $context - * @param PreviewResolverInterface $previewResolver - * @param Stopwatch $stopwatch - * @param LoggerInterface $logger * @param class-string $defaultControllerClass */ public function __construct( @@ -33,33 +28,25 @@ public function __construct( PreviewResolverInterface $previewResolver, Stopwatch $stopwatch, LoggerInterface $logger, - private readonly string $defaultControllerClass + private readonly string $defaultControllerClass, ) { parent::__construct($context, $previewResolver, $stopwatch, $logger); } - /** - * @return array - */ public function getSupportedFormatExtensions(): array { return ['xml', 'json', 'pdf', 'html']; } - /** - * @return string - */ public function getDefaultSupportedFormatExtension(): string { return 'html'; } - /** - * @inheritDoc - */ public function match(string $pathinfo): array { $decodedUrl = rawurldecode($pathinfo); + /* * Try nodes routes */ @@ -77,11 +64,6 @@ protected function getNodeRouteHelper(NodesSources $nodeSource, ?Theme $theme): ); } - /** - * @param string $decodedUrl - * @param Theme|null $theme - * @return array - */ public function matchNode(string $decodedUrl, ?Theme $theme): array { $resourceInfo = $this->pathResolver->resolvePath( @@ -103,7 +85,7 @@ public function matchNode(string $decodedUrl, ?Theme $theme): array } return [ - '_controller' => $nodeRouteHelper->getController() . '::' . $nodeRouteHelper->getMethod(), + '_controller' => $nodeRouteHelper->getController().'::'.$nodeRouteHelper->getMethod(), '_locale' => $resourceInfo->getLocale(), '_route' => RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, '_format' => $resourceInfo->getFormat(), diff --git a/lib/RoadizCoreBundle/src/Routing/NodesSourcesPathResolver.php b/lib/RoadizCoreBundle/src/Routing/NodesSourcesPathResolver.php index 2e8167c1..ba517195 100644 --- a/lib/RoadizCoreBundle/src/Routing/NodesSourcesPathResolver.php +++ b/lib/RoadizCoreBundle/src/Routing/NodesSourcesPathResolver.php @@ -12,8 +12,8 @@ use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\Roadiz\CoreBundle\Entity\NodeType; use RZ\Roadiz\CoreBundle\Entity\Translation; -use RZ\Roadiz\CoreBundle\Repository\TranslationRepository; use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface; +use RZ\Roadiz\CoreBundle\Repository\TranslationRepository; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Stopwatch\Stopwatch; @@ -28,28 +28,25 @@ public function __construct( private readonly Stopwatch $stopwatch, private readonly Settings $settingsBag, private readonly RequestStack $requestStack, - private readonly bool $useAcceptLanguageHeader + private readonly bool $useAcceptLanguageHeader, ) { } - /** - * @inheritDoc - */ public function resolvePath( string $path, array $supportedFormatExtensions = ['html'], bool $allowRootPaths = false, - bool $allowNonReachableNodes = true + bool $allowNonReachableNodes = true, ): ResourceInfo { $resourceInfo = new ResourceInfo(); $tokens = $this->tokenizePath($path); $_format = 'html'; - if (count($tokens) === 0 && !$allowRootPaths) { + if (0 === count($tokens) && !$allowRootPaths) { throw new ResourceNotFoundException(); } - if ($path === '/') { + if ('/' === $path) { $this->stopwatch->start('parseRootPath', 'routing'); $translation = $this->parseTranslation(); $nodeSource = $this->getHome($translation); @@ -60,11 +57,11 @@ public function resolvePath( $identifier = strip_tags($tokens[(int) (count($tokens) - 1)]); } - if ($identifier !== '') { + if ('' !== $identifier) { /* * Prevent searching nodes with special characters. */ - if (0 === preg_match('#' . static::$nodeNamePattern . '#', $identifier)) { + if (0 === preg_match('#'.static::$nodeNamePattern.'#', $identifier)) { throw new ResourceNotFoundException(); } @@ -73,7 +70,7 @@ public function resolvePath( */ if ( 0 !== preg_match( - '#^(' . static::$nodeNamePattern . ')\.(' . implode('|', $supportedFormatExtensions) . ')$#', + '#^('.static::$nodeNamePattern.')\.('.implode('|', $supportedFormatExtensions).')$#', $identifier, $matches ) @@ -104,14 +101,12 @@ public function resolvePath( $resourceInfo->setTranslation($nodeSource->getTranslation()); $resourceInfo->setFormat($_format); $resourceInfo->setLocale($nodeSource->getTranslation()->getPreferredLocale()); + return $resourceInfo; } /** * Split path into meaningful tokens. - * - * @param string $path - * @return array */ private function tokenizePath(string $path): array { @@ -121,13 +116,9 @@ private function tokenizePath(string $path): array return $tokens; } - /** - * @param TranslationInterface $translation - * @return NodesSources|null - */ private function getHome(TranslationInterface $translation): ?NodesSources { - /** + /* * Resolve home page * @phpstan-ignore-next-line */ @@ -135,7 +126,7 @@ private function getHome(TranslationInterface $translation): ?NodesSources ->getRepository(NodesSources::class) ->findOneBy([ 'node.home' => true, - 'translation' => $translation + 'translation' => $translation, ]); } @@ -144,7 +135,6 @@ private function getHome(TranslationInterface $translation): ?NodesSources * * @param array $tokens * - * @return TranslationInterface|null * @throws NonUniqueResultException */ private function parseTranslation(array &$tokens = []): ?TranslationInterface @@ -159,7 +149,7 @@ private function parseTranslation(array &$tokens = []): ?TranslationInterface $firstToken = $tokens[0]; $locale = \mb_strtolower(strip_tags((string) $firstToken)); // First token is for language and should not exceed 11 chars, i.e. tzm-Latn-DZ - if ($locale !== null && $locale != '' && \mb_strlen($locale) <= 11) { + if (null !== $locale && '' != $locale && \mb_strlen($locale) <= 11) { $translation = $repository->$findOneByMethod($locale); if (null !== $translation) { return $translation; @@ -170,8 +160,8 @@ private function parseTranslation(array &$tokens = []): ?TranslationInterface } if ( - $this->useAcceptLanguageHeader && - $this->settingsBag->get('force_locale', false) === true + $this->useAcceptLanguageHeader + && true === $this->settingsBag->get('force_locale', false) ) { /* * When no information to find locale is found and "force_locale" is ON, @@ -181,8 +171,8 @@ private function parseTranslation(array &$tokens = []): ?TranslationInterface */ $request = $this->requestStack->getMainRequest(); if ( - null !== $request && - null !== $preferredLocale = $request->getPreferredLanguage($repository->getAvailableLocales()) + null !== $request + && null !== $preferredLocale = $request->getPreferredLanguage($repository->getAvailableLocales()) ) { $translation = $repository->$findOneByMethod($preferredLocale); if (null !== $translation) { @@ -196,14 +186,11 @@ private function parseTranslation(array &$tokens = []): ?TranslationInterface /** * @param array $tokens - * @param TranslationInterface|null $translation - * @param bool $allowNonReachableNodes - * @return NodesSources|null */ private function parseFromIdentifier( array &$tokens, ?TranslationInterface $translation = null, - bool $allowNonReachableNodes = true + bool $allowNonReachableNodes = true, ): ?NodesSources { if (!empty($tokens[0])) { /* @@ -211,7 +198,7 @@ private function parseFromIdentifier( */ if (count($tokens) > 1 || !in_array($tokens[0], Translation::getAvailableLocales())) { $identifier = \mb_strtolower(strip_tags($tokens[(int) (count($tokens) - 1)])); - if ($identifier !== null && $identifier != '') { + if (null !== $identifier && '' != $identifier) { $array = $this->managerRegistry ->getRepository(Node::class) ->findNodeTypeNameAndSourceIdByIdentifier( @@ -225,8 +212,9 @@ private function parseFromIdentifier( $nodeSource = $this->managerRegistry ->getRepository($this->getNodeTypeClassname($array['name'])) ->findOneBy([ - 'id' => $array['id'] + 'id' => $array['id'], ]); + return $nodeSource; } else { $this->stopwatch->stop('parseFromIdentifier'); @@ -243,15 +231,15 @@ private function parseFromIdentifier( } /** - * @param string $name * @return class-string */ private function getNodeTypeClassname(string $name): string { - $fqcn = NodeType::getGeneratedEntitiesNamespace() . '\\NS' . ucwords($name); + $fqcn = NodeType::getGeneratedEntitiesNamespace().'\\NS'.ucwords($name); if (!class_exists($fqcn)) { - throw new ResourceNotFoundException($fqcn . ' entity does not exist.'); + throw new ResourceNotFoundException($fqcn.' entity does not exist.'); } + return $fqcn; } } diff --git a/lib/RoadizCoreBundle/src/Routing/NodesSourcesUrlGenerator.php b/lib/RoadizCoreBundle/src/Routing/NodesSourcesUrlGenerator.php index 1b3b8fc2..65b1cc30 100644 --- a/lib/RoadizCoreBundle/src/Routing/NodesSourcesUrlGenerator.php +++ b/lib/RoadizCoreBundle/src/Routing/NodesSourcesUrlGenerator.php @@ -16,14 +16,10 @@ public function __construct( private readonly NodesSourcesPathAggregator $pathAggregator, private readonly ?NodesSources $nodeSource = null, private readonly bool $forceLocale = false, - private readonly bool $forceLocaleWithUrlAlias = false + private readonly bool $forceLocaleWithUrlAlias = false, ) { } - /** - * @param NodesSources $nodeSource - * @return bool - */ protected function isNodeSourceHome(NodesSources $nodeSource): bool { if ($nodeSource->getNode()->isHome()) { @@ -38,19 +34,14 @@ protected function isNodeSourceHome(NodesSources $nodeSource): bool * root folder. * * It returns a relative url to Roadiz, not relative to your server root. - * - * @param Theme|null $theme - * @param array $parameters - * - * @return string */ public function getNonContextualUrl(?Theme $theme = null, array $parameters = []): string { if (null !== $this->nodeSource) { if ($this->isNodeSourceHome($this->nodeSource)) { if ( - $this->nodeSource->getTranslation()->isDefaultTranslation() && - false === $this->forceLocale + $this->nodeSource->getTranslation()->isDefaultTranslation() + && false === $this->forceLocale ) { return ''; } else { @@ -65,30 +56,25 @@ public function getNonContextualUrl(?Theme $theme = null, array $parameters = [] * translation is not the default one. */ if ($this->urlNeedsLocalePrefix($this->nodeSource)) { - $path = $this->nodeSource->getTranslation()->getPreferredLocale() . '/' . $path; + $path = $this->nodeSource->getTranslation()->getPreferredLocale().'/'.$path; } - if (null !== $theme && $theme->getRoutePrefix() != '') { - $path = $theme->getRoutePrefix() . '/' . $path; + if (null !== $theme && '' != $theme->getRoutePrefix()) { + $path = $theme->getRoutePrefix().'/'.$path; } /* * Add non default format at the path end. */ if (isset($parameters['_format']) && in_array($parameters['_format'], ['xml', 'json', 'pdf'])) { - $path .= '.' . $parameters['_format']; + $path .= '.'.$parameters['_format']; } return $path; } else { - throw new \RuntimeException("Cannot generate Url for a NULL NodesSources", 1); + throw new \RuntimeException('Cannot generate Url for a NULL NodesSources', 1); } } - /** - * @param NodesSources $nodesSources - * - * @return bool - */ protected function useUrlAlias(NodesSources $nodesSources): bool { if ($nodesSources->getIdentifier() !== $nodesSources->getNode()->getNodeName()) { @@ -98,11 +84,6 @@ protected function useUrlAlias(NodesSources $nodesSources): bool return false; } - /** - * @param NodesSources $nodesSources - * - * @return bool - */ protected function urlNeedsLocalePrefix(NodesSources $nodesSources): bool { /* @@ -113,15 +94,15 @@ protected function urlNeedsLocalePrefix(NodesSources $nodesSources): bool */ if ( ( - !$this->useUrlAlias($nodesSources) && - !$nodesSources->getTranslation()->isDefaultTranslation() - ) || - ( - $this->useUrlAlias($nodesSources) && - !$nodesSources->getTranslation()->isDefaultTranslation() && - true === $this->forceLocaleWithUrlAlias - ) || - true === $this->forceLocale + !$this->useUrlAlias($nodesSources) + && !$nodesSources->getTranslation()->isDefaultTranslation() + ) + || ( + $this->useUrlAlias($nodesSources) + && !$nodesSources->getTranslation()->isDefaultTranslation() + && true === $this->forceLocaleWithUrlAlias + ) + || true === $this->forceLocale ) { return true; } diff --git a/lib/RoadizCoreBundle/src/Routing/NullLoader.php b/lib/RoadizCoreBundle/src/Routing/NullLoader.php index 673b621d..981a2959 100644 --- a/lib/RoadizCoreBundle/src/Routing/NullLoader.php +++ b/lib/RoadizCoreBundle/src/Routing/NullLoader.php @@ -9,33 +9,21 @@ final class NullLoader implements LoaderInterface { - /** - * @inheritDoc - */ - public function load(mixed $resource, string $type = null): mixed + public function load(mixed $resource, ?string $type = null): mixed { return null; } - /** - * @inheritDoc - */ - public function supports(mixed $resource, string $type = null): bool + public function supports(mixed $resource, ?string $type = null): bool { return true; } - /** - * @inheritDoc - */ public function getResolver(): ?LoaderResolverInterface { return null; } - /** - * @inheritDoc - */ public function setResolver(LoaderResolverInterface $resolver): self { return $this; diff --git a/lib/RoadizCoreBundle/src/Routing/OptimizedNodesSourcesGraphPathAggregator.php b/lib/RoadizCoreBundle/src/Routing/OptimizedNodesSourcesGraphPathAggregator.php index 0d171edf..42ace114 100644 --- a/lib/RoadizCoreBundle/src/Routing/OptimizedNodesSourcesGraphPathAggregator.php +++ b/lib/RoadizCoreBundle/src/Routing/OptimizedNodesSourcesGraphPathAggregator.php @@ -15,28 +15,26 @@ final class OptimizedNodesSourcesGraphPathAggregator implements NodesSourcesPath { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly CacheItemPoolInterface $cacheAdapter + private readonly CacheItemPoolInterface $cacheAdapter, ) { } private function getCacheKey(NodesSources $nodesSources): string { - return 'ns_url_' . $nodesSources->getId(); + return 'ns_url_'.$nodesSources->getId(); } /** - * @param NodesSources $nodesSources - * @param array $parameters - * @return string * @throws InvalidArgumentException */ public function aggregatePath(NodesSources $nodesSources, array $parameters = []): string { if ( - isset($parameters[NodeRouter::NO_CACHE_PARAMETER]) && - $parameters[NodeRouter::NO_CACHE_PARAMETER] === true + isset($parameters[NodeRouter::NO_CACHE_PARAMETER]) + && true === $parameters[NodeRouter::NO_CACHE_PARAMETER] ) { $urlTokens = array_reverse($this->getIdentifiers($nodesSources)); + return implode('/', $urlTokens); } @@ -46,18 +44,17 @@ public function aggregatePath(NodesSources $nodesSources, array $parameters = [] $cacheItem->set(implode('/', $urlTokens)); $this->cacheAdapter->save($cacheItem); } + return $cacheItem->get(); } /** - * @param Node $parent - * * @return array */ private function getParentsIds(Node $parent): array { $parentIds = []; - while ($parent !== null && !$parent->isHome()) { + while (null !== $parent && !$parent->isHome()) { $parentIds[] = $parent->getId(); $parent = $parent->getParent(); } @@ -68,10 +65,6 @@ private function getParentsIds(Node $parent): array /** * Get every nodeSource parents identifier from current to * farthest ancestor. - * - * @param NodesSources $source - * - * @return array */ private function getIdentifiers(NodesSources $source): array { @@ -84,8 +77,7 @@ private function getIdentifiers(NodesSources $source): array $parentIds = $this->getParentsIds($parentNode); if (count($parentIds) > 0) { /** - * - * Do a partial query to optimize SQL time + * Do a partial query to optimize SQL time. */ $qb = $this->managerRegistry ->getRepository(NodesSources::class) @@ -99,7 +91,7 @@ private function getIdentifiers(NodesSources $source): array ->setParameters([ 'parentIds' => $parentIds, 'visible' => true, - 'translation' => $source->getTranslation() + 'translation' => $source->getTranslation(), ]) ->getQuery() ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) diff --git a/lib/RoadizCoreBundle/src/Routing/PathResolverInterface.php b/lib/RoadizCoreBundle/src/Routing/PathResolverInterface.php index 45b3429c..ad934d74 100644 --- a/lib/RoadizCoreBundle/src/Routing/PathResolverInterface.php +++ b/lib/RoadizCoreBundle/src/Routing/PathResolverInterface.php @@ -9,16 +9,14 @@ interface PathResolverInterface /** * Resolve a ResourceInfo containing AbstractEntity, format and translation using a unique path. * - * @param string $path * @param array $supportedFormatExtensions - * @param bool $allowRootPaths Allow resolving / and /en, /fr paths to home pages - * @param bool $allowNonReachableNodes Allow resolving non-reachable nodes - * @return ResourceInfo + * @param bool $allowRootPaths Allow resolving / and /en, /fr paths to home pages + * @param bool $allowNonReachableNodes Allow resolving non-reachable nodes */ public function resolvePath( string $path, array $supportedFormatExtensions = ['html'], bool $allowRootPaths = false, - bool $allowNonReachableNodes = true + bool $allowNonReachableNodes = true, ): ResourceInfo; } diff --git a/lib/RoadizCoreBundle/src/Routing/RedirectableUrlMatcher.php b/lib/RoadizCoreBundle/src/Routing/RedirectableUrlMatcher.php index b6f3c486..bca8a00b 100644 --- a/lib/RoadizCoreBundle/src/Routing/RedirectableUrlMatcher.php +++ b/lib/RoadizCoreBundle/src/Routing/RedirectableUrlMatcher.php @@ -12,8 +12,8 @@ final class RedirectableUrlMatcher extends BaseMatcher /** * Redirects the user to another URL. * - * @param string $path The path info to redirect to - * @param string $route The route that matched + * @param string $path The path info to redirect to + * @param string $route The route that matched * @param string|null $scheme The URL scheme (null to keep the current one) * * @return array An array of parameters @@ -21,7 +21,7 @@ final class RedirectableUrlMatcher extends BaseMatcher public function redirect(string $path, string $route, ?string $scheme = null): array { return [ - '_controller' => RedirectionController::class . '::redirectToRouteAction', + '_controller' => RedirectionController::class.'::redirectToRouteAction', 'path' => $path, 'permanent' => true, 'scheme' => $scheme, diff --git a/lib/RoadizCoreBundle/src/Routing/RedirectionMatcher.php b/lib/RoadizCoreBundle/src/Routing/RedirectionMatcher.php index 81001bee..6258a3dd 100644 --- a/lib/RoadizCoreBundle/src/Routing/RedirectionMatcher.php +++ b/lib/RoadizCoreBundle/src/Routing/RedirectionMatcher.php @@ -21,14 +21,11 @@ final class RedirectionMatcher extends UrlMatcher public function __construct( RequestContext $context, private readonly RedirectionPathResolver $pathResolver, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { parent::__construct(new RouteCollection(), $context); } - /** - * {@inheritdoc} - */ public function match(string $pathinfo): array { $decodedUrl = rawurldecode($pathinfo); @@ -38,8 +35,9 @@ public function match(string $pathinfo): array */ if (null !== $redirection = $this->matchRedirection($decodedUrl)) { $this->logger->debug('Matched redirection.', ['query' => $redirection->getQuery()]); + return [ - '_controller' => RedirectionController::class . '::redirectAction', + '_controller' => RedirectionController::class.'::redirectAction', 'redirection' => $redirection, '_route' => null, ]; @@ -48,13 +46,10 @@ public function match(string $pathinfo): array throw new ResourceNotFoundException(sprintf('%s did not match any Doctrine Redirection', $pathinfo)); } - /** - * @param string $decodedUrl - * @return Redirection|null - */ protected function matchRedirection(string $decodedUrl): ?Redirection { $resource = $this->pathResolver->resolvePath($decodedUrl)->getResource(); + return $resource instanceof Redirection ? $resource : null; } } diff --git a/lib/RoadizCoreBundle/src/Routing/RedirectionPathResolver.php b/lib/RoadizCoreBundle/src/Routing/RedirectionPathResolver.php index d6947849..78a8f8b8 100644 --- a/lib/RoadizCoreBundle/src/Routing/RedirectionPathResolver.php +++ b/lib/RoadizCoreBundle/src/Routing/RedirectionPathResolver.php @@ -25,7 +25,7 @@ public function resolvePath( string $path, array $supportedFormatExtensions = ['html'], bool $allowRootPaths = false, - bool $allowNonReachableNodes = true + bool $allowNonReachableNodes = true, ): ResourceInfo { $this->stopwatch->start('lookForRedirection', 'routing'); $cacheItem = $this->cacheAdapter->getItem(self::CACHE_KEY); diff --git a/lib/RoadizCoreBundle/src/Routing/RedirectionRouter.php b/lib/RoadizCoreBundle/src/Routing/RedirectionRouter.php index 1ec14a2e..0cb3adc0 100644 --- a/lib/RoadizCoreBundle/src/Routing/RedirectionRouter.php +++ b/lib/RoadizCoreBundle/src/Routing/RedirectionRouter.php @@ -21,8 +21,8 @@ public function __construct( protected readonly ManagerRegistry $managerRegistry, protected readonly Stopwatch $stopwatch, array $options = [], - RequestContext $context = null, - LoggerInterface $logger = null, + ?RequestContext $context = null, + ?LoggerInterface $logger = null, ) { parent::__construct( new NullLoader(), @@ -34,20 +34,14 @@ public function __construct( $this->matcher = $matcher; } - /** - * {@inheritdoc} - */ public function getRouteCollection(): RouteCollection { return new RouteCollection(); } - /** - * {@inheritdoc} - */ public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string { - throw new RouteNotFoundException(get_class($this) . ' does not support path generation.'); + throw new RouteNotFoundException(get_class($this).' does not support path generation.'); } /** @@ -55,7 +49,7 @@ public function generate(string $name, array $parameters = [], int $referenceTyp */ public function getGenerator(): UrlGeneratorInterface { - throw new \BadMethodCallException(get_class($this) . ' does not support path generation.'); + throw new \BadMethodCallException(get_class($this).' does not support path generation.'); } public function getRouteDebugMessage(mixed $name, array $parameters = []): string diff --git a/lib/RoadizCoreBundle/src/Routing/ResourceInfo.php b/lib/RoadizCoreBundle/src/Routing/ResourceInfo.php index d25db2f5..47b128d7 100644 --- a/lib/RoadizCoreBundle/src/Routing/ResourceInfo.php +++ b/lib/RoadizCoreBundle/src/Routing/ResourceInfo.php @@ -14,75 +14,51 @@ final class ResourceInfo protected ?string $format = null; protected ?string $locale = null; - /** - * @return PersistableInterface|null - */ public function getResource(): ?PersistableInterface { return $this->resource; } - /** - * @param PersistableInterface|null $resource - * @return ResourceInfo - */ public function setResource(?PersistableInterface $resource): ResourceInfo { $this->resource = $resource; + return $this; } - /** - * @return TranslationInterface|null - */ public function getTranslation(): ?TranslationInterface { return $this->translation; } - /** - * @param TranslationInterface|null $translation - * @return ResourceInfo - */ public function setTranslation(?TranslationInterface $translation): ResourceInfo { $this->translation = $translation; + return $this; } - /** - * @return string|null - */ public function getFormat(): ?string { return $this->format; } - /** - * @param string|null $format - * @return ResourceInfo - */ public function setFormat(?string $format): ResourceInfo { $this->format = $format; + return $this; } - /** - * @return string|null - */ public function getLocale(): ?string { return $this->locale; } - /** - * @param string|null $locale - * @return ResourceInfo - */ public function setLocale(?string $locale): ResourceInfo { $this->locale = $locale; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Routing/RouteHandler.php b/lib/RoadizCoreBundle/src/Routing/RouteHandler.php index 01146723..373e9674 100644 --- a/lib/RoadizCoreBundle/src/Routing/RouteHandler.php +++ b/lib/RoadizCoreBundle/src/Routing/RouteHandler.php @@ -15,8 +15,9 @@ class RouteHandler public static function getBaseRoute(string $path): string { if ((new UnicodeString($path))->endsWith('Locale')) { - $path = StringHandler::replaceLast("Locale", "", $path); + $path = StringHandler::replaceLast('Locale', '', $path); } + return $path; } } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/AbstractSearchHandler.php b/lib/RoadizCoreBundle/src/SearchEngine/AbstractSearchHandler.php index 133f3691..bd8cf3b1 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/AbstractSearchHandler.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/AbstractSearchHandler.php @@ -25,7 +25,7 @@ public function __construct( ClientRegistry $clientRegistry, ObjectManager $em, LoggerInterface $searchEngineLogger, - EventDispatcherInterface $eventDispatcher + EventDispatcherInterface $eventDispatcher, ) { $this->clientRegistry = $clientRegistry; $this->em = $em; @@ -39,37 +39,35 @@ public function getSolr(): Client if (null === $solr) { throw new SolrServerNotAvailableException(); } + return $solr; } /** - * Search on Solr with pre-filled argument for highlighting + * Search on Solr with pre-filled argument for highlighting. * * * $q is the search criteria. * * $args is an array with solr query argument. * The common argument can be found [here](https://cwiki.apache.org/confluence/display/solr/Common+Query+Parameters) * and for highlighting argument is [here](https://cwiki.apache.org/confluence/display/solr/Standard+Highlighter). * - * @param string $q - * @param array $args - * @param int $rows * @param bool $searchTags Search in tags/folders too, even if a node don’t match - * @param int $page * - * @return SearchResultsInterface Return a SearchResultsInterface iterable object. + * @return SearchResultsInterface return a SearchResultsInterface iterable object */ public function searchWithHighlight( string $q, array $args = [], int $rows = 20, bool $searchTags = false, - int $page = 1 + int $page = 1, ): SearchResultsInterface { $args = $this->argFqProcess($args); - $args["fq"][] = "document_type_s:" . $this->getDocumentType(); - $args["hl.q"] = $this->buildHighlightingQuery($q); + $args['fq'][] = 'document_type_s:'.$this->getDocumentType(); + $args['hl.q'] = $this->buildHighlightingQuery($q); $args = array_merge($this->getHighlightingOptions($args), $args); $response = $this->nativeSearch($q, $args, $rows, $searchTags, $page); + return $this->createSearchResultsFromResponse($response); } @@ -78,38 +76,22 @@ protected function createSearchResultsFromResponse(?array $response): SolrSearch return new SolrSearchResults(null !== $response ? $response : [], $this->em); } - /** - * @param array $args - * @return array - */ abstract protected function argFqProcess(array &$args): array; - /** - * @return string - */ abstract protected function getDocumentType(): string; - /** - * @param array $args - * @return array - */ protected function getHighlightingOptions(array &$args = []): array { $tmp = []; - $tmp["hl"] = true; - $tmp["hl.fl"] = $this->getTitleField($args) . ' ' . $this->getCollectionField($args); - $tmp["hl.fragsize"] = $this->getHighlightingFragmentSize(); - $tmp["hl.simple.pre"] = ''; - $tmp["hl.simple.post"] = ''; + $tmp['hl'] = true; + $tmp['hl.fl'] = $this->getTitleField($args).' '.$this->getCollectionField($args); + $tmp['hl.fragsize'] = $this->getHighlightingFragmentSize(); + $tmp['hl.simple.pre'] = ''; + $tmp['hl.simple.post'] = ''; return $tmp; } - /** - * @param array $args - * - * @return string - */ protected function getCollectionField(array &$args): string { /* @@ -117,27 +99,20 @@ protected function getCollectionField(array &$args): string * is filtered by translation. */ if (isset($args['locale']) && is_string($args['locale'])) { - return 'collection_txt_' . \Locale::getPrimaryLanguage($args['locale']); + return 'collection_txt_'.\Locale::getPrimaryLanguage($args['locale']); } if (isset($args['translation']) && $args['translation'] instanceof Translation) { - return 'collection_txt_' . \Locale::getPrimaryLanguage($args['translation']->getLocale()); + return 'collection_txt_'.\Locale::getPrimaryLanguage($args['translation']->getLocale()); } + return 'collection_txt'; } - /** - * @return int - */ public function getHighlightingFragmentSize(): int { return $this->highlightingFragmentSize; } - /** - * @param int $highlightingFragmentSize - * - * @return AbstractSearchHandler - */ public function setHighlightingFragmentSize(int $highlightingFragmentSize): AbstractSearchHandler { $this->highlightingFragmentSize = $highlightingFragmentSize; @@ -145,21 +120,12 @@ public function setHighlightingFragmentSize(int $highlightingFragmentSize): Abst return $this; } - /** - * @param string $q - * @param array $args - * @param int $rows - * @param bool $searchTags - * @param int $page - * - * @return array|null - */ abstract protected function nativeSearch( string $q, array $args = [], int $rows = 20, bool $searchTags = false, - int $page = 1 + int $page = 1, ): ?array; /** @@ -186,12 +152,9 @@ abstract protected function nativeSearch( * * this explicitly filter by title. * - * - * @param string $q - * @param array $args - * @param int $rows Results per page + * @param int $rows Results per page * @param bool $searchTags Search in tags/folders too, even if a node don’t match - * @param int $page Retrieve a specific page + * @param int $page Retrieve a specific page * * @return SearchResultsInterface Return an array of doctrine Entities (Document, NodesSources) */ @@ -200,21 +163,18 @@ public function search( array $args = [], int $rows = 20, bool $searchTags = false, - int $page = 1 + int $page = 1, ): SearchResultsInterface { $args = $this->argFqProcess($args); - $args["fq"][] = "document_type_s:" . $this->getDocumentType(); + $args['fq'][] = 'document_type_s:'.$this->getDocumentType(); $tmp = []; $args = array_merge($tmp, $args); $response = $this->nativeSearch($q, $args, $rows, $searchTags, $page); + return $this->createSearchResultsFromResponse($response); } - /** - * @param string $input - * @return string - */ public function escapeQuery(string $input): string { $qHelper = new Helper(); @@ -222,20 +182,20 @@ public function escapeQuery(string $input): string $input = $qHelper->escapeTerm($input); // Solarium does not escape Lucene reserved words // https://stackoverflow.com/questions/10337908/how-to-properly-escape-or-and-and-in-lucene-query - $input = preg_replace("#\\b(AND|OR|NOT)\\b#", "\\\\\\\\$1", $input); + $input = preg_replace('#\\b(AND|OR|NOT)\\b#', '\\\\\\\$1', $input); return $input; } /** - * @param string $q * @return array [$exactQuery, $fuzzyQuery, $wildcardQuery] */ protected function getFormattedQuery(string $q): array { $q = trim($q); /** - * Generate a fuzzy query by appending proximity to each word + * Generate a fuzzy query by appending proximity to each word. + * * @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); @@ -248,8 +208,9 @@ protected function getFormattedQuery(string $q): array * Proximity is set to 1 by default for single-words */ if (\mb_strlen($word) > 3) { - return $this->escapeQuery($word) . '~2'; + return $this->escapeQuery($word).'~2'; } + return $this->escapeQuery($word); }, $words)); /* @@ -259,7 +220,7 @@ protected function getFormattedQuery(string $q): array /* * Wildcard search for allowing autocomplete */ - $wildcardQuery = $this->escapeQuery($q) . '*~2'; + $wildcardQuery = $this->escapeQuery($q).'*~2'; return [$exactQuery, $fuzzyiedQuery, $wildcardQuery]; } @@ -268,11 +229,6 @@ protected function getFormattedQuery(string $q): array * Default Solr query builder. * * Extends this method to customize your Solr queries. Eg. to boost custom fields. - * - * @param string $q - * @param array $args - * @param bool $searchTags - * @return string */ protected function buildQuery(string $q, array &$args, bool $searchTags = false): string { @@ -287,7 +243,7 @@ protected function buildQuery(string $q, array &$args, bool $searchTags = false) if ($searchTags) { // Need to use Fuzzy search AND Exact search return sprintf( - '(' . $titleField . ':%s)^10 (' . $titleField . ':%s) (' . $titleField . ':%s) (' . $collectionField . ':%s)^2 (' . $collectionField . ':%s) (' . $tagsField . ':%s) (' . $tagsField . ':%s)', + '('.$titleField.':%s)^10 ('.$titleField.':%s) ('.$titleField.':%s) ('.$collectionField.':%s)^2 ('.$collectionField.':%s) ('.$tagsField.':%s) ('.$tagsField.':%s)', $exactQuery, $fuzzyiedQuery, $wildcardQuery, @@ -298,7 +254,7 @@ protected function buildQuery(string $q, array &$args, bool $searchTags = false) ); } else { return sprintf( - '(' . $titleField . ':%s)^10 (' . $titleField . ':%s) (' . $titleField . ':%s) (' . $collectionField . ':%s)^2 (' . $collectionField . ':%s)', + '('.$titleField.':%s)^10 ('.$titleField.':%s) ('.$titleField.':%s) ('.$collectionField.':%s)^2 ('.$collectionField.':%s)', $exactQuery, $fuzzyiedQuery, $wildcardQuery, @@ -317,14 +273,10 @@ protected function buildHighlightingQuery(string $q): string } $q = $this->escapeQuery($q); + return sprintf('%s~2', $q); } - /** - * @param array $args - * @param bool $searchTags - * @return string - */ protected function buildQueryFields(array &$args, bool $searchTags = true): string { $titleField = $this->getTitleField($args); @@ -332,19 +284,15 @@ protected function buildQueryFields(array &$args, bool $searchTags = true): stri $tagsField = $this->getTagsField($args); if ($searchTags) { - return $titleField . '^10 ' . $collectionField . '^2 ' . $tagsField . ' slug_s'; + return $titleField.'^10 '.$collectionField.'^2 '.$tagsField.' slug_s'; } - return $titleField . ' ' . $collectionField . ' slug_s'; + + return $titleField.' '.$collectionField.' slug_s'; } - /** - * @param string $q - * - * @return bool - */ protected function isQuerySingleWord(string $q): bool { - return preg_match('#[\s\-\'\"\–\—\’\”\‘\“\/\+\.\,]#', $q) !== 1; + return 1 !== preg_match('#[\s\-\'\"\–\—\’\”\‘\“\/\+\.\,]#', $q); } protected function formatDateTimeToUTC(\DateTimeInterface $dateTime): string @@ -352,11 +300,6 @@ protected function formatDateTimeToUTC(\DateTimeInterface $dateTime): string return gmdate('Y-m-d\TH:i:s\Z', $dateTime->getTimestamp()); } - /** - * @param array $args - * - * @return string - */ protected function getTitleField(array &$args): string { /* @@ -364,19 +307,15 @@ protected function getTitleField(array &$args): string * is filtered by translation. */ if (isset($args['locale']) && is_string($args['locale'])) { - return 'title_txt_' . \Locale::getPrimaryLanguage($args['locale']); + return 'title_txt_'.\Locale::getPrimaryLanguage($args['locale']); } if (isset($args['translation']) && $args['translation'] instanceof Translation) { - return 'title_txt_' . \Locale::getPrimaryLanguage($args['translation']->getLocale()); + return 'title_txt_'.\Locale::getPrimaryLanguage($args['translation']->getLocale()); } + return 'title'; } - /** - * @param array $args - * - * @return string - */ protected function getTagsField(array &$args): string { /* @@ -384,21 +323,17 @@ protected function getTagsField(array &$args): string * is filtered by translation. */ if (isset($args['locale']) && is_string($args['locale'])) { - return 'tags_txt_' . \Locale::getPrimaryLanguage($args['locale']); + return 'tags_txt_'.\Locale::getPrimaryLanguage($args['locale']); } if (isset($args['translation']) && $args['translation'] instanceof Translation) { - return 'tags_txt_' . \Locale::getPrimaryLanguage($args['translation']->getLocale()); + return 'tags_txt_'.\Locale::getPrimaryLanguage($args['translation']->getLocale()); } + return 'tags_txt'; } /** * Create Solr Select query. Override it to add DisMax fields and rules. - * - * @param array $args - * @param int $rows - * @param int $page - * @return Query */ protected function createSolrQuery(array &$args = [], int $rows = 20, int $page = 1): Query { @@ -408,15 +343,15 @@ protected function createSolrQuery(array &$args = [], int $rows = 20, int $page if (is_array($value)) { foreach ($value as $k => $v) { $query->addFilterQuery([ - "key" => "fq" . $k, - "query" => $v, + 'key' => 'fq'.$k, + 'query' => $v, ]); } } elseif (is_scalar($value)) { $query->addParam($key, $value); } } - /** + /* * Add start if not first page. */ if ($page > 1) { diff --git a/lib/RoadizCoreBundle/src/SearchEngine/AbstractSolarium.php b/lib/RoadizCoreBundle/src/SearchEngine/AbstractSolarium.php index d4ac841a..39afa738 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/AbstractSolarium.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/AbstractSolarium.php @@ -13,9 +13,6 @@ use Solarium\QueryType\Update\Query\Document; use Solarium\QueryType\Update\Query\Query; -/** - * @package RZ\Roadiz\CoreBundle\SearchEngine - */ abstract class AbstractSolarium { public const DOCUMENT_TYPE = 'AbstractDocument'; @@ -64,7 +61,7 @@ abstract class AbstractSolarium public function __construct( ClientRegistry $clientRegistry, LoggerInterface $searchEngineLogger, - MarkdownInterface $markdown + MarkdownInterface $markdown, ) { $this->logger = $searchEngineLogger; $this->markdown = $markdown; @@ -77,6 +74,7 @@ public function getSolr(): Client if (null === $solr) { throw new SolrServerNotAvailableException(); } + return $solr; } @@ -85,7 +83,6 @@ public function getSolr(): Client * * Use this method only when you need to index single NodeSources. * - * @return ResultInterface|null * @throws \Exception */ public function indexAndCommit(): ?ResultInterface @@ -109,7 +106,6 @@ public function indexAndCommit(): ?ResultInterface * * Use this method **only** when you need to re-index a single NodeSources. * - * @return ResultInterface|null * @throws \Exception */ public function updateAndCommit(): ?ResultInterface @@ -119,6 +115,7 @@ public function updateAndCommit(): ?ResultInterface $update->addCommit(true, true, false); $this->logger->debug('[Solr] Document updated.'); + return $this->getSolr()->update($update); } @@ -127,8 +124,6 @@ public function updateAndCommit(): ?ResultInterface * * Use this method only when you need to re-index bulk NodeSources. * - * @param Query $update - * * @throws \Exception */ public function update(Query $update): void @@ -143,9 +138,7 @@ public function update(Query $update): void /** * Remove current document from SearchEngine index. * - * @param Query $update - * @return bool - * @throws \RuntimeException If no document is available. + * @throws \RuntimeException if no document is available */ public function remove(Query $update): bool { @@ -172,6 +165,7 @@ public function removeAndCommit(): void $this->getSolr()->update($update); } } + /** * Remove any document linked to current node-source and commit after. * @@ -190,7 +184,6 @@ public function cleanAndCommit(): void /** * Index current document with entity data. * - * @return bool * @throws \Exception */ public function index(): bool @@ -204,61 +197,56 @@ public function index(): bool $this->document->setField($key, $value); } } + return true; } catch (\RuntimeException $e) { return false; } } - throw new \RuntimeException("No Solr item available for current entity", 1); + throw new \RuntimeException('No Solr item available for current entity', 1); } - /** - * @return DocumentInterface|null - */ public function getDocument(): ?DocumentInterface { return $this->document; } /** - * @param DocumentInterface $document * @return $this - * @deprecated Use createEmptyDocument instead of set an empty Solr document. + * + * @deprecated use createEmptyDocument instead of set an empty Solr document */ public function setDocument(DocumentInterface $document): self { $this->document = $document; + return $this; } /** - * @param Query $update * @return $this */ public function createEmptyDocument(Query $update): self { $this->document = $update->createDocument(); + return $this; } abstract public function clean(Query $update): bool; - - /** - * @return int|string - */ abstract public function getDocumentId(): int|string; /** * Get document from Solr index. * - * @return bool *FALSE* if no document found linked to current node-source. + * @return bool *FALSE* if no document found linked to current node-source */ public function getDocumentFromIndex(): bool { $query = $this->getSolr()->createSelect(); - $query->setQuery(static::IDENTIFIER_KEY . ':' . $this->getDocumentId()); - $query->createFilterQuery('type')->setQuery(static::TYPE_DISCRIMINATOR . ':' . static::DOCUMENT_TYPE); + $query->setQuery(static::IDENTIFIER_KEY.':'.$this->getDocumentId()); + $query->createFilterQuery('type')->setQuery(static::TYPE_DISCRIMINATOR.':'.static::DOCUMENT_TYPE); // this executes the query and returns the result $resultset = $this->getSolr()->select($query); @@ -268,26 +256,21 @@ public function getDocumentFromIndex(): bool } else { foreach ($resultset as $document) { $this->document = $document; + return true; } } + return false; } /** * Get a key/value array representation of current indexed object. * - * @return array * @throws \Exception */ abstract protected function getFieldsAssoc(): array; - /** - * @param string|null $content - * @param bool $stripMarkdown - * - * @return string|null - */ public function cleanTextContent(?string $content, bool $stripMarkdown = true): ?string { if (!is_string($content)) { @@ -305,16 +288,15 @@ public function cleanTextContent(?string $content, bool $stripMarkdown = true): /* * Remove ctrl characters */ - $content = preg_replace("[:cntrl:]", "", $content); + $content = preg_replace('[:cntrl:]', '', $content); $content = preg_replace('/[\x00-\x1F]/', '', $content); + return $content; } /** * You MUST override this method to provide an idempotent identifier. * This identifier MUST be the same for the same entity. - * - * @return string */ protected function getIdempotentIdentifier(): string { diff --git a/lib/RoadizCoreBundle/src/SearchEngine/ClientRegistry.php b/lib/RoadizCoreBundle/src/SearchEngine/ClientRegistry.php index 85ef24f8..28b20ec4 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/ClientRegistry.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/ClientRegistry.php @@ -23,8 +23,9 @@ public function getClient(): ?Client return null; } if (!($client instanceof Client)) { - throw new \RuntimeException('Solr client must be an instance of ' . Client::class); + throw new \RuntimeException('Solr client must be an instance of '.Client::class); } + return $client; } @@ -36,6 +37,7 @@ public function isClientReady(?Client $client): bool $ping = $client->createPing(); try { $client->ping($ping); + return true; } catch (\Exception $e) { return false; diff --git a/lib/RoadizCoreBundle/src/SearchEngine/DocumentSearchHandler.php b/lib/RoadizCoreBundle/src/SearchEngine/DocumentSearchHandler.php index eb83052a..7ccdb773 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/DocumentSearchHandler.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/DocumentSearchHandler.php @@ -8,26 +8,14 @@ use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\SearchEngine\Event\DocumentSearchQueryEvent; -/** - * @package RZ\Roadiz\CoreBundle\SearchEngine - */ class DocumentSearchHandler extends AbstractSearchHandler { - /** - * @param string $q - * @param array $args - * @param integer $rows - * @param bool $searchTags - * @param integer $page - * - * @return array|null - */ protected function nativeSearch( string $q, array $args = [], int $rows = 20, bool $searchTags = false, - int $page = 1 + int $page = 1, ): ?array { if (empty($q)) { return null; @@ -51,7 +39,7 @@ protected function nativeSearch( $this->logger->debug('[Solr] Request document search…', [ 'query' => $queryTxt, - 'fq' => $args["fq"] ?? [], + 'fq' => $args['fq'] ?? [], 'params' => $query->getParams(), ]); @@ -62,17 +50,14 @@ protected function nativeSearch( $query = $event->getQuery(); $solrRequest = $this->getSolr()->execute($query); + return $solrRequest->getData(); } - /** - * @param array $args - * @return array - */ protected function argFqProcess(array &$args): array { - if (!isset($args["fq"])) { - $args["fq"] = []; + if (!isset($args['fq'])) { + $args['fq'] = []; } /* @@ -80,11 +65,11 @@ protected function argFqProcess(array &$args): array */ if (!empty($args['folders'])) { if ($args['folders'] instanceof Folder) { - $args["fq"][] = sprintf('all_tags_slugs_ss:"%s"', $args['folders']->getFolderName()); + $args['fq'][] = sprintf('all_tags_slugs_ss:"%s"', $args['folders']->getFolderName()); } elseif (is_array($args['folders'])) { foreach ($args['folders'] as $folder) { if ($folder instanceof Folder) { - $args["fq"][] = sprintf('all_tags_slugs_ss:"%s"', $folder->getFolderName()); + $args['fq'][] = sprintf('all_tags_slugs_ss:"%s"', $folder->getFolderName()); } } } @@ -92,48 +77,45 @@ protected function argFqProcess(array &$args): array } if (isset($args['mimeType'])) { - $tmp = "mime_type_s:"; + $tmp = 'mime_type_s:'; if (!is_array($args['mimeType'])) { $tmp .= (string) $args['mimeType']; } else { $value = implode(' AND ', $args['mimeType']); - $tmp .= '(' . $value . ')'; + $tmp .= '('.$value.')'; } unset($args['mimeType']); - $args["fq"][] = $tmp; + $args['fq'][] = $tmp; } /* * Filter by translation or locale */ if (isset($args['translation']) && $args['translation'] instanceof Translation) { - $args["fq"][] = "locale_s:" . $args['translation']->getLocale(); + $args['fq'][] = 'locale_s:'.$args['translation']->getLocale(); } if (isset($args['locale']) && is_string($args['locale'])) { - $args["fq"][] = "locale_s:" . $args['locale']; + $args['fq'][] = 'locale_s:'.$args['locale']; } /* * Filter by filename */ if (isset($args['filename'])) { - $args["fq"][] = sprintf('filename_s:"%s"', trim($args['filename'])); + $args['fq'][] = sprintf('filename_s:"%s"', trim($args['filename'])); } /* * Filter out non-valid copyright documents */ if (isset($args['copyrightValid'])) { - $args["fq"][] = '(copyright_valid_since_dt:[* TO NOW] AND copyright_valid_until_dt:[NOW TO *])'; + $args['fq'][] = '(copyright_valid_since_dt:[* TO NOW] AND copyright_valid_until_dt:[NOW TO *])'; unset($args['copyrightValid']); } return $args; } - /** - * @return string - */ protected function getDocumentType(): string { return 'DocumentTranslation'; diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Event/AbstractSearchQueryEvent.php b/lib/RoadizCoreBundle/src/SearchEngine/Event/AbstractSearchQueryEvent.php index 0b65abda..0507d533 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Event/AbstractSearchQueryEvent.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Event/AbstractSearchQueryEvent.php @@ -18,17 +18,11 @@ public function __construct(Query $query, array $args) $this->args = $args; } - /** - * @return Query - */ public function getQuery(): Query { return $this->query; } - /** - * @return array - */ public function getArgs(): array { return $this->args; diff --git a/lib/RoadizCoreBundle/src/SearchEngine/GlobalNodeSourceSearchHandler.php b/lib/RoadizCoreBundle/src/SearchEngine/GlobalNodeSourceSearchHandler.php index 761a221d..f6892e60 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/GlobalNodeSourceSearchHandler.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/GlobalNodeSourceSearchHandler.php @@ -10,9 +10,6 @@ use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\Roadiz\CoreBundle\Entity\Translation; -/** - * @package RZ\Roadiz\CoreBundle\SearchEngine - */ class GlobalNodeSourceSearchHandler { private ObjectManager $em; @@ -31,26 +28,22 @@ protected function getRepository(): EntityRepository } /** - * @param bool $displayNonPublishedNodes - * * @return $this */ public function setDisplayNonPublishedNodes(bool $displayNonPublishedNodes): self { $this->getRepository()->setDisplayingNotPublishedNodes($displayNonPublishedNodes); + return $this; } /** - * @param string $searchTerm - * @param int $resultCount - * @param Translation|null $translation * @return NodesSources[] */ public function getNodeSourcesBySearchTerm( string $searchTerm, int $resultCount, - ?Translation $translation = null + ?Translation $translation = null, ): array { $safeSearchTerms = strip_tags($searchTerm); @@ -80,7 +73,7 @@ public function getNodeSourcesBySearchTerm( $resultCount ); - if (count($nodesSources) === 0) { + if (0 === count($nodesSources)) { /* * Then try with node name. */ @@ -93,7 +86,7 @@ public function getNodeSourcesBySearchTerm( $qb->expr()->like('ns.title', ':nodeName') )) ->setMaxResults($resultCount) - ->setParameter('nodeName', '%' . $safeSearchTerms . '%'); + ->setParameter('nodeName', '%'.$safeSearchTerms.'%'); if (null !== $translation) { $qb->andWhere($qb->expr()->eq('ns.translation', ':translation')) diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/AbstractIndexer.php b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/AbstractIndexer.php index 94e9716c..3bfded51 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/AbstractIndexer.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/AbstractIndexer.php @@ -21,37 +21,30 @@ public function __construct( protected readonly ClientRegistry $clientRegistry, protected readonly ManagerRegistry $managerRegistry, protected readonly SolariumFactoryInterface $solariumFactory, - readonly LoggerInterface $searchEngineLogger + readonly LoggerInterface $searchEngineLogger, ) { $this->logger = $searchEngineLogger; } - /** - * @return Client - */ public function getSolr(): Client { $solr = $this->clientRegistry->getClient(); if (null === $solr) { throw new SolrServerNotAvailableException(); } + return $solr; } - /** - * @param SymfonyStyle|null $io - * @return AbstractIndexer - */ public function setIo(?SymfonyStyle $io): self { $this->io = $io; + return $this; } /** * Empty Solr index. - * - * @param string|null $documentType */ public function emptySolr(?string $documentType = null): void { diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/Indexer.php b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/Indexer.php index 2030841b..020c8da1 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/Indexer.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/Indexer.php @@ -7,8 +7,12 @@ interface Indexer { public function reindexAll(): void; + public function index(mixed $id): void; + public function delete(mixed $id): void; + public function emptySolr(?string $documentType = null): void; + public function optimizeSolr(): void; } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactory.php b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactory.php index 22ad1cba..3241853a 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactory.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactory.php @@ -4,7 +4,6 @@ namespace RZ\Roadiz\CoreBundle\SearchEngine\Indexer; -use LogicException; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; @@ -25,7 +24,7 @@ public function __construct(ContainerInterface $serviceLocator) /** * @param class-string $classname - * @return Indexer + * * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ @@ -37,7 +36,7 @@ public function getIndexerFor(string $classname): Indexer Document::class => $this->serviceLocator->get(DocumentIndexer::class), Tag::class => $this->serviceLocator->get(TagIndexer::class), Folder::class => $this->serviceLocator->get(FolderIndexer::class), - default => throw new LogicException(sprintf('No indexer found for "%s"', $classname)), + default => throw new \LogicException(sprintf('No indexer found for "%s"', $classname)), }; } } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactoryInterface.php b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactoryInterface.php index 03952dff..ac2b946c 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactoryInterface.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/IndexerFactoryInterface.php @@ -8,7 +8,6 @@ interface IndexerFactoryInterface { /** * @param class-string $classname - * @return Indexer */ public function getIndexerFor(string $classname): Indexer; } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/NodesSourcesIndexer.php b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/NodesSourcesIndexer.php index 65279dd0..eae097a8 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Indexer/NodesSourcesIndexer.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Indexer/NodesSourcesIndexer.php @@ -56,9 +56,7 @@ protected function deleteNodeSource(?NodesSources $nodeSource): void } /** - * Overridable - * - * @return QueryBuilder + * Overridable. */ protected function getAllQueryBuilder(): QueryBuilder { @@ -71,8 +69,9 @@ protected function getAllQueryBuilder(): QueryBuilder /** * Loop over every NodesSources to index them again. * - * @param int $batchCount Split reindex span to several batches. - * @param int $batchNumber Execute reindex on a specific batch. + * @param int $batchCount split reindex span to several batches + * @param int $batchNumber execute reindex on a specific batch + * * @throws \Doctrine\ORM\NoResultException * @throws \Doctrine\ORM\NonUniqueResultException */ diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Message/AbstractSolrMessage.php b/lib/RoadizCoreBundle/src/SearchEngine/Message/AbstractSolrMessage.php index 9ce292a4..3633ad68 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Message/AbstractSolrMessage.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Message/AbstractSolrMessage.php @@ -9,36 +9,22 @@ abstract class AbstractSolrMessage implements AsyncMessage { /** - * Cannot typehint with class-string: breaks Symfony Serializer 5.4 - * @var string + * Cannot typehint with class-string: breaks Symfony Serializer 5.4. */ protected string $classname; - /** - * @var mixed - */ protected mixed $identifier; - /** - * @param string $classname - * @param mixed $identifier - */ public function __construct(string $classname, mixed $identifier) { $this->classname = $classname; $this->identifier = $identifier; } - /** - * @return string - */ public function getClassname(): string { return $this->classname; } - /** - * @return mixed - */ public function getIdentifier(): mixed { return $this->identifier; diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrDeleteMessageHandler.php b/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrDeleteMessageHandler.php index 359e559b..7d330c82 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrDeleteMessageHandler.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrDeleteMessageHandler.php @@ -15,7 +15,7 @@ final class SolrDeleteMessageHandler { public function __construct( private readonly IndexerFactoryInterface $indexerFactory, - private readonly LoggerInterface $searchEngineLogger + private readonly LoggerInterface $searchEngineLogger, ) { } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrReindexMessageHandler.php b/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrReindexMessageHandler.php index d6372a3a..55442258 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrReindexMessageHandler.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Message/Handler/SolrReindexMessageHandler.php @@ -15,7 +15,7 @@ final class SolrReindexMessageHandler { public function __construct( private readonly IndexerFactoryInterface $indexerFactory, - private readonly LoggerInterface $searchEngineLogger + private readonly LoggerInterface $searchEngineLogger, ) { } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandler.php b/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandler.php index 56c6a166..f2cf19ab 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandler.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandler.php @@ -11,30 +11,18 @@ use RZ\Roadiz\CoreBundle\Entity\Tag; use RZ\Roadiz\CoreBundle\SearchEngine\Event\NodeSourceSearchQueryEvent; -/** - * @package RZ\Roadiz\CoreBundle\SearchEngine - */ class NodeSourceSearchHandler extends AbstractSearchHandler implements NodeSourceSearchHandlerInterface { protected bool $boostByPublicationDate = false; protected bool $boostByUpdateDate = false; protected bool $boostByCreationDate = false; - /** - * @param string $q - * @param array $args - * @param integer $rows - * @param bool $searchTags - * @param int $page - * - * @return array|null - */ protected function nativeSearch( string $q, array $args = [], int $rows = 20, bool $searchTags = false, - int $page = 1 + int $page = 1, ): ?array { if (empty($q)) { return null; @@ -44,15 +32,15 @@ protected function nativeSearch( if ($this->boostByPublicationDate) { $boost = '{!boost b=recip(ms(NOW,published_at_dt),3.16e-11,1,1)}'; - $queryTxt = $boost . $queryTxt; + $queryTxt = $boost.$queryTxt; } if ($this->boostByUpdateDate) { $boost = '{!boost b=recip(ms(NOW,updated_at_dt),3.16e-11,1,1)}'; - $queryTxt = $boost . $queryTxt; + $queryTxt = $boost.$queryTxt; } if ($this->boostByCreationDate) { $boost = '{!boost b=recip(ms(NOW,created_at_dt),3.16e-11,1,1)}'; - $queryTxt = $boost . $queryTxt; + $queryTxt = $boost.$queryTxt; } $query->setQuery($queryTxt); @@ -72,7 +60,7 @@ protected function nativeSearch( $this->logger->debug('[Solr] Request node-sources search…', [ 'query' => $queryTxt, - 'fq' => $args["fq"] ?? [], + 'fq' => $args['fq'] ?? [], 'params' => $query->getParams(), ]); @@ -83,25 +71,22 @@ protected function nativeSearch( $query = $event->getQuery(); $solrRequest = $this->getSolr()->execute($query); + return $solrRequest->getData(); } - /** - * @param array $args - * @return array - */ protected function argFqProcess(array &$args): array { - if (!isset($args["fq"])) { - $args["fq"] = []; + if (!isset($args['fq'])) { + $args['fq'] = []; } $visible = $args['visible'] ?? $args['node.visible'] ?? null; if (isset($visible)) { - $tmp = "node_visible_b:" . (($visible) ? 'true' : 'false'); + $tmp = 'node_visible_b:'.(($visible) ? 'true' : 'false'); unset($args['visible']); unset($args['node.visible']); - $args["fq"][] = $tmp; + $args['fq'][] = $tmp; } /* @@ -110,11 +95,11 @@ protected function argFqProcess(array &$args): array */ if (!empty($args['tags'])) { if ($args['tags'] instanceof Tag) { - $args["fq"][] = sprintf('all_tags_slugs_ss:"%s"', $args['tags']->getTagName()); + $args['fq'][] = sprintf('all_tags_slugs_ss:"%s"', $args['tags']->getTagName()); } elseif (is_array($args['tags'])) { foreach ($args['tags'] as $tag) { if ($tag instanceof Tag) { - $args["fq"][] = sprintf('all_tags_slugs_ss:"%s"', $tag->getTagName()); + $args['fq'][] = sprintf('all_tags_slugs_ss:"%s"', $tag->getTagName()); } } } @@ -135,11 +120,11 @@ protected function argFqProcess(array &$args): array $orQuery[] = $singleNodeType; } } - $args["fq"][] = "node_type_s:(" . implode(' OR ', $orQuery) . ')'; + $args['fq'][] = 'node_type_s:('.implode(' OR ', $orQuery).')'; } elseif ($nodeType instanceof NodeTypeInterface) { - $args["fq"][] = "node_type_s:" . $nodeType->getName(); + $args['fq'][] = 'node_type_s:'.$nodeType->getName(); } else { - $args["fq"][] = "node_type_s:" . $nodeType; + $args['fq'][] = 'node_type_s:'.$nodeType; } unset($args['nodeType']); unset($args['node.nodeType']); @@ -151,11 +136,11 @@ protected function argFqProcess(array &$args): array $parent = $args['parent'] ?? $args['node.parent'] ?? null; if (!empty($parent)) { if ($parent instanceof Node) { - $args["fq"][] = "node_parent_i:" . $parent->getId(); + $args['fq'][] = 'node_parent_i:'.$parent->getId(); } elseif (is_string($parent)) { - $args["fq"][] = "node_parent_s:" . trim($parent); + $args['fq'][] = 'node_parent_s:'.trim($parent); } elseif (is_numeric($parent)) { - $args["fq"][] = "node_parent_i:" . (int) $parent; + $args['fq'][] = 'node_parent_i:'.(int) $parent; } unset($args['parent']); unset($args['node.parent']); @@ -165,81 +150,75 @@ protected function argFqProcess(array &$args): array * Handle publication date-time filtering */ if (isset($args['publishedAt'])) { - $tmp = "published_at_dt:"; + $tmp = 'published_at_dt:'; if (!is_array($args['publishedAt']) && $args['publishedAt'] instanceof \DateTimeInterface) { $tmp .= $this->formatDateTimeToUTC($args['publishedAt']); } elseif ( - isset($args['publishedAt'][0]) && - $args['publishedAt'][0] === "BETWEEN" && - isset($args['publishedAt'][1]) && - $args['publishedAt'][1] instanceof \DateTimeInterface && - isset($args['publishedAt'][2]) && - $args['publishedAt'][2] instanceof \DateTimeInterface + isset($args['publishedAt'][0]) + && 'BETWEEN' === $args['publishedAt'][0] + && isset($args['publishedAt'][1]) + && $args['publishedAt'][1] instanceof \DateTimeInterface + && isset($args['publishedAt'][2]) + && $args['publishedAt'][2] instanceof \DateTimeInterface ) { - $tmp .= "[" . - $this->formatDateTimeToUTC($args['publishedAt'][1]) . - " TO " . - $this->formatDateTimeToUTC($args['publishedAt'][2]) . "]"; + $tmp .= '['. + $this->formatDateTimeToUTC($args['publishedAt'][1]). + ' TO '. + $this->formatDateTimeToUTC($args['publishedAt'][2]).']'; } elseif ( - isset($args['publishedAt'][0]) && - $args['publishedAt'][0] === "<=" && - isset($args['publishedAt'][1]) && - $args['publishedAt'][1] instanceof \DateTimeInterface + isset($args['publishedAt'][0]) + && '<=' === $args['publishedAt'][0] + && isset($args['publishedAt'][1]) + && $args['publishedAt'][1] instanceof \DateTimeInterface ) { - $tmp .= "[* TO " . $this->formatDateTimeToUTC($args['publishedAt'][1]) . "]"; + $tmp .= '[* TO '.$this->formatDateTimeToUTC($args['publishedAt'][1]).']'; } elseif ( - isset($args['publishedAt'][0]) && - $args['publishedAt'][0] === ">=" && - isset($args['publishedAt'][1]) && - $args['publishedAt'][1] instanceof \DateTimeInterface + isset($args['publishedAt'][0]) + && '>=' === $args['publishedAt'][0] + && isset($args['publishedAt'][1]) + && $args['publishedAt'][1] instanceof \DateTimeInterface ) { - $tmp .= "[" . $this->formatDateTimeToUTC($args['publishedAt'][1]) . " TO *]"; + $tmp .= '['.$this->formatDateTimeToUTC($args['publishedAt'][1]).' TO *]'; } unset($args['publishedAt']); - $args["fq"][] = $tmp; + $args['fq'][] = $tmp; } $status = $args['status'] ?? $args['node.status'] ?? null; if (isset($status)) { - $tmp = "node_status_i:"; + $tmp = 'node_status_i:'; if (!is_array($status)) { $tmp .= (string) $status; - } elseif ($status[0] == "<=") { - $tmp .= "[* TO " . (string) $status[1] . "]"; - } elseif ($status[0] == ">=") { - $tmp .= "[" . (string) $status[1] . " TO *]"; + } elseif ('<=' == $status[0]) { + $tmp .= '[* TO '.(string) $status[1].']'; + } elseif ('>=' == $status[0]) { + $tmp .= '['.(string) $status[1].' TO *]'; } unset($args['status']); unset($args['node.status']); - $args["fq"][] = $tmp; + $args['fq'][] = $tmp; } else { - $args["fq"][] = "node_status_i:" . (string) (Node::PUBLISHED); + $args['fq'][] = 'node_status_i:'.(string) Node::PUBLISHED; } /* * Filter by translation or locale */ if (isset($args['translation']) && $args['translation'] instanceof TranslationInterface) { - $args["fq"][] = "locale_s:" . $args['translation']->getLocale(); + $args['fq'][] = 'locale_s:'.$args['translation']->getLocale(); } if (isset($args['locale']) && is_string($args['locale'])) { - $args["fq"][] = "locale_s:" . $args['locale']; + $args['fq'][] = 'locale_s:'.$args['locale']; } return $args; } - /** - * @return string - */ protected function getDocumentType(): string { return 'NodesSources'; } - /** - * @return NodeSourceSearchHandler - */ public function boostByPublicationDate(): NodeSourceSearchHandler { $this->boostByPublicationDate = true; @@ -249,9 +228,6 @@ public function boostByPublicationDate(): NodeSourceSearchHandler return $this; } - /** - * @return NodeSourceSearchHandler - */ public function boostByUpdateDate(): NodeSourceSearchHandler { $this->boostByPublicationDate = false; @@ -261,9 +237,6 @@ public function boostByUpdateDate(): NodeSourceSearchHandler return $this; } - /** - * @return NodeSourceSearchHandler - */ public function boostByCreationDate(): NodeSourceSearchHandler { $this->boostByPublicationDate = false; diff --git a/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandlerInterface.php b/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandlerInterface.php index e14e4faa..c451a9cf 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandlerInterface.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/NodeSourceSearchHandlerInterface.php @@ -7,6 +7,8 @@ interface NodeSourceSearchHandlerInterface extends SearchHandlerInterface { public function boostByPublicationDate(): NodeSourceSearchHandlerInterface; + public function boostByUpdateDate(): NodeSourceSearchHandlerInterface; + public function boostByCreationDate(): NodeSourceSearchHandlerInterface; } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SearchHandlerInterface.php b/lib/RoadizCoreBundle/src/SearchEngine/SearchHandlerInterface.php index 9612829c..c1bf2a94 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SearchHandlerInterface.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SearchHandlerInterface.php @@ -7,11 +7,9 @@ interface SearchHandlerInterface { /** - * @param string $q - * @param array $args - * @param int $rows Results per page + * @param int $rows Results per page * @param bool $searchTags Search in tags/folders too, even if a node don’t match - * @param int $page Retrieve a specific page + * @param int $page Retrieve a specific page * * @return SearchResultsInterface Return an array of doctrine Entities (Document, NodesSources) */ @@ -20,31 +18,23 @@ public function search( array $args = [], int $rows = 20, bool $searchTags = false, - int $page = 1 + int $page = 1, ): SearchResultsInterface; /** * Search with pre-filled argument for highlighting. * - * @param string $q - * @param array $args - * @param int $rows - * @param boolean $searchTags Search in tags/folders too, even if a node don’t match - * @param int $page + * @param bool $searchTags Search in tags/folders too, even if a node don’t match * - * @return SearchResultsInterface Return a SearchResultsInterface iterable object. + * @return SearchResultsInterface return a SearchResultsInterface iterable object */ public function searchWithHighlight( string $q, array $args = [], int $rows = 20, bool $searchTags = false, - int $page = 1 + int $page = 1, ): SearchResultsInterface; - /** - * @param int $highlightingFragmentSize - * @return SearchHandlerInterface - */ public function setHighlightingFragmentSize(int $highlightingFragmentSize): SearchHandlerInterface; } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SearchResultsInterface.php b/lib/RoadizCoreBundle/src/SearchEngine/SearchResultsInterface.php index 8705097a..de5c4011 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SearchResultsInterface.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SearchResultsInterface.php @@ -10,9 +10,11 @@ interface SearchResultsInterface extends \Iterator { public function getResultCount(): int; + /** * @return array */ public function getResultItems(): array; + public function map(callable $callable): array; } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocument.php b/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocument.php index 666606c2..f44c5ea1 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocument.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocument.php @@ -5,36 +5,25 @@ namespace RZ\Roadiz\CoreBundle\SearchEngine; use Psr\Log\LoggerInterface; -use RZ\Roadiz\Core\AbstractEntities\PersistableInterface; use RZ\Roadiz\CoreBundle\Entity\Document; use RZ\Roadiz\Markdown\MarkdownInterface; use Solarium\Core\Query\DocumentInterface; use Solarium\Core\Query\Result\ResultInterface; use Solarium\QueryType\Update\Query\Query; -use Symfony\Component\String\Slugger\AsciiSlugger; /** * Wrap a Solarium and a Document’ translations together to ease indexing. - * - * @package RZ\Roadiz\CoreBundle\SearchEngine */ class SolariumDocument extends AbstractSolarium { protected array $documentTranslationItems; - /** - * @param Document $rzDocument - * @param SolariumFactoryInterface $solariumFactory - * @param ClientRegistry $clientRegistry - * @param LoggerInterface $searchEngineLogger - * @param MarkdownInterface $markdown - */ public function __construct( Document $rzDocument, SolariumFactoryInterface $solariumFactory, ClientRegistry $clientRegistry, LoggerInterface $searchEngineLogger, - MarkdownInterface $markdown + MarkdownInterface $markdown, ) { parent::__construct($clientRegistry, $searchEngineLogger, $markdown); $this->documentTranslationItems = []; @@ -74,7 +63,7 @@ public function getDocumentId(): string|int /** * Get document from Solr index. * - * @return bool *FALSE* if no document found linked to current Roadiz document. + * @return bool *FALSE* if no document found linked to current Roadiz document */ public function getDocumentFromIndex(): bool { @@ -87,7 +76,6 @@ public function getDocumentFromIndex(): bool } /** - * @param Query $update * @return $this */ public function createEmptyDocument(Query $update): self @@ -96,6 +84,7 @@ public function createEmptyDocument(Query $update): self foreach ($this->documentTranslationItems as $documentTranslationItem) { $documentTranslationItem->createEmptyDocument($update); } + return $this; } @@ -104,11 +93,6 @@ protected function getFieldsAssoc(): array return []; } - /** - * @param Query $update - * - * @return bool - */ public function clean(Query $update): bool { /** @var SolariumDocumentTranslation $documentTranslationItem */ @@ -126,11 +110,11 @@ public function indexAndCommit(): ?ResultInterface foreach ($this->documentTranslationItems as $documentTranslationItem) { $lastResult = $documentTranslationItem->indexAndCommit(); } + return $lastResult; } /** - * @return ResultInterface|null * @throws \Exception */ public function updateAndCommit(): ?ResultInterface @@ -145,8 +129,6 @@ public function updateAndCommit(): ?ResultInterface } /** - * @param Query $update - * * @throws \Exception */ public function update(Query $update): void @@ -157,23 +139,16 @@ public function update(Query $update): void } } - /** - * @param Query $update - * - * @return bool - */ public function remove(Query $update): bool { /** @var SolariumDocumentTranslation $documentTranslationItem */ foreach ($this->documentTranslationItems as $documentTranslationItem) { $documentTranslationItem->remove($update); } + return true; } - /** - * @inheritdoc - */ public function removeAndCommit(): void { /** @var SolariumDocumentTranslation $documentTranslationItem */ @@ -182,9 +157,6 @@ public function removeAndCommit(): void } } - /** - * @inheritdoc - */ public function cleanAndCommit(): void { /** @var SolariumDocumentTranslation $documentTranslationItem */ @@ -193,9 +165,6 @@ public function cleanAndCommit(): void } } - /** - * @inheritdoc - */ public function index(): bool { /** @var SolariumDocumentTranslation $documentTranslationItem */ diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocumentTranslation.php b/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocumentTranslation.php index 8ea8b2fa..50f800a9 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocumentTranslation.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SolariumDocumentTranslation.php @@ -14,8 +14,6 @@ /** * Wrap a Solarium and a DocumentTranslation together to ease indexing. - * - * @package RZ\Roadiz\CoreBundle\SearchEngine */ class SolariumDocumentTranslation extends AbstractSolarium { @@ -30,7 +28,7 @@ public function __construct( ClientRegistry $clientRegistry, EventDispatcherInterface $dispatcher, LoggerInterface $searchEngineLogger, - MarkdownInterface $markdown + MarkdownInterface $markdown, ) { parent::__construct($clientRegistry, $searchEngineLogger, $markdown); @@ -48,21 +46,19 @@ public function getFieldsAssoc(bool $subResource = false): array $event = new DocumentTranslationIndexingEvent($this->documentTranslation, [], $this); /** @var DocumentTranslationIndexingEvent $event */ $event = $this->dispatcher->dispatch($event); + return $event->getAssociations(); } /** * Remove any document linked to current node-source. - * - * @param Query $update - * @return bool */ public function clean(Query $update): bool { $update->addDeleteQuery( - static::IDENTIFIER_KEY . ':"' . $this->documentTranslation->getId() . '"' . - '&' . static::TYPE_DISCRIMINATOR . ':"' . static::DOCUMENT_TYPE . '"' . - '&locale_s:"' . $this->documentTranslation->getTranslation()->getLocale() . '"' + static::IDENTIFIER_KEY.':"'.$this->documentTranslation->getId().'"'. + '&'.static::TYPE_DISCRIMINATOR.':"'.static::DOCUMENT_TYPE.'"'. + '&locale_s:"'.$this->documentTranslation->getTranslation()->getLocale().'"' ); return true; @@ -73,6 +69,7 @@ protected function getIdempotentIdentifier(): string $namespace = explode('\\', get_class($this->documentTranslation)); // get last 3 parts of namespace $namespace = array_slice($namespace, -3); - return (new AsciiSlugger())->slug(implode(' ', $namespace))->lower()->snake() . '.' . $this->documentTranslation->getId(); + + return (new AsciiSlugger())->slug(implode(' ', $namespace))->lower()->snake().'.'.$this->documentTranslation->getId(); } } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactory.php b/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactory.php index 34fa3d51..05f7966a 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactory.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactory.php @@ -25,7 +25,7 @@ public function __construct( LoggerInterface $searchEngineLogger, MarkdownInterface $markdown, EventDispatcherInterface $dispatcher, - HandlerFactoryInterface $handlerFactory + HandlerFactoryInterface $handlerFactory, ) { $this->clientRegistry = $clientRegistry; $this->logger = $searchEngineLogger; diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactoryInterface.php b/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactoryInterface.php index ab59410c..4a140cc3 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactoryInterface.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SolariumFactoryInterface.php @@ -11,6 +11,8 @@ interface SolariumFactoryInterface { public function createWithDocument(Document $document): SolariumDocument; + public function createWithDocumentTranslation(DocumentTranslation $documentTranslation): SolariumDocumentTranslation; + public function createWithNodesSources(NodesSources $nodeSource): SolariumNodeSource; } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SolariumNodeSource.php b/lib/RoadizCoreBundle/src/SearchEngine/SolariumNodeSource.php index 0c9ecf23..289e1aec 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SolariumNodeSource.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SolariumNodeSource.php @@ -28,7 +28,7 @@ public function __construct( ClientRegistry $clientRegistry, EventDispatcherInterface $dispatcher, LoggerInterface $searchEngineLogger, - MarkdownInterface $markdown + MarkdownInterface $markdown, ) { parent::__construct($clientRegistry, $searchEngineLogger, $markdown); $this->nodeSource = $nodeSource; @@ -45,7 +45,6 @@ public function getDocumentId(): int|string * * @param bool $subResource Tell when this field gathering is for a main resource indexation or a sub-resource * - * @return array * @throws \Exception */ public function getFieldsAssoc(bool $subResource = false): array @@ -53,21 +52,19 @@ public function getFieldsAssoc(bool $subResource = false): array $event = new NodesSourcesIndexingEvent($this->nodeSource, [], $this); /** @var NodesSourcesIndexingEvent $event */ $event = $this->dispatcher->dispatch($event); + return $event->getAssociations(); } /** * Remove any document linked to current node-source. - * - * @param Query $update - * @return bool */ public function clean(Query $update): bool { $update->addDeleteQuery( - static::IDENTIFIER_KEY . ':"' . $this->nodeSource->getId() . '"' . - '&' . static::TYPE_DISCRIMINATOR . ':"' . static::DOCUMENT_TYPE . '"' . - '&locale_s:"' . $this->nodeSource->getTranslation()->getLocale() . '"' + static::IDENTIFIER_KEY.':"'.$this->nodeSource->getId().'"'. + '&'.static::TYPE_DISCRIMINATOR.':"'.static::DOCUMENT_TYPE.'"'. + '&locale_s:"'.$this->nodeSource->getTranslation()->getLocale().'"' ); return true; @@ -78,6 +75,7 @@ protected function getIdempotentIdentifier(): string $namespace = explode('\\', get_class($this->nodeSource)); // get last 3 parts of namespace $namespace = array_slice($namespace, -3); - return (new AsciiSlugger())->slug(implode(' ', $namespace))->lower()->snake() . '.' . $this->nodeSource->getId(); + + return (new AsciiSlugger())->slug(implode(' ', $namespace))->lower()->snake().'.'.$this->nodeSource->getId(); } } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResultItem.php b/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResultItem.php index ac474955..b25d94c6 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResultItem.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResultItem.php @@ -17,12 +17,12 @@ final class SolrSearchResultItem { /** - * @param T $item + * @param T $item * @param array> $highlighting */ public function __construct( private readonly object $item, - private readonly array $highlighting = [] + private readonly array $highlighting = [], ) { } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResults.php b/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResults.php index 50d7bc52..b08e049a 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResults.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/SolrSearchResults.php @@ -32,16 +32,13 @@ public function __construct( protected readonly array $response, #[JMS\Exclude] #[Ignore] - protected readonly ObjectManager $entityManager + protected readonly ObjectManager $entityManager, ) { $this->position = 0; $this->resultItems = null; } - /** - * @return int - */ - #[JMS\Groups(["search_results"])] + #[JMS\Groups(['search_results'])] #[JMS\VirtualProperty()] public function getResultCount(): int { @@ -50,13 +47,14 @@ public function getResultCount(): int ) { return (int) $this->response['response']['numFound']; } + return 0; } /** * @return array */ - #[JMS\Groups(["search_results"])] + #[JMS\Groups(['search_results'])] #[JMS\VirtualProperty()] public function getResultItems(): array { @@ -72,6 +70,7 @@ function (array $item) { return null; } $highlighting = $this->getHighlighting($item['id']); + return new SolrSearchResultItem( $object, $highlighting @@ -89,7 +88,6 @@ function (array $item) { * Get highlighting for one field. * This does not merge highlighting for all fields anymore. * - * @param string $id * @return array */ protected function getHighlighting(string $id): array @@ -97,22 +95,16 @@ protected function getHighlighting(string $id): array if (isset($this->response['highlighting'][$id]) && \is_array($this->response['highlighting'][$id])) { return $this->response['highlighting'][$id]; } + return []; } - /** - * @param callable $callable - * - * @return array - */ public function map(callable $callable): array { return array_map($callable, $this->getResultItems()); } /** - * @param array $item - * * @return array|object|null */ protected function getHydratedItem(array $item): mixed @@ -129,6 +121,7 @@ protected function getHydratedItem(array $item): mixed DocumentTranslation::class, $item[SolariumDocumentTranslation::IDENTIFIER_KEY] ); + return $documentTranslation?->getDocument(); } } @@ -137,10 +130,9 @@ protected function getHydratedItem(array $item): mixed } /** - * Return the current element + * Return the current element. * - * @link https://php.net/manual/en/iterator.current.php - * @return SolrSearchResultItem + * @see https://php.net/manual/en/iterator.current.php * @since 5.0 */ #[\ReturnTypeWillChange] @@ -150,10 +142,12 @@ public function current(): SolrSearchResultItem } /** - * Move forward to next element + * Move forward to next element. + * + * @see https://php.net/manual/en/iterator.next.php + * + * @return void any returned value is ignored * - * @link https://php.net/manual/en/iterator.next.php - * @return void Any returned value is ignored. * @since 5.0 */ public function next(): void @@ -162,10 +156,9 @@ public function next(): void } /** - * Return the key of the current element + * Return the key of the current element. * - * @link https://php.net/manual/en/iterator.key.php - * @return int + * @see https://php.net/manual/en/iterator.key.php * @since 5.0 */ #[\ReturnTypeWillChange] @@ -175,11 +168,13 @@ public function key(): int } /** - * Checks if current position is valid + * Checks if current position is valid. + * + * @see https://php.net/manual/en/iterator.valid.php * - * @link https://php.net/manual/en/iterator.valid.php * @return bool The return value will be casted to boolean and then evaluated. - * Returns true on success or false on failure. + * Returns true on success or false on failure. + * * @since 5.0 */ public function valid(): bool @@ -188,10 +183,12 @@ public function valid(): bool } /** - * Rewind the Iterator to the first element + * Rewind the Iterator to the first element. + * + * @see https://php.net/manual/en/iterator.rewind.php + * + * @return void any returned value is ignored * - * @link https://php.net/manual/en/iterator.rewind.php - * @return void Any returned value is ignored. * @since 5.0 */ public function rewind(): void diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AbstractIndexingSubscriber.php b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AbstractIndexingSubscriber.php index 3bb5c452..008ee936 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AbstractIndexingSubscriber.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AbstractIndexingSubscriber.php @@ -31,12 +31,13 @@ protected function formatGeoJsonFeature(mixed $geoJson): ?string } if ( - isset($geoJson['type']) && - $geoJson['type'] === 'Feature' && - isset($geoJson['geometry']['coordinates']) + isset($geoJson['type']) + && 'Feature' === $geoJson['type'] + && isset($geoJson['geometry']['coordinates']) ) { - return $geoJson['geometry']['coordinates'][1] . ',' . $geoJson['geometry']['coordinates'][0]; + return $geoJson['geometry']['coordinates'][1].','.$geoJson['geometry']['coordinates'][0]; } + return null; } @@ -52,15 +53,16 @@ protected function formatGeoJsonFeatureCollection(mixed $geoJson): ?array return null; } if ( - isset($geoJson['type']) && - $geoJson['type'] === 'FeatureCollection' && - isset($geoJson['features']) && - \count($geoJson['features']) > 0 + isset($geoJson['type']) + && 'FeatureCollection' === $geoJson['type'] + && isset($geoJson['features']) + && \count($geoJson['features']) > 0 ) { return array_filter(array_map(function ($feature) { return $this->formatGeoJsonFeature($feature); }, $geoJson['features'])); } + return null; } } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AttributeValueIndexingSubscriber.php b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AttributeValueIndexingSubscriber.php index 929a85e9..bb11e791 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AttributeValueIndexingSubscriber.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/AttributeValueIndexingSubscriber.php @@ -12,9 +12,6 @@ final class AttributeValueIndexingSubscriber extends AbstractIndexingSubscriber { - /** - * {@inheritdoc} - */ public static function getSubscribedEvents(): array { return [ @@ -33,7 +30,7 @@ public function onIndexing(NodesSourcesIndexingEvent $event): void ->getNode() ->getAttributesValuesForTranslation($event->getNodeSource()->getTranslation()); - if ($attributeValues->count() === 0) { + if (0 === $attributeValues->count()) { return; } @@ -80,7 +77,7 @@ public function onIndexing(NodesSourcesIndexingEvent $event): void $associations['collection_txt'][] = $content; if (null !== $lang) { // Compile all text content into a single localized text field. - $associations['collection_txt_' . $lang] = $this->flattenTextCollection($associations['collection_txt']); + $associations['collection_txt_'.$lang] = $this->flattenTextCollection($associations['collection_txt']); } break; case AttributeInterface::DATETIME_T: @@ -96,7 +93,7 @@ public function onIndexing(NodesSourcesIndexingEvent $event): void * with right language */ if (null !== $lang) { - $fieldName .= '_txt_' . $lang; + $fieldName .= '_txt_'.$lang; } else { $lang = null; $fieldName .= '_t'; @@ -111,7 +108,7 @@ public function onIndexing(NodesSourcesIndexingEvent $event): void $associations['collection_txt'][] = $content; if (null !== $lang) { // Compile all text content into a single localized text field. - $associations['collection_txt_' . $lang] = $this->flattenTextCollection($associations['collection_txt']); + $associations['collection_txt_'.$lang] = $this->flattenTextCollection($associations['collection_txt']); } } break; diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultDocumentTranslationIndexingSubscriber.php b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultDocumentTranslationIndexingSubscriber.php index a4da9db0..3b6ce386 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultDocumentTranslationIndexingSubscriber.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultDocumentTranslationIndexingSubscriber.php @@ -13,9 +13,6 @@ final class DefaultDocumentTranslationIndexingSubscriber extends AbstractIndexingSubscriber { - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ @@ -56,23 +53,23 @@ public function onIndexing(DocumentTranslationIndexingEvent $event): void */ $suffix = '_t'; if (in_array($lang, SolariumDocumentTranslation::$availableLocalizedTextFields)) { - $suffix = '_txt_' . $lang; + $suffix = '_txt_'.$lang; } $assoc['title'] = $documentTranslation->getName(); - $assoc['title' . $suffix] = $documentTranslation->getName(); + $assoc['title'.$suffix] = $documentTranslation->getName(); /* * Remove ctrl characters */ $description = $event->getSolariumDocument()->cleanTextContent($documentTranslation->getDescription()); - $assoc['description' . $suffix] = $description; + $assoc['description'.$suffix] = $description; - $assoc['copyright' . $suffix] = $documentTranslation->getCopyright(); + $assoc['copyright'.$suffix] = $documentTranslation->getCopyright(); $collection[] = $assoc['title']; - $collection[] = $assoc['description' . $suffix]; - $collection[] = $assoc['copyright' . $suffix]; + $collection[] = $assoc['description'.$suffix]; + $collection[] = $assoc['copyright'.$suffix]; /* * `tags_txt` Must store only public, visible and user-searchable content. @@ -92,7 +89,7 @@ public function onIndexing(DocumentTranslationIndexingEvent $event): void // Use tags_txt to be compatible with other data types $assoc['tags_txt'] = $visibleFolderNames; // Compile all tags names into a single localized text field. - $assoc['tags_txt_' . $lang] = implode(' ', $visibleFolderNames); + $assoc['tags_txt_'.$lang] = implode(' ', $visibleFolderNames); /* * `all_tags_slugs_ss` can store all folders, even technical one, this fields should not user searchable. @@ -112,7 +109,7 @@ public function onIndexing(DocumentTranslationIndexingEvent $event): void */ $assoc['collection_txt'] = $collection; // Compile all text content into a single localized text field. - $assoc['collection_txt_' . $lang] = $this->flattenTextCollection($collection); + $assoc['collection_txt_'.$lang] = $this->flattenTextCollection($collection); $event->setAssociations($assoc); } } diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultNodesSourcesIndexingSubscriber.php b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultNodesSourcesIndexingSubscriber.php index f86bb8e1..7c7bedfd 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultNodesSourcesIndexingSubscriber.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/DefaultNodesSourcesIndexingSubscriber.php @@ -13,9 +13,6 @@ final class DefaultNodesSourcesIndexingSubscriber extends AbstractIndexingSubscriber { - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ @@ -46,7 +43,7 @@ public function onIndexing(NodesSourcesIndexingEvent $event): void */ $title = $event->getSolariumDocument()->cleanTextContent($nodeSource->getTitle(), false); $assoc['title'] = $title; - $assoc['title_txt_' . $lang] = $title; + $assoc['title_txt_'.$lang] = $title; /* * Do not index locale and tags if this is a sub-resource @@ -62,7 +59,7 @@ public function onIndexing(NodesSourcesIndexingEvent $event): void $assoc['updated_at_dt'] = $this->formatDateTimeToUTC($node->getUpdatedAt()); if (null !== $nodeSource->getPublishedAt()) { - $assoc['published_at_dt'] = $this->formatDateTimeToUTC($nodeSource->getPublishedAt()); + $assoc['published_at_dt'] = $this->formatDateTimeToUTC($nodeSource->getPublishedAt()); } if ($this->canIndexTitleInCollection($nodeSource)) { @@ -86,6 +83,7 @@ function (Tag $tag) use ($event, $nodeSource) { $tagName = $translatedTag ? $translatedTag->getName() : $tag->getTagName(); + return $event->getSolariumDocument()->cleanTextContent($tagName, false); }, $nodeSource->getNode()->getTags()->filter(function (Tag $tag) { @@ -96,7 +94,7 @@ function (Tag $tag) use ($event, $nodeSource) { // Use tags_txt to be compatible with other data types $assoc['tags_txt'] = $out; // Compile all tags names into a single localized text field. - $assoc['tags_txt_' . $lang] = implode(' ', $out); + $assoc['tags_txt_'.$lang] = implode(' ', $out); /* * `all_tags_slugs_ss` can store all tags, even technical one, this fields should not user searchable. @@ -182,7 +180,7 @@ function (Tag $tag) { * with right language */ if (in_array($lang, SolariumNodeSource::$availableLocalizedTextFields)) { - $name .= '_txt_' . $lang; + $name .= '_txt_'.$lang; } else { $name .= '_t'; } @@ -196,16 +194,12 @@ function (Tag $tag) { */ $assoc['collection_txt'] = $collection; // Compile all text content into a single localized text field. - $assoc['collection_txt_' . $lang] = $this->flattenTextCollection($collection); + $assoc['collection_txt_'.$lang] = $this->flattenTextCollection($collection); $event->setAssociations($assoc); } /** * @param iterable $fields - * @param string $suffix - * @param NodesSources $nodeSource - * @param array $assoc - * @return void */ protected function indexSuffixedFields(iterable $fields, string $suffix, NodesSources $nodeSource, array &$assoc): void { @@ -222,17 +216,13 @@ protected function indexSuffixedFields(iterable $fields, string $suffix, NodesSo } } - /** - * @param NodesSources $source - * @return bool - */ protected function canIndexTitleInCollection(NodesSources $source): bool { if (method_exists($source, 'getHideTitle')) { return !((bool) $source->getHideTitle()); } if (method_exists($source, 'getShowTitle')) { - return ((bool) $source->getShowTitle()); + return (bool) $source->getShowTitle(); } return $source->getNode()->getNodeType()->isSearchable(); diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/SolariumSubscriber.php b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/SolariumSubscriber.php index 397b1455..500eddb1 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/SolariumSubscriber.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/SolariumSubscriber.php @@ -63,9 +63,6 @@ public static function getSubscribedEvents(): array ]; } - /** - * @param Event $event - */ public function onSolariumNodeWorkflowComplete(Event $event): void { $node = $event->getSubject(); @@ -77,8 +74,6 @@ public function onSolariumNodeWorkflowComplete(Event $event): void /** * Update or create Solr document for current Node-source. * - * @param NodesSourcesUpdatedEvent $event - * * @throws \Exception */ public function onSolariumSingleUpdate(NodesSourcesUpdatedEvent $event): void @@ -88,8 +83,6 @@ public function onSolariumSingleUpdate(NodesSourcesUpdatedEvent $event): void /** * Delete solr document for current Node-source. - * - * @param NodesSourcesDeletedEvent $event */ public function onSolariumSingleDelete(NodesSourcesDeletedEvent $event): void { @@ -98,8 +91,6 @@ public function onSolariumSingleDelete(NodesSourcesDeletedEvent $event): void /** * Delete solr documents for each Node sources. - * - * @param NodeDeletedEvent $event */ public function onSolariumNodeDelete(NodeDeletedEvent $event): void { @@ -109,8 +100,6 @@ public function onSolariumNodeDelete(NodeDeletedEvent $event): void /** * Update or create solr documents for each Node sources. * - * @param FilterNodeEvent $event - * * @throws \Exception */ public function onSolariumNodeUpdate(FilterNodeEvent $event): void @@ -118,11 +107,8 @@ public function onSolariumNodeUpdate(FilterNodeEvent $event): void $this->messageBus->dispatch(new Envelope(new SolrReindexMessage(Node::class, $event->getNode()->getId()))); } - /** * Delete solr documents for each Document translation. - * - * @param FilterDocumentEvent $event */ public function onSolariumDocumentDelete(FilterDocumentEvent $event): void { @@ -135,8 +121,6 @@ public function onSolariumDocumentDelete(FilterDocumentEvent $event): void /** * Update or create solr documents for each Document translation. * - * @param FilterDocumentEvent $event - * * @throws \Exception */ public function onSolariumDocumentUpdate(FilterDocumentEvent $event): void @@ -150,9 +134,8 @@ public function onSolariumDocumentUpdate(FilterDocumentEvent $event): void /** * Update solr documents linked to current event Tag. * - * @param TagUpdatedEvent $event - * * @throws \Exception + * * @deprecated This can lead to a timeout if more than 500 nodes use that tag! */ public function onSolariumTagUpdate(TagUpdatedEvent $event): void @@ -163,9 +146,8 @@ public function onSolariumTagUpdate(TagUpdatedEvent $event): void /** * Update solr documents linked to current event Folder. * - * @param FolderUpdatedEvent $event - * * @throws \Exception + * * @deprecated This can lead to a timeout if more than 500 documents use that folder! */ public function onSolariumFolderUpdate(FolderUpdatedEvent $event): void diff --git a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/TreeWalkerIndexingEventSubscriber.php b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/TreeWalkerIndexingEventSubscriber.php index cc104e46..310d437b 100644 --- a/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/TreeWalkerIndexingEventSubscriber.php +++ b/lib/RoadizCoreBundle/src/SearchEngine/Subscriber/TreeWalkerIndexingEventSubscriber.php @@ -20,13 +20,10 @@ public function __construct( private readonly WalkerContextInterface $walkerContext, private readonly SolariumFactoryInterface $solariumFactory, private readonly int $maxLevel = 5, - private readonly string $defaultLocale = 'en' + private readonly string $defaultLocale = 'en', ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ @@ -64,9 +61,6 @@ public function onIndexing(NodesSourcesIndexingEvent $event): void } /** - * @param WalkerInterface $walker - * @param array $assoc - * @param string $locale * @throws \Exception */ protected function walkAndIndex(WalkerInterface $walker, array &$assoc, string $locale): void @@ -80,7 +74,7 @@ protected function walkAndIndex(WalkerInterface $walker, array &$assoc, string $ $assoc['collection_txt'], $childAssoc['collection_txt'] )); - $assoc['collection_txt_' . $locale] = $this->flattenTextCollection($assoc['collection_txt']); + $assoc['collection_txt_'.$locale] = $this->flattenTextCollection($assoc['collection_txt']); } if ($walker->count() > 0) { foreach ($walker->getChildren() as $subWalker) { diff --git a/lib/RoadizCoreBundle/src/Security/Authentication/BackofficeAuthenticationSuccessHandler.php b/lib/RoadizCoreBundle/src/Security/Authentication/BackofficeAuthenticationSuccessHandler.php index 01844589..61402417 100644 --- a/lib/RoadizCoreBundle/src/Security/Authentication/BackofficeAuthenticationSuccessHandler.php +++ b/lib/RoadizCoreBundle/src/Security/Authentication/BackofficeAuthenticationSuccessHandler.php @@ -17,12 +17,10 @@ final class BackofficeAuthenticationSuccessHandler implements AuthenticationSucc { public function __construct( private readonly UrlGeneratorInterface $urlGenerator, - private readonly ManagerRegistry $managerRegistry + private readonly ManagerRegistry $managerRegistry, ) { } - /** - * @inheritDoc - */ + public function onAuthenticationSuccess(Request $request, TokenInterface $token): ?Response { $user = $token->getUser(); diff --git a/lib/RoadizCoreBundle/src/Security/Authentication/RoadizAuthenticator.php b/lib/RoadizCoreBundle/src/Security/Authentication/RoadizAuthenticator.php index 5d58b3cc..a4ab0d1f 100644 --- a/lib/RoadizCoreBundle/src/Security/Authentication/RoadizAuthenticator.php +++ b/lib/RoadizCoreBundle/src/Security/Authentication/RoadizAuthenticator.php @@ -36,7 +36,7 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly LoggerInterface $logger, private readonly string $usernamePath = 'username', - private readonly string $passwordPath = 'password' + private readonly string $passwordPath = 'password', ) { } @@ -78,20 +78,18 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio $ipAddress = $request->getClientIp(); $this->logger->error($exception->getMessage(), [ 'username' => $credentials['username'], - 'ipAddress' => $ipAddress + 'ipAddress' => $ipAddress, ]); return parent::onAuthenticationFailure($request, $exception); } - protected function getLoginUrl(Request $request): string { return $this->urlGenerator->generate(self::LOGIN_ROUTE); } /** - * @param Request $request * @return array<'username'|'password', string> */ private function getCredentials(Request $request): array diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/AccessDeniedHandler.php b/lib/RoadizCoreBundle/src/Security/Authorization/AccessDeniedHandler.php index f1bab71c..6172dc1f 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/AccessDeniedHandler.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/AccessDeniedHandler.php @@ -23,29 +23,26 @@ public function __construct( private readonly UrlGeneratorInterface $urlGenerator, private readonly ?LoggerInterface $logger, private readonly string $redirectRoute = '', - private readonly array $redirectParameters = [] + private readonly array $redirectParameters = [], ) { } /** - * Handles access denied failure redirecting to home page - * - * @param Request $request - * @param AccessDeniedException $accessDeniedException + * Handles access denied failure redirecting to home page. * * @return Response|null may return null */ public function handle(Request $request, AccessDeniedException $accessDeniedException): ?Response { - $this->logger->error('User tried to access: ' . $request->getUri()); + $this->logger->error('User tried to access: '.$request->getUri()); - $returnJson = $request->isXmlHttpRequest() || - $request->getRequestFormat() === 'json' || - ( - count($request->getAcceptableContentTypes()) === 1 && - $request->getAcceptableContentTypes()[0] === 'application/json' - ) || - ($request->attributes->has('_format') && $request->attributes->get('_format') === 'json'); + $returnJson = $request->isXmlHttpRequest() + || 'json' === $request->getRequestFormat() + || ( + 1 === count($request->getAcceptableContentTypes()) + && 'application/json' === $request->getAcceptableContentTypes()[0] + ) + || ($request->attributes->has('_format') && 'json' === $request->attributes->get('_format')); if ($returnJson) { return new JsonResponse( @@ -62,6 +59,7 @@ public function handle(Request $request, AccessDeniedException $accessDeniedExce } else { $redirectUrl = $request->getBaseUrl(); } + // Forbidden code should be set on final response, not the redirection! return new RedirectResponse($redirectUrl, Response::HTTP_FOUND); } diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootChainResolver.php b/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootChainResolver.php index e6f32657..2d3f79bf 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootChainResolver.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootChainResolver.php @@ -11,8 +11,6 @@ /** * Loops over NodeChrootResolver implementations to find the right one supporting * a given UserInterface or string User representation (from a Token for example). - * - * @package RZ\Roadiz\CoreBundle\Security\Authorization\Chroot */ final class NodeChrootChainResolver implements NodeChrootResolver { @@ -20,15 +18,13 @@ public function __construct(private readonly array $resolvers) { foreach ($this->resolvers as $resolver) { if (!($resolver instanceof NodeChrootResolver)) { - throw new \InvalidArgumentException('Resolver must implements ' . NodeChrootResolver::class); + throw new \InvalidArgumentException('Resolver must implements '.NodeChrootResolver::class); } } } /** * @param User|UserInterface|string|null $user - * - * @return Node|null */ public function getChroot(mixed $user): ?Node { @@ -38,13 +34,12 @@ public function getChroot(mixed $user): ?Node return $resolver->getChroot($user); } } + return null; } /** * @param User|UserInterface|string|null $user - * - * @return bool */ public function supports(mixed $user): bool { @@ -54,6 +49,7 @@ public function supports(mixed $user): bool return true; } } + return false; } } diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootResolver.php b/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootResolver.php index bff72072..4f9d4a75 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootResolver.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/NodeChrootResolver.php @@ -12,22 +12,10 @@ * * This enables third-party User from OAuth2 or SSO to be locked using their * own business logic, without need of a Roadiz User. - * - * @package RZ\Roadiz\CoreBundle\Security\Authorization\Chroot */ interface NodeChrootResolver { - /** - * @param mixed $user - * - * @return bool - */ public function supports(mixed $user): bool; - /** - * @param mixed $user - * - * @return Node|null - */ public function getChroot(mixed $user): ?Node; } diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/RoadizUserNodeChrootResolver.php b/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/RoadizUserNodeChrootResolver.php index 4e226260..17023eba 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/RoadizUserNodeChrootResolver.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Chroot/RoadizUserNodeChrootResolver.php @@ -9,8 +9,6 @@ /** * Classic Roadiz User chroot from Doctrine relation. - * - * @package RZ\Roadiz\CoreBundle\Security\Authorization\Chroot */ final class RoadizUserNodeChrootResolver implements NodeChrootResolver { @@ -21,8 +19,6 @@ public function supports(mixed $user): bool /** * @param User $user - * - * @return Node|null */ public function getChroot(mixed $user): ?Node { diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/GroupVoter.php b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/GroupVoter.php index a6d8a341..8bfda235 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/GroupVoter.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/GroupVoter.php @@ -28,9 +28,6 @@ protected function extractRoles(TokenInterface $token): array return $this->roleHierarchy->getReachableRoleNames($token->getRoleNames()); } - /** - * @inheritDoc - */ public function vote(TokenInterface $token, $subject, array $attributes): int { $result = VoterInterface::ACCESS_ABSTAIN; @@ -54,8 +51,8 @@ public function vote(TokenInterface $token, $subject, array $attributes): int * If user is part of current tested group, grant it. */ if ( - $user instanceof User && - $user->getGroups()->exists(function ($key, Group $group) use ($attribute) { + $user instanceof User + && $user->getGroups()->exists(function ($key, Group $group) use ($attribute) { return $attribute->getId() === $group->getId(); }) ) { @@ -76,8 +73,6 @@ public function vote(TokenInterface $token, $subject, array $attributes): int } /** - * @param Group $group - * * @return string[] */ protected function extractGroupRoles(Group $group): array @@ -86,10 +81,7 @@ protected function extractGroupRoles(Group $group): array } /** - * @param string $role * @param string[] $roles - * - * @return bool */ protected function isRoleContained(string $role, array $roles): bool { diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeTypeFieldVoter.php b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeTypeFieldVoter.php index eb55732c..a0b35cbf 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeTypeFieldVoter.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeTypeFieldVoter.php @@ -15,7 +15,7 @@ final class NodeTypeFieldVoter extends Voter public const VIEW = 'VIEW'; public function __construct( - private readonly Security $security + private readonly Security $security, ) { } @@ -24,6 +24,7 @@ protected function supports(string $attribute, mixed $subject): bool if (!\in_array($attribute, [self::VIEW])) { return false; } + return $subject instanceof NodeTypeField; } @@ -38,7 +39,7 @@ protected function voteOnAttribute(string $attribute, mixed $subject, TokenInter return match ($attribute) { self::VIEW => $this->canView($subject, $user), - default => throw new \LogicException('This code should not be reached!') + default => throw new \LogicException('This code should not be reached!'), }; } diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeVoter.php b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeVoter.php index f8e6c97b..0cc9115f 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeVoter.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/NodeVoter.php @@ -46,10 +46,10 @@ protected function supports(string $attribute, mixed $subject): bool { if ( \in_array($attribute, [ - self::CREATE_AT_ROOT, - self::READ_AT_ROOT, - self::SEARCH, - self::EMPTY_TRASH, + self::CREATE_AT_ROOT, + self::READ_AT_ROOT, + self::SEARCH, + self::EMPTY_TRASH, ]) ) { return true; @@ -57,17 +57,17 @@ protected function supports(string $attribute, mixed $subject): bool if ( !\in_array($attribute, [ - self::CREATE, - self::DUPLICATE, - self::READ, - self::READ_LOGS, - self::EDIT_CONTENT, - self::EDIT_SETTING, - self::EDIT_TAGS, - self::EDIT_REALMS, - self::EDIT_STATUS, - self::EDIT_ATTRIBUTE, - self::DELETE + self::CREATE, + self::DUPLICATE, + self::READ, + self::READ_LOGS, + self::EDIT_CONTENT, + self::EDIT_SETTING, + self::EDIT_TAGS, + self::EDIT_REALMS, + self::EDIT_STATUS, + self::EDIT_ATTRIBUTE, + self::DELETE, ]) ) { return false; @@ -109,7 +109,7 @@ protected function voteOnAttribute(string $attribute, mixed $subject, TokenInter self::EDIT_ATTRIBUTE => $this->canEditAttribute($subject, $user), self::DELETE => $this->canDelete($subject, $user), self::EMPTY_TRASH => $this->canEmptyTrash($user), - default => throw new \LogicException('This code should not be reached!') + default => throw new \LogicException('This code should not be reached!'), }; } @@ -133,19 +133,21 @@ private function isGrantedWithUserChroot(NodeInterface $node, UserInterface $use return $this->security->isGranted($roles); } - return $this->security->isGranted($roles) && - $this->isNodeInsideUserChroot($node, $chroot, $includeChroot); + return $this->security->isGranted($roles) + && $this->isNodeInsideUserChroot($node, $chroot, $includeChroot); } private function canCreateAtRoot(UserInterface $user): bool { $chroot = $this->chrootResolver->getChroot($user); + return null === $chroot && $this->security->isGranted('ROLE_ACCESS_NODES'); } private function canReadAtRoot(UserInterface $user): bool { $chroot = $this->chrootResolver->getChroot($user); + return null === $chroot && $this->security->isGranted('ROLE_ACCESS_NODES'); } @@ -160,10 +162,10 @@ private function canSearch(UserInterface $user): bool private function canEmptyTrash(UserInterface $user): bool { $chroot = $this->chrootResolver->getChroot($user); + return null === $chroot && $this->security->isGranted('ROLE_ACCESS_NODES_DELETE'); } - private function canCreate(NodeInterface $node, UserInterface $user): bool { /* diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RealmVoter.php b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RealmVoter.php index 204508da..7e3c2bdd 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RealmVoter.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RealmVoter.php @@ -21,13 +21,13 @@ final class RealmVoter extends Voter public function __construct( private readonly Security $security, - private readonly RequestStack $requestStack + private readonly RequestStack $requestStack, ) { } public function supportsAttribute(string $attribute): bool { - return $attribute === self::READ; + return self::READ === $attribute; } protected function supports(string $attribute, mixed $subject): bool @@ -36,10 +36,7 @@ protected function supports(string $attribute, mixed $subject): bool } /** - * @param string $attribute * @param RealmInterface $subject - * @param TokenInterface $token - * @return bool */ public function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool { @@ -51,49 +48,34 @@ public function voteOnAttribute(string $attribute, mixed $subject, TokenInterfac }; } - /** - * @param string $attribute - * @param RealmInterface $subject - * @param TokenInterface $token - * @return bool - */ private function voteForRole(string $attribute, RealmInterface $subject, TokenInterface $token): bool { if (null === $role = $subject->getRole()) { return false; } + return $this->security->isGranted($role); } - /** - * @param string $attribute - * @param RealmInterface $subject - * @param TokenInterface $token - * @return bool - */ private function voteForUser(string $attribute, RealmInterface $subject, TokenInterface $token): bool { - if ($subject->getUsers()->count() === 0 || null === $token->getUser()) { + if (0 === $subject->getUsers()->count() || null === $token->getUser()) { return false; } + return $subject->getUsers()->exists(function ($key, UserInterface $user) use ($token) { return $user->getUserIdentifier() === $token->getUserIdentifier(); }); } - /** - * @param string $attribute - * @param RealmInterface $subject - * @param TokenInterface $token - * @return bool - */ private function voteForPassword(string $attribute, RealmInterface $subject, TokenInterface $token): bool { $request = $this->requestStack->getCurrentRequest(); if (null === $request || empty($subject->getPlainPassword())) { return false; } - return $request->query->has(self::PASSWORD_QUERY_PARAMETER) && - $request->query->get(self::PASSWORD_QUERY_PARAMETER) === $subject->getPlainPassword(); + + return $request->query->has(self::PASSWORD_QUERY_PARAMETER) + && $request->query->get(self::PASSWORD_QUERY_PARAMETER) === $subject->getPlainPassword(); } } diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RoleArrayVoter.php b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RoleArrayVoter.php index b373a3c2..27015f63 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RoleArrayVoter.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/RoleArrayVoter.php @@ -13,9 +13,6 @@ */ class RoleArrayVoter extends RoleVoter { - /** - * {@inheritdoc} - */ public function vote(TokenInterface $token, $subject, array $attributes): int { if (isset($attributes[0]) && !\is_array($attributes[0])) { diff --git a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/SuperAdminRoleHierarchyVoter.php b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/SuperAdminRoleHierarchyVoter.php index b7c6dac5..e1b45baf 100644 --- a/lib/RoadizCoreBundle/src/Security/Authorization/Voter/SuperAdminRoleHierarchyVoter.php +++ b/lib/RoadizCoreBundle/src/Security/Authorization/Voter/SuperAdminRoleHierarchyVoter.php @@ -24,15 +24,17 @@ protected function extractRoles(TokenInterface $token): array $this->managerRegistry->getRepository(Role::class)->getAllBasicRoleName() ); } + return $roleNames; } private function isSuperAdmin(TokenInterface $token): bool { $roleNames = parent::extractRoles($token); - return ( - \in_array('ROLE_SUPER_ADMIN', $roleNames) || - \in_array('ROLE_SUPERADMIN', $roleNames) - ); + + return + \in_array('ROLE_SUPER_ADMIN', $roleNames) + || \in_array('ROLE_SUPERADMIN', $roleNames) + ; } } diff --git a/lib/RoadizCoreBundle/src/Security/Blacklist/Top500Provider.php b/lib/RoadizCoreBundle/src/Security/Blacklist/Top500Provider.php index 34404252..07f63c45 100644 --- a/lib/RoadizCoreBundle/src/Security/Blacklist/Top500Provider.php +++ b/lib/RoadizCoreBundle/src/Security/Blacklist/Top500Provider.php @@ -11,9 +11,6 @@ */ final class Top500Provider extends ArrayProvider { - /** - * @inheritDoc - */ public function __construct() { parent::__construct([ diff --git a/lib/RoadizCoreBundle/src/Security/LoginLink/EmailLoginLinkSender.php b/lib/RoadizCoreBundle/src/Security/LoginLink/EmailLoginLinkSender.php index d58c49eb..b0b8abdc 100644 --- a/lib/RoadizCoreBundle/src/Security/LoginLink/EmailLoginLinkSender.php +++ b/lib/RoadizCoreBundle/src/Security/LoginLink/EmailLoginLinkSender.php @@ -18,11 +18,11 @@ public function __construct( private EmailManagerFactory $emailManagerFactory, private TranslatorInterface $translator, private string $htmlTemplate = '@RoadizCore/email/users/login_link_email.html.twig', - private string $txtTemplate = '@RoadizCore/email/users/login_link_email.txt.twig' + private string $txtTemplate = '@RoadizCore/email/users/login_link_email.txt.twig', ) { } - public function sendLoginLink(UserInterface $user, LoginLinkDetails $loginLinkDetails,): void + public function sendLoginLink(UserInterface $user, LoginLinkDetails $loginLinkDetails): void { if ($user instanceof User && !$user->isEnabled()) { throw new \InvalidArgumentException('User must be enabled to send a login link.'); diff --git a/lib/RoadizCoreBundle/src/Security/User/AdvancedUserInterface.php b/lib/RoadizCoreBundle/src/Security/User/AdvancedUserInterface.php index 4409f9d2..b3852687 100644 --- a/lib/RoadizCoreBundle/src/Security/User/AdvancedUserInterface.php +++ b/lib/RoadizCoreBundle/src/Security/User/AdvancedUserInterface.php @@ -7,7 +7,10 @@ interface AdvancedUserInterface { public function isAccountNonExpired(): bool; + public function isAccountNonLocked(): bool; + public function isCredentialsNonExpired(): bool; + public function isEnabled(): bool; } diff --git a/lib/RoadizCoreBundle/src/Security/User/UserProvider.php b/lib/RoadizCoreBundle/src/Security/User/UserProvider.php index 5b84c38a..f7e254d7 100644 --- a/lib/RoadizCoreBundle/src/Security/User/UserProvider.php +++ b/lib/RoadizCoreBundle/src/Security/User/UserProvider.php @@ -18,8 +18,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) } /** - * @param string $username - * @return UserInterface * @deprecated since Symfony 5.3, use loadUserByIdentifier() instead */ public function loadUserByUsername(string $username): UserInterface @@ -34,14 +32,14 @@ protected function loadUserByUsernameOrEmail(string $identifier): UserInterface ->getRepository(User::class) ->findOneBy(['username' => $identifier]); - if ($user === null) { + if (null === $user) { /** @var User|null $user */ $user = $this->managerRegistry ->getRepository(User::class) ->findOneBy(['email' => $identifier]); } - if ($user !== null) { + if (null !== $user) { return $user; } else { throw new UserNotFoundException(); @@ -61,8 +59,8 @@ public function loadUserByIdentifier(string $identifier): UserInterface * object can just be merged into some internal array of users / identity * map. * - * @param UserInterface $user * @return User + * * @throws UnsupportedUserException */ public function refreshUser(UserInterface $user): UserInterface @@ -72,10 +70,10 @@ public function refreshUser(UserInterface $user): UserInterface /** @var User|null $refreshUser */ $refreshUser = $manager->find(User::class, (int) $user->getId()); if ( - $refreshUser !== null && - $refreshUser->isEnabled() && - $refreshUser->isAccountNonExpired() && - $refreshUser->isAccountNonLocked() + null !== $refreshUser + && $refreshUser->isEnabled() + && $refreshUser->isAccountNonExpired() + && $refreshUser->isAccountNonLocked() ) { // Always refresh User from database: too much related entities to rely only on token. return $refreshUser; @@ -87,13 +85,12 @@ public function refreshUser(UserInterface $user): UserInterface } /** - * Whether this provider supports the given user class + * Whether this provider supports the given user class. * * @param class-string $class - * @return bool */ public function supportsClass($class): bool { - return $class === User::class; + return User::class === $class; } } diff --git a/lib/RoadizCoreBundle/src/Security/User/UserViewer.php b/lib/RoadizCoreBundle/src/Security/User/UserViewer.php index fbc03f10..d2a52e2c 100644 --- a/lib/RoadizCoreBundle/src/Security/User/UserViewer.php +++ b/lib/RoadizCoreBundle/src/Security/User/UserViewer.php @@ -24,26 +24,20 @@ public function __construct( private readonly TranslatorInterface $translator, private readonly EmailManagerFactory $emailManagerFactory, private readonly LoggerInterface $logger, - private readonly LoginLinkSenderInterface $loginLinkSender + private readonly LoginLinkSenderInterface $loginLinkSender, ) { } /** * Send email to reset user password. * - * @param User $user - * @param object|string $route - * @param string $htmlTemplate - * @param string $txtTemplate - * - * @return bool * @throws TransportExceptionInterface */ public function sendPasswordResetLink( User $user, object|string $route = 'loginResetPage', string $htmlTemplate = '@RoadizCore/email/users/reset_password_email.html.twig', - string $txtTemplate = '@RoadizCore/email/users/reset_password_email.txt.twig' + string $txtTemplate = '@RoadizCore/email/users/reset_password_email.txt.twig', ): bool { $emailManager = $this->emailManagerFactory->create(); $emailContact = $this->getContactEmail(); @@ -85,6 +79,7 @@ public function sendPasswordResetLink( // Send the message $emailManager->send(); + return true; } catch (\Exception $e) { // Silent error not to prevent user creation if mailer is not configured @@ -93,6 +88,7 @@ public function sendPasswordResetLink( 'message' => $e->getMessage(), 'entity' => $user, ]); + return false; } } @@ -104,32 +100,26 @@ public function sendLoginLink( UserInterface $user, LoginLinkDetails $loginLinkDetails, string $htmlTemplate = '@RoadizCore/email/users/login_link_email.html.twig', - string $txtTemplate = '@RoadizCore/email/users/login_link_email.txt.twig' + string $txtTemplate = '@RoadizCore/email/users/login_link_email.txt.twig', ): void { $this->loginLinkSender->sendLoginLink($user, $loginLinkDetails); } - /** - * @return string - */ protected function getContactEmail(): string { $emailContact = $this->settingsBag->get('email_sender') ?? ''; if (empty($emailContact)) { - $emailContact = "noreply@roadiz.io"; + $emailContact = 'noreply@roadiz.io'; } return $emailContact; } - /** - * @return string - */ protected function getSiteName(): string { $siteName = $this->settingsBag->get('site_name') ?? ''; if (empty($siteName)) { - $siteName = "Unnamed site"; + $siteName = 'Unnamed site'; } return $siteName; diff --git a/lib/RoadizCoreBundle/src/Serializer/CircularReferenceHandler.php b/lib/RoadizCoreBundle/src/Serializer/CircularReferenceHandler.php index 3fe75ab4..62dff123 100644 --- a/lib/RoadizCoreBundle/src/Serializer/CircularReferenceHandler.php +++ b/lib/RoadizCoreBundle/src/Serializer/CircularReferenceHandler.php @@ -26,6 +26,7 @@ public function __invoke(mixed $object, string $format, array $context): ?string if (is_object($object) && method_exists($object, 'getId')) { return (string) $object->getId(); } + return ''; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/AbstractPathNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/AbstractPathNormalizer.php index b8dc894b..c4a3b320 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/AbstractPathNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/AbstractPathNormalizer.php @@ -21,7 +21,7 @@ abstract class AbstractPathNormalizer implements NormalizerInterface, Denormaliz public function __construct( NormalizerInterface $decorated, protected readonly UrlGeneratorInterface $urlGenerator, - protected readonly Stopwatch $stopwatch + protected readonly Stopwatch $stopwatch, ) { if (!$decorated instanceof DenormalizerInterface) { throw new \InvalidArgumentException(sprintf('The decorated normalizer must implement the %s.', DenormalizerInterface::class)); @@ -30,25 +30,20 @@ public function __construct( $this->decorated = $decorated; } - public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool + public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool { - return $this->decorated->supportsNormalization($data, $format/*, $context*/); + return $this->decorated->supportsNormalization($data, $format/* , $context */); } - public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool + public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool { - return $this->decorated->supportsDenormalization($data, $type, $format/*, $context*/); + return $this->decorated->supportsDenormalization($data, $type, $format/* , $context */); } /** - * @param mixed $data - * @param string $type - * @param string|null $format - * @param array $context - * @return mixed * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ - public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed + public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed { return $this->decorated->denormalize($data, $type, $format, $context); } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/AttributeValueNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/AttributeValueNormalizer.php index 2769a69b..5e89ef2d 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/AttributeValueNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/AttributeValueNormalizer.php @@ -15,10 +15,8 @@ final class AttributeValueNormalizer extends AbstractPathNormalizer { /** - * @param mixed $object - * @param string|null $format - * @param array $context * @return array|\ArrayObject|bool|float|int|mixed|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed @@ -38,8 +36,8 @@ public function normalize(mixed $object, ?string $format = null, array $context $translatedData = $object->getAttributeValueTranslation($context['translation']); $data['label'] = $object->getAttribute()->getLabelOrCode($context['translation']); if ( - $translatedData instanceof AttributeValueTranslationInterface && - $translatedData->getValue() !== null + $translatedData instanceof AttributeValueTranslationInterface + && null !== $translatedData->getValue() ) { $data['value'] = $translatedData->getValue(); } else { @@ -60,6 +58,7 @@ public function normalize(mixed $object, ?string $format = null, array $context } $this->stopwatch->stop('normalizeAttributeValue'); } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/CustomFormNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/CustomFormNormalizer.php index 6faf3844..41f60cdd 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/CustomFormNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/CustomFormNormalizer.php @@ -12,11 +12,9 @@ */ final class CustomFormNormalizer extends AbstractPathNormalizer { - /** - * @param mixed $object - * @param string|null $format - * @param array $context + /** * @return array|\ArrayObject|bool|float|int|mixed|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed @@ -30,17 +28,18 @@ public function normalize(mixed $object, ?string $format = null, array $context $data['open'] = $object->isFormStillOpen(); if ( - isset($context['groups']) && - \in_array('urls', $context['groups'], true) + isset($context['groups']) + && \in_array('urls', $context['groups'], true) ) { $data['definitionUrl'] = $this->urlGenerator->generate('api_custom_forms_item_definition', [ - 'id' => $object->getId() + 'id' => $object->getId(), ]); $data['postUrl'] = $this->urlGenerator->generate('api_custom_forms_item_post', [ - 'id' => $object->getId() + 'id' => $object->getId(), ]); } } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentNormalizer.php index d255d37d..58018e81 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentNormalizer.php @@ -30,18 +30,16 @@ public function __construct( } /** - * @param mixed $object - * @param string|null $format - * @param array $context * @return array|\ArrayObject|bool|float|int|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed { $data = $this->decorated->normalize($object, $format, $context); if ( - $object instanceof Document && - is_array($data) + $object instanceof Document + && is_array($data) ) { $this->stopwatch->start('normalizeDocument', 'serializer'); /** @var array $serializationGroups */ @@ -49,8 +47,8 @@ public function normalize(mixed $object, ?string $format = null, array $context $data['type'] = $object->getShortType(); if ( - !$object->isPrivate() && - !$object->isProcessable() + !$object->isPrivate() + && !$object->isProcessable() ) { $mountPath = $object->getMountPath(); if (null !== $mountPath) { @@ -59,9 +57,9 @@ public function normalize(mixed $object, ?string $format = null, array $context } if ( - !$object->isPrivate() && - $object->isProcessable() && - null !== $alignment = $object->getImageCropAlignment() + !$object->isPrivate() + && $object->isProcessable() + && null !== $alignment = $object->getImageCropAlignment() ) { $data['imageCropAlignment'] = $alignment; } @@ -86,8 +84,8 @@ public function normalize(mixed $object, ?string $format = null, array $context } if ( - $object->getEmbedPlatform() && - $object->getEmbedId() + $object->getEmbedPlatform() + && $object->getEmbedId() ) { $embedFinder = $this->embedFinderFactory->createForPlatform( $object->getEmbedPlatform(), @@ -115,6 +113,7 @@ public function normalize(mixed $object, ?string $format = null, array $context $this->stopwatch->stop('normalizeDocument'); } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentSourcesNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentSourcesNormalizer.php index 827f3735..238d9ac7 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentSourcesNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/DocumentSourcesNormalizer.php @@ -22,10 +22,8 @@ public function __construct( } /** - * @param mixed $object - * @param string|null $format - * @param array $context * @return array|\ArrayObject|bool|float|int|mixed|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed @@ -59,6 +57,7 @@ public function normalize(mixed $object, ?string $format = null, array $context } } } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/FolderNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/FolderNormalizer.php index c9573a21..3290cb72 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/FolderNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/FolderNormalizer.php @@ -13,11 +13,9 @@ */ final class FolderNormalizer extends AbstractPathNormalizer { - /** - * @param mixed $object - * @param string|null $format - * @param array $context + /** * @return array|\ArrayObject|bool|float|int|mixed|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed @@ -35,6 +33,7 @@ public function normalize(mixed $object, ?string $format = null, array $context } } } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/NodesSourcesPathNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/NodesSourcesPathNormalizer.php index 7f66552a..53b98c3c 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/NodesSourcesPathNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/NodesSourcesPathNormalizer.php @@ -9,33 +9,32 @@ final class NodesSourcesPathNormalizer extends AbstractPathNormalizer { - /** - * @param mixed $object - * @param string|null $format - * @param array $context + /** * @return array|\ArrayObject|bool|float|int|mixed|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed { $data = $this->decorated->normalize($object, $format, $context); if ( - $object instanceof NodesSources && - $object->isReachable() && - \is_array($data) && - !isset($data['url']) && - isset($context['groups']) && - \in_array('urls', $context['groups'], true) + $object instanceof NodesSources + && $object->isReachable() + && \is_array($data) + && !isset($data['url']) + && isset($context['groups']) + && \in_array('urls', $context['groups'], true) ) { $this->stopwatch->start('normalizeNodesSourcesUrl', 'serializer'); $data['url'] = $this->urlGenerator->generate( RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ - RouteObjectInterface::ROUTE_OBJECT => $object + RouteObjectInterface::ROUTE_OBJECT => $object, ] ); $this->stopwatch->stop('normalizeNodesSourcesUrl'); } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/RealmSerializationGroupNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/RealmSerializationGroupNormalizer.php index a470c7eb..06713d95 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/RealmSerializationGroupNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/RealmSerializationGroupNormalizer.php @@ -23,14 +23,11 @@ final class RealmSerializationGroupNormalizer implements NormalizerInterface, No public function __construct( private readonly Security $security, private readonly RealmResolver $realmResolver, - private readonly Stopwatch $stopwatch + private readonly Stopwatch $stopwatch, ) { } - /** - * @inheritDoc - */ - public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool + public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool { if (!($data instanceof NodesSources)) { return false; @@ -51,7 +48,6 @@ public function getSupportedTypes(?string $format): array } /** - * @inheritDoc * @return array|string|int|float|bool|\ArrayObject|null */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/TagNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/TagNormalizer.php index 99a01547..4f690bb6 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/TagNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/TagNormalizer.php @@ -14,21 +14,19 @@ */ final class TagNormalizer extends AbstractPathNormalizer { - /** - * @param mixed $object - * @param string|null $format - * @param array $context + /** * @return array|\ArrayObject|bool|float|int|mixed|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed { $data = $this->decorated->normalize($object, $format, $context); if ( - $object instanceof Tag && - is_array($data) && - isset($context['translation']) && - $context['translation'] instanceof TranslationInterface + $object instanceof Tag + && is_array($data) + && isset($context['translation']) + && $context['translation'] instanceof TranslationInterface ) { $this->stopwatch->start('normalizeTag', 'serializer'); /** @var array $serializationGroups */ @@ -52,6 +50,7 @@ public function normalize(mixed $object, ?string $format = null, array $context } $this->stopwatch->stop('normalizeTag'); } + return $data; } } diff --git a/lib/RoadizCoreBundle/src/Serializer/Normalizer/TranslationAwareNormalizer.php b/lib/RoadizCoreBundle/src/Serializer/Normalizer/TranslationAwareNormalizer.php index eb1c3df2..3f840279 100644 --- a/lib/RoadizCoreBundle/src/Serializer/Normalizer/TranslationAwareNormalizer.php +++ b/lib/RoadizCoreBundle/src/Serializer/Normalizer/TranslationAwareNormalizer.php @@ -12,9 +12,9 @@ use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface; use RZ\Roadiz\CoreBundle\Repository\TranslationRepository; use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; final class TranslationAwareNormalizer implements NormalizerInterface, NormalizerAwareInterface { @@ -25,15 +25,13 @@ final class TranslationAwareNormalizer implements NormalizerInterface, Normalize public function __construct( private readonly RequestStack $requestStack, private readonly ManagerRegistry $managerRegistry, - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } /** - * @param mixed $object - * @param string|null $format - * @param array $context * @return array|\ArrayObject|bool|float|int|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize(mixed $object, ?string $format = null, array $context = []): mixed @@ -92,8 +90,8 @@ private function getTranslationFromRequest(): ?TranslationInterface $locale = $request->query->get('_locale', $request->getLocale()); if ( - \is_string($locale) && - null !== $translation = $this->getTranslationFromLocale($locale) + \is_string($locale) + && null !== $translation = $this->getTranslationFromLocale($locale) ) { return $translation; } @@ -101,7 +99,7 @@ private function getTranslationFromRequest(): ?TranslationInterface return null; } - public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool + public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool { // Make sure we're not called twice if (isset($context[self::ALREADY_CALLED])) { diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AbstractTypedObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AbstractTypedObjectConstructor.php index 476a75dd..39569646 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AbstractTypedObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AbstractTypedObjectConstructor.php @@ -15,48 +15,33 @@ abstract class AbstractTypedObjectConstructor implements TypedObjectConstructorI { public function __construct( protected readonly ObjectManager $entityManager, - protected readonly ObjectConstructorInterface $fallbackConstructor + protected readonly ObjectConstructorInterface $fallbackConstructor, ) { } - /** - * @param mixed $data - * @param DeserializationContext $context - * - * @return object|null - */ abstract protected function findObject(mixed $data, DeserializationContext $context): ?object; - /** - * @param object $object - * @param array $data - */ abstract protected function fillIdentifier(object $object, array $data): void; - /** - * @return bool - */ protected function canBeFlushed(): bool { return true; } - /** - * @inheritDoc - */ + public function construct( DeserializationVisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, - DeserializationContext $context + DeserializationContext $context, ): ?object { // Entity update, load it from database $object = $this->findObject($data, $context); if ( - null !== $object && - $context->hasAttribute(static::EXCEPTION_ON_EXISTING) && - true === $context->getAttribute(static::EXCEPTION_ON_EXISTING) + null !== $object + && $context->hasAttribute(static::EXCEPTION_ON_EXISTING) + && true === $context->getAttribute(static::EXCEPTION_ON_EXISTING) ) { throw new EntityAlreadyExistsException('Object already exists in database.'); } @@ -64,8 +49,8 @@ public function construct( if (null === $object) { $object = $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context); if ( - $context->hasAttribute(static::PERSIST_NEW_OBJECTS) && - true === $context->getAttribute(static::PERSIST_NEW_OBJECTS) + $context->hasAttribute(static::PERSIST_NEW_OBJECTS) + && true === $context->getAttribute(static::PERSIST_NEW_OBJECTS) ) { $this->entityManager->persist($object); } @@ -78,8 +63,8 @@ public function construct( $this->fillIdentifier($object, $data); if ( - $context->hasAttribute(static::FLUSH_NEW_OBJECTS) && - true === $context->getAttribute(static::FLUSH_NEW_OBJECTS) + $context->hasAttribute(static::FLUSH_NEW_OBJECTS) + && true === $context->getAttribute(static::FLUSH_NEW_OBJECTS) ) { $this->entityManager->flush(); } diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AttributeObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AttributeObjectConstructor.php index ba437452..70d66028 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AttributeObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/AttributeObjectConstructor.php @@ -13,19 +13,13 @@ final class AttributeObjectConstructor extends AbstractTypedObjectConstructor { public const EXCEPTION_ON_EXISTING = 'exception_on_existing_attribute'; - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return ( + return \is_subclass_of($className, AttributeInterface::class) - ) && \array_key_exists('code', $data); + && \array_key_exists('code', $data); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { if (empty($data['code'])) { @@ -36,9 +30,9 @@ protected function findObject(mixed $data, DeserializationContext $context): ?ob ->findOneByCode($data['code']); if ( - null !== $tag && - $context->hasAttribute(self::EXCEPTION_ON_EXISTING) && - true === $context->hasAttribute(self::EXCEPTION_ON_EXISTING) + null !== $tag + && $context->hasAttribute(self::EXCEPTION_ON_EXISTING) + && true === $context->hasAttribute(self::EXCEPTION_ON_EXISTING) ) { throw new EntityAlreadyExistsException('Attribute already exists in database.'); } diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ChainDoctrineObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ChainDoctrineObjectConstructor.php index eeff57cc..bd61f5e0 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ChainDoctrineObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ChainDoctrineObjectConstructor.php @@ -16,24 +16,19 @@ final class ChainDoctrineObjectConstructor implements ObjectConstructorInterface public function __construct( private readonly ?ObjectManager $entityManager, private readonly ObjectConstructorInterface $fallbackConstructor, - private readonly array $typedObjectConstructors + private readonly array $typedObjectConstructors, ) { } /** - * @param DeserializationVisitorInterface $visitor - * @param ClassMetadata $metadata * @param PersistableInterface|array $data - * @param array $type - * @param DeserializationContext $context - * @return object|null */ public function construct( DeserializationVisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, - DeserializationContext $context + DeserializationContext $context, ): ?object { if (null === $this->entityManager) { // No ObjectManager found, proceed with normal deserialization diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/GroupObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/GroupObjectConstructor.php index 9cd71848..6fdcb934 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/GroupObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/GroupObjectConstructor.php @@ -10,22 +10,17 @@ final class GroupObjectConstructor extends AbstractTypedObjectConstructor { - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return $className === Group::class && array_key_exists('name', $data); + return Group::class === $className && array_key_exists('name', $data); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { - if (null === $data['name'] || $data['name'] === '') { + if (null === $data['name'] || '' === $data['name']) { throw new ObjectConstructionException('Group name can not be empty'); } + return $this->entityManager->getRepository(Group::class)->findOneByName($data['name']); } @@ -34,9 +29,6 @@ protected function fillIdentifier(object $object, array $data): void trigger_error('Cannot call fillIdentifier on Group', E_USER_WARNING); } - /** - * @return bool - */ protected function canBeFlushed(): bool { return false; diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeObjectConstructor.php index ec0cc75c..9919cae3 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeObjectConstructor.php @@ -11,17 +11,11 @@ final class NodeObjectConstructor extends AbstractTypedObjectConstructor { - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return $className === Node::class && array_key_exists('nodeName', $data); + return Node::class === $className && array_key_exists('nodeName', $data); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { if (empty($data['nodeName']) && empty($data['node_name'])) { @@ -31,6 +25,7 @@ protected function findObject(mixed $data, DeserializationContext $context): ?ob $nodeRepository = $this->entityManager ->getRepository(Node::class) ->setDisplayingAllNodesStatuses(true); + return $nodeRepository->findOneByNodeName($data['nodeName'] ?? $data['node_name']); } diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeTypeObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeTypeObjectConstructor.php index 4d51fccd..18a4a37d 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeTypeObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/NodeTypeObjectConstructor.php @@ -11,23 +11,18 @@ final class NodeTypeObjectConstructor extends AbstractTypedObjectConstructor { - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return \is_subclass_of($className, NodeTypeInterface::class) && - array_key_exists('name', $data); + return \is_subclass_of($className, NodeTypeInterface::class) + && array_key_exists('name', $data); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { - if (null === $data['name'] || $data['name'] === '') { + if (null === $data['name'] || '' === $data['name']) { throw new ObjectConstructionException('NodeType name can not be empty'); } + return $this->entityManager ->getRepository(NodeType::class) ->findOneByName($data['name']); diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ObjectConstructor.php index b56536c5..5a8077b3 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/ObjectConstructor.php @@ -16,9 +16,10 @@ public function construct( ClassMetadata $metadata, $data, array $type, - DeserializationContext $context + DeserializationContext $context, ): ?object { $className = $metadata->name; + return new $className(); } } diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/RoleObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/RoleObjectConstructor.php index 00698c86..0e5d88f9 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/RoleObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/RoleObjectConstructor.php @@ -10,22 +10,17 @@ final class RoleObjectConstructor extends AbstractTypedObjectConstructor { - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return $className === Role::class && array_key_exists('name', $data); + return Role::class === $className && array_key_exists('name', $data); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { - if (null === $data['name'] || $data['name'] === '') { + if (null === $data['name'] || '' === $data['name']) { throw new ObjectConstructionException('Role name can not be empty'); } + return $this->entityManager ->getRepository(Role::class) ->findOneByName($data['name']); diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingGroupObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingGroupObjectConstructor.php index 19834d39..e202a606 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingGroupObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingGroupObjectConstructor.php @@ -10,22 +10,17 @@ final class SettingGroupObjectConstructor extends AbstractTypedObjectConstructor { - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return $className === SettingGroup::class && array_key_exists('name', $data); + return SettingGroup::class === $className && array_key_exists('name', $data); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { - if (null === $data['name'] || $data['name'] === '') { + if (null === $data['name'] || '' === $data['name']) { throw new ObjectConstructionException('SettingGroup name can not be empty'); } + return $this->entityManager ->getRepository(SettingGroup::class) ->findOneByName($data['name']); diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingObjectConstructor.php index c43a7384..77523e80 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/SettingObjectConstructor.php @@ -10,22 +10,17 @@ final class SettingObjectConstructor extends AbstractTypedObjectConstructor { - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return $className === Setting::class && array_key_exists('name', $data); + return Setting::class === $className && array_key_exists('name', $data); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { - if (null === $data['name'] || $data['name'] === '') { + if (null === $data['name'] || '' === $data['name']) { throw new ObjectConstructionException('Setting name can not be empty'); } + return $this->entityManager->getRepository(Setting::class)->findOneByName($data['name']); } diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TagObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TagObjectConstructor.php index cc984c9a..726601b8 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TagObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TagObjectConstructor.php @@ -13,20 +13,14 @@ final class TagObjectConstructor extends AbstractTypedObjectConstructor { public const EXCEPTION_ON_EXISTING_TAG = 'exception_on_existing_tag'; - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return $className === Tag::class && ( - \array_key_exists('tagName', $data) || - \array_key_exists('tag_name', $data) + return Tag::class === $className && ( + \array_key_exists('tagName', $data) + || \array_key_exists('tag_name', $data) ); } - /** - * @inheritDoc - */ protected function findObject(mixed $data, DeserializationContext $context): ?object { if (empty($data['tagName']) && empty($data['tag_name'])) { @@ -37,9 +31,9 @@ protected function findObject(mixed $data, DeserializationContext $context): ?ob ->findOneByTagName($data['tagName'] ?? $data['tag_name']); if ( - null !== $tag && - $context->hasAttribute(static::EXCEPTION_ON_EXISTING_TAG) && - true === $context->hasAttribute(static::EXCEPTION_ON_EXISTING_TAG) + null !== $tag + && $context->hasAttribute(static::EXCEPTION_ON_EXISTING_TAG) + && true === $context->hasAttribute(static::EXCEPTION_ON_EXISTING_TAG) ) { throw new EntityAlreadyExistsException('Tag already exists in database.'); } diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TranslationObjectConstructor.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TranslationObjectConstructor.php index 4bc72788..059b9fb7 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TranslationObjectConstructor.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TranslationObjectConstructor.php @@ -10,21 +10,15 @@ final class TranslationObjectConstructor extends AbstractTypedObjectConstructor { - /** - * @inheritDoc - */ public function supports(string $className, array $data): bool { - return \is_subclass_of($className, TranslationInterface::class) && - array_key_exists('locale', $data); + return \is_subclass_of($className, TranslationInterface::class) + && array_key_exists('locale', $data); } - /** - * @inheritDoc - */ - protected function findObject($data, DeserializationContext $context): ?object + protected function findObject(mixed $data, DeserializationContext $context): ?object { - if (null === $data['locale'] || $data['locale'] === '') { + if (null === $data['locale'] || '' === $data['locale']) { throw new ObjectConstructionException('Translation locale can not be empty'); } diff --git a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TypedObjectConstructorInterface.php b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TypedObjectConstructorInterface.php index 6e8460b3..2576fa22 100644 --- a/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TypedObjectConstructorInterface.php +++ b/lib/RoadizCoreBundle/src/Serializer/ObjectConstructor/TypedObjectConstructorInterface.php @@ -12,11 +12,5 @@ interface TypedObjectConstructorInterface extends ObjectConstructorInterface public const FLUSH_NEW_OBJECTS = 'flush_on_deserialize'; public const EXCEPTION_ON_EXISTING = 'exception_on_existing'; - /** - * @param string $className - * @param array $data - * - * @return bool - */ public function supports(string $className, array $data): bool; } diff --git a/lib/RoadizCoreBundle/src/Serializer/TranslationAwareContextBuilder.php b/lib/RoadizCoreBundle/src/Serializer/TranslationAwareContextBuilder.php index 8804fead..6f63866e 100644 --- a/lib/RoadizCoreBundle/src/Serializer/TranslationAwareContextBuilder.php +++ b/lib/RoadizCoreBundle/src/Serializer/TranslationAwareContextBuilder.php @@ -16,13 +16,11 @@ final class TranslationAwareContextBuilder implements SerializerContextBuilderIn public function __construct( private readonly SerializerContextBuilderInterface $decorated, private readonly ManagerRegistry $managerRegistry, - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } - /** - * @inheritDoc - */ - public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null): array + + public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array { $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes); @@ -37,6 +35,7 @@ public function createFromRequest(Request $request, bool $normalization, array $ $requestTranslation = $request->attributes->get('_translation'); if ($requestTranslation instanceof TranslationInterface) { $context['translation'] = $requestTranslation; + return $context; } diff --git a/lib/RoadizCoreBundle/src/Tag/TagFactory.php b/lib/RoadizCoreBundle/src/Tag/TagFactory.php index 9a7c79fa..b89738e5 100644 --- a/lib/RoadizCoreBundle/src/Tag/TagFactory.php +++ b/lib/RoadizCoreBundle/src/Tag/TagFactory.php @@ -18,12 +18,7 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) } /** - * @param string $name - * @param TranslationInterface|null $translation - * @param Tag|null $parent * @param int|float $latestPosition - * - * @return Tag */ public function create(string $name, ?TranslationInterface $translation = null, ?Tag $parent = null, $latestPosition = 0): Tag { @@ -43,7 +38,7 @@ public function create(string $name, ?TranslationInterface $translation = null, return $tag; } - if ($translation === null) { + if (null === $translation) { $translation = $this->managerRegistry->getRepository(TranslationInterface::class)->findDefault(); } diff --git a/lib/RoadizCoreBundle/src/Traits/LoginRequestTrait.php b/lib/RoadizCoreBundle/src/Traits/LoginRequestTrait.php index 19ea1b16..a5dba0ae 100644 --- a/lib/RoadizCoreBundle/src/Traits/LoginRequestTrait.php +++ b/lib/RoadizCoreBundle/src/Traits/LoginRequestTrait.php @@ -23,13 +23,8 @@ trait LoginRequestTrait abstract protected function getUserViewer(): UserViewer; /** - * @param FormInterface $form - * @param ObjectManager $entityManager - * @param LoggerInterface $logger - * @param UrlGeneratorInterface $urlGenerator - * @param string $resetRoute - * * @return bool TRUE if confirmation has been sent. FALSE if errors + * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException */ @@ -38,7 +33,7 @@ public function sendConfirmationEmail( ObjectManager $entityManager, LoggerInterface $logger, UrlGeneratorInterface $urlGenerator, - string $resetRoute = 'loginResetPage' + string $resetRoute = 'loginResetPage', ): bool { $email = $form->get('email')->getData(); /** @var User $user */ @@ -53,6 +48,7 @@ public function sendConfirmationEmail( $entityManager->flush(); $userViewer = $this->getUserViewer(); $userViewer->sendPasswordResetLink($user, $resetRoute); + return true; } catch (\Throwable $e) { $user->setPasswordRequestedAt(null); diff --git a/lib/RoadizCoreBundle/src/Traits/LoginResetTrait.php b/lib/RoadizCoreBundle/src/Traits/LoginResetTrait.php index 08a3e7e3..83520e60 100644 --- a/lib/RoadizCoreBundle/src/Traits/LoginResetTrait.php +++ b/lib/RoadizCoreBundle/src/Traits/LoginResetTrait.php @@ -10,21 +10,12 @@ trait LoginResetTrait { - /** - * @param ObjectManager $entityManager - * @param string $token - * @return null|User - */ public function getUserByToken(ObjectManager $entityManager, string $token): ?User { return $entityManager->getRepository(User::class)->findOneByConfirmationToken($token); } /** - * @param FormInterface $form - * @param User $user - * @param ObjectManager $entityManager - * * @return bool */ public function updateUserPassword(FormInterface $form, User $user, ObjectManager $entityManager) diff --git a/lib/RoadizCoreBundle/src/Translation/TranslationViewer.php b/lib/RoadizCoreBundle/src/Translation/TranslationViewer.php index 450d746b..5011143c 100644 --- a/lib/RoadizCoreBundle/src/Translation/TranslationViewer.php +++ b/lib/RoadizCoreBundle/src/Translation/TranslationViewer.php @@ -27,13 +27,10 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly Settings $settingsBag, private readonly RouterInterface $router, - private readonly PreviewResolverInterface $previewResolver + private readonly PreviewResolverInterface $previewResolver, ) { } - /** - * @return TranslationRepository - */ public function getRepository(): TranslationRepository { return $this->managerRegistry->getRepository(Translation::class); @@ -71,10 +68,8 @@ public function getRepository(): TranslationRepository * 'active' => boolean false * 'translation' => string 'Spanish' * - * @param Request $request * @param bool $absolute Generate absolute url or relative paths * - * @return array * @throws ORMException */ public function getTranslationMenuAssignation(Request $request, bool $absolute = false): array @@ -83,9 +78,9 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = $query = $request->query->all(); $name = ''; $forceLocale = (bool) $this->settingsBag->get('force_locale'); - $useStaticRouting = !empty($attr['_route']) && - is_string($attr['_route']) && - $attr['_route'] !== RouteObjectInterface::OBJECT_BASED_ROUTE_NAME; + $useStaticRouting = !empty($attr['_route']) + && is_string($attr['_route']) + && RouteObjectInterface::OBJECT_BASED_ROUTE_NAME !== $attr['_route']; /* * Fix absolute boolean to Int constant. @@ -93,7 +88,7 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = $absolute = $absolute ? UrlGeneratorInterface::ABSOLUTE_URL : UrlGeneratorInterface::ABSOLUTE_PATH; if (key_exists('node', $attr) && $attr['node'] instanceof Node) { - $node = $attr["node"]; + $node = $attr['node']; $this->managerRegistry->getManagerForClass(Node::class)->refresh($node); } else { $node = null; @@ -106,9 +101,9 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = /* * Search for a route without Locale suffix */ - $baseRoute = RouteHandler::getBaseRoute($attr["_route"]); + $baseRoute = RouteHandler::getBaseRoute($attr['_route']); if (null !== $this->router->getRouteCollection()->get($baseRoute)) { - $attr["_route"] = $baseRoute; + $attr['_route'] = $baseRoute; } } elseif (null !== $node) { /* @@ -119,7 +114,7 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = } else { $translations = $this->getRepository()->findStrictlyAvailableTranslationsForNode($node); } - $name = "node"; + $name = 'node'; } else { return []; } @@ -132,7 +127,7 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = * Remove existing _locale in query string */ if (key_exists('_locale', $query)) { - unset($query["_locale"]); + unset($query['_locale']); } /* * Remove existing page parameter in query string @@ -154,8 +149,8 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = /* * Search for a Locale suffixed route */ - if (null !== $this->router->getRouteCollection()->get($attr['_route'] . "Locale")) { - $name = $attr['_route'] . 'Locale'; + if (null !== $this->router->getRouteCollection()->get($attr['_route'].'Locale')) { + $name = $attr['_route'].'Locale'; } $attr['_route_params']['_locale'] = $translation->getPreferredLocale(); @@ -185,7 +180,7 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = $url = $this->router->generate( RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, array_merge($attr['_route_params'], $query, [ - RouteObjectInterface::ROUTE_OBJECT => $name + RouteObjectInterface::ROUTE_OBJECT => $name, ]), $absolute ); @@ -196,7 +191,7 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = $url = $this->router->generate( RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, array_merge($query, [ - RouteObjectInterface::ROUTE_OBJECT => $nodesSources + RouteObjectInterface::ROUTE_OBJECT => $nodesSources, ]), $absolute ); @@ -213,24 +208,22 @@ public function getTranslationMenuAssignation(Request $request, bool $absolute = ]; } } + return $return; } - /** - * @return TranslationInterface|null - */ public function getTranslation(): ?TranslationInterface { return $this->translation; } /** - * @param TranslationInterface|null $translation * @return TranslationViewer */ public function setTranslation(?TranslationInterface $translation) { $this->translation = $translation; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/AttributesExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/AttributesExtension.php index 92755704..588e0193 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/AttributesExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/AttributesExtension.php @@ -90,23 +90,17 @@ public function isPercent(AttributeValueTranslationInterface $attributeValueTran public function isNumber(AttributeValueTranslationInterface $attributeValueTranslation): bool { - return $attributeValueTranslation->getAttributeValue()->getAttribute()->isInteger() || - $attributeValueTranslation->getAttributeValue()->getAttribute()->isDecimal(); + return $attributeValueTranslation->getAttributeValue()->getAttribute()->isInteger() + || $attributeValueTranslation->getAttributeValue()->getAttribute()->isDecimal(); } - /** - * @param AttributableInterface|null $attributable - * @param TranslationInterface $translation - * @param bool $hideNotTranslated - * - * @return array * @throws SyntaxError */ public function getAttributeValues( ?AttributableInterface $attributable, TranslationInterface $translation, - bool $hideNotTranslated = false + bool $hideNotTranslated = false, ): array { if (null === $attributable) { throw new SyntaxError('Cannot call get_attributes on NULL'); @@ -150,10 +144,6 @@ public function getAttributeValues( } /** - * @param NodesSources|null $nodesSources - * @param bool $hideNotTranslated - * - * @return array * @throws SyntaxError */ public function getNodeSourceAttributeValues(?NodesSources $nodesSources, bool $hideNotTranslated = false): array @@ -161,14 +151,11 @@ public function getNodeSourceAttributeValues(?NodesSources $nodesSources, bool $ if (null === $nodesSources) { throw new SyntaxError('Cannot call node_source_attributes on NULL'); } + return $this->getAttributeValues($nodesSources->getNode(), $nodesSources->getTranslation(), $hideNotTranslated); } /** - * @param NodesSources|null $nodesSources - * @param bool $hideNotTranslated - * - * @return array * @throws SyntaxError */ public function getNodeSourceGroupedAttributeValues(?NodesSources $nodesSources, bool $hideNotTranslated = false): array @@ -176,10 +163,10 @@ public function getNodeSourceGroupedAttributeValues(?NodesSources $nodesSources, $groups = [ INF => [ 'group' => null, - 'attributeValues' => [] - ] + 'attributeValues' => [], + ], ]; - $attributeValueTranslations = $this->getNodeSourceAttributeValues($nodesSources, $hideNotTranslated); + $attributeValueTranslations = $this->getNodeSourceAttributeValues($nodesSources, $hideNotTranslated); /** @var AttributeValueTranslationInterface $attributeValueTranslation */ foreach ($attributeValueTranslations as $attributeValueTranslation) { $group = $attributeValueTranslation->getAttributeValue()->getAttribute()->getGroup(); @@ -187,7 +174,7 @@ public function getNodeSourceGroupedAttributeValues(?NodesSources $nodesSources, if (!isset($groups[$group->getCanonicalName()])) { $groups[$group->getCanonicalName()] = [ 'group' => $group, - 'attributeValues' => [] + 'attributeValues' => [], ]; } $groups[$group->getCanonicalName()]['attributeValues'][] = $attributeValueTranslation; @@ -201,13 +188,7 @@ public function getNodeSourceGroupedAttributeValues(?NodesSources $nodesSources, }); } - /** - * @param mixed $mixed - * @param TranslationInterface|null $translation - * - * @return string|null - */ - public function getAttributeLabelOrCode(mixed $mixed, TranslationInterface $translation = null): ?string + public function getAttributeLabelOrCode(mixed $mixed, ?TranslationInterface $translation = null): ?string { if (null === $mixed) { return null; @@ -223,18 +204,14 @@ public function getAttributeLabelOrCode(mixed $mixed, TranslationInterface $tran if (null === $translation) { $translation = $mixed->getTranslation(); } + return $mixed->getAttributeValue()->getAttribute()->getLabelOrCode($translation); } return null; } - /** - * @param mixed $mixed - * @param TranslationInterface|null $translation - * @return string|null - */ - public function getAttributeGroupLabelOrCode(mixed $mixed, TranslationInterface $translation = null): ?string + public function getAttributeGroupLabelOrCode(mixed $mixed, ?TranslationInterface $translation = null): ?string { if (null === $mixed) { return null; @@ -252,6 +229,7 @@ public function getAttributeGroupLabelOrCode(mixed $mixed, TranslationInterface if (null === $translation) { $translation = $mixed->getTranslation(); } + return $mixed->getAttribute()->getGroup()->getTranslatedName($translation); } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/BlockRenderExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/BlockRenderExtension.php index 5e028743..c023d81b 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/BlockRenderExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/BlockRenderExtension.php @@ -29,49 +29,39 @@ public function getFilters(): array } /** - * @param NodesSources|null $nodeSource - * @param string $themeName - * @param array $assignation - * - * @return string * @throws RuntimeError */ - public function blockRender(NodesSources $nodeSource = null, string $themeName = "DefaultTheme", array $assignation = []): string + public function blockRender(?NodesSources $nodeSource = null, string $themeName = 'DefaultTheme', array $assignation = []): string { if (null !== $nodeSource) { if (!empty($themeName)) { $class = $this->getNodeSourceControllerName($nodeSource, $themeName); if (class_exists($class) && method_exists($class, 'blockAction')) { - $controllerReference = new ControllerReference($class . '::blockAction', [ + $controllerReference = new ControllerReference($class.'::blockAction', [ 'source' => $nodeSource, 'assignation' => $assignation, ]); + /* * ignore_errors option MUST BE false in order to catch ForceResponseException * from Master request render method and redirect users. */ return $this->handler->render($controllerReference, 'inline', [ - 'ignore_errors' => false + 'ignore_errors' => false, ]); } else { - throw new RuntimeError($class . "::blockAction() action does not exist."); + throw new RuntimeError($class.'::blockAction() action does not exist.'); } } else { - throw new RuntimeError("Invalid name formatting for your theme."); + throw new RuntimeError('Invalid name formatting for your theme.'); } } - throw new RuntimeError("Invalid NodesSources."); + throw new RuntimeError('Invalid NodesSources.'); } - /** - * @param NodesSources $nodeSource - * @param string $themeName - * - * @return string - */ protected function getNodeSourceControllerName(NodesSources $nodeSource, string $themeName): string { - return '\\Themes\\' . $themeName . '\\Controllers\\Blocks\\' . - $nodeSource->getNodeTypeName() . 'Controller'; + return '\\Themes\\'.$themeName.'\\Controllers\\Blocks\\'. + $nodeSource->getNodeTypeName().'Controller'; } } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/CentralTruncateExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/CentralTruncateExtension.php index 077e73e9..1265c2d6 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/CentralTruncateExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/CentralTruncateExtension.php @@ -21,17 +21,10 @@ public function getFilters(): array new TwigFilter( 'central_truncate', [$this, 'centralTruncate'] - ) + ), ]; } - /** - * @param string|null $object - * @param int $length - * @param int $offset - * @param string $ellipsis - * @return string|null - */ public function centralTruncate(?string $object, int $length, int $offset = 0, string $ellipsis = '[…]'): ?string { if (null === $object) { @@ -40,9 +33,10 @@ public function centralTruncate(?string $object, int $length, int $offset = 0, s $unicode = u($object); $unicodeEllipsis = u($ellipsis); if ($unicode->length() > $length + $unicodeEllipsis->length()) { - $str1 = $unicode->slice(0, (int)(floor($length / 2) + floor($offset / 2))); - $str2 = $unicode->slice((int)((floor($length / 2) * -1) + floor($offset / 2))); - return $str1 . $ellipsis . $str2; + $str1 = $unicode->slice(0, (int) (floor($length / 2) + floor($offset / 2))); + $str2 = $unicode->slice((int) ((floor($length / 2) * -1) + floor($offset / 2))); + + return $str1.$ellipsis.$str2; } return $object; diff --git a/lib/RoadizCoreBundle/src/TwigExtension/DocumentUrlExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/DocumentUrlExtension.php index af68dd7d..07c5c002 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/DocumentUrlExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/DocumentUrlExtension.php @@ -13,19 +13,16 @@ use Twig\TwigFilter; /** - * Extension that allow render documents Url + * Extension that allow render documents Url. */ final class DocumentUrlExtension extends AbstractExtension { public function __construct( private readonly DocumentUrlGeneratorInterface $documentUrlGenerator, - private readonly bool $throwExceptions = false + private readonly bool $throwExceptions = false, ) { } - /** - * @return array - */ public function getFilters(): array { return [ @@ -40,18 +37,15 @@ public function getFilters(): array * * - Document * - * @param PersistableInterface|null $mixed - * @param array $criteria - * @return string * @throws RuntimeError */ - public function getUrl(PersistableInterface $mixed = null, array $criteria = []): string + public function getUrl(?PersistableInterface $mixed = null, array $criteria = []): string { if (null === $mixed) { if ($this->throwExceptions) { - throw new RuntimeError("Twig “url” filter must be used with a not null object"); + throw new RuntimeError('Twig “url” filter must be used with a not null object'); } else { - return ""; + return ''; } } @@ -64,12 +58,13 @@ public function getUrl(PersistableInterface $mixed = null, array $criteria = []) $this->documentUrlGenerator->setOptions($criteria); $this->documentUrlGenerator->setDocument($mixed); + return $this->documentUrlGenerator->getUrl($absolute); } catch (InvalidArgumentException $e) { throw new RuntimeError($e->getMessage(), -1, null, $e); } } - throw new RuntimeError("Twig “url” filter can be only used with a Document"); + throw new RuntimeError('Twig “url” filter can be only used with a Document'); } } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/HandlerExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/HandlerExtension.php index 46bd6cd0..8a432159 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/HandlerExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/HandlerExtension.php @@ -27,8 +27,6 @@ public function getFilters(): array } /** - * @param mixed $mixed - * @return AbstractHandler|null * @throws RuntimeError * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface diff --git a/lib/RoadizCoreBundle/src/TwigExtension/JwtExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/JwtExtension.php index 246e20d8..070e0e63 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/JwtExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/JwtExtension.php @@ -17,7 +17,7 @@ final class JwtExtension extends AbstractExtension public function __construct( private readonly JWTTokenManagerInterface $tokenManager, private readonly LoggerInterface $logger, - private readonly PreviewUserProviderInterface $previewUserProvider + private readonly PreviewUserProviderInterface $previewUserProvider, ) { } @@ -34,9 +34,11 @@ public function createPreviewJwt(): ?string return $this->tokenManager->create($this->previewUserProvider->createFromSecurity()); } catch (AccessDeniedException $exception) { $this->logger->warning($exception->getMessage()); + return null; } catch (JWTFailureException $exception) { $this->logger->warning($exception->getMessage()); + return null; } } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/LogExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/LogExtension.php index cfaa612e..2e45ebe2 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/LogExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/LogExtension.php @@ -13,8 +13,8 @@ use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\User; use RZ\Roadiz\CoreBundle\Logger\Entity\Log; -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Bundle\SecurityBundle\Security; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; @@ -22,7 +22,7 @@ final class LogExtension extends AbstractExtension { public function __construct( private readonly Security $security, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { } @@ -43,9 +43,9 @@ public function getEditPath(?object $log): ?string case Node::class: case NodesSources::class: if ( - $this->security->isGranted('ROLE_ACCESS_NODES') && - isset($log->getAdditionalData()['node_id']) && - isset($log->getAdditionalData()['translation_id']) + $this->security->isGranted('ROLE_ACCESS_NODES') + && isset($log->getAdditionalData()['node_id']) + && isset($log->getAdditionalData()['translation_id']) ) { return $this->urlGenerator->generate('nodesEditSourcePage', [ 'nodeId' => $log->getAdditionalData()['node_id'], diff --git a/lib/RoadizCoreBundle/src/TwigExtension/NodesSourcesExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/NodesSourcesExtension.php index 55d8fcc8..b4e8506a 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/NodesSourcesExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/NodesSourcesExtension.php @@ -17,14 +17,14 @@ use Twig\TwigTest; /** - * Extension that allow to gather nodes-source from hierarchy + * Extension that allow to gather nodes-source from hierarchy. */ final class NodesSourcesExtension extends AbstractExtension { public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly NodeTypes $nodeTypesBag, - private readonly bool $throwExceptions = false + private readonly bool $throwExceptions = false, ) { } @@ -59,17 +59,15 @@ public function getTests(): array } /** - * @param NodesSources|null $ns - * @param array|null $criteria - * @param array|null $order * @return iterable + * * @throws RuntimeError */ - public function getChildren(NodesSources $ns = null, array $criteria = null, array $order = null): iterable + public function getChildren(?NodesSources $ns = null, ?array $criteria = null, ?array $order = null): iterable { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get children from a NULL node-source."); + throw new RuntimeError('Cannot get children from a NULL node-source.'); } else { return []; } @@ -81,17 +79,13 @@ public function getChildren(NodesSources $ns = null, array $criteria = null, arr } /** - * @param NodesSources|null $ns - * @param array|null $criteria - * @param array|null $order - * @return NodesSources|null * @throws RuntimeError */ - public function getNext(NodesSources $ns = null, array $criteria = null, array $order = null): ?NodesSources + public function getNext(?NodesSources $ns = null, ?array $criteria = null, ?array $order = null): ?NodesSources { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get next sibling from a NULL node-source."); + throw new RuntimeError('Cannot get next sibling from a NULL node-source.'); } else { return null; } @@ -103,17 +97,13 @@ public function getNext(NodesSources $ns = null, array $criteria = null, array $ } /** - * @param NodesSources|null $ns - * @param array|null $criteria - * @param array|null $order - * @return NodesSources|null * @throws RuntimeError */ - public function getPrevious(NodesSources $ns = null, array $criteria = null, array $order = null): ?NodesSources + public function getPrevious(?NodesSources $ns = null, ?array $criteria = null, ?array $order = null): ?NodesSources { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get previous sibling from a NULL node-source."); + throw new RuntimeError('Cannot get previous sibling from a NULL node-source.'); } else { return null; } @@ -125,17 +115,13 @@ public function getPrevious(NodesSources $ns = null, array $criteria = null, arr } /** - * @param NodesSources|null $ns - * @param array|null $criteria - * @param array|null $order - * @return NodesSources|null * @throws RuntimeError */ - public function getLastSibling(NodesSources $ns = null, array $criteria = null, array $order = null): ?NodesSources + public function getLastSibling(?NodesSources $ns = null, ?array $criteria = null, ?array $order = null): ?NodesSources { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get last sibling from a NULL node-source."); + throw new RuntimeError('Cannot get last sibling from a NULL node-source.'); } else { return null; } @@ -147,17 +133,13 @@ public function getLastSibling(NodesSources $ns = null, array $criteria = null, } /** - * @param NodesSources|null $ns - * @param array|null $criteria - * @param array|null $order - * @return NodesSources|null * @throws RuntimeError */ - public function getFirstSibling(NodesSources $ns = null, array $criteria = null, array $order = null): ?NodesSources + public function getFirstSibling(?NodesSources $ns = null, ?array $criteria = null, ?array $order = null): ?NodesSources { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get first sibling from a NULL node-source."); + throw new RuntimeError('Cannot get first sibling from a NULL node-source.'); } else { return null; } @@ -169,15 +151,13 @@ public function getFirstSibling(NodesSources $ns = null, array $criteria = null, } /** - * @param NodesSources|null $ns - * @return NodesSources|null * @throws RuntimeError */ - public function getParent(NodesSources $ns = null): ?NodesSources + public function getParent(?NodesSources $ns = null): ?NodesSources { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get parent from a NULL node-source."); + throw new RuntimeError('Cannot get parent from a NULL node-source.'); } else { return null; } @@ -187,19 +167,16 @@ public function getParent(NodesSources $ns = null): ?NodesSources } /** - * @param NodesSources|null $ns - * @param array|null $criteria - * @return array * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface * @throws RuntimeError * @throws NonUniqueResultException */ - public function getParents(NodesSources $ns = null, array $criteria = null): array + public function getParents(?NodesSources $ns = null, ?array $criteria = null): array { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get parents from a NULL node-source."); + throw new RuntimeError('Cannot get parents from a NULL node-source.'); } else { return []; } @@ -211,17 +188,17 @@ public function getParents(NodesSources $ns = null, array $criteria = null): arr } /** - * @param NodesSources|null $ns * @return iterable + * * @throws RuntimeError * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ - public function getTags(NodesSources $ns = null): iterable + public function getTags(?NodesSources $ns = null): iterable { if (null === $ns) { if ($this->throwExceptions) { - throw new RuntimeError("Cannot get tags from a NULL node-source."); + throw new RuntimeError('Cannot get tags from a NULL node-source.'); } else { return []; } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/RoadizExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/RoadizExtension.php index 3946bd8f..96aee690 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/RoadizExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/RoadizExtension.php @@ -21,13 +21,10 @@ public function __construct( private readonly string $cmsVersion, private readonly string $cmsVersionPrefix, private readonly bool $hideRoadizVersion, - private readonly int $maxVersionsShowed + private readonly int $maxVersionsShowed, ) { } - /** - * @return array - */ public function getGlobals(): array { return [ @@ -46,7 +43,7 @@ public function getGlobals(): array 'siteName' => $this->settingsBag->get('site_name'), 'siteCopyright' => $this->settingsBag->get('site_copyright'), 'siteDescription' => $this->settingsBag->get('seo_description'), - ] + ], ]; } } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/RoutingExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/RoutingExtension.php index adb4d9ac..1b2ccb2e 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/RoutingExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/RoutingExtension.php @@ -19,13 +19,10 @@ final class RoutingExtension extends AbstractExtension { public function __construct( private readonly BaseRoutingExtension $decorated, - private readonly UrlGeneratorInterface $generator + private readonly UrlGeneratorInterface $generator, ) { } - /** - * {@inheritdoc} - */ public function getFunctions(): array { return [ @@ -35,10 +32,6 @@ public function getFunctions(): array } /** - * @param string|object|null $name - * @param array $parameters - * @param bool $relative - * @return string * @throws RuntimeError */ public function getPath(string|object|null $name, array $parameters = [], bool $relative = false): string @@ -61,10 +54,6 @@ public function getPath(string|object|null $name, array $parameters = [], bool $ } /** - * @param string|object|null $name - * @param array $parameters - * @param bool $schemeRelative - * @return string * @throws RuntimeError */ public function getUrl(string|object|null $name, array $parameters = [], bool $schemeRelative = false): string diff --git a/lib/RoadizCoreBundle/src/TwigExtension/TokenParser/TransChoiceTokenParser.php b/lib/RoadizCoreBundle/src/TwigExtension/TokenParser/TransChoiceTokenParser.php index bcd01d02..d899ec84 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/TokenParser/TransChoiceTokenParser.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/TokenParser/TransChoiceTokenParser.php @@ -24,11 +24,6 @@ */ class TransChoiceTokenParser extends AbstractTokenParser { - /** - * {@inheritdoc} - * - * @return Node - */ public function parse(Token $token): Node { $lineno = $token->getLine(); @@ -77,11 +72,6 @@ public function decideTransChoiceFork(Token $token): bool return $token->test(['endtranschoice']); } - /** - * {@inheritdoc} - * - * @return string - */ public function getTag(): string { return 'transchoice'; diff --git a/lib/RoadizCoreBundle/src/TwigExtension/TransChoiceExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/TransChoiceExtension.php index 96c19b15..d3eb996f 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/TransChoiceExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/TransChoiceExtension.php @@ -49,7 +49,7 @@ public function transchoice( int $count, array $arguments = [], ?string $domain = null, - ?string $locale = null + ?string $locale = null, ): string { return $this->translator->trans($message, array_merge(['%count%' => $count], $arguments), $domain, $locale); } diff --git a/lib/RoadizCoreBundle/src/TwigExtension/TranslationExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/TranslationExtension.php index cd248352..ec52773d 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/TranslationExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/TranslationExtension.php @@ -25,15 +25,10 @@ public function getFilters(): array public function getTests(): array { return [ - new TwigTest('rtl', [$this, 'isLocaleRtl']) + new TwigTest('rtl', [$this, 'isLocaleRtl']), ]; } - /** - * @param mixed $mixed - * - * @return bool - */ public function isLocaleRtl(mixed $mixed): bool { if ($mixed instanceof TranslationInterface) { @@ -47,22 +42,11 @@ public function isLocaleRtl(mixed $mixed): bool return false; } - /** - * @param string $iso - * @param string|null $locale - * @return string - */ public function getCountryName(string $iso, ?string $locale = null): string { return Countries::getName($iso, $locale); } - /** - * @param string $iso - * @param string|null $locale - * - * @return string - */ public function getLocaleName(string $iso, ?string $locale = null): string { return Locales::getName($iso, $locale); diff --git a/lib/RoadizCoreBundle/src/TwigExtension/TranslationMenuExtension.php b/lib/RoadizCoreBundle/src/TwigExtension/TranslationMenuExtension.php index 2c0bccd8..01a82375 100644 --- a/lib/RoadizCoreBundle/src/TwigExtension/TranslationMenuExtension.php +++ b/lib/RoadizCoreBundle/src/TwigExtension/TranslationMenuExtension.php @@ -15,7 +15,7 @@ final class TranslationMenuExtension extends AbstractExtension { public function __construct( private readonly RequestStack $requestStack, - private readonly TranslationViewer $translationViewer + private readonly TranslationViewer $translationViewer, ) { } @@ -27,16 +27,13 @@ public function getFilters(): array } /** - * @param TranslationInterface|null $translation - * @param bool $absolute - * - * @return array * @throws ORMException */ - public function getMenuAssignation(TranslationInterface $translation = null, bool $absolute = false): array + public function getMenuAssignation(?TranslationInterface $translation = null, bool $absolute = false): array { if (null !== $translation) { $this->translationViewer->setTranslation($translation); + return $this->translationViewer->getTranslationMenuAssignation($this->requestStack->getCurrentRequest(), $absolute); } else { return []; diff --git a/lib/RoadizCoreBundle/src/Webhook/Exception/TooManyWebhookTriggeredException.php b/lib/RoadizCoreBundle/src/Webhook/Exception/TooManyWebhookTriggeredException.php index c53c4b58..662e0197 100644 --- a/lib/RoadizCoreBundle/src/Webhook/Exception/TooManyWebhookTriggeredException.php +++ b/lib/RoadizCoreBundle/src/Webhook/Exception/TooManyWebhookTriggeredException.php @@ -4,22 +4,17 @@ namespace RZ\Roadiz\CoreBundle\Webhook\Exception; -use Throwable; - final class TooManyWebhookTriggeredException extends \RuntimeException { public function __construct( private readonly ?\DateTimeImmutable $doNotTriggerBefore = null, - string $message = "", + string $message = '', int $code = 0, - Throwable $previous = null + ?\Throwable $previous = null, ) { parent::__construct($message, $code, $previous); } - /** - * @return \DateTimeImmutable - */ public function getDoNotTriggerBefore(): \DateTimeImmutable { return $this->doNotTriggerBefore ?? \DateTimeImmutable::createFromMutable((new \DateTime())->add(new \DateInterval('PT30S'))); diff --git a/lib/RoadizCoreBundle/src/Webhook/Message/GenericJsonPostMessage.php b/lib/RoadizCoreBundle/src/Webhook/Message/GenericJsonPostMessage.php index cd8d9c4b..c64aacea 100644 --- a/lib/RoadizCoreBundle/src/Webhook/Message/GenericJsonPostMessage.php +++ b/lib/RoadizCoreBundle/src/Webhook/Message/GenericJsonPostMessage.php @@ -6,16 +6,16 @@ use GuzzleHttp\Psr7\Request; use Psr\Http\Message\RequestInterface; +use RZ\Roadiz\CoreBundle\Entity\Webhook; use RZ\Roadiz\CoreBundle\Message\AsyncMessage; use RZ\Roadiz\CoreBundle\Message\HttpRequestMessage; -use RZ\Roadiz\CoreBundle\Entity\Webhook; use RZ\Roadiz\CoreBundle\Webhook\WebhookInterface; final class GenericJsonPostMessage implements AsyncMessage, HttpRequestMessage, WebhookMessage { public function __construct( private readonly string $uri, - private readonly ?array $payload = null + private readonly ?array $payload = null, ) { } @@ -26,25 +26,23 @@ public function getRequest(): RequestInterface $this->uri, [ 'Content-Type' => 'application/json', - 'Accept' => 'application/json' + 'Accept' => 'application/json', ], json_encode($this->payload ?? [], JSON_NUMERIC_CHECK | JSON_THROW_ON_ERROR) ); } - /** - * @return array - */ public function getOptions(): array { return [ 'debug' => false, - 'timeout' => 3 + 'timeout' => 3, ]; } /** * @param Webhook $webhook + * * @return static */ public static function fromWebhook(WebhookInterface $webhook): self diff --git a/lib/RoadizCoreBundle/src/Webhook/Message/GitlabPipelineTriggerMessage.php b/lib/RoadizCoreBundle/src/Webhook/Message/GitlabPipelineTriggerMessage.php index 8783c286..b9d27893 100644 --- a/lib/RoadizCoreBundle/src/Webhook/Message/GitlabPipelineTriggerMessage.php +++ b/lib/RoadizCoreBundle/src/Webhook/Message/GitlabPipelineTriggerMessage.php @@ -16,7 +16,7 @@ public function __construct( private readonly string $uri, private readonly string $token, private readonly string $ref = 'main', - private readonly ?array $variables = null + private readonly ?array $variables = null, ) { } @@ -35,30 +35,27 @@ public function getRequest(): RequestInterface $this->uri, [ 'Content-Type' => 'application/x-www-form-urlencoded', - 'Accept' => 'application/json' + 'Accept' => 'application/json', ], http_build_query($postBody) ); } - /** - * @return array - */ public function getOptions(): array { return [ 'debug' => false, - 'timeout' => 3 + 'timeout' => 3, ]; } /** - * @param WebhookInterface $webhook * @return static */ public static function fromWebhook(WebhookInterface $webhook): self { $payload = $webhook->getPayload(); + return new self( $webhook->getUri(), $payload['token'] ?? '', diff --git a/lib/RoadizCoreBundle/src/Webhook/Message/NetlifyBuildHookMessage.php b/lib/RoadizCoreBundle/src/Webhook/Message/NetlifyBuildHookMessage.php index dc0ee797..7138dc08 100644 --- a/lib/RoadizCoreBundle/src/Webhook/Message/NetlifyBuildHookMessage.php +++ b/lib/RoadizCoreBundle/src/Webhook/Message/NetlifyBuildHookMessage.php @@ -14,7 +14,7 @@ final class NetlifyBuildHookMessage implements AsyncMessage, HttpRequestMessage, { public function __construct( private readonly string $uri, - private readonly ?array $payload = null + private readonly ?array $payload = null, ) { } @@ -26,27 +26,24 @@ public function getRequest(): RequestInterface $this->uri, [ 'Content-Type' => 'application/x-www-form-urlencoded', - 'Accept' => 'application/json' + 'Accept' => 'application/json', ], http_build_query($this->payload) ); } + return new Request('POST', $this->uri); } - /** - * @return array - */ public function getOptions(): array { return [ 'debug' => false, - 'timeout' => 3 + 'timeout' => 3, ]; } /** - * @param WebhookInterface $webhook * @return static */ public static function fromWebhook(WebhookInterface $webhook): self diff --git a/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessage.php b/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessage.php index 012c98de..37821439 100644 --- a/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessage.php +++ b/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessage.php @@ -9,7 +9,6 @@ interface WebhookMessage { /** - * @param WebhookInterface $webhook * @return static */ public static function fromWebhook(WebhookInterface $webhook); diff --git a/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessageFactory.php b/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessageFactory.php index bd248e0a..7c080174 100644 --- a/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessageFactory.php +++ b/lib/RoadizCoreBundle/src/Webhook/Message/WebhookMessageFactory.php @@ -22,7 +22,7 @@ public function createMessage(WebhookInterface $webhook): HttpRequestMessage throw new \LogicException('Webhook message type does not exist.'); } if (!in_array(WebhookMessage::class, class_implements($messageType))) { - throw new \LogicException('Webhook message type does not implement ' . WebhookMessage::class); + throw new \LogicException('Webhook message type does not implement '.WebhookMessage::class); } return $messageType::fromWebhook($webhook); diff --git a/lib/RoadizCoreBundle/src/Webhook/ThrottledWebhookDispatcher.php b/lib/RoadizCoreBundle/src/Webhook/ThrottledWebhookDispatcher.php index 82e08d8d..563243b6 100644 --- a/lib/RoadizCoreBundle/src/Webhook/ThrottledWebhookDispatcher.php +++ b/lib/RoadizCoreBundle/src/Webhook/ThrottledWebhookDispatcher.php @@ -15,20 +15,19 @@ final class ThrottledWebhookDispatcher implements WebhookDispatcher public function __construct( private readonly WebhookMessageFactoryInterface $messageFactory, private readonly MessageBusInterface $messageBus, - private readonly RateLimiterFactory $throttledWebhooksLimiter + private readonly RateLimiterFactory $throttledWebhooksLimiter, ) { } /** - * @param WebhookInterface $webhook * @throws \Exception */ public function dispatch(WebhookInterface $webhook): void { $doNotTriggerBefore = $webhook->doNotTriggerBefore(); if ( - null !== $doNotTriggerBefore && - $doNotTriggerBefore > new \DateTime() + null !== $doNotTriggerBefore + && $doNotTriggerBefore > new \DateTime() ) { throw new TooManyWebhookTriggeredException(\DateTimeImmutable::createFromMutable($doNotTriggerBefore)); } diff --git a/lib/RoadizCoreBundle/src/Webhook/WebhookInterface.php b/lib/RoadizCoreBundle/src/Webhook/WebhookInterface.php index 4ad3a08e..3c8821f0 100644 --- a/lib/RoadizCoreBundle/src/Webhook/WebhookInterface.php +++ b/lib/RoadizCoreBundle/src/Webhook/WebhookInterface.php @@ -10,16 +10,25 @@ interface WebhookInterface * @return string|null */ public function getId(); + /** * @return string */ public function __toString(); + public function getUri(): ?string; + public function getMessageType(): ?string; + public function getPayload(): ?array; + public function getThrottleSeconds(): int; + public function doNotTriggerBefore(): ?\DateTime; + public function setLastTriggeredAt(?\DateTime $lastTriggeredAt): self; + public function getLastTriggeredAt(): ?\DateTime; + public function isAutomatic(): bool; } diff --git a/lib/RoadizCoreBundle/src/Workflow/Event/NodeStatusGuardListener.php b/lib/RoadizCoreBundle/src/Workflow/Event/NodeStatusGuardListener.php index 742fa04c..8f80d78b 100644 --- a/lib/RoadizCoreBundle/src/Workflow/Event/NodeStatusGuardListener.php +++ b/lib/RoadizCoreBundle/src/Workflow/Event/NodeStatusGuardListener.php @@ -6,8 +6,8 @@ use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Security\Authorization\Voter\NodeVoter; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Bundle\SecurityBundle\Security; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Workflow\Event\GuardEvent; use Symfony\Component\Workflow\TransitionBlocker; @@ -17,9 +17,6 @@ public function __construct(private readonly Security $security) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizCoreBundle/src/Workflow/NodeWorkflow.php b/lib/RoadizCoreBundle/src/Workflow/NodeWorkflow.php index e8b51897..52352802 100644 --- a/lib/RoadizCoreBundle/src/Workflow/NodeWorkflow.php +++ b/lib/RoadizCoreBundle/src/Workflow/NodeWorkflow.php @@ -23,7 +23,7 @@ public function __construct(EventDispatcherInterface $dispatcher) $this->toPlace(Node::PENDING), $this->toPlace(Node::PUBLISHED), $this->toPlace(Node::ARCHIVED), - $this->toPlace(Node::DELETED) + $this->toPlace(Node::DELETED), ]) ->addTransition(new Transition('review', $this->toPlace(Node::DRAFT), $this->toPlace(Node::PENDING))) ->addTransition(new Transition('review', $this->toPlace(Node::PUBLISHED), $this->toPlace(Node::PENDING))) diff --git a/lib/RoadizCoreBundle/src/Xlsx/AbstractXlsxSerializer.php b/lib/RoadizCoreBundle/src/Xlsx/AbstractXlsxSerializer.php index 664457b4..0d10950f 100644 --- a/lib/RoadizCoreBundle/src/Xlsx/AbstractXlsxSerializer.php +++ b/lib/RoadizCoreBundle/src/Xlsx/AbstractXlsxSerializer.php @@ -19,13 +19,10 @@ public function __construct(protected readonly TranslatorInterface $translator) /** * Serializes data. * - * @param mixed $obj - * - * @return string * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ - public function serialize($obj): string + public function serialize(mixed $obj): string { $data = $this->toArray($obj); $exporter = new XlsxExporter($this->translator); @@ -33,9 +30,6 @@ public function serialize($obj): string return $exporter->exportXlsx($data); } - /** - * @return TranslatorInterface - */ public function getTranslator(): TranslatorInterface { return $this->translator; diff --git a/lib/RoadizCoreBundle/src/Xlsx/NodeSourceXlsxSerializer.php b/lib/RoadizCoreBundle/src/Xlsx/NodeSourceXlsxSerializer.php index 40747f99..a21ba602 100644 --- a/lib/RoadizCoreBundle/src/Xlsx/NodeSourceXlsxSerializer.php +++ b/lib/RoadizCoreBundle/src/Xlsx/NodeSourceXlsxSerializer.php @@ -25,7 +25,7 @@ final class NodeSourceXlsxSerializer extends AbstractXlsxSerializer public function __construct( TranslatorInterface $translator, private readonly ObjectManager $objectManager, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { parent::__construct($translator); } @@ -34,18 +34,17 @@ public function __construct( * Create a simple associative array with a NodeSource. * * @param NodesSources|iterable|null $nodeSource - * @return array */ - public function toArray($nodeSource): array + public function toArray(mixed $nodeSource): array { $data = []; if ($nodeSource instanceof NodesSources) { - if ($this->addUrls === true) { + if (true === $this->addUrls) { $data['_url'] = $this->urlGenerator->generate( RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ - RouteObjectInterface::ROUTE_OBJECT => $nodeSource + RouteObjectInterface::ROUTE_OBJECT => $nodeSource, ], UrlGeneratorInterface::ABSOLUTE_URL ); @@ -71,7 +70,6 @@ public function toArray($nodeSource): array } /** - * @param NodesSources $nodeSource * @return array */ protected function getSourceFields(NodesSources $nodeSource): array @@ -91,7 +89,6 @@ protected function getSourceFields(NodesSources $nodeSource): array } /** - * @param NodeTypeInterface $nodeType * @return NodeTypeField[] */ protected function getFields(NodeTypeInterface $nodeType): array @@ -131,32 +128,25 @@ protected function getFields(NodeTypeInterface $nodeType): array ->findBy($criteria, ['position' => 'ASC']); } - /** - * {@inheritDoc} - */ - public function deserialize($string) + public function deserialize(string $string): null { return null; } /** * Serialize only texts. - * - * @param bool $onlyTexts - * @return NodeSourceXlsxSerializer */ public function setOnlyTexts(bool $onlyTexts = true): self { $this->onlyTexts = $onlyTexts; + return $this; } - /** - * @return NodeSourceXlsxSerializer - */ public function addUrls(): self { $this->addUrls = true; + return $this; } } diff --git a/lib/RoadizCoreBundle/src/Xlsx/SerializerInterface.php b/lib/RoadizCoreBundle/src/Xlsx/SerializerInterface.php index 7cfde0e3..026cbef3 100644 --- a/lib/RoadizCoreBundle/src/Xlsx/SerializerInterface.php +++ b/lib/RoadizCoreBundle/src/Xlsx/SerializerInterface.php @@ -12,29 +12,18 @@ interface SerializerInterface { /** * Serializes data. - * - * @param mixed $obj - * - * @return mixed */ - public function serialize($obj); - + public function serialize(mixed $obj): string; /** * Create a simple associative array with an entity. - * - * @param mixed $obj - * - * @return array */ - public function toArray($obj); + public function toArray(mixed $obj): array; /** - * Deserializes a json file into a readable array of datas. + * Deserializes a json file into a readable array of data. * * @param string $string Input to deserialize - * - * @return mixed */ - public function deserialize($string); + public function deserialize(string $string): mixed; } diff --git a/lib/RoadizCoreBundle/src/Xlsx/XlsxExporter.php b/lib/RoadizCoreBundle/src/Xlsx/XlsxExporter.php index e82e931f..7cbdf331 100644 --- a/lib/RoadizCoreBundle/src/Xlsx/XlsxExporter.php +++ b/lib/RoadizCoreBundle/src/Xlsx/XlsxExporter.php @@ -12,11 +12,11 @@ use Symfony\Contracts\Translation\TranslatorInterface; /** - * @deprecated XLSX serialization is deprecated and will be removed in next major version. + * @deprecated XLSX serialization is deprecated and will be removed in next major version */ -class XlsxExporter +readonly class XlsxExporter { - public function __construct(protected readonly TranslatorInterface $translator) + public function __construct(protected TranslatorInterface $translator) { } @@ -27,6 +27,7 @@ public function __construct(protected readonly TranslatorInterface $translator) * @param array $keys * * @return string + * * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ @@ -35,9 +36,9 @@ public function exportXlsx($data, $keys = []) $spreadsheet = new Spreadsheet(); // Set document properties - $spreadsheet->getProperties()->setCreator("Roadiz CMS") - ->setLastModifiedBy("Roadiz CMS") - ->setCategory(""); + $spreadsheet->getProperties()->setCreator('Roadiz CMS') + ->setLastModifiedBy('Roadiz CMS') + ->setCategory(''); $spreadsheet->setActiveSheetIndex(0); $activeSheet = $spreadsheet->getActiveSheet(); @@ -60,10 +61,10 @@ public function exportXlsx($data, $keys = []) if (count($keys) > 0) { foreach ($keys as $key => $value) { $columnAlpha = Coordinate::stringFromColumnIndex($key + 1); - $activeSheet->getStyle($columnAlpha . ($activeRow))->applyFromArray($headerStyles); + $activeSheet->getStyle($columnAlpha.$activeRow)->applyFromArray($headerStyles); $activeSheet->setCellValueByColumnAndRow($key + 1, $activeRow, $this->translator->trans($value)); } - $activeRow++; + ++$activeRow; $hasGlobalHeader = true; } @@ -75,19 +76,19 @@ public function exportXlsx($data, $keys = []) * we print them */ if ( - false === $hasGlobalHeader && - $headerkeys != array_keys($answer) + false === $hasGlobalHeader + && $headerkeys != array_keys($answer) ) { $headerkeys = array_keys($answer); foreach ($headerkeys as $key => $value) { $columnAlpha = Coordinate::stringFromColumnIndex($key + 1); - $activeSheet->getStyle($columnAlpha . $activeRow)->applyFromArray($headerStyles); + $activeSheet->getStyle($columnAlpha.$activeRow)->applyFromArray($headerStyles); if (\is_string($value)) { $value = $this->translator->trans($value); } $activeSheet->setCellValueByColumnAndRow($key + 1, $activeRow, $value); } - $activeRow++; + ++$activeRow; } /* @@ -98,26 +99,26 @@ public function exportXlsx($data, $keys = []) $columnAlpha = Coordinate::stringFromColumnIndex($k + 1); if ( - $value instanceof Collection || - is_array($value) + $value instanceof Collection + || is_array($value) ) { continue; } if ($value instanceof \DateTimeInterface) { $value = Date::PHPToExcel($value); - $activeSheet->getStyle($columnAlpha . ($activeRow)) + $activeSheet->getStyle($columnAlpha.$activeRow) ->getNumberFormat() ->setFormatCode('dd.mm.yyyy hh:MM:ss'); } /* * Set value into cell */ - $activeSheet->getStyle($columnAlpha . $activeRow)->getAlignment()->setWrapText(true); + $activeSheet->getStyle($columnAlpha.$activeRow)->getAlignment()->setWrapText(true); $activeSheet->setCellValueByColumnAndRow($k + 1, $activeRow, $this->translator->trans((string) $value)); } - $activeRow++; + ++$activeRow; } /* @@ -129,7 +130,6 @@ public function exportXlsx($data, $keys = []) ->setWidth(50); } - // Set active sheet index to the first sheet, so Excel opens this as the first sheet $writer = new Xlsx($spreadsheet); ob_start(); @@ -139,6 +139,7 @@ public function exportXlsx($data, $keys = []) if (!\is_string($output)) { throw new \RuntimeException('Output is not a string.'); } + return $output; } } diff --git a/lib/RoadizCoreBundle/tests/NodeType/ApiResourceGeneratorTest.php b/lib/RoadizCoreBundle/tests/NodeType/ApiResourceGeneratorTest.php index a1e633eb..1424881c 100644 --- a/lib/RoadizCoreBundle/tests/NodeType/ApiResourceGeneratorTest.php +++ b/lib/RoadizCoreBundle/tests/NodeType/ApiResourceGeneratorTest.php @@ -16,7 +16,7 @@ class ApiResourceGeneratorTest extends KernelTestCase { protected static function getGeneratedPath(): string { - return dirname(__DIR__) . '/generated_api_resources'; + return dirname(__DIR__).'/generated_api_resources'; } protected function getApiResourceGenerator(): ApiResourceGenerator @@ -45,7 +45,7 @@ public function testGenerate(): void $resourcePath = $apiResourceGenerator->getResourcePath($nodeType); $this->assertFileExists($resourcePath); $this->assertFileEquals( - dirname(__DIR__) . '/expected_api_resources/nstest.yml', + dirname(__DIR__).'/expected_api_resources/nstest.yml', $resourcePath ); } @@ -61,14 +61,14 @@ public function testReachableGenerate(): void $apiResourceGenerator->generate($nodeType); $resourcePath = $apiResourceGenerator->getResourcePath($nodeType); $this->assertFileExists($resourcePath); - $this->assertFileExists(dirname(__DIR__) . '/generated_api_resources/web_response.yml'); + $this->assertFileExists(dirname(__DIR__).'/generated_api_resources/web_response.yml'); $this->assertFileEquals( - dirname(__DIR__) . '/expected_api_resources/nstest.yml', + dirname(__DIR__).'/expected_api_resources/nstest.yml', $resourcePath ); $this->assertFileEquals( - dirname(__DIR__) . '/expected_api_resources/web_response.yml', - dirname(__DIR__) . '/generated_api_resources/web_response.yml', + dirname(__DIR__).'/expected_api_resources/web_response.yml', + dirname(__DIR__).'/generated_api_resources/web_response.yml', ); } @@ -88,7 +88,7 @@ public function testMultipleGenerate(): void $resourcePath = $apiResourceGenerator->getResourcePath($nodeType); $this->assertFileExists($resourcePath); $this->assertFileEquals( - dirname(__DIR__) . '/expected_api_resources/nstest.yml', + dirname(__DIR__).'/expected_api_resources/nstest.yml', $resourcePath ); @@ -96,14 +96,14 @@ public function testMultipleGenerate(): void $resourcePath2 = $apiResourceGenerator->getResourcePath($nodeType2); $this->assertFileExists($resourcePath2); $this->assertFileEquals( - dirname(__DIR__) . '/expected_api_resources/nssecondtest.yml', + dirname(__DIR__).'/expected_api_resources/nssecondtest.yml', $resourcePath2 ); - $this->assertFileExists(dirname(__DIR__) . '/generated_api_resources/web_response.yml'); + $this->assertFileExists(dirname(__DIR__).'/generated_api_resources/web_response.yml'); $this->assertFileEquals( - dirname(__DIR__) . '/expected_api_resources/web_response_multiple.yml', - dirname(__DIR__) . '/generated_api_resources/web_response.yml', + dirname(__DIR__).'/expected_api_resources/web_response_multiple.yml', + dirname(__DIR__).'/generated_api_resources/web_response.yml', ); } @@ -128,10 +128,10 @@ public function testRemoveGenerate(): void $resourcePath2 = $apiResourceGenerator->getResourcePath($nodeType2); $this->assertFileDoesNotExist($resourcePath2); - $this->assertFileExists(dirname(__DIR__) . '/generated_api_resources/web_response.yml'); + $this->assertFileExists(dirname(__DIR__).'/generated_api_resources/web_response.yml'); $this->assertFileEquals( - dirname(__DIR__) . '/expected_api_resources/web_response.yml', - dirname(__DIR__) . '/generated_api_resources/web_response.yml', + dirname(__DIR__).'/expected_api_resources/web_response.yml', + dirname(__DIR__).'/generated_api_resources/web_response.yml', ); } @@ -143,7 +143,6 @@ protected function setUp(): void $filesystem->mkdir(static::getGeneratedPath()); } - protected function tearDown(): void { parent::tearDown(); diff --git a/lib/RoadizCoreBundle/tests/bootstrap.php b/lib/RoadizCoreBundle/tests/bootstrap.php index 7cfee6d9..39bdebc4 100644 --- a/lib/RoadizCoreBundle/tests/bootstrap.php +++ b/lib/RoadizCoreBundle/tests/bootstrap.php @@ -1,5 +1,7 @@ bootEnv(__DIR__ . '/../.env'); +(new Dotenv())->bootEnv(__DIR__.'/../.env'); $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']); $kernel->boot(); + return $kernel->getContainer()->get('doctrine')->getManager(); diff --git a/lib/RoadizFontBundle/src/Controller/Admin/FontsController.php b/lib/RoadizFontBundle/src/Controller/Admin/FontsController.php index 894ea810..96569531 100644 --- a/lib/RoadizFontBundle/src/Controller/Admin/FontsController.php +++ b/lib/RoadizFontBundle/src/Controller/Admin/FontsController.php @@ -27,121 +27,82 @@ class FontsController extends AbstractAdminController public function __construct( FilesystemOperator $fontStorage, SerializerInterface $serializer, - UrlGeneratorInterface $urlGenerator + UrlGeneratorInterface $urlGenerator, ) { parent::__construct($serializer, $urlGenerator); $this->fontStorage = $fontStorage; } - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof Font; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'font'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { return new Font(); } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizFont/admin'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_FONTS'; } - /** - * @inheritDoc - */ protected function getEntityClass(): string { return Font::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return FontType::class; } - /** - * @inheritDoc - */ protected function getDefaultOrder(Request $request): array { return ['name' => 'ASC']; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'fontsHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'fontsEditPage'; } - /** - * @inheritDoc - */ protected function createUpdateEvent(PersistableInterface $item): ?Event { if ($item instanceof Font) { return new PreUpdatedFontEvent($item); } + return null; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { if ($item instanceof Font) { return $item->getName(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } /** * Return a ZipArchive of requested font. * - * @param Request $request - * @param int $id - * - * @return BinaryFileResponse * @throws FilesystemException */ public function downloadAction(Request $request, int $id): BinaryFileResponse @@ -151,37 +112,37 @@ public function downloadAction(Request $request, int $id): BinaryFileResponse /** @var Font|null $font */ $font = $this->em()->find(Font::class, $id); - if ($font !== null) { + if (null !== $font) { // Prepare File - $file = tempnam(sys_get_temp_dir(), "font_" . $font->getId()); + $file = tempnam(sys_get_temp_dir(), 'font_'.$font->getId()); if (false === $file) { throw new \RuntimeException('Cannot create temporary file.'); } $zip = new \ZipArchive(); $zip->open($file, \ZipArchive::CREATE); - if ("" != $font->getEOTFilename()) { + if ('' != $font->getEOTFilename()) { $zip->addFromString($font->getEOTFilename(), $this->fontStorage->read($font->getEOTRelativeUrl())); } - if ("" != $font->getSVGFilename()) { + if ('' != $font->getSVGFilename()) { $zip->addFromString($font->getSVGFilename(), $this->fontStorage->read($font->getSVGRelativeUrl())); } - if ("" != $font->getWOFFFilename()) { + if ('' != $font->getWOFFFilename()) { $zip->addFromString($font->getWOFFFilename(), $this->fontStorage->read($font->getWOFFRelativeUrl())); } - if ("" != $font->getWOFF2Filename()) { + if ('' != $font->getWOFF2Filename()) { $zip->addFromString($font->getWOFF2Filename(), $this->fontStorage->read($font->getWOFF2RelativeUrl())); } - if ("" != $font->getOTFFilename()) { + if ('' != $font->getOTFFilename()) { $zip->addFromString($font->getOTFFilename(), $this->fontStorage->read($font->getOTFRelativeUrl())); } // Close and send to users $zip->close(); - $filename = StringHandler::slugify($font->getName() . ' ' . $font->getReadableVariant()) . '.zip'; + $filename = StringHandler::slugify($font->getName().' '.$font->getReadableVariant()).'.zip'; return (new BinaryFileResponse($file, Response::HTTP_OK, [ 'content-type' => 'application/zip', - 'content-disposition' => 'attachment; filename=' . $filename, + 'content-disposition' => 'attachment; filename='.$filename, ], false))->deleteFileAfterSend(true); } diff --git a/lib/RoadizFontBundle/src/Controller/FontFaceController.php b/lib/RoadizFontBundle/src/Controller/FontFaceController.php index 54805b54..c6268f0a 100644 --- a/lib/RoadizFontBundle/src/Controller/FontFaceController.php +++ b/lib/RoadizFontBundle/src/Controller/FontFaceController.php @@ -28,27 +28,27 @@ private function getFontData(Font $font, string $extension): ?array return match ($extension) { 'eot' => [ $this->fontStorage->read($font->getEOTRelativeUrl()), - Font::MIME_EOT + Font::MIME_EOT, ], 'woff' => [ $this->fontStorage->read($font->getWOFFRelativeUrl()), - Font::MIME_WOFF + Font::MIME_WOFF, ], 'woff2' => [ $this->fontStorage->read($font->getWOFF2RelativeUrl()), - Font::MIME_WOFF2 + Font::MIME_WOFF2, ], 'svg' => [ $this->fontStorage->read($font->getSVGRelativeUrl()), - Font::MIME_SVG + Font::MIME_SVG, ], 'otf' => [ $this->fontStorage->read($font->getOTFRelativeUrl()), - Font::MIME_OTF + Font::MIME_OTF, ], 'ttf' => [ $this->fontStorage->read($font->getOTFRelativeUrl()), - Font::MIME_TTF + Font::MIME_TTF, ], default => null, }; @@ -60,12 +60,6 @@ private function getFontData(Font $font, string $extension): ?array /** * Request a single protected font file from Roadiz. * - * @param Request $request - * @param string $filename - * @param int $variant - * @param string $extension - * - * @return Response * @throws \Exception */ public function fontFileAction(Request $request, string $filename, int $variant, string $extension): Response @@ -103,7 +97,7 @@ public function fontFileAction(Request $request, string $filename, int $variant, return $response; } } - $msg = "Font doesn't exist " . $filename; + $msg = "Font doesn't exist ".$filename; return new Response( $msg, @@ -115,9 +109,6 @@ public function fontFileAction(Request $request, string $filename, int $variant, /** * Request the font-face CSS file listing available fonts. * - * @param Request $request - * - * @return Response * @throws \Exception */ public function fontFacesAction(Request $request): Response @@ -151,7 +142,7 @@ public function fontFacesAction(Request $request): Response ]; /** @var Font $font */ foreach ($fonts as $font) { - $variantHash = $font->getHash() . $font->getVariant(); + $variantHash = $font->getHash().$font->getVariant(); $assignation['fonts'][] = [ 'font' => $font, 'variantHash' => $variantHash, diff --git a/lib/RoadizFontBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php b/lib/RoadizFontBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php index 0c30e6b7..5370dfdf 100644 --- a/lib/RoadizFontBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php +++ b/lib/RoadizFontBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php @@ -4,15 +4,11 @@ namespace RZ\Roadiz\FontBundle\DependencyInjection\Compiler; -use RuntimeException; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class DoctrineMigrationCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->hasDefinition('doctrine.migrations.configuration')) { @@ -27,13 +23,13 @@ public function process(ContainerBuilder $container): void private function checkIfBundleRelativePath(string $path, ContainerBuilder $container): string { - if (isset($path[0]) && $path[0] === '@') { - $pathParts = explode('/', $path); + if (isset($path[0]) && '@' === $path[0]) { + $pathParts = explode('/', $path); $bundleName = \mb_substr($pathParts[0], 1); $bundlePath = $this->getBundlePath($bundleName, $container); - return $bundlePath . \mb_substr($path, \mb_strlen('@' . $bundleName)); + return $bundlePath.\mb_substr($path, \mb_strlen('@'.$bundleName)); } return $path; @@ -44,14 +40,8 @@ private function getBundlePath(string $bundleName, ContainerBuilder $container): $bundleMetadata = $container->getParameter('kernel.bundles_metadata'); assert(is_array($bundleMetadata)); - if (! isset($bundleMetadata[$bundleName])) { - throw new RuntimeException( - sprintf( - 'The bundle "%s" has not been registered, available bundles: %s', - $bundleName, - implode(', ', array_keys($bundleMetadata)) - ) - ); + if (!isset($bundleMetadata[$bundleName])) { + throw new \RuntimeException(sprintf('The bundle "%s" has not been registered, available bundles: %s', $bundleName, implode(', ', array_keys($bundleMetadata)))); } return $bundleMetadata[$bundleName]['path']; diff --git a/lib/RoadizFontBundle/src/DependencyInjection/RoadizFontExtension.php b/lib/RoadizFontBundle/src/DependencyInjection/RoadizFontExtension.php index 256a0d6e..3b610728 100644 --- a/lib/RoadizFontBundle/src/DependencyInjection/RoadizFontExtension.php +++ b/lib/RoadizFontBundle/src/DependencyInjection/RoadizFontExtension.php @@ -16,12 +16,9 @@ public function getAlias(): string return 'roadiz_font'; } - /** - * @inheritDoc - */ public function load(array $configs, ContainerBuilder $container): void { - $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__) . '/../config')); + $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__).'/../config')); $loader->load('services.yaml'); } } diff --git a/lib/RoadizFontBundle/src/Doctrine/EventSubscriber/FontLifeCycleSubscriber.php b/lib/RoadizFontBundle/src/Doctrine/EventSubscriber/FontLifeCycleSubscriber.php index c3ce3ac8..49252430 100644 --- a/lib/RoadizFontBundle/src/Doctrine/EventSubscriber/FontLifeCycleSubscriber.php +++ b/lib/RoadizFontBundle/src/Doctrine/EventSubscriber/FontLifeCycleSubscriber.php @@ -31,7 +31,7 @@ final class FontLifeCycleSubscriber public function __construct( private readonly FilesystemOperator $fontStorage, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } @@ -79,8 +79,8 @@ public function preRemove(PreRemoveEventArgs $args): void try { // factorize previous code with loop foreach (self::$formats as $format) { - $getter = 'get' . \mb_strtoupper($format) . 'Filename'; - $relativeUrlGetter = 'get' . \mb_strtoupper($format) . 'RelativeUrl'; + $getter = 'get'.\mb_strtoupper($format).'Filename'; + $relativeUrlGetter = 'get'.\mb_strtoupper($format).'RelativeUrl'; if (null !== $entity->$getter() && $this->fontStorage->fileExists($entity->$relativeUrlGetter())) { $this->fontStorage->delete($entity->$relativeUrlGetter()); $this->logger->info('Font file deleted', ['file' => $entity->$relativeUrlGetter()]); @@ -100,38 +100,36 @@ public function preRemove(PreRemoveEventArgs $args): void } } } catch (FilesystemException $e) { - //do nothing + // do nothing } } } public function setFontFilesNames(Font $font): void { - if ($font->getHash() == "") { + if ('' == $font->getHash()) { $font->generateHashWithSecret('default_roadiz_secret'); } foreach (self::$formats as $format) { /** @var UploadedFile|null $file */ - $file = $font->{'get' . ucfirst($format) . 'File'}(); + $file = $font->{'get'.ucfirst($format).'File'}(); if (null !== $file) { - $font->{'set' . \mb_strtoupper($format) . 'Filename'}($file->getClientOriginalName()); + $font->{'set'.\mb_strtoupper($format).'Filename'}($file->getClientOriginalName()); } } } /** - * @param Font $font - * @return void * @throws FilesystemException */ public function upload(Font $font): void { foreach (self::$formats as $format) { /** @var UploadedFile|null $file */ - $file = $font->{'get' . ucfirst($format) . 'File'}(); + $file = $font->{'get'.ucfirst($format).'File'}(); /** @var string|null $relativeUrl */ - $relativeUrl = $font->{'get' . \mb_strtoupper($format) . 'RelativeUrl'}(); + $relativeUrl = $font->{'get'.\mb_strtoupper($format).'RelativeUrl'}(); if (null !== $file && null !== $relativeUrl) { $filename = $file->getPathname(); $fontResource = fopen($file->getPathname(), 'r'); @@ -140,7 +138,7 @@ public function upload(Font $font): void $relativeUrl, $fontResource ); - $font->{'set' . ucfirst($format) . 'File'}(null); + $font->{'set'.ucfirst($format).'File'}(null); fclose($fontResource); $this->logger->info('Font file uploaded', ['file' => $relativeUrl]); } diff --git a/lib/RoadizFontBundle/src/Entity/Font.php b/lib/RoadizFontBundle/src/Entity/Font.php index 39cc3de6..ebb3316a 100644 --- a/lib/RoadizFontBundle/src/Entity/Font.php +++ b/lib/RoadizFontBundle/src/Entity/Font.php @@ -18,11 +18,11 @@ */ #[ ORM\Entity(repositoryClass: FontRepository::class), - ORM\Table(name: "fonts"), - ORM\UniqueConstraint(columns: ["name", "variant"]), - ORM\Index(columns: ["created_at"], name: "font_created_at"), - ORM\Index(columns: ["updated_at"], name: "font_updated_at"), - UniqueEntity(fields: ["name", "variant"]) + ORM\Table(name: 'fonts'), + ORM\UniqueConstraint(columns: ['name', 'variant']), + ORM\Index(columns: ['created_at'], name: 'font_created_at'), + ORM\Index(columns: ['updated_at'], name: 'font_updated_at'), + UniqueEntity(fields: ['name', 'variant']) ] class Font extends AbstractDateTimed { @@ -54,7 +54,7 @@ class Font extends AbstractDateTimed public const MIME_EOT = 'application/vnd.ms-fontobject'; /** - * Get readable variant association + * Get readable variant association. * * @var array */ @@ -130,36 +130,30 @@ class Font extends AbstractDateTimed */ public function __construct() { - $this->folder = \mb_substr(hash("crc32b", date('YmdHi')), 0, 12); + $this->folder = \mb_substr(hash('crc32b', date('YmdHi')), 0, 12); $this->initAbstractDateTimed(); } /** * Get a readable string to describe current font variant. - * - * @return string */ public function getReadableVariant(): string { return static::$variantToHuman[$this->getVariant()]; } - /** - * @return int - */ public function getVariant(): int { return $this->variant; } /** - * @param int $variant - * * @return $this */ public function setVariant(int $variant): Font { $this->variant = $variant; + return $this; } @@ -171,7 +165,6 @@ public function setVariant(int $variant): Font * * weight * * @see https://developer.mozilla.org/fr/docs/Web/CSS/font-weight - * @return array */ public function getFontVariantInfos(): array { @@ -287,35 +280,27 @@ public function getFontVariantInfos(): array } } - /** - * @return string - */ public function getName(): string { return $this->name; } /** - * @param string $name * @return $this */ public function setName(string $name): Font { $this->name = $name; + return $this; } - /** - * @return string - */ public function getHash(): string { return $this->hash; } /** - * @param string $hash - * * @return $this */ public function setHash(string $hash): Font @@ -326,178 +311,137 @@ public function setHash(string $hash): Font } /** - * @param string $secret * @return $this */ public function generateHashWithSecret(string $secret): Font { - $this->hash = \mb_substr(hash("crc32b", $this->name . $secret), 0, 12); + $this->hash = \mb_substr(hash('crc32b', $this->name.$secret), 0, 12); return $this; } - /** - * @return string|null - */ public function getEOTRelativeUrl(): ?string { - return $this->getFolder() . '/' . $this->getEOTFilename(); + return $this->getFolder().'/'.$this->getEOTFilename(); } - /** - * @return string - */ public function getFolder(): string { return $this->folder; } - /** - * @return string|null - */ public function getEOTFilename(): ?string { return $this->eotFilename; } /** - * @param string|null $eotFilename * @return $this */ public function setEOTFilename(?string $eotFilename): Font { $this->eotFilename = StringHandler::cleanForFilename($eotFilename); + return $this; } - /** - * @return string|null - */ public function getWOFFRelativeUrl(): ?string { - return $this->getFolder() . '/' . $this->getWOFFFilename(); + return $this->getFolder().'/'.$this->getWOFFFilename(); } - /** - * @return string|null - */ public function getWOFFFilename(): ?string { return $this->woffFilename; } /** - * @param string|null $woffFilename * @return $this */ public function setWOFFFilename(?string $woffFilename): Font { $this->woffFilename = StringHandler::cleanForFilename($woffFilename); + return $this; } - /** - * @return string|null - */ public function getWOFF2RelativeUrl(): ?string { - return $this->getFolder() . '/' . $this->getWOFF2Filename(); + return $this->getFolder().'/'.$this->getWOFF2Filename(); } - /** - * @return string|null - */ public function getWOFF2Filename(): ?string { return $this->woff2Filename; } /** - * @param string|null $woff2Filename - * * @return $this */ public function setWOFF2Filename(?string $woff2Filename): Font { $this->woff2Filename = StringHandler::cleanForFilename($woff2Filename); + return $this; } - /** - * @return string|null - */ public function getOTFRelativeUrl(): ?string { - return $this->getFolder() . '/' . $this->getOTFFilename(); + return $this->getFolder().'/'.$this->getOTFFilename(); } - /** - * @return string|null - */ public function getOTFFilename(): ?string { return $this->otfFilename; } /** - * @param string|null $otfFilename * @return $this */ public function setOTFFilename(?string $otfFilename): Font { $this->otfFilename = StringHandler::cleanForFilename($otfFilename); + return $this; } - /** - * @return string|null - */ public function getSVGRelativeUrl(): ?string { - return $this->getFolder() . '/' . $this->getSVGFilename(); + return $this->getFolder().'/'.$this->getSVGFilename(); } - /** - * @return string|null - */ public function getSVGFilename(): ?string { return $this->svgFilename; } /** - * @param string|null $svgFilename * @return $this */ public function setSVGFilename(?string $svgFilename): Font { $this->svgFilename = StringHandler::cleanForFilename($svgFilename); + return $this; } - /** - * @return string|null - */ public function getDescription(): ?string { return $this->description; } /** - * @param string|null $description - * * @return $this */ public function setDescription(?string $description): Font { $this->description = $description; + return $this; } /** * Gets the value of eotFile. - * - * @return UploadedFile|null */ public function getEotFile(): ?UploadedFile { @@ -508,18 +452,16 @@ public function getEotFile(): ?UploadedFile * Sets the value of eotFile. * * @param UploadedFile|null $eotFile the eot file - * @return Font */ public function setEotFile(?UploadedFile $eotFile): Font { $this->eotFile = $eotFile; + return $this; } /** * Gets the value of woffFile. - * - * @return UploadedFile|null */ public function getWoffFile(): ?UploadedFile { @@ -530,18 +472,16 @@ public function getWoffFile(): ?UploadedFile * Sets the value of woffFile. * * @param UploadedFile|null $woffFile the woff file - * @return Font */ public function setWoffFile(?UploadedFile $woffFile): Font { $this->woffFile = $woffFile; + return $this; } /** * Gets the value of woff2File. - * - * @return UploadedFile|null */ public function getWoff2File(): ?UploadedFile { @@ -552,18 +492,16 @@ public function getWoff2File(): ?UploadedFile * Sets the value of woff2File. * * @param UploadedFile|null $woff2File the woff2 file - * @return Font */ public function setWoff2File(?UploadedFile $woff2File): Font { $this->woff2File = $woff2File; + return $this; } /** * Gets the value of otfFile. - * - * @return UploadedFile|null */ public function getOtfFile(): ?UploadedFile { @@ -574,18 +512,16 @@ public function getOtfFile(): ?UploadedFile * Sets the value of otfFile. * * @param UploadedFile|null $otfFile the otf file - * @return Font */ public function setOtfFile(?UploadedFile $otfFile): Font { $this->otfFile = $otfFile; + return $this; } /** * Gets the value of svgFile. - * - * @return UploadedFile|null */ public function getSvgFile(): ?UploadedFile { @@ -596,11 +532,11 @@ public function getSvgFile(): ?UploadedFile * Sets the value of svgFile. * * @param UploadedFile|null $svgFile the svg file - * @return Font */ public function setSvgFile(?UploadedFile $svgFile): Font { $this->svgFile = $svgFile; + return $this; } } diff --git a/lib/RoadizFontBundle/src/Event/Font/FontEvent.php b/lib/RoadizFontBundle/src/Event/Font/FontEvent.php index 18bc115a..5513ce95 100644 --- a/lib/RoadizFontBundle/src/Event/Font/FontEvent.php +++ b/lib/RoadizFontBundle/src/Event/Font/FontEvent.php @@ -9,34 +9,22 @@ abstract class FontEvent extends Event { - /** - * @var Font|null - */ protected ?Font $font = null; - /** - * @param Font|null $font - */ public function __construct(?Font $font) { $this->font = $font; } - /** - * @return Font|null - */ public function getFont(): ?Font { return $this->font; } - /** - * @param Font|null $font - * @return FontEvent - */ public function setFont(?Font $font): FontEvent { $this->font = $font; + return $this; } } diff --git a/lib/RoadizFontBundle/src/EventSubscriber/UpdateFontSubscriber.php b/lib/RoadizFontBundle/src/EventSubscriber/UpdateFontSubscriber.php index dbdd92d1..72d6702a 100644 --- a/lib/RoadizFontBundle/src/EventSubscriber/UpdateFontSubscriber.php +++ b/lib/RoadizFontBundle/src/EventSubscriber/UpdateFontSubscriber.php @@ -11,8 +11,6 @@ /** * Calls font life cycle methods when no data changed according to Doctrine. - * - * @package RZ\Roadiz\CoreBundle\Event */ final class UpdateFontSubscriber implements EventSubscriberInterface { @@ -20,9 +18,6 @@ public function __construct(private readonly FontLifeCycleSubscriber $fontSubscr { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizFontBundle/src/Form/FontType.php b/lib/RoadizFontBundle/src/Form/FontType.php index 9c860531..39ece505 100644 --- a/lib/RoadizFontBundle/src/Form/FontType.php +++ b/lib/RoadizFontBundle/src/Form/FontType.php @@ -17,17 +17,13 @@ */ class FontType extends AbstractType { - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('name', TextType::class, [ - 'label' => 'font.name', - 'empty_data' => '', - 'help' => 'font_name_should_be_the_same_for_all_variants', - ]) + 'label' => 'font.name', + 'empty_data' => '', + 'help' => 'font_name_should_be_the_same_for_all_variants', + ]) ->add('hash', TextType::class, [ 'label' => 'font.cssfamily', 'empty_data' => '', diff --git a/lib/RoadizFontBundle/src/Form/FontVariantsType.php b/lib/RoadizFontBundle/src/Form/FontVariantsType.php index 4a76fe6d..89d280ac 100644 --- a/lib/RoadizFontBundle/src/Form/FontVariantsType.php +++ b/lib/RoadizFontBundle/src/Form/FontVariantsType.php @@ -15,7 +15,6 @@ class FontVariantsType extends AbstractType { /** - * {@inheritdoc} * @param OptionsResolver $resolver [description] */ public function configureOptions(OptionsResolver $resolver): void @@ -24,16 +23,12 @@ public function configureOptions(OptionsResolver $resolver): void 'choices' => array_flip(Font::$variantToHuman), ]); } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'font_variants'; diff --git a/lib/RoadizFontBundle/src/Repository/FontRepository.php b/lib/RoadizFontBundle/src/Repository/FontRepository.php index de702bfa..b53221e5 100644 --- a/lib/RoadizFontBundle/src/Repository/FontRepository.php +++ b/lib/RoadizFontBundle/src/Repository/FontRepository.php @@ -18,7 +18,7 @@ final class FontRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, Font::class, $dispatcher); } diff --git a/lib/RoadizRozierBundle/src/Controller/Document/DocumentArchiveController.php b/lib/RoadizRozierBundle/src/Controller/Document/DocumentArchiveController.php index 4c1f4b20..c524a76b 100644 --- a/lib/RoadizRozierBundle/src/Controller/Document/DocumentArchiveController.php +++ b/lib/RoadizRozierBundle/src/Controller/Document/DocumentArchiveController.php @@ -24,16 +24,13 @@ final class DocumentArchiveController extends RozierApp public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly TranslatorInterface $translator, - private readonly DocumentArchiver $documentArchiver + private readonly DocumentArchiver $documentArchiver, ) { } /** * Return an deletion form for multiple docs. * - * @param Request $request - * - * @return Response * @throws FilesystemException * @throws RuntimeError */ @@ -71,7 +68,7 @@ public function bulkDownloadAction(Request $request): Response } $this->assignation['form'] = $form->createView(); - $this->assignation['action'] = '?' . http_build_query(['documents' => $documentsIds]); + $this->assignation['action'] = '?'.http_build_query(['documents' => $documentsIds]); $this->assignation['thumbnailFormat'] = [ 'quality' => 50, 'fit' => '128x128', @@ -88,14 +85,13 @@ public function bulkDownloadAction(Request $request): Response throw new ResourceNotFoundException(); } - private function buildBulkDownloadForm(array $documentsIds): FormInterface { $defaults = [ 'checksum' => md5(serialize($documentsIds)), ]; $builder = $this->createFormBuilder($defaults, [ - 'action' => '?' . http_build_query(['documents' => $documentsIds]), + 'action' => '?'.http_build_query(['documents' => $documentsIds]), ]) ->add('checksum', HiddenType::class, [ 'constraints' => [ diff --git a/lib/RoadizRozierBundle/src/Controller/Document/DocumentDuplicatesController.php b/lib/RoadizRozierBundle/src/Controller/Document/DocumentDuplicatesController.php index 21f3a635..b70a1f97 100644 --- a/lib/RoadizRozierBundle/src/Controller/Document/DocumentDuplicatesController.php +++ b/lib/RoadizRozierBundle/src/Controller/Document/DocumentDuplicatesController.php @@ -19,10 +19,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) { } - /** - * @param Request $request - * @return Response - */ public function duplicatedAction(Request $request): Response { $this->denyAccessUnlessGranted('ROLE_ACCESS_DOCUMENTS'); diff --git a/lib/RoadizRozierBundle/src/Controller/Document/DocumentLimitationsController.php b/lib/RoadizRozierBundle/src/Controller/Document/DocumentLimitationsController.php index cc83453d..d471ae4f 100644 --- a/lib/RoadizRozierBundle/src/Controller/Document/DocumentLimitationsController.php +++ b/lib/RoadizRozierBundle/src/Controller/Document/DocumentLimitationsController.php @@ -37,10 +37,11 @@ public function limitationsAction(Request $request, Document $document): Respons ); $this->managerRegistry->getManager()->flush(); + return $this->redirectToRoute( 'documentsLimitationsPage', [ - 'id' => $document->getId() + 'id' => $document->getId(), ] ); } diff --git a/lib/RoadizRozierBundle/src/Controller/Document/DocumentPreviewController.php b/lib/RoadizRozierBundle/src/Controller/Document/DocumentPreviewController.php index bf5d26d3..42f37267 100644 --- a/lib/RoadizRozierBundle/src/Controller/Document/DocumentPreviewController.php +++ b/lib/RoadizRozierBundle/src/Controller/Document/DocumentPreviewController.php @@ -14,19 +14,12 @@ class DocumentPreviewController extends RozierApp { private DocumentFinderInterface $documentFinder; - /** - * @param DocumentFinderInterface $documentFinder - */ public function __construct(DocumentFinderInterface $documentFinder) { $this->documentFinder = $documentFinder; } /** - * @param Request $request - * @param Document $documentId - * - * @return Response * @throws \Twig\Error\RuntimeError */ public function previewAction(Request $request, Document $documentId): Response @@ -79,11 +72,11 @@ public function previewAction(Request $request, Document $documentId): Response $this->assignation['thumbnailFormat']['picture'] = true; $this->assignation['infos'] = []; if ($document->isProcessable() || $document->isSvg()) { - $this->assignation['infos']['width'] = $document->getImageWidth() . 'px'; - $this->assignation['infos']['height'] = $document->getImageHeight() . 'px'; + $this->assignation['infos']['width'] = $document->getImageWidth().'px'; + $this->assignation['infos']['height'] = $document->getImageHeight().'px'; } if ($document->getMediaDuration() > 0) { - $this->assignation['infos']['duration'] = $document->getMediaDuration() . ' sec'; + $this->assignation['infos']['duration'] = $document->getMediaDuration().' sec'; } return $this->render('@RoadizRozier/documents/preview.html.twig', $this->assignation); diff --git a/lib/RoadizRozierBundle/src/Controller/Document/DocumentPublicListController.php b/lib/RoadizRozierBundle/src/Controller/Document/DocumentPublicListController.php index 15a1ab1c..86e9619c 100644 --- a/lib/RoadizRozierBundle/src/Controller/Document/DocumentPublicListController.php +++ b/lib/RoadizRozierBundle/src/Controller/Document/DocumentPublicListController.php @@ -26,9 +26,6 @@ class DocumentPublicListController extends RozierApp { private array $documentPlatforms; - /** - * @param array $documentPlatforms - */ public function __construct(array $documentPlatforms) { $this->documentPlatforms = $documentPlatforms; @@ -39,6 +36,7 @@ protected function getFolder(?int $folderId): ?Folder if (null === $folderId || $folderId <= 0) { return null; } + return $this->em()->find(Folder::class, $folderId); } @@ -62,9 +60,6 @@ public function prepareBaseAssignation(): static } /** - * @param Request $request - * @param int|null $folderId - * @return Response * @throws RuntimeError */ public function indexAction(Request $request, ?int $folderId = null): Response @@ -87,12 +82,12 @@ public function indexAction(Request $request, ?int $folderId = null): Response $type = $request->query->get('type'); $embedPlatform = $request->query->get('embedPlatform'); - if (\is_string($type) && $type !== '') { + if (\is_string($type) && '' !== $type) { $prefilters['mimeType'] = trim($type); $this->assignation['mimeType'] = trim($type); } - if (\is_string($embedPlatform) && $embedPlatform !== '') { + if (\is_string($embedPlatform) && '' !== $embedPlatform) { $prefilters['embedPlatform'] = trim($embedPlatform); $this->assignation['embedPlatform'] = trim($embedPlatform); } @@ -157,15 +152,13 @@ public function indexAction(Request $request, ?int $folderId = null): Response protected function getListingTemplate(Request $request): string { - if ($request->query->get('list') === '1') { + if ('1' === $request->query->get('list')) { return '@RoadizRozier/documents/list-table.html.twig'; } + return '@RoadizRozier/documents/list.html.twig'; } - /** - * @return FormInterface - */ private function buildLinkFoldersForm(): FormInterface { $builder = $this->createNamedFormBuilder('folderForm') @@ -192,7 +185,7 @@ private function buildLinkFoldersForm(): FormInterface 'attr' => [ 'class' => 'uk-button uk-button-primary', 'title' => 'link.folders', - 'data-uk-tooltip' => "{animation:true}", + 'data-uk-tooltip' => '{animation:true}', ], ]) ->add('submitUnfolder', SubmitType::class, [ @@ -200,7 +193,7 @@ private function buildLinkFoldersForm(): FormInterface 'attr' => [ 'class' => 'uk-button', 'title' => 'unlink.folders', - 'data-uk-tooltip' => "{animation:true}", + 'data-uk-tooltip' => '{animation:true}', ], ]); @@ -208,7 +201,6 @@ private function buildLinkFoldersForm(): FormInterface } /** - * @param array $data * @return string Status message */ private function joinFolder(array $data): string @@ -216,8 +208,8 @@ private function joinFolder(array $data): string $msg = $this->getTranslator()->trans('no_documents.linked_to.folders'); if ( - !empty($data['documentsId']) && - !empty($data['folderPaths']) + !empty($data['documentsId']) + && !empty($data['folderPaths']) ) { $documentsIds = explode(',', $data['documentsId']); @@ -261,7 +253,6 @@ private function joinFolder(array $data): string } /** - * @param array $data * @return string Status message */ private function leaveFolder(array $data): string @@ -269,8 +260,8 @@ private function leaveFolder(array $data): string $msg = $this->getTranslator()->trans('no_documents.removed_from.folders'); if ( - !empty($data['documentsId']) && - !empty($data['folderPaths']) + !empty($data['documentsId']) + && !empty($data['folderPaths']) ) { $documentsIds = explode(',', $data['documentsId']); diff --git a/lib/RoadizRozierBundle/src/Controller/Document/DocumentUnusedController.php b/lib/RoadizRozierBundle/src/Controller/Document/DocumentUnusedController.php index 6958e5ab..f411ddeb 100644 --- a/lib/RoadizRozierBundle/src/Controller/Document/DocumentUnusedController.php +++ b/lib/RoadizRozierBundle/src/Controller/Document/DocumentUnusedController.php @@ -23,8 +23,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) /** * See unused documents. * - * @param Request $request - * @return Response * @throws RuntimeError */ public function unusedAction(Request $request): Response diff --git a/lib/RoadizRozierBundle/src/Controller/Login/LoginRequestController.php b/lib/RoadizRozierBundle/src/Controller/Login/LoginRequestController.php index 4fa16cbe..f25b349f 100644 --- a/lib/RoadizRozierBundle/src/Controller/Login/LoginRequestController.php +++ b/lib/RoadizRozierBundle/src/Controller/Login/LoginRequestController.php @@ -23,7 +23,7 @@ final class LoginRequestController extends RozierApp public function __construct( private readonly LoggerInterface $logger, private readonly UrlGeneratorInterface $urlGenerator, - private readonly UserViewer $userViewer + private readonly UserViewer $userViewer, ) { } @@ -33,9 +33,6 @@ protected function getUserViewer(): UserViewer } /** - * @param Request $request - * - * @return Response * @throws RuntimeError * @throws ORMException * @throws OptimisticLockException @@ -54,6 +51,7 @@ public function indexAction(Request $request): Response $this->urlGenerator ); } + /* * Always go to confirm even if email is not valid * for avoiding database sniffing. @@ -69,7 +67,6 @@ public function indexAction(Request $request): Response } /** - * @return Response * @throws RuntimeError */ public function confirmAction(): Response diff --git a/lib/RoadizRozierBundle/src/Controller/Node/NodesTagsController.php b/lib/RoadizRozierBundle/src/Controller/Node/NodesTagsController.php index 34f7c989..66606375 100644 --- a/lib/RoadizRozierBundle/src/Controller/Node/NodesTagsController.php +++ b/lib/RoadizRozierBundle/src/Controller/Node/NodesTagsController.php @@ -37,10 +37,6 @@ protected function getNodeFactory(): NodeFactory /** * Return tags form for requested node. * - * @param Request $request - * @param Node $nodeId - * - * @return Response * @throws \Twig\Error\RuntimeError */ public function editTagsAction(Request $request, Node $nodeId): Response diff --git a/lib/RoadizRozierBundle/src/Controller/Node/RealmNodeController.php b/lib/RoadizRozierBundle/src/Controller/Node/RealmNodeController.php index 129d5970..942565c6 100644 --- a/lib/RoadizRozierBundle/src/Controller/Node/RealmNodeController.php +++ b/lib/RoadizRozierBundle/src/Controller/Node/RealmNodeController.php @@ -26,7 +26,7 @@ final class RealmNodeController extends RozierApp public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly TranslatorInterface $translator, - private readonly EventDispatcherInterface $eventDispatcher + private readonly EventDispatcherInterface $eventDispatcher, ) { } @@ -58,13 +58,13 @@ public function defaultAction(Request $request, Node $id): Response 'node.%node%.joined.%realm%', [ '%node%' => $nodeSource->getTitle(), - '%realm%' => $realmNode->getRealm()->getName() + '%realm%' => $realmNode->getRealm()->getName(), ] ); $this->publishConfirmMessage($request, $msg); return $this->redirectToRoute('nodesRealmsPage', [ - 'id' => $node->getId() + 'id' => $node->getId(), ]); } @@ -109,13 +109,13 @@ public function deleteAction(Request $request, int $id, int $realmNodeId): Respo 'node.%node%.left.%realm%', [ '%node%' => $nodeSource->getTitle(), - '%realm%' => $realmNode->getRealm()->getName() + '%realm%' => $realmNode->getRealm()->getName(), ] ); $this->publishConfirmMessage($request, $msg); return $this->redirectToRoute('nodesRealmsPage', [ - 'id' => $node->getId() + 'id' => $node->getId(), ]); } diff --git a/lib/RoadizRozierBundle/src/Controller/Node/SeoController.php b/lib/RoadizRozierBundle/src/Controller/Node/SeoController.php index fb2ee2fd..ca58bddb 100644 --- a/lib/RoadizRozierBundle/src/Controller/Node/SeoController.php +++ b/lib/RoadizRozierBundle/src/Controller/Node/SeoController.php @@ -38,7 +38,7 @@ public function __construct(private readonly FormFactoryInterface $formFactory) public function editAliasesAction( Request $request, Node $nodeId, - ?Translation $translationId = null + ?Translation $translationId = null, ): Response { if (null === $translationId) { $translation = $this->em()->getRepository(Translation::class)->findDefault(); @@ -46,7 +46,7 @@ public function editAliasesAction( $translation = $translationId; } - if ($translation === null) { + if (null === $translation) { throw new ResourceNotFoundException(); } @@ -54,7 +54,7 @@ public function editAliasesAction( /** @var NodesSources|false $source */ $source = $nodeId->getNodeSourcesByTranslation($translation)->first(); - if ($source === false) { + if (false === $source) { throw new ResourceNotFoundException(); } $this->denyAccessUnlessGranted(NodeVoter::EDIT_CONTENT, $source); @@ -62,7 +62,7 @@ public function editAliasesAction( $redirections = $this->em() ->getRepository(Redirection::class) ->findBy([ - 'redirectNodeSource' => $node->getNodeSources()->toArray() + 'redirectNodeSource' => $node->getNodeSources()->toArray(), ]); $uas = $this->em() ->getRepository(UrlAlias::class) @@ -91,6 +91,7 @@ public function editAliasesAction( * Dispatch event */ $this->dispatchEvent(new NodesSourcesUpdatedEvent($source)); + return $this->redirectToRoute( 'nodesEditSEOPage', ['nodeId' => $node->getId(), 'translationId' => $translationId] @@ -122,11 +123,11 @@ public function editAliasesAction( */ $alias = new UrlAlias(); $addAliasForm = $this->formFactory->createNamed( - 'add_urlalias_' . $node->getId(), + 'add_urlalias_'.$node->getId(), UrlAliasType::class, $alias, [ - 'with_translation' => true + 'with_translation' => true, ] ); $addAliasForm->handleRequest($request); @@ -146,7 +147,7 @@ public function editAliasesAction( return $this->redirect($this->generateUrl( 'nodesEditSEOPage', ['nodeId' => $node->getId(), 'translationId' => $translationId] - ) . '#manage-aliases'); + ).'#manage-aliases'); } catch (EntityAlreadyExistsException $e) { $addAliasForm->addError(new FormError($e->getMessage())); } catch (NoTranslationAvailableException $e) { @@ -162,12 +163,6 @@ public function editAliasesAction( return $this->render('@RoadizRozier/nodes/editAliases.html.twig', $this->assignation); } - /** - * @param UrlAlias $alias - * @param Node $node - * @param Translation $translation - * @return UrlAlias - */ private function addNodeUrlAlias(UrlAlias $alias, Node $node, Translation $translation): UrlAlias { /** @var NodesSources|null $nodeSource */ @@ -177,7 +172,7 @@ private function addNodeUrlAlias(UrlAlias $alias, Node $node, Translation $trans ->setDisplayingNotPublishedNodes(true) ->findOneBy(['node' => $node, 'translation' => $translation]); - if ($nodeSource !== null) { + if (null !== $nodeSource) { $alias->setNodeSource($nodeSource); $this->em()->persist($alias); $this->em()->flush(); @@ -185,26 +180,20 @@ private function addNodeUrlAlias(UrlAlias $alias, Node $node, Translation $trans return $alias; } else { $msg = $this->getTranslator()->trans('url_alias.no_translation.%translation%', [ - '%translation%' => $translation->getName() + '%translation%' => $translation->getName(), ]); throw new NoTranslationAvailableException($msg); } } - /** - * @param UrlAlias $alias - * @param Request $request - * - * @return RedirectResponse|null - */ private function handleSingleUrlAlias(UrlAlias $alias, Request $request): ?RedirectResponse { $editForm = $this->formFactory->createNamed( - 'edit_urlalias_' . $alias->getId(), + 'edit_urlalias_'.$alias->getId(), UrlAliasType::class, $alias ); - $deleteForm = $this->formFactory->createNamed('delete_urlalias_' . $alias->getId()); + $deleteForm = $this->formFactory->createNamed('delete_urlalias_'.$alias->getId()); // Match edit $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { @@ -227,9 +216,9 @@ private function handleSingleUrlAlias(UrlAlias $alias, Request $request): ?Redir 'nodesEditSEOPage', [ 'nodeId' => $alias->getNodeSource()->getNode()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] - ) . '#manage-aliases'); + ).'#manage-aliases'); } catch (\RuntimeException $exception) { $editForm->addError(new FormError($exception->getMessage())); } @@ -258,9 +247,9 @@ private function handleSingleUrlAlias(UrlAlias $alias, Request $request): ?Redir 'nodesEditSEOPage', [ 'nodeId' => $alias->getNodeSource()->getNode()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] - ) . '#manage-aliases'); + ).'#manage-aliases'); } $this->assignation['aliases'][] = [ @@ -272,11 +261,6 @@ private function handleSingleUrlAlias(UrlAlias $alias, Request $request): ?Redir return null; } - /** - * @param NodesSources $source - * @param Request $request - * @return RedirectResponse|null - */ private function handleAddRedirection(NodesSources $source, Request $request): ?RedirectResponse { $redirection = new Redirection(); @@ -289,7 +273,7 @@ private function handleAddRedirection(NodesSources $source, Request $request): ? $redirection, [ 'placeholder' => $this->generateUrl($source), - 'only_query' => true + 'only_query' => true, ] ); @@ -306,9 +290,9 @@ private function handleAddRedirection(NodesSources $source, Request $request): ? 'nodesEditSEOPage', [ 'nodeId' => $redirection->getRedirectNodeSource()->getNode()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] - ) . '#manage-redirections'); + ).'#manage-redirections'); } if ($source->isReachable()) { @@ -318,38 +302,34 @@ private function handleAddRedirection(NodesSources $source, Request $request): ? return null; } - /** - * @param Redirection $redirection - * @param Request $request - * @return RedirectResponse|null - */ private function handleSingleRedirection(Redirection $redirection, Request $request): ?RedirectResponse { $editForm = $this->formFactory->createNamed( - 'edit_redirection_' . $redirection->getId(), + 'edit_redirection_'.$redirection->getId(), RedirectionType::class, $redirection, [ - 'only_query' => true + 'only_query' => true, ] ); /** @var Translation $translation */ $translation = $redirection->getRedirectNodeSource()->getTranslation(); - $deleteForm = $this->formFactory->createNamed('delete_redirection_' . $redirection->getId()); + $deleteForm = $this->formFactory->createNamed('delete_redirection_'.$redirection->getId()); $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { $this->em()->flush(); $this->dispatchEvent(new PostUpdatedRedirectionEvent($redirection)); + return $this->redirect($this->generateUrl( 'nodesEditSEOPage', [ 'nodeId' => $redirection->getRedirectNodeSource()->getNode()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] - ) . '#manage-redirections'); + ).'#manage-redirections'); } // Match delete @@ -358,13 +338,14 @@ private function handleSingleRedirection(Redirection $redirection, Request $requ $this->em()->remove($redirection); $this->em()->flush(); $this->dispatchEvent(new PostCreatedRedirectionEvent($redirection)); + return $this->redirect($this->generateUrl( 'nodesEditSEOPage', [ 'nodeId' => $redirection->getRedirectNodeSource()->getNode()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] - ) . '#manage-redirections'); + ).'#manage-redirections'); } $this->assignation['redirections'][] = [ 'redirection' => $redirection, diff --git a/lib/RoadizRozierBundle/src/Controller/Node/TranslateController.php b/lib/RoadizRozierBundle/src/Controller/Node/TranslateController.php index 0745ce17..affaf69e 100644 --- a/lib/RoadizRozierBundle/src/Controller/Node/TranslateController.php +++ b/lib/RoadizRozierBundle/src/Controller/Node/TranslateController.php @@ -58,6 +58,7 @@ public function translateAction(Request $request, Node $nodeId): Response $msg, $nodeSource ?: null ); + return $this->redirectToRoute( 'nodesEditSourcePage', ['nodeId' => $node->getId(), 'translationId' => $destinationTranslation->getId()] diff --git a/lib/RoadizRozierBundle/src/Controller/Realm/RealmController.php b/lib/RoadizRozierBundle/src/Controller/Realm/RealmController.php index c4af292b..1b130fec 100644 --- a/lib/RoadizRozierBundle/src/Controller/Realm/RealmController.php +++ b/lib/RoadizRozierBundle/src/Controller/Realm/RealmController.php @@ -13,81 +13,51 @@ class RealmController extends AbstractAdminWithBulkController { - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof RealmInterface; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'realms'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { return new Realm(); } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizRozier/realms'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_REALMS'; } - /** - * @inheritDoc - */ protected function getEntityClass(): string { return Realm::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return RealmType::class; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'realmsHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'realmsEditPage'; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { return $item instanceof RealmInterface ? $item->getName() : ''; diff --git a/lib/RoadizRozierBundle/src/Controller/SecurityController.php b/lib/RoadizRozierBundle/src/Controller/SecurityController.php index 5e3cae55..4cbc7db8 100644 --- a/lib/RoadizRozierBundle/src/Controller/SecurityController.php +++ b/lib/RoadizRozierBundle/src/Controller/SecurityController.php @@ -27,7 +27,7 @@ public function __construct( private readonly LoggerInterface $logger, private readonly Settings $settingsBag, private readonly RozierServiceRegistry $rozierServiceRegistry, - private readonly LoginLinkSenderInterface $loginLinkSender + private readonly LoginLinkSenderInterface $loginLinkSender, ) { } @@ -47,8 +47,8 @@ public function login(Request $request, AuthenticationUtils $authenticationUtils 'error' => $error, 'themeServices' => $this->rozierServiceRegistry, 'head' => [ - 'siteTitle' => $this->settingsBag->get('site_name') . ' backstage', - ] + 'siteTitle' => $this->settingsBag->get('site_name').' backstage', + ], ]; try { @@ -70,13 +70,13 @@ public function login(Request $request, AuthenticationUtils $authenticationUtils public function requestLoginLink( LoginLinkHandlerInterface $loginLinkHandler, UserRepository $userRepository, - Request $request + Request $request, ): Response { $assignation = [ 'themeServices' => $this->rozierServiceRegistry, 'head' => [ - 'siteTitle' => $this->settingsBag->get('site_name') . ' backstage', - ] + 'siteTitle' => $this->settingsBag->get('site_name').' backstage', + ], ]; // check if form is submitted if ($request->isMethod('POST')) { diff --git a/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/JwtRoleStrategyCompilerPass.php b/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/JwtRoleStrategyCompilerPass.php index 78bb0483..8b86c895 100644 --- a/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/JwtRoleStrategyCompilerPass.php +++ b/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/JwtRoleStrategyCompilerPass.php @@ -11,9 +11,6 @@ class JwtRoleStrategyCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->has(ChainJwtRoleStrategy::class)) { diff --git a/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/RozierPathsCompilerPass.php b/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/RozierPathsCompilerPass.php index bd19d2ce..81ea2f79 100644 --- a/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/RozierPathsCompilerPass.php +++ b/lib/RoadizRozierBundle/src/DependencyInjection/Compiler/RozierPathsCompilerPass.php @@ -13,9 +13,6 @@ class RozierPathsCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->hasDefinition('translator.default')) { @@ -41,26 +38,26 @@ private function registerThemeTranslatorResources(ContainerBuilder $container): $name = 'Rozier'; // Register asset packages $container->setDefinition( - 'roadiz_rozier.assets._package.' . $name, + 'roadiz_rozier.assets._package.'.$name, (new Definition()) ->setClass(PathPackage::class) ->setArguments([ - 'themes/' . $name . '/static', + 'themes/'.$name.'/static', new Reference('assets.empty_version_strategy'), - new Reference('assets.context') + new Reference('assets.context'), ]) ->addTag('assets.package', [ - 'package' => $name + 'package' => $name, ]) ); /* * add translations paths */ - $translationFolder = realpath($themeDir . '/Resources/translations'); + $translationFolder = realpath($themeDir.'/Resources/translations'); if (false === $translationFolder || !file_exists($translationFolder)) { - throw new \RuntimeException($themeDir . '/Resources/translations' . ' is not a valid directory'); + throw new \RuntimeException($themeDir.'/Resources/translations is not a valid directory'); } if ($container->hasDefinition('translator.default')) { @@ -70,8 +67,8 @@ private function registerThemeTranslatorResources(ContainerBuilder $container): ->followLinks() ->files() ->filter(function (\SplFileInfo $file) { - return 2 <= \mb_substr_count($file->getBasename(), '.') && - preg_match('/\.\w+$/', $file->getBasename()); + return 2 <= \mb_substr_count($file->getBasename(), '.') + && preg_match('/\.\w+$/', $file->getBasename()); }) ->in($translationFolder) ->sortByName() @@ -95,7 +92,7 @@ private function registerThemeTranslatorResources(ContainerBuilder $container): 'scanned_directories' => $scannedDirectories = [$translationFolder], 'cache_vary' => [ 'scanned_directories' => array_map(static function (string $dir) use ($projectDir): string { - return str_starts_with($dir, $projectDir . '/') ? \mb_substr($dir, 1 + \mb_strlen($projectDir)) : $dir; + return str_starts_with($dir, $projectDir.'/') ? \mb_substr($dir, 1 + \mb_strlen($projectDir)) : $dir; }, $scannedDirectories), ], ] diff --git a/lib/RoadizRozierBundle/src/DependencyInjection/Configuration.php b/lib/RoadizRozierBundle/src/DependencyInjection/Configuration.php index 7be2e570..3a0a54bf 100644 --- a/lib/RoadizRozierBundle/src/DependencyInjection/Configuration.php +++ b/lib/RoadizRozierBundle/src/DependencyInjection/Configuration.php @@ -60,6 +60,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->end() ->append($this->addOpenIdNode()) ; + return $builder; } diff --git a/lib/RoadizRozierBundle/src/DependencyInjection/RoadizRozierExtension.php b/lib/RoadizRozierBundle/src/DependencyInjection/RoadizRozierExtension.php index ff65da90..18afbc44 100644 --- a/lib/RoadizRozierBundle/src/DependencyInjection/RoadizRozierExtension.php +++ b/lib/RoadizRozierBundle/src/DependencyInjection/RoadizRozierExtension.php @@ -16,9 +16,6 @@ class RoadizRozierExtension extends Extension { - /** - * @inheritDoc - */ public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); @@ -33,10 +30,10 @@ public function load(array $configs, ContainerBuilder $container): void $container->setParameter('roadiz_rozier.add_node_form.class', $config['add_node_form']); $container->setParameter( 'roadiz_rozier.theme_dir', - $projectDir . DIRECTORY_SEPARATOR . trim($config['theme_dir'], "/ \t\n\r\0\x0B") + $projectDir.DIRECTORY_SEPARATOR.trim($config['theme_dir'], "/ \t\n\r\0\x0B") ); - $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__) . '/../config')); + $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__).'/../config')); $loader->load('services.yaml'); $this->registerOpenId($config, $container); @@ -68,8 +65,8 @@ private function registerOpenId(array $config, ContainerBuilder $container): voi ->setArguments([ $config['open_id']['discovery_url'], new Reference(\Psr\Cache\CacheItemPoolInterface::class), - new Reference(\Symfony\Contracts\HttpClient\HttpClientInterface::class), - new Reference(\Psr\Log\LoggerInterface::class) + new Reference(HttpClientInterface::class), + new Reference(\Psr\Log\LoggerInterface::class), ]) ); } @@ -102,7 +99,7 @@ private function registerOpenId(array $config, ContainerBuilder $container): voi new Reference(\RZ\Roadiz\OpenId\Authentication\Provider\ChainJwtRoleStrategy::class), new Reference('roadiz_rozier.open_id.jwt_configuration_factory'), new Reference(\Symfony\Component\Routing\Generator\UrlGeneratorInterface::class), - new Reference(\Symfony\Contracts\HttpClient\HttpClientInterface::class), + new Reference(HttpClientInterface::class), 'loginPage', 'adminHomePage', $config['open_id']['oauth_client_id'], diff --git a/lib/RoadizRozierBundle/src/Form/DataTransformer/NodesTagsTransformer.php b/lib/RoadizRozierBundle/src/Form/DataTransformer/NodesTagsTransformer.php index e808b8b6..737025cd 100644 --- a/lib/RoadizRozierBundle/src/Form/DataTransformer/NodesTagsTransformer.php +++ b/lib/RoadizRozierBundle/src/Form/DataTransformer/NodesTagsTransformer.php @@ -22,6 +22,7 @@ public function __construct(ManagerRegistry $managerRegistry) /** * @param iterable $value + * * @return int[] */ public function transform(mixed $value): array @@ -38,6 +39,7 @@ public function transform(mixed $value): array /** * @param iterable $value + * * @return Collection */ public function reverseTransform(mixed $value): Collection diff --git a/lib/RoadizRozierBundle/src/Form/DocumentLimitationsType.php b/lib/RoadizRozierBundle/src/Form/DocumentLimitationsType.php index 89abfcb3..9370a9ce 100644 --- a/lib/RoadizRozierBundle/src/Form/DocumentLimitationsType.php +++ b/lib/RoadizRozierBundle/src/Form/DocumentLimitationsType.php @@ -44,13 +44,10 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ; } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ - 'data_class' => Document::class + 'data_class' => Document::class, ]); $resolver->setRequired('referer'); diff --git a/lib/RoadizRozierBundle/src/Form/NodesTagsType.php b/lib/RoadizRozierBundle/src/Form/NodesTagsType.php index cec311cf..284d5354 100644 --- a/lib/RoadizRozierBundle/src/Form/NodesTagsType.php +++ b/lib/RoadizRozierBundle/src/Form/NodesTagsType.php @@ -18,12 +18,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) { } - /** - * {@inheritdoc} - * - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('nodesTags', TagsType::class, [ @@ -33,19 +27,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ->addViewTransformer(new NodesTagsTransformer($this->managerRegistry)); } - /** - * {@inheritdoc} - * - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', Node::class); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'node_tags'; diff --git a/lib/RoadizRozierBundle/src/Form/TranslateNodeType.php b/lib/RoadizRozierBundle/src/Form/TranslateNodeType.php index 7178cc84..bcc4cf20 100644 --- a/lib/RoadizRozierBundle/src/Form/TranslateNodeType.php +++ b/lib/RoadizRozierBundle/src/Form/TranslateNodeType.php @@ -17,18 +17,11 @@ class TranslateNodeType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $translations = $this->managerRegistry @@ -63,17 +56,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * @return string - */ public function getBlockPrefix(): string { return 'translate_node'; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ diff --git a/lib/RoadizRozierBundle/src/Security/RozierAuthenticator.php b/lib/RoadizRozierBundle/src/Security/RozierAuthenticator.php index 1338f9e7..81aac98b 100644 --- a/lib/RoadizRozierBundle/src/Security/RozierAuthenticator.php +++ b/lib/RoadizRozierBundle/src/Security/RozierAuthenticator.php @@ -1,5 +1,7 @@ twoFactorUserProvider->getFromUser($user); if (!$twoFactorUser instanceof TwoFactorUser) { - $io->warning('User “' . $name . '” does not have two-factor authentication enabled.'); + $io->warning('User “'.$name.'” does not have two-factor authentication enabled.'); + return 1; } $this->twoFactorUserProvider->disable($twoFactorUser); - $io->success('Two-factor authentication disabled for user “' . $name . '”.'); + $io->success('Two-factor authentication disabled for user “'.$name.'”.'); return 0; } diff --git a/lib/RoadizTwoFactorBundle/src/Console/UsersCommand.php b/lib/RoadizTwoFactorBundle/src/Console/UsersCommand.php index 729aa16a..ea25facb 100644 --- a/lib/RoadizTwoFactorBundle/src/Console/UsersCommand.php +++ b/lib/RoadizTwoFactorBundle/src/Console/UsersCommand.php @@ -18,7 +18,7 @@ class UsersCommand extends \RZ\Roadiz\CoreBundle\Console\UsersCommand public function __construct( protected readonly TwoFactorUserProviderInterface $twoFactorUserProvider, ManagerRegistry $managerRegistry, - string $name = null + ?string $name = null, ) { parent::__construct($managerRegistry, $name); } @@ -26,6 +26,7 @@ public function __construct( protected function getUserTableRow(User $user): array { $twoFactorUser = $this->twoFactorUserProvider->getFromUser($user); + return [ 'Id' => $user->getId(), 'Username' => $user->getUsername(), diff --git a/lib/RoadizTwoFactorBundle/src/Controller/BackupCodesAdminController.php b/lib/RoadizTwoFactorBundle/src/Controller/BackupCodesAdminController.php index 87916399..63829515 100644 --- a/lib/RoadizTwoFactorBundle/src/Controller/BackupCodesAdminController.php +++ b/lib/RoadizTwoFactorBundle/src/Controller/BackupCodesAdminController.php @@ -16,7 +16,7 @@ final class BackupCodesAdminController extends RozierApp { public function __construct( - private readonly TwoFactorUserProviderInterface $twoFactorUserProvider + private readonly TwoFactorUserProviderInterface $twoFactorUserProvider, ) { } diff --git a/lib/RoadizTwoFactorBundle/src/Controller/QrCodeController.php b/lib/RoadizTwoFactorBundle/src/Controller/QrCodeController.php index 412c9de6..82df278e 100644 --- a/lib/RoadizTwoFactorBundle/src/Controller/QrCodeController.php +++ b/lib/RoadizTwoFactorBundle/src/Controller/QrCodeController.php @@ -24,7 +24,7 @@ final class QrCodeController extends AbstractController public function __construct( private readonly TwoFactorUserProviderInterface $twoFactorUserProvider, private readonly TotpAuthenticatorInterface $totpAuthenticator, - private readonly GoogleAuthenticatorInterface $googleAuthenticator + private readonly GoogleAuthenticatorInterface $googleAuthenticator, ) { } diff --git a/lib/RoadizTwoFactorBundle/src/Controller/TwoFactorAdminController.php b/lib/RoadizTwoFactorBundle/src/Controller/TwoFactorAdminController.php index ac768103..b2396365 100644 --- a/lib/RoadizTwoFactorBundle/src/Controller/TwoFactorAdminController.php +++ b/lib/RoadizTwoFactorBundle/src/Controller/TwoFactorAdminController.php @@ -48,6 +48,7 @@ public function twoFactorAdminAction(Request $request, TokenStorageInterface $to $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->twoFactorUserProvider->createForUser($user); + return $this->redirectToRoute('2fa_admin_two_factor'); } $this->assignation['form'] = $form->createView(); @@ -67,6 +68,7 @@ public function twoFactorAdminAction(Request $request, TokenStorageInterface $to ) ) { $this->twoFactorUserProvider->activate($twoFactorUser); + return $this->redirectToRoute('2fa_admin_two_factor'); } @@ -96,6 +98,7 @@ public function twoFactorDisableAction(Request $request, TokenStorageInterface $ $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->twoFactorUserProvider->disable($twoFactorUser); + return $this->redirectToRoute('2fa_admin_two_factor'); } $this->assignation['form'] = $form->createView(); diff --git a/lib/RoadizTwoFactorBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php b/lib/RoadizTwoFactorBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php index f1b93c7c..1443620a 100644 --- a/lib/RoadizTwoFactorBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php +++ b/lib/RoadizTwoFactorBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php @@ -4,15 +4,11 @@ namespace RZ\Roadiz\TwoFactorBundle\DependencyInjection\Compiler; -use RuntimeException; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class DoctrineMigrationCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->hasDefinition('doctrine.migrations.configuration')) { @@ -27,13 +23,13 @@ public function process(ContainerBuilder $container): void private function checkIfBundleRelativePath(string $path, ContainerBuilder $container): string { - if (isset($path[0]) && $path[0] === '@') { - $pathParts = explode('/', $path); + if (isset($path[0]) && '@' === $path[0]) { + $pathParts = explode('/', $path); $bundleName = \mb_substr($pathParts[0], 1); $bundlePath = $this->getBundlePath($bundleName, $container); - return $bundlePath . \mb_substr($path, \mb_strlen('@' . $bundleName)); + return $bundlePath.\mb_substr($path, \mb_strlen('@'.$bundleName)); } return $path; @@ -44,14 +40,8 @@ private function getBundlePath(string $bundleName, ContainerBuilder $container): $bundleMetadata = $container->getParameter('kernel.bundles_metadata'); assert(is_array($bundleMetadata)); - if (! isset($bundleMetadata[$bundleName])) { - throw new RuntimeException( - sprintf( - 'The bundle "%s" has not been registered, available bundles: %s', - $bundleName, - implode(', ', array_keys($bundleMetadata)) - ) - ); + if (!isset($bundleMetadata[$bundleName])) { + throw new \RuntimeException(sprintf('The bundle "%s" has not been registered, available bundles: %s', $bundleName, implode(', ', array_keys($bundleMetadata)))); } return $bundleMetadata[$bundleName]['path']; diff --git a/lib/RoadizTwoFactorBundle/src/DependencyInjection/RoadizTwoFactorExtension.php b/lib/RoadizTwoFactorBundle/src/DependencyInjection/RoadizTwoFactorExtension.php index 448252f2..c27dfb98 100644 --- a/lib/RoadizTwoFactorBundle/src/DependencyInjection/RoadizTwoFactorExtension.php +++ b/lib/RoadizTwoFactorBundle/src/DependencyInjection/RoadizTwoFactorExtension.php @@ -17,12 +17,11 @@ public function getAlias(): string } /** - * @inheritDoc * @throws \Exception */ public function load(array $configs, ContainerBuilder $container): void { - $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__) . '/../config')); + $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__).'/../config')); $loader->load('services.yaml'); $container->setParameter( diff --git a/lib/RoadizTwoFactorBundle/src/Entity/TwoFactorUser.php b/lib/RoadizTwoFactorBundle/src/Entity/TwoFactorUser.php index 95797677..ee01c1aa 100644 --- a/lib/RoadizTwoFactorBundle/src/Entity/TwoFactorUser.php +++ b/lib/RoadizTwoFactorBundle/src/Entity/TwoFactorUser.php @@ -8,23 +8,23 @@ use RZ\Roadiz\CoreBundle\Entity\User; use RZ\Roadiz\TwoFactorBundle\Repository\TwoFactorUserRepository; use Scheb\TwoFactorBundle\Model\BackupCodeInterface; +use Scheb\TwoFactorBundle\Model\Google\TwoFactorInterface as GoogleAuthenticatorTwoFactorInterface; use Scheb\TwoFactorBundle\Model\Totp\TotpConfiguration; use Scheb\TwoFactorBundle\Model\Totp\TotpConfigurationInterface; use Scheb\TwoFactorBundle\Model\Totp\TwoFactorInterface as TotpTwoFactorInterface; -use Scheb\TwoFactorBundle\Model\Google\TwoFactorInterface as GoogleAuthenticatorTwoFactorInterface; use Scheb\TwoFactorBundle\Model\TrustedDeviceInterface; use Symfony\Component\Validator\Constraints as Assert; #[ ORM\Entity(repositoryClass: TwoFactorUserRepository::class), - ORM\Table(name: "two_factor_users"), - ORM\UniqueConstraint(columns: ["user_id"]), + ORM\Table(name: 'two_factor_users'), + ORM\UniqueConstraint(columns: ['user_id']), ] class TwoFactorUser implements TotpTwoFactorInterface, BackupCodeInterface, TrustedDeviceInterface, GoogleAuthenticatorTwoFactorInterface { #[ORM\OneToOne(targetEntity: User::class)] #[ORM\Id] - #[ORM\JoinColumn(name: "user_id", referencedColumnName: "id", nullable: false, onDelete: "CASCADE")] + #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')] // @phpstan-ignore-next-line private ?User $user = null; @@ -54,116 +54,84 @@ class TwoFactorUser implements TotpTwoFactorInterface, BackupCodeInterface, Trus #[ORM\Column(type: 'smallint', nullable: true)] private ?int $digits = 6; - /** - * @return User|null - */ public function getUser(): ?User { return $this->user; } - /** - * @param User|null $user - * @return TwoFactorUser - */ public function setUser(?User $user): TwoFactorUser { $this->user = $user; + return $this; } - /** - * @param string|null $secret - * @return TwoFactorUser - */ public function setSecret(?string $secret): TwoFactorUser { $this->secret = $secret; + return $this; } - /** - * @return \DateTimeInterface|null - */ public function getActivatedAt(): ?\DateTimeInterface { return $this->activatedAt; } - /** - * @param \DateTimeInterface|null $activatedAt - * @return TwoFactorUser - */ public function setActivatedAt(?\DateTimeInterface $activatedAt): TwoFactorUser { $this->activatedAt = $activatedAt; + return $this; } - /** - * @return string - */ public function getAlgorithm(): string { return $this->algorithm ?? TotpConfiguration::ALGORITHM_SHA1; } - /** - * @param string|null $algorithm - * @return TwoFactorUser - */ public function setAlgorithm(?string $algorithm): TwoFactorUser { $this->algorithm = $algorithm; + return $this; } - /** - * @return int - */ public function getPeriod(): int { return $this->period ?? 30; } - /** - * @param int|null $period - * @return TwoFactorUser - */ public function setPeriod(?int $period): TwoFactorUser { $this->period = $period; + return $this; } - /** - * @return int - */ public function getDigits(): int { return $this->digits ?? 6; } - /** - * @param int|null $digits - * @return TwoFactorUser - */ public function setDigits(?int $digits): TwoFactorUser { $this->digits = $digits; + return $this; } public function isTotpAuthenticationEnabled(): bool { - return (bool) $this->secret && $this->activatedAt !== null; + return (bool) $this->secret && null !== $this->activatedAt; } public function getTotpAuthenticationUsername(): string { - if ($this->user === null) { + if (null === $this->user) { throw new \RuntimeException('User cannot be null'); } + return $this->user->getUserIdentifier(); } @@ -175,19 +143,20 @@ public function getTotpAuthenticationConfiguration(): ?TotpConfigurationInterfac public function isGoogleAuthenticatorEnabled(): bool { - return (bool) $this->secret && - $this->activatedAt !== null && - $this->digits === 6 && - $this->period === 30 && - $this->algorithm === TotpConfiguration::ALGORITHM_SHA1 + return (bool) $this->secret + && null !== $this->activatedAt + && 6 === $this->digits + && 30 === $this->period + && TotpConfiguration::ALGORITHM_SHA1 === $this->algorithm ; } public function getGoogleAuthenticatorUsername(): string { - if ($this->user === null) { + if (null === $this->user) { throw new \RuntimeException('User cannot be null'); } + return $this->user->getUserIdentifier(); } @@ -212,7 +181,7 @@ public function isBackupCode(string $code): bool } /** - * Invalidate a backup code + * Invalidate a backup code. */ public function invalidateBackupCode(string $code): void { @@ -226,7 +195,7 @@ public function invalidateBackupCode(string $code): void } /** - * Add a backup code + * Add a backup code. */ public function addBackUpCode(string $backUpCode): void { diff --git a/lib/RoadizTwoFactorBundle/src/EventSubscriber/UserActionsMenuEventSubscriber.php b/lib/RoadizTwoFactorBundle/src/EventSubscriber/UserActionsMenuEventSubscriber.php index 9e265316..3d20b834 100644 --- a/lib/RoadizTwoFactorBundle/src/EventSubscriber/UserActionsMenuEventSubscriber.php +++ b/lib/RoadizTwoFactorBundle/src/EventSubscriber/UserActionsMenuEventSubscriber.php @@ -4,16 +4,16 @@ namespace RZ\Roadiz\TwoFactorBundle\EventSubscriber; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -use Symfony\Bundle\SecurityBundle\Security; use Themes\Rozier\Event\UserActionsMenuEvent; final class UserActionsMenuEventSubscriber implements EventSubscriberInterface { public function __construct( private readonly UrlGeneratorInterface $urlGenerator, - private readonly Security $security + private readonly Security $security, ) { } diff --git a/lib/RoadizTwoFactorBundle/src/Form/TwoFactorCodeActivationType.php b/lib/RoadizTwoFactorBundle/src/Form/TwoFactorCodeActivationType.php index ae50a409..a60dc115 100644 --- a/lib/RoadizTwoFactorBundle/src/Form/TwoFactorCodeActivationType.php +++ b/lib/RoadizTwoFactorBundle/src/Form/TwoFactorCodeActivationType.php @@ -20,10 +20,10 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'label' => 'twoFactorCode', 'help' => 'twoFactorCode.help', 'attr' => [ - 'autocomplete' => "one-time-code", + 'autocomplete' => 'one-time-code', 'autofocus' => true, - 'inputmode' => "numeric", - 'pattern' => "[0-9]*", + 'inputmode' => 'numeric', + 'pattern' => '[0-9]*', ], 'constraints' => [ new NotBlank(), diff --git a/lib/RoadizTwoFactorBundle/src/Repository/TwoFactorUserRepository.php b/lib/RoadizTwoFactorBundle/src/Repository/TwoFactorUserRepository.php index 4f836812..a931ba9d 100644 --- a/lib/RoadizTwoFactorBundle/src/Repository/TwoFactorUserRepository.php +++ b/lib/RoadizTwoFactorBundle/src/Repository/TwoFactorUserRepository.php @@ -16,7 +16,7 @@ class TwoFactorUserRepository extends EntityRepository { public function __construct( ManagerRegistry $registry, - EventDispatcherInterface $dispatcher + EventDispatcherInterface $dispatcher, ) { parent::__construct($registry, TwoFactorUser::class, $dispatcher); } diff --git a/lib/RoadizTwoFactorBundle/src/Security/Provider/AuthenticatorTwoFactorProvider.php b/lib/RoadizTwoFactorBundle/src/Security/Provider/AuthenticatorTwoFactorProvider.php index 7d2d6b1d..9c290c1f 100644 --- a/lib/RoadizTwoFactorBundle/src/Security/Provider/AuthenticatorTwoFactorProvider.php +++ b/lib/RoadizTwoFactorBundle/src/Security/Provider/AuthenticatorTwoFactorProvider.php @@ -37,16 +37,12 @@ public function beginAuthentication(AuthenticationContextInterface $context): bo $totpConfiguration = $twoFactorUser->getTotpAuthenticationConfiguration(); if (null === $totpConfiguration) { - throw new TwoFactorProviderLogicException( - 'User has to provide a TotpAuthenticationConfiguration for TOTP authentication.' - ); + throw new TwoFactorProviderLogicException('User has to provide a TotpAuthenticationConfiguration for TOTP authentication.'); } $secret = $totpConfiguration->getSecret(); if (0 === \mb_strlen($secret)) { - throw new TwoFactorProviderLogicException( - 'User has to provide a secret code for TOTP authentication.' - ); + throw new TwoFactorProviderLogicException('User has to provide a secret code for TOTP authentication.'); } return true; diff --git a/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProvider.php b/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProvider.php index 685c3536..44ed6303 100644 --- a/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProvider.php +++ b/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProvider.php @@ -13,7 +13,7 @@ final class TwoFactorUserProvider implements TwoFactorUserProviderInterface { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly TotpAuthenticatorInterface $totpAuthenticator + private readonly TotpAuthenticatorInterface $totpAuthenticator, ) { } @@ -57,10 +57,10 @@ public function generateBackupCodes(TwoFactorUser $user): array $length = $user->getDigits(); // generate 10 random numeric codes of $length $codes = []; - for ($i = 0; $i < 10; $i++) { + for ($i = 0; $i < 10; ++$i) { // use random_int to generate a random number of $length $digits = []; - for ($j = 0; $j < $length; $j++) { + for ($j = 0; $j < $length; ++$j) { $digits[] = (string) \random_int(0, 9); } $code = implode('', $digits); diff --git a/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProviderInterface.php b/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProviderInterface.php index 3306e299..c6385931 100644 --- a/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProviderInterface.php +++ b/lib/RoadizTwoFactorBundle/src/Security/Provider/TwoFactorUserProviderInterface.php @@ -6,7 +6,6 @@ use RZ\Roadiz\CoreBundle\Entity\User; use RZ\Roadiz\TwoFactorBundle\Entity\TwoFactorUser; -use Scheb\TwoFactorBundle\Model\BackupCodeInterface; interface TwoFactorUserProviderInterface { diff --git a/lib/RoadizUserBundle/src/Console/PurgeUserValidationTokenCommand.php b/lib/RoadizUserBundle/src/Console/PurgeUserValidationTokenCommand.php index 9dd0140c..739f6422 100644 --- a/lib/RoadizUserBundle/src/Console/PurgeUserValidationTokenCommand.php +++ b/lib/RoadizUserBundle/src/Console/PurgeUserValidationTokenCommand.php @@ -13,7 +13,7 @@ final class PurgeUserValidationTokenCommand extends Command { - public function __construct(private readonly ManagerRegistry $managerRegistry, string $name = null) + public function __construct(private readonly ManagerRegistry $managerRegistry, ?string $name = null) { parent::__construct($name); } @@ -32,6 +32,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $count = $this->managerRegistry->getRepository(UserValidationToken::class)->deleteAllExpired(); $io->success(sprintf('%d expired user validation token(s) were deleted.', $count)); + return 0; } } diff --git a/lib/RoadizUserBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php b/lib/RoadizUserBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php index 431bb454..5bc9ede3 100644 --- a/lib/RoadizUserBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php +++ b/lib/RoadizUserBundle/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php @@ -4,15 +4,11 @@ namespace RZ\Roadiz\UserBundle\DependencyInjection\Compiler; -use RuntimeException; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class DoctrineMigrationCompilerPass implements CompilerPassInterface { - /** - * @inheritDoc - */ public function process(ContainerBuilder $container): void { if ($container->hasDefinition('doctrine.migrations.configuration')) { @@ -27,13 +23,13 @@ public function process(ContainerBuilder $container): void private function checkIfBundleRelativePath(string $path, ContainerBuilder $container): string { - if (isset($path[0]) && $path[0] === '@') { - $pathParts = explode('/', $path); + if (isset($path[0]) && '@' === $path[0]) { + $pathParts = explode('/', $path); $bundleName = \mb_substr($pathParts[0], 1); $bundlePath = $this->getBundlePath($bundleName, $container); - return $bundlePath . \mb_substr($path, \mb_strlen('@' . $bundleName)); + return $bundlePath.\mb_substr($path, \mb_strlen('@'.$bundleName)); } return $path; @@ -44,14 +40,8 @@ private function getBundlePath(string $bundleName, ContainerBuilder $container): $bundleMetadata = $container->getParameter('kernel.bundles_metadata'); assert(is_array($bundleMetadata)); - if (! isset($bundleMetadata[$bundleName])) { - throw new RuntimeException( - sprintf( - 'The bundle "%s" has not been registered, available bundles: %s', - $bundleName, - implode(', ', array_keys($bundleMetadata)) - ) - ); + if (!isset($bundleMetadata[$bundleName])) { + throw new \RuntimeException(sprintf('The bundle "%s" has not been registered, available bundles: %s', $bundleName, implode(', ', array_keys($bundleMetadata)))); } return $bundleMetadata[$bundleName]['path']; diff --git a/lib/RoadizUserBundle/src/DependencyInjection/Configuration.php b/lib/RoadizUserBundle/src/DependencyInjection/Configuration.php index 98bb7361..9d74de39 100644 --- a/lib/RoadizUserBundle/src/DependencyInjection/Configuration.php +++ b/lib/RoadizUserBundle/src/DependencyInjection/Configuration.php @@ -58,6 +58,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->scalarNode('email_validated_role_name') ->defaultValue('ROLE_EMAIL_VALIDATED') ->end(); + return $builder; } } diff --git a/lib/RoadizUserBundle/src/DependencyInjection/RoadizUserExtension.php b/lib/RoadizUserBundle/src/DependencyInjection/RoadizUserExtension.php index 8e694f24..4e981314 100644 --- a/lib/RoadizUserBundle/src/DependencyInjection/RoadizUserExtension.php +++ b/lib/RoadizUserBundle/src/DependencyInjection/RoadizUserExtension.php @@ -11,12 +11,9 @@ class RoadizUserExtension extends Extension { - /** - * @inheritDoc - */ public function load(array $configs, ContainerBuilder $container): void { - $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__) . '/../config')); + $loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__).'/../config')); $loader->load('services.yaml'); $configuration = new Configuration(); diff --git a/lib/RoadizUserBundle/src/Entity/UserMetadata.php b/lib/RoadizUserBundle/src/Entity/UserMetadata.php index 5a056588..8733b389 100644 --- a/lib/RoadizUserBundle/src/Entity/UserMetadata.php +++ b/lib/RoadizUserBundle/src/Entity/UserMetadata.php @@ -23,57 +23,39 @@ class UserMetadata #[ORM\Column(name: 'metadata', type: 'json', nullable: true)] private ?array $metadata = []; - /** - * @return int|null - */ public function getId(): ?int { return $this->id; } - /** - * @param int $id - * @return UserMetadata - */ public function setId(int $id): UserMetadata { $this->id = $id; + return $this; } - /** - * @return User|null - */ public function getUser(): ?User { return $this->user; } - /** - * @param User|null $user - * @return UserMetadata - */ public function setUser(?User $user): UserMetadata { $this->user = $user; + return $this; } - /** - * @return array|null - */ public function getMetadata(): ?array { return $this->metadata; } - /** - * @param array|null $metadata - * @return UserMetadata - */ public function setMetadata(?array $metadata): UserMetadata { $this->metadata = $metadata; + return $this; } } diff --git a/lib/RoadizUserBundle/src/Entity/UserValidationToken.php b/lib/RoadizUserBundle/src/Entity/UserValidationToken.php index 87bf7347..129355bd 100644 --- a/lib/RoadizUserBundle/src/Entity/UserValidationToken.php +++ b/lib/RoadizUserBundle/src/Entity/UserValidationToken.php @@ -33,76 +33,51 @@ class UserValidationToken #[ORM\Column(name: 'token_valid_until', type: 'datetime', unique: false, nullable: true)] private ?\DateTime $tokenValidUntil = null; - /** - * @return int - */ public function getId(): int { return $this->id; } - /** - * @param int $id - * @return UserValidationToken - */ public function setId(int $id): UserValidationToken { $this->id = $id; + return $this; } - - /** - * @return UserInterface|null - */ public function getUser(): ?UserInterface { return $this->user; } - /** - * @param UserInterface|null $user - * @return UserValidationToken - */ public function setUser(?UserInterface $user): UserValidationToken { $this->user = $user; + return $this; } - /** - * @return string - */ public function getToken(): string { return $this->token; } - /** - * @param string $token - * @return UserValidationToken - */ public function setToken(string $token): UserValidationToken { $this->token = $token; + return $this; } - /** - * @return \DateTime|null - */ public function getTokenValidUntil(): ?\DateTime { return $this->tokenValidUntil; } - /** - * @param \DateTime|null $tokenValidUntil - * @return UserValidationToken - */ public function setTokenValidUntil(?\DateTime $tokenValidUntil): UserValidationToken { $this->tokenValidUntil = $tokenValidUntil; + return $this; } } diff --git a/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessAuthenticationSuccessEventSubscriber.php b/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessAuthenticationSuccessEventSubscriber.php index 22d0c5f6..198cac51 100644 --- a/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessAuthenticationSuccessEventSubscriber.php +++ b/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessAuthenticationSuccessEventSubscriber.php @@ -24,9 +24,6 @@ public function __construct( ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ diff --git a/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessUserSignedUpSubscriber.php b/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessUserSignedUpSubscriber.php index 9dbd590d..1aa70593 100644 --- a/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessUserSignedUpSubscriber.php +++ b/lib/RoadizUserBundle/src/EventSubscriber/PasswordlessUserSignedUpSubscriber.php @@ -11,17 +11,14 @@ final readonly class PasswordlessUserSignedUpSubscriber implements EventSubscriberInterface { public function __construct( - private UserValidationTokenManagerInterface $userValidationTokenManager + private UserValidationTokenManagerInterface $userValidationTokenManager, ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ - PasswordlessUserSignedUp::class => 'onUserSignedUp' + PasswordlessUserSignedUp::class => 'onUserSignedUp', ]; } diff --git a/lib/RoadizUserBundle/src/EventSubscriber/UserSignedUpSubscriber.php b/lib/RoadizUserBundle/src/EventSubscriber/UserSignedUpSubscriber.php index 4e72bc05..092c6aff 100644 --- a/lib/RoadizUserBundle/src/EventSubscriber/UserSignedUpSubscriber.php +++ b/lib/RoadizUserBundle/src/EventSubscriber/UserSignedUpSubscriber.php @@ -11,17 +11,14 @@ final class UserSignedUpSubscriber implements EventSubscriberInterface { public function __construct( - private readonly UserValidationTokenManagerInterface $userValidationTokenManager + private readonly UserValidationTokenManagerInterface $userValidationTokenManager, ) { } - /** - * @inheritDoc - */ public static function getSubscribedEvents(): array { return [ - UserSignedUp::class => 'onUserSignedUp' + UserSignedUp::class => 'onUserSignedUp', ]; } diff --git a/lib/RoadizUserBundle/src/Manager/UserMetadataManager.php b/lib/RoadizUserBundle/src/Manager/UserMetadataManager.php index fe6609de..f9dc8584 100644 --- a/lib/RoadizUserBundle/src/Manager/UserMetadataManager.php +++ b/lib/RoadizUserBundle/src/Manager/UserMetadataManager.php @@ -24,6 +24,7 @@ public function createMetadataForUser(User $user): UserMetadata $userMetadata = new UserMetadata(); $userMetadata->setUser($user); $this->managerRegistry->getManager()->persist($userMetadata); + return $userMetadata; } } diff --git a/lib/RoadizUserBundle/src/Manager/UserMetadataManagerInterface.php b/lib/RoadizUserBundle/src/Manager/UserMetadataManagerInterface.php index 20c5dc61..a161c1fa 100644 --- a/lib/RoadizUserBundle/src/Manager/UserMetadataManagerInterface.php +++ b/lib/RoadizUserBundle/src/Manager/UserMetadataManagerInterface.php @@ -10,5 +10,6 @@ interface UserMetadataManagerInterface { public function getMetadataForUser(User $user): ?UserMetadata; + public function createMetadataForUser(User $user): UserMetadata; } diff --git a/lib/RoadizUserBundle/src/Manager/UserValidationTokenManager.php b/lib/RoadizUserBundle/src/Manager/UserValidationTokenManager.php index 5111b470..3f228d78 100644 --- a/lib/RoadizUserBundle/src/Manager/UserValidationTokenManager.php +++ b/lib/RoadizUserBundle/src/Manager/UserValidationTokenManager.php @@ -30,7 +30,7 @@ public function __construct( private RoleHierarchyInterface $roleHierarchy, private string $emailValidatedRoleName, private int $userValidationExpiresIn, - private string $userValidationUrl + private string $userValidationUrl, ) { } @@ -54,17 +54,18 @@ public function createForUser(UserInterface $user, bool $sendEmail = true): User if ($sendEmail) { $this->sendUserValidationEmail($existingValidationToken); } + return $existingValidationToken; } public function isUserEmailValidated(UserInterface $user): bool { $reachableRoles = $this->roleHierarchy->getReachableRoleNames($user->getRoles()); - return \in_array($this->emailValidatedRoleName, $reachableRoles) || - \in_array('ROLE_SUPER_ADMIN', $reachableRoles) || - \in_array('ROLE_SUPERADMIN', $reachableRoles); - } + return \in_array($this->emailValidatedRoleName, $reachableRoles) + || \in_array('ROLE_SUPER_ADMIN', $reachableRoles) + || \in_array('ROLE_SUPERADMIN', $reachableRoles); + } private function sendUserValidationEmail(UserValidationToken $userValidationToken): void { @@ -92,7 +93,7 @@ private function sendUserValidationEmail(UserValidationToken $userValidationToke UrlGeneratorInterface::ABSOLUTE_URL ); } catch (RouteNotFoundException $exception) { - $validationLink = $this->userValidationUrl . '?' . http_build_query( + $validationLink = $this->userValidationUrl.'?'.http_build_query( [ 'token' => $userValidationToken->getToken(), '_locale' => $user->getLocale(), diff --git a/lib/RoadizUserBundle/src/Manager/UserValidationTokenManagerInterface.php b/lib/RoadizUserBundle/src/Manager/UserValidationTokenManagerInterface.php index 5378f174..4084c096 100644 --- a/lib/RoadizUserBundle/src/Manager/UserValidationTokenManagerInterface.php +++ b/lib/RoadizUserBundle/src/Manager/UserValidationTokenManagerInterface.php @@ -10,5 +10,6 @@ interface UserValidationTokenManagerInterface { public function createForUser(UserInterface $user, bool $sendEmail = true): UserValidationToken; + public function isUserEmailValidated(UserInterface $user): bool; } diff --git a/lib/RoadizUserBundle/src/Repository/UserValidationTokenRepository.php b/lib/RoadizUserBundle/src/Repository/UserValidationTokenRepository.php index a8c1f161..9eed654a 100644 --- a/lib/RoadizUserBundle/src/Repository/UserValidationTokenRepository.php +++ b/lib/RoadizUserBundle/src/Repository/UserValidationTokenRepository.php @@ -22,6 +22,7 @@ public function deleteAllExpired(): int public function findOneByValidToken(string $token): ?UserValidationToken { $qb = $this->createQueryBuilder('t'); + return $qb->andWhere($qb->expr()->eq('t.token', ':token')) ->andWhere($qb->expr()->gte('t.tokenValidUntil', ':now')) ->setParameter('token', $token) diff --git a/lib/RoadizUserBundle/src/Security/FrontendLoginLinkHandler.php b/lib/RoadizUserBundle/src/Security/FrontendLoginLinkHandler.php index ffdfc7a9..eb375546 100644 --- a/lib/RoadizUserBundle/src/Security/FrontendLoginLinkHandler.php +++ b/lib/RoadizUserBundle/src/Security/FrontendLoginLinkHandler.php @@ -22,20 +22,17 @@ public function __construct( private string $frontendLoginCheckRoute, private SignatureHasher $signatureHasher, private array $frontendLoginLinkRequestRoutes, - array $options = [] + array $options = [], ) { $this->options = array_merge([ 'lifetime' => 600, ], $options); } - /** - * @inheritDoc - */ public function createLoginLink( UserInterface $user, ?Request $request = null, - int $lifetime = null + ?int $lifetime = null, ): LoginLinkDetails { if (null === $request) { throw new \InvalidArgumentException('Request cannot be null.'); @@ -48,7 +45,7 @@ public function createLoginLink( } $expires = time() + ($lifetime ?: $this->options['lifetime']); - $expiresAt = new \DateTimeImmutable('@' . $expires); + $expiresAt = new \DateTimeImmutable('@'.$expires); $parameters = [ 'user' => $user->getUserIdentifier(), @@ -60,18 +57,15 @@ public function createLoginLink( $parameters['redirect'] = $redirect; } - $url = $this->frontendLoginCheckRoute . '?' . http_build_query($parameters); + $url = $this->frontendLoginCheckRoute.'?'.http_build_query($parameters); - if (filter_var($url, FILTER_VALIDATE_URL) === false) { + if (false === filter_var($url, FILTER_VALIDATE_URL)) { throw new \InvalidArgumentException(sprintf('The URL "%s" is not valid.', $url)); } return new LoginLinkDetails($url, $expiresAt); } - /** - * @inheritDoc - */ public function consumeLoginLink(Request $request): UserInterface { return $this->decorated->consumeLoginLink($request); diff --git a/lib/RoadizUserBundle/src/State/RecaptchaProtectedTrait.php b/lib/RoadizUserBundle/src/State/RecaptchaProtectedTrait.php index 76f4d4b2..c1570872 100644 --- a/lib/RoadizUserBundle/src/State/RecaptchaProtectedTrait.php +++ b/lib/RoadizUserBundle/src/State/RecaptchaProtectedTrait.php @@ -11,6 +11,7 @@ trait RecaptchaProtectedTrait { abstract protected function getRecaptchaHeaderName(): string; + abstract protected function getRecaptchaService(): RecaptchaServiceInterface; protected function validateRecaptchaHeader(Request $request): void @@ -21,11 +22,11 @@ protected function validateRecaptchaHeader(Request $request): void } if (true !== $response = $this->getRecaptchaService()->check($responseValue)) { if (\is_string($response)) { - throw new BadRequestHttpException($this->getRecaptchaHeaderName() . ': ' . $response); + throw new BadRequestHttpException($this->getRecaptchaHeaderName().': '.$response); } elseif (\is_array($response)) { - throw new BadRequestHttpException($this->getRecaptchaHeaderName() . ': ' . reset($response)); + throw new BadRequestHttpException($this->getRecaptchaHeaderName().': '.reset($response)); } - throw new BadRequestHttpException($this->getRecaptchaHeaderName() . ': Recaptcha response is not valid.'); + throw new BadRequestHttpException($this->getRecaptchaHeaderName().': Recaptcha response is not valid.'); } } } diff --git a/lib/RoadizUserBundle/src/State/SignupProcessorTrait.php b/lib/RoadizUserBundle/src/State/SignupProcessorTrait.php index 8f942c86..f551ec40 100644 --- a/lib/RoadizUserBundle/src/State/SignupProcessorTrait.php +++ b/lib/RoadizUserBundle/src/State/SignupProcessorTrait.php @@ -15,6 +15,7 @@ trait SignupProcessorTrait { abstract protected function getSecurity(): Security; + abstract protected function getUserSignupLimiter(): RateLimiterFactory; protected function validateRequest(?Request $request): void diff --git a/lib/RoadizUserBundle/src/State/UserPasswordRequestProcessor.php b/lib/RoadizUserBundle/src/State/UserPasswordRequestProcessor.php index fdf1b631..7fa25888 100644 --- a/lib/RoadizUserBundle/src/State/UserPasswordRequestProcessor.php +++ b/lib/RoadizUserBundle/src/State/UserPasswordRequestProcessor.php @@ -45,7 +45,7 @@ public function __construct( private UrlGeneratorInterface $urlGenerator, private RecaptchaServiceInterface $recaptchaService, private string $passwordResetUrl, - private string $recaptchaHeaderName = 'x-g-recaptcha-response' + private string $recaptchaHeaderName = 'x-g-recaptcha-response', ) { } @@ -118,6 +118,7 @@ private function getUser(string $identifier): ?User } } catch (AuthenticationException $exception) { } + return null; } @@ -140,11 +141,11 @@ private function sendPasswordResetLink(Request $request, User $user): void UrlGeneratorInterface::ABSOLUTE_URL ); } catch (RouteNotFoundException $exception) { - $resetLink = $this->passwordResetUrl . '?' . http_build_query( + $resetLink = $this->passwordResetUrl.'?'.http_build_query( [ - 'token' => $user->getConfirmationToken(), - '_locale' => $request->getLocale(), - ] + 'token' => $user->getConfirmationToken(), + '_locale' => $request->getLocale(), + ] ); } diff --git a/lib/RoadizUserBundle/src/State/UserPasswordResetProcessor.php b/lib/RoadizUserBundle/src/State/UserPasswordResetProcessor.php index 8d6e67ef..51e947c3 100644 --- a/lib/RoadizUserBundle/src/State/UserPasswordResetProcessor.php +++ b/lib/RoadizUserBundle/src/State/UserPasswordResetProcessor.php @@ -27,7 +27,7 @@ public function __construct( private ValidatorInterface $validator, private RateLimiterFactory $passwordResetLimiter, private RequestStack $requestStack, - private int $passwordResetExpiresIn + private int $passwordResetExpiresIn, ) { } diff --git a/lib/RoadizUserBundle/src/State/UserTokenProvider.php b/lib/RoadizUserBundle/src/State/UserTokenProvider.php index 0b28dca9..0b133f2a 100644 --- a/lib/RoadizUserBundle/src/State/UserTokenProvider.php +++ b/lib/RoadizUserBundle/src/State/UserTokenProvider.php @@ -54,6 +54,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c } $userOutput->emailValidated = $this->userValidationTokenManager->isUserEmailValidated($user); + return $userOutput; } } diff --git a/lib/RoadizUserBundle/src/State/UserValidationRequestProcessor.php b/lib/RoadizUserBundle/src/State/UserValidationRequestProcessor.php index 7ee766ba..15a93d27 100644 --- a/lib/RoadizUserBundle/src/State/UserValidationRequestProcessor.php +++ b/lib/RoadizUserBundle/src/State/UserValidationRequestProcessor.php @@ -12,9 +12,9 @@ use RZ\Roadiz\UserBundle\Api\Dto\UserValidationRequestInput; use RZ\Roadiz\UserBundle\Api\Dto\VoidOutput; use RZ\Roadiz\UserBundle\Manager\UserValidationTokenManagerInterface; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; -use Symfony\Bundle\SecurityBundle\Security; final readonly class UserValidationRequestProcessor implements ProcessorInterface { @@ -23,7 +23,7 @@ public function __construct( private Security $security, private UserValidationTokenManagerInterface $userValidationTokenManager, private ManagerRegistry $managerRegistry, - private string $emailValidatedRoleName + private string $emailValidatedRoleName, ) { } diff --git a/lib/RoadizUserBundle/src/State/UserValidationTokenProcessor.php b/lib/RoadizUserBundle/src/State/UserValidationTokenProcessor.php index 65713bf0..c20752a8 100644 --- a/lib/RoadizUserBundle/src/State/UserValidationTokenProcessor.php +++ b/lib/RoadizUserBundle/src/State/UserValidationTokenProcessor.php @@ -13,9 +13,9 @@ use RZ\Roadiz\UserBundle\Api\Dto\VoidOutput; use RZ\Roadiz\UserBundle\Entity\UserValidationToken; use RZ\Roadiz\UserBundle\Event\UserEmailValidated; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; -use Symfony\Bundle\SecurityBundle\Security; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; final readonly class UserValidationTokenProcessor implements ProcessorInterface @@ -25,7 +25,7 @@ public function __construct( private Roles $rolesBag, private Security $security, private EventDispatcherInterface $eventDispatcher, - private string $emailValidatedRoleName + private string $emailValidatedRoleName, ) { } diff --git a/lib/Rozier/src/AjaxControllers/AbstractAjaxController.php b/lib/Rozier/src/AjaxControllers/AbstractAjaxController.php index 54027996..a56cc6a1 100644 --- a/lib/Rozier/src/AjaxControllers/AbstractAjaxController.php +++ b/lib/Rozier/src/AjaxControllers/AbstractAjaxController.php @@ -20,7 +20,7 @@ abstract class AbstractAjaxController extends RozierApp { public function __construct( - protected readonly SerializerInterface $serializer + protected readonly SerializerInterface $serializer, ) { } @@ -46,11 +46,7 @@ protected function getTranslation(Request $request): ?TranslationInterface } /** - * @param Request $request - * @param string $method - * @param bool $requestCsrfToken - * - * @return bool Return true if request is valid, else throw exception + * @return bool Return true if request is valid, else throw exception */ protected function validateRequest(Request $request, string $method = 'POST', bool $requestCsrfToken = true): bool { @@ -59,15 +55,15 @@ protected function validateRequest(Request $request, string $method = 'POST', bo } if ( - $requestCsrfToken === true && - !$this->isCsrfTokenValid(static::AJAX_TOKEN_INTENTION, $request->get('_token')) + true === $requestCsrfToken + && !$this->isCsrfTokenValid(static::AJAX_TOKEN_INTENTION, $request->get('_token')) ) { throw new BadRequestHttpException('Bad CSRF token'); } if ( - in_array(\mb_strtolower($method), static::$validMethods) && - \mb_strtolower($request->getMethod()) != \mb_strtolower($method) + in_array(\mb_strtolower($method), static::$validMethods) + && \mb_strtolower($request->getMethod()) != \mb_strtolower($method) ) { throw new BadRequestHttpException('Bad method'); } @@ -84,7 +80,7 @@ protected function sortIsh(array &$arr, array $map): array if ($element == $value->getId()) { $return[] = $value; unset($arr[$key]); - break 1; + break; } } } @@ -92,10 +88,6 @@ protected function sortIsh(array &$arr, array $map): array return $return; } - /** - * @param array $data - * @return JsonResponse - */ protected function createSerializedResponse(array $data): JsonResponse { return new JsonResponse( @@ -105,7 +97,7 @@ protected function createSerializedResponse(array $data): JsonResponse SerializationContext::create()->setGroups([ 'document_display', 'explorer_thumbnail', - 'model' + 'model', ]) ), 200, diff --git a/lib/Rozier/src/AjaxControllers/AjaxAbstractFieldsController.php b/lib/Rozier/src/AjaxControllers/AjaxAbstractFieldsController.php index 3fc4ab69..1ba0980c 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxAbstractFieldsController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxAbstractFieldsController.php @@ -16,7 +16,7 @@ abstract class AjaxAbstractFieldsController extends AbstractAjaxController { public function __construct( protected readonly HandlerFactoryInterface $handlerFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -28,21 +28,16 @@ protected function findEntity(int|string $entityId): ?AbstractField /** * Handle actions for any abstract fields. - * - * @param Request $request - * @param AbstractField|null $field - * - * @return null|Response */ - protected function handleFieldActions(Request $request, AbstractField $field = null): ?Response + protected function handleFieldActions(Request $request, ?AbstractField $field = null): ?Response { $this->validateRequest($request); - if ($field !== null) { + if (null !== $field) { /* * Get the right update method against "_action" parameter */ - if ($request->get('_action') !== 'updatePosition') { + if ('updatePosition' !== $request->get('_action')) { throw new BadRequestHttpException('Action does not exist'); } @@ -57,13 +52,7 @@ protected function handleFieldActions(Request $request, AbstractField $field = n return null; } - /** - * @param array $parameters - * @param AbstractField|null $field - * - * @return array - */ - protected function updatePosition(array $parameters, AbstractField $field = null): array + protected function updatePosition(array $parameters, ?AbstractField $field = null): array { if (!empty($parameters['afterFieldId']) && is_numeric($parameters['afterFieldId'])) { $afterField = $this->findEntity((int) $parameters['afterFieldId']); @@ -76,6 +65,7 @@ protected function updatePosition(array $parameters, AbstractField $field = null $handler = $this->handlerFactory->getHandler($field); $handler->cleanPositions(); $this->em()->flush(); + return [ 'statusCode' => '200', 'status' => 'success', @@ -95,6 +85,7 @@ protected function updatePosition(array $parameters, AbstractField $field = null $handler = $this->handlerFactory->getHandler($field); $handler->cleanPositions(); $this->em()->flush(); + return [ 'statusCode' => '200', 'status' => 'success', diff --git a/lib/Rozier/src/AjaxControllers/AjaxAttributeValuesController.php b/lib/Rozier/src/AjaxControllers/AjaxAttributeValuesController.php index a4bc2108..c728aa33 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxAttributeValuesController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxAttributeValuesController.php @@ -21,9 +21,6 @@ final class AjaxAttributeValuesController extends AbstractAjaxController * Handle AJAX edition requests for NodeTypeFields * such as coming from widgets. * - * @param Request $request - * @param int $attributeValueId - * * @return Response JSON response */ public function editAction(Request $request, int $attributeValueId): Response @@ -36,13 +33,8 @@ public function editAction(Request $request, int $attributeValueId): Response /** @var AttributeValue|null $attributeValue */ $attributeValue = $this->em()->find(AttributeValue::class, (int) $attributeValueId); - if ($attributeValue === null) { - throw $this->createNotFoundException($this->getTranslator()->trans( - 'attribute_value.%attributeValueId%.not_exists', - [ - '%attributeValueId%' => $attributeValueId - ] - )); + if (null === $attributeValue) { + throw $this->createNotFoundException($this->getTranslator()->trans('attribute_value.%attributeValueId%.not_exists', ['%attributeValueId%' => $attributeValueId])); } $this->denyAccessUnlessGranted(NodeVoter::EDIT_ATTRIBUTE, $attributeValue->getAttributable()); @@ -79,6 +71,7 @@ protected function updatePosition(array $parameters, AttributeValue $attributeVa } $attributeValue->setPosition($afterAttributeValue->getPosition() + 0.5); $this->em()->flush(); + return [ 'statusCode' => '200', 'status' => 'success', @@ -96,6 +89,7 @@ protected function updatePosition(array $parameters, AttributeValue $attributeVa } $attributeValue->setPosition($beforeAttributeValue->getPosition() - 0.5); $this->em()->flush(); + return [ 'statusCode' => '200', 'status' => 'success', diff --git a/lib/Rozier/src/AjaxControllers/AjaxCustomFormFieldsController.php b/lib/Rozier/src/AjaxControllers/AjaxCustomFormFieldsController.php index 4f475a08..7a014d5a 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxCustomFormFieldsController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxCustomFormFieldsController.php @@ -14,9 +14,6 @@ final class AjaxCustomFormFieldsController extends AjaxAbstractFieldsController * Handle AJAX edition requests for CustomFormFields * such as coming from widgets. * - * @param Request $request - * @param int $customFormFieldId - * * @return Response JSON response */ public function editAction(Request $request, int $customFormFieldId): Response @@ -30,12 +27,7 @@ public function editAction(Request $request, int $customFormFieldId): Response return $response; } - throw $this->createNotFoundException($this->getTranslator()->trans( - 'field.%customFormFieldId%.not_exists', - [ - '%customFormFieldId%' => $customFormFieldId - ] - )); + throw $this->createNotFoundException($this->getTranslator()->trans('field.%customFormFieldId%.not_exists', ['%customFormFieldId%' => $customFormFieldId])); } protected function getEntityClass(): string diff --git a/lib/Rozier/src/AjaxControllers/AjaxCustomFormsExplorerController.php b/lib/Rozier/src/AjaxControllers/AjaxCustomFormsExplorerController.php index 8450efa2..39834df3 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxCustomFormsExplorerController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxCustomFormsExplorerController.php @@ -17,14 +17,12 @@ final class AjaxCustomFormsExplorerController extends AbstractAjaxController { public function __construct( private readonly ExplorerItemFactoryInterface $explorerItemFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } /** - * @param Request $request - * * @return Response JSON response */ public function indexAction(Request $request): Response @@ -60,8 +58,6 @@ public function indexAction(Request $request): Response /** * Get a CustomForm list from an array of id. * - * @param Request $request - * @return Response * @throws NotSupported */ public function listAction(Request $request): Response @@ -73,7 +69,7 @@ public function listAction(Request $request): Response $this->denyAccessUnlessGranted('ROLE_ACCESS_CUSTOMFORMS'); $cleanCustomFormsIds = array_filter($request->query->filter('ids', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])); $customFormsArray = []; @@ -91,7 +87,7 @@ public function listAction(Request $request): Response return $this->createSerializedResponse([ 'status' => 'confirm', 'statusCode' => 200, - 'forms' => $customFormsArray + 'forms' => $customFormsArray, ]); } @@ -99,7 +95,6 @@ public function listAction(Request $request): Response * Normalize response CustomForm list result. * * @param iterable $customForms - * @return array */ private function normalizeCustomForms(iterable $customForms): array { diff --git a/lib/Rozier/src/AjaxControllers/AjaxDocumentsExplorerController.php b/lib/Rozier/src/AjaxControllers/AjaxDocumentsExplorerController.php index 17300f07..c2c06817 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxDocumentsExplorerController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxDocumentsExplorerController.php @@ -16,7 +16,7 @@ final class AjaxDocumentsExplorerController extends AbstractAjaxController { public function __construct( private readonly ExplorerItemFactoryInterface $explorerItemFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -47,7 +47,7 @@ public function indexAction(Request $request): JsonResponse Document::class, $arrayFilter, [ - 'createdAt' => 'DESC' + 'createdAt' => 'DESC', ] ); $listManager->setDisplayingNotPublishedNodes(true); @@ -69,7 +69,7 @@ public function indexAction(Request $request): JsonResponse if ($request->query->has('folderId') && $request->get('folderId') > 0) { $responseArray['filters'] = array_merge($responseArray['filters'], [ - 'folderId' => $request->get('folderId') + 'folderId' => $request->get('folderId'), ]); } @@ -80,9 +80,6 @@ public function indexAction(Request $request): JsonResponse /** * Get a Document list from an array of id. - * - * @param Request $request - * @return JsonResponse */ public function listAction(Request $request): JsonResponse { @@ -92,7 +89,7 @@ public function listAction(Request $request): JsonResponse throw new InvalidParameterException('Ids should be provided within an array'); } $cleanDocumentIds = array_filter($request->query->filter('ids', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])); $documentsArray = []; @@ -111,7 +108,7 @@ public function listAction(Request $request): JsonResponse 'status' => 'confirm', 'statusCode' => 200, 'documents' => $documentsArray, - 'trans' => $this->getTrans() + 'trans' => $this->getTrans(), ]); } @@ -119,7 +116,6 @@ public function listAction(Request $request): JsonResponse * Normalize response Document list result. * * @param iterable $documents - * @return array */ private function normalizeDocuments(iterable $documents): array { @@ -135,8 +131,6 @@ private function normalizeDocuments(iterable $documents): array /** * Get an array of translations. - * - * @return array */ private function getTrans(): array { @@ -144,7 +138,7 @@ private function getTrans(): array 'editDocument' => $this->getTranslator()->trans('edit.document'), 'unlinkDocument' => $this->getTranslator()->trans('unlink.document'), 'linkDocument' => $this->getTranslator()->trans('link.document'), - 'moreItems' => $this->getTranslator()->trans('more.documents') + 'moreItems' => $this->getTranslator()->trans('more.documents'), ]; } } diff --git a/lib/Rozier/src/AjaxControllers/AjaxEntitiesExplorerController.php b/lib/Rozier/src/AjaxControllers/AjaxEntitiesExplorerController.php index dcab945e..6f46ac3e 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxEntitiesExplorerController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxEntitiesExplorerController.php @@ -21,20 +21,16 @@ final class AjaxEntitiesExplorerController extends AbstractAjaxController { public function __construct( private readonly ExplorerItemFactoryInterface $explorerItemFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } - /** - * @param NodeTypeField $nodeTypeField - * @return array - */ protected function getFieldConfiguration(NodeTypeField $nodeTypeField): array { if ( - $nodeTypeField->getType() !== AbstractField::MANY_TO_MANY_T && - $nodeTypeField->getType() !== AbstractField::MANY_TO_ONE_T + AbstractField::MANY_TO_MANY_T !== $nodeTypeField->getType() + && AbstractField::MANY_TO_ONE_T !== $nodeTypeField->getType() ) { throw new BadRequestHttpException('nodeTypeField is not a valid entity join.'); } @@ -127,7 +123,7 @@ public function listAction(Request $request): JsonResponse $className = $configuration['classname']; $cleanNodeIds = array_filter($request->query->filter('ids', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])); $entitiesArray = []; @@ -144,7 +140,7 @@ public function listAction(Request $request): JsonResponse return $this->createSerializedResponse([ 'status' => 'confirm', 'statusCode' => 200, - 'items' => $entitiesArray + 'items' => $entitiesArray, ]); } @@ -152,7 +148,7 @@ public function listAction(Request $request): JsonResponse * Normalize response Node list result. * * @param iterable $entities - * @param array $configuration + * * @return array */ private function normalizeEntities(iterable $entities, array $configuration): array diff --git a/lib/Rozier/src/AjaxControllers/AjaxExplorerProviderController.php b/lib/Rozier/src/AjaxControllers/AjaxExplorerProviderController.php index 32e8092b..06bb1bfc 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxExplorerProviderController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxExplorerProviderController.php @@ -18,14 +18,14 @@ class AjaxExplorerProviderController extends AbstractAjaxController { public function __construct( private readonly ContainerInterface $psrContainer, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } /** * @param class-string $providerClass - * @return ExplorerProviderInterface + * * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ @@ -34,6 +34,7 @@ protected function getProvider(string $providerClass): ExplorerProviderInterface if ($this->psrContainer->has($providerClass)) { return $this->psrContainer->get($providerClass); } + return new $providerClass(); } @@ -62,8 +63,6 @@ protected function getProviderFromRequest(Request $request): ExplorerProviderInt } /** - * @param Request $request - * @return JsonResponse * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ @@ -80,7 +79,7 @@ public function indexAction(Request $request): JsonResponse if ($request->query->has('options')) { $options = array_merge( array_filter($request->query->filter('options', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])), $options ); @@ -105,8 +104,6 @@ public function indexAction(Request $request): JsonResponse /** * Get a Node list from an array of id. * - * @param Request $request - * @return JsonResponse * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ @@ -117,10 +114,11 @@ public function listAction(Request $request): JsonResponse $provider = $this->getProviderFromRequest($request); $entitiesArray = []; $cleanNodeIds = array_filter($request->query->filter('ids', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])); $cleanNodeIds = array_filter($cleanNodeIds, function ($value) { $nullValues = ['null', null, 0, '0', false, 'false']; + return !in_array($value, $nullValues, true); }); @@ -137,7 +135,7 @@ public function listAction(Request $request): JsonResponse return $this->createSerializedResponse([ 'status' => 'confirm', 'statusCode' => 200, - 'items' => $entitiesArray + 'items' => $entitiesArray, ]); } } diff --git a/lib/Rozier/src/AjaxControllers/AjaxFolderTreeController.php b/lib/Rozier/src/AjaxControllers/AjaxFolderTreeController.php index f9339b22..6f013398 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxFolderTreeController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxFolderTreeController.php @@ -15,7 +15,7 @@ final class AjaxFolderTreeController extends AbstractAjaxController { public function __construct( private readonly TreeWidgetFactory $treeWidgetFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -28,7 +28,7 @@ public function getTreeAction(Request $request): JsonResponse /** @var FolderTreeWidget|null $folderTree */ $folderTree = null; - switch ($request->get("_action")) { + switch ($request->get('_action')) { /* * Inner folder edit for folderTree */ @@ -48,9 +48,9 @@ public function getTreeAction(Request $request): JsonResponse $this->assignation['mainFolderTree'] = false; break; - /* - * Main panel tree folderTree - */ + /* + * Main panel tree folderTree + */ case 'requestMainFolderTree': $parent = null; $folderTree = $this->treeWidgetFactory->createFolderTree($parent, $translation); diff --git a/lib/Rozier/src/AjaxControllers/AjaxFoldersController.php b/lib/Rozier/src/AjaxControllers/AjaxFoldersController.php index 3e2c68f3..788600d1 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxFoldersController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxFoldersController.php @@ -5,9 +5,9 @@ namespace Themes\Rozier\AjaxControllers; use JMS\Serializer\SerializerInterface; +use RZ\Roadiz\Core\Handlers\HandlerFactoryInterface; use RZ\Roadiz\CoreBundle\Entity\Folder; use RZ\Roadiz\CoreBundle\EntityHandler\FolderHandler; -use RZ\Roadiz\Core\Handlers\HandlerFactoryInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -17,7 +17,7 @@ final class AjaxFoldersController extends AbstractAjaxController { public function __construct( private readonly HandlerFactoryInterface $handlerFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -33,11 +33,11 @@ public function editAction(Request $request, int $folderId): JsonResponse $folder = $this->em()->find(Folder::class, (int) $folderId); - if ($folder === null) { + if (null === $folder) { throw $this->createNotFoundException($this->getTranslator()->trans('folder.does_not_exist')); } - if ($request->get('_action') !== 'updatePosition') { + if ('updatePosition' !== $request->get('_action')) { throw new BadRequestHttpException('Action does not exist'); } @@ -49,21 +49,17 @@ public function editAction(Request $request, int $folderId): JsonResponse 'status' => 'success', 'responseText' => $this->getTranslator()->trans('folder.%name%.updated', [ '%name%' => $folder->getName(), - ]) + ]), ], Response::HTTP_PARTIAL_CONTENT ); } - /** - * @param Request $request - * @return JsonResponse - */ public function searchAction(Request $request): JsonResponse { $this->denyAccessUnlessGranted('ROLE_ACCESS_DOCUMENTS'); - if ($request->query->has('search') && $request->get('search') != "") { + if ($request->query->has('search') && '' != $request->get('search')) { $responseArray = []; $pattern = strip_tags($request->get('search')); @@ -95,14 +91,14 @@ protected function updatePosition(array $parameters, Folder $folder): void * First, we set the new parent */ if ( - !empty($parameters['newParent']) && - is_numeric($parameters['newParent']) && - $parameters['newParent'] > 0 + !empty($parameters['newParent']) + && is_numeric($parameters['newParent']) + && $parameters['newParent'] > 0 ) { /** @var Folder $parent */ $parent = $this->em()->find(Folder::class, (int) $parameters['newParent']); - if ($parent !== null) { + if (null !== $parent) { $folder->setParent($parent); } } else { @@ -113,22 +109,22 @@ protected function updatePosition(array $parameters, Folder $folder): void * Then compute new position */ if ( - !empty($parameters['nextFolderId']) && - $parameters['nextFolderId'] > 0 + !empty($parameters['nextFolderId']) + && $parameters['nextFolderId'] > 0 ) { /** @var Folder $nextFolder */ $nextFolder = $this->em()->find(Folder::class, (int) $parameters['nextFolderId']); - if ($nextFolder !== null) { + if (null !== $nextFolder) { $folder->setPosition($nextFolder->getPosition() - 0.5); } } elseif ( - !empty($parameters['prevFolderId']) && - $parameters['prevFolderId'] > 0 + !empty($parameters['prevFolderId']) + && $parameters['prevFolderId'] > 0 ) { /** @var Folder $prevFolder */ $prevFolder = $this->em() ->find(Folder::class, (int) $parameters['prevFolderId']); - if ($prevFolder !== null) { + if (null !== $prevFolder) { $folder->setPosition($prevFolder->getPosition() + 0.5); } } diff --git a/lib/Rozier/src/AjaxControllers/AjaxFoldersExplorerController.php b/lib/Rozier/src/AjaxControllers/AjaxFoldersExplorerController.php index e41aeb20..12cbfcc5 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxFoldersExplorerController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxFoldersExplorerController.php @@ -35,7 +35,7 @@ public function indexAction(Request $request): JsonResponse protected function recurseFolders(?iterable $folders = null): array { $foldersArray = []; - if ($folders !== null) { + if (null !== $folders) { /** @var Folder $folder */ foreach ($folders as $folder) { $children = $this->recurseFolders($folder->getChildren()); diff --git a/lib/Rozier/src/AjaxControllers/AjaxNodeTreeController.php b/lib/Rozier/src/AjaxControllers/AjaxNodeTreeController.php index 88f4db18..1dc5bd73 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxNodeTreeController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxNodeTreeController.php @@ -21,7 +21,7 @@ public function __construct( private readonly NodeChrootResolver $nodeChrootResolver, private readonly TreeWidgetFactory $treeWidgetFactory, private readonly NodeTypes $nodeTypesBag, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -35,7 +35,7 @@ public function getTreeAction(Request $request): JsonResponse $nodeTree = null; $linkedTypes = []; - switch ($request->get("_action")) { + switch ($request->get('_action')) { /* * Inner node edit for nodeTree */ @@ -55,8 +55,8 @@ public function getTreeAction(Request $request): JsonResponse $nodeTree = $this->treeWidgetFactory->createNodeTree($node, $translation); if ( - $request->get('tagId') && - $request->get('tagId') > 0 + $request->get('tagId') + && $request->get('tagId') > 0 ) { $filterTag = $this->em() ->find( @@ -77,7 +77,7 @@ public function getTreeAction(Request $request): JsonResponse }, $linkedTypes)); $nodeTree->setAdditionalCriteria([ - 'nodeType' => $linkedTypes + 'nodeType' => $linkedTypes, ]); } @@ -87,9 +87,9 @@ public function getTreeAction(Request $request): JsonResponse $nodeTree->setStackTree(true); } break; - /* - * Main panel tree nodeTree - */ + /* + * Main panel tree nodeTree + */ case 'requestMainNodeTree': $parent = null; if (null !== $this->getUser()) { diff --git a/lib/Rozier/src/AjaxControllers/AjaxNodeTypeFieldsController.php b/lib/Rozier/src/AjaxControllers/AjaxNodeTypeFieldsController.php index ce6ce419..7ee8f75c 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxNodeTypeFieldsController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxNodeTypeFieldsController.php @@ -14,9 +14,6 @@ final class AjaxNodeTypeFieldsController extends AjaxAbstractFieldsController * Handle AJAX edition requests for NodeTypeFields * such as coming from widgets. * - * @param Request $request - * @param int $nodeTypeFieldId - * * @return Response JSON response */ public function editAction(Request $request, int $nodeTypeFieldId): Response @@ -30,12 +27,7 @@ public function editAction(Request $request, int $nodeTypeFieldId): Response return $response; } - throw $this->createNotFoundException($this->getTranslator()->trans( - 'field.%nodeTypeFieldId%.not_exists', - [ - '%nodeTypeFieldId%' => $nodeTypeFieldId - ] - )); + throw $this->createNotFoundException($this->getTranslator()->trans('field.%nodeTypeFieldId%.not_exists', ['%nodeTypeFieldId%' => $nodeTypeFieldId])); } protected function getEntityClass(): string diff --git a/lib/Rozier/src/AjaxControllers/AjaxNodeTypesController.php b/lib/Rozier/src/AjaxControllers/AjaxNodeTypesController.php index 3419c2a0..fab7e3f4 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxNodeTypesController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxNodeTypesController.php @@ -18,14 +18,12 @@ final class AjaxNodeTypesController extends AbstractAjaxController { public function __construct( private readonly ExplorerItemFactoryInterface $explorerItemFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } /** - * @param Request $request - * * @return Response JSON response */ public function indexAction(Request $request): Response @@ -52,15 +50,15 @@ public function indexAction(Request $request): Response 'statusCode' => 200, 'nodeTypes' => $documentsArray, 'nodeTypesCount' => count($nodeTypes), - 'filters' => $listManager->getAssignation() + 'filters' => $listManager->getAssignation(), ]); } /** * Get a NodeType list from an array of id. * - * @param Request $request * @return JsonResponse + * * @throws NotSupported */ public function listAction(Request $request): Response @@ -72,7 +70,7 @@ public function listAction(Request $request): Response } $cleanNodeTypesName = array_filter($request->query->filter('names', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])); $nodesArray = []; @@ -80,7 +78,7 @@ public function listAction(Request $request): Response /** @var EntityManager $em */ $em = $this->em(); $nodeTypes = $em->getRepository(NodeType::class)->findBy([ - 'name' => $cleanNodeTypesName + 'name' => $cleanNodeTypesName, ]); // Sort array by ids given in request @@ -90,7 +88,7 @@ public function listAction(Request $request): Response return $this->createSerializedResponse([ 'status' => 'confirm', 'statusCode' => 200, - 'items' => $nodesArray + 'items' => $nodesArray, ]); } @@ -98,7 +96,6 @@ public function listAction(Request $request): Response * Normalize response NodeType list result. * * @param iterable $nodeTypes - * @return array */ private function normalizeNodeType(iterable $nodeTypes): array { diff --git a/lib/Rozier/src/AjaxControllers/AjaxNodesController.php b/lib/Rozier/src/AjaxControllers/AjaxNodesController.php index cbc5c64a..354818f1 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxNodesController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxNodesController.php @@ -36,16 +36,11 @@ public function __construct( private readonly NodeChrootResolver $nodeChrootResolver, private readonly Registry $workflowRegistry, private readonly UniqueNodeGenerator $uniqueNodeGenerator, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } - /** - * @param Request $request - * @param int $nodeId - * @return JsonResponse - */ public function getTagsAction(Request $request, int $nodeId): JsonResponse { $tags = []; @@ -71,9 +66,6 @@ public function getTagsAction(Request $request, int $nodeId): JsonResponse * Handle AJAX edition requests for Node * such as coming from node-tree widgets. * - * @param Request $request - * @param int|string $nodeId - * * @return Response JSON response */ public function editAction(Request $request, int|string $nodeId): Response @@ -84,9 +76,7 @@ public function editAction(Request $request, int|string $nodeId): Response $node = $this->em()->find(Node::class, (int) $nodeId); if (null === $node) { - throw $this->createNotFoundException($this->getTranslator()->trans('node.%nodeId%.not_exists', [ - '%nodeId%' => $nodeId, - ])); + throw $this->createNotFoundException($this->getTranslator()->trans('node.%nodeId%.not_exists', ['%nodeId%' => $nodeId])); } /* * Get the right update method against "_action" parameter @@ -138,10 +128,6 @@ public function editAction(Request $request, int|string $nodeId): Response ); } - /** - * @param array $parameters - * @param Node $node - */ protected function updatePosition(array $parameters, Node $node): void { if ($node->isLocked()) { @@ -189,59 +175,47 @@ protected function updatePosition(array $parameters, Node $node): void $this->em()->flush(); } - /** - * @param array $parameters - * - * @return Node|null - */ protected function parseParentNode(array $parameters): ?Node { if ( - !empty($parameters['newParent']) && - is_numeric($parameters['newParent']) && - $parameters['newParent'] > 0 + !empty($parameters['newParent']) + && is_numeric($parameters['newParent']) + && $parameters['newParent'] > 0 ) { return $this->em()->find(Node::class, (int) $parameters['newParent']); } elseif (null !== $this->getUser()) { // If user is jailed in a node, prevent moving nodes out. return $this->nodeChrootResolver->getChroot($this->getUser()); } + return null; } - /** - * @param array $parameters - * @param float $default - * - * @return float - */ protected function parsePosition(array $parameters, float $default = 0.0): float { if (key_exists('nextNodeId', $parameters) && (int) $parameters['nextNodeId'] > 0) { /** @var Node $nextNode */ $nextNode = $this->em()->find(Node::class, (int) $parameters['nextNodeId']); - if ($nextNode !== null) { + if (null !== $nextNode) { return $nextNode->getPosition() - 0.5; } } elseif (key_exists('prevNodeId', $parameters) && $parameters['prevNodeId'] > 0) { /** @var Node $prevNode */ $prevNode = $this->em()->find(Node::class, (int) $parameters['prevNodeId']); - if ($prevNode !== null) { + if (null !== $prevNode) { return $prevNode->getPosition() + 0.5; } - } elseif (key_exists('firstPosition', $parameters) && (bool) $parameters['firstPosition'] === true) { + } elseif (key_exists('firstPosition', $parameters) && true === (bool) $parameters['firstPosition']) { return -0.5; - } elseif (key_exists('lastPosition', $parameters) && (bool) $parameters['lastPosition'] === true) { + } elseif (key_exists('lastPosition', $parameters) && true === (bool) $parameters['lastPosition']) { return 99999999; } + return $default; } /** * Update node's status. - * - * @param Request $request - * @return JsonResponse */ public function statusesAction(Request $request): JsonResponse { @@ -254,9 +228,7 @@ public function statusesAction(Request $request): JsonResponse /** @var Node|null $node */ $node = $this->em()->find(Node::class, (int) $request->get('nodeId')); if (null === $node) { - throw $this->createNotFoundException($this->getTranslator()->trans('node.%nodeId%.not_exists', [ - '%nodeId%' => $request->get('nodeId'), - ])); + throw $this->createNotFoundException($this->getTranslator()->trans('node.%nodeId%.not_exists', ['%nodeId%' => $request->get('nodeId')])); } $this->denyAccessUnlessGranted(NodeVoter::EDIT_STATUS, $node); @@ -268,8 +240,8 @@ public function statusesAction(Request $request): JsonResponse 'sterile' => 'setSterile', ]; - if ("nodeChangeStatus" == $request->get('_action') && "" != $request->get('statusName')) { - if ($request->get('statusName') === 'status') { + if ('nodeChangeStatus' == $request->get('_action') && '' != $request->get('statusName')) { + if ('status' === $request->get('statusName')) { return $this->changeNodeStatus($node, $request->get('statusValue')); } @@ -285,7 +257,7 @@ public function statusesAction(Request $request): JsonResponse * If set locked to true, * need to disable dynamic nodeName */ - if ($request->get('statusName') == 'locked' && $value === true) { + if ('locked' == $request->get('statusName') && true === $value) { $node->setDynamicNodeName(false); } @@ -294,7 +266,7 @@ public function statusesAction(Request $request): JsonResponse /* * Dispatch event */ - if ($request->get('statusName') === 'visible') { + if ('visible' === $request->get('statusName')) { $msg = $this->getTranslator()->trans('node.%name%.visibility_changed_to.%visible%', [ '%name%' => $node->getNodeName(), '%visible%' => $node->isVisible() ? $this->getTranslator()->trans('visible') : $this->getTranslator()->trans('invisible'), @@ -319,9 +291,7 @@ public function statusesAction(Request $request): JsonResponse 'value' => $value, ]; } else { - throw new BadRequestHttpException($this->getTranslator()->trans('node.has_no.field.%field%', [ - '%field%' => $request->get('statusName'), - ])); + throw new BadRequestHttpException($this->getTranslator()->trans('node.has_no.field.%field%', ['%field%' => $request->get('statusName')])); } } else { throw new BadRequestHttpException('Status field name is invalid.'); @@ -333,12 +303,6 @@ public function statusesAction(Request $request): JsonResponse ); } - /** - * @param Node $node - * @param string $transition - * - * @return JsonResponse - */ protected function changeNodeStatus(Node $node, string $transition): JsonResponse { $request = $this->getRequest(); @@ -364,10 +328,6 @@ protected function changeNodeStatus(Node $node, string $transition): JsonRespons ); } - /** - * @param Request $request - * @return JsonResponse - */ public function quickAddAction(Request $request): JsonResponse { /* diff --git a/lib/Rozier/src/AjaxControllers/AjaxNodesExplorerController.php b/lib/Rozier/src/AjaxControllers/AjaxNodesExplorerController.php index b2c924dc..a4c85360 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxNodesExplorerController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxNodesExplorerController.php @@ -29,7 +29,7 @@ public function __construct( private readonly ClientRegistry $clientRegistry, private readonly NodeSourceSearchHandlerInterface $nodeSourceSearchHandler, private readonly NodeTypeApi $nodeTypeApi, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -41,12 +41,10 @@ protected function getItemPerPage(): int protected function isSearchEngineAvailable(Request $request): bool { - return $request->get('search') !== '' && null !== $this->clientRegistry->getClient(); + return '' !== $request->get('search') && null !== $this->clientRegistry->getClient(); } /** - * @param Request $request - * * @return Response JSON response */ public function indexAction(Request $request): Response @@ -64,17 +62,13 @@ public function indexAction(Request $request): Response if ($request->query->has('tagId') && $request->get('tagId') > 0) { $responseArray['filters'] = array_merge($responseArray['filters'], [ - 'tagId' => $request->get('tagId') + 'tagId' => $request->get('tagId'), ]); } return $this->createSerializedResponse($responseArray); } - /** - * @param Request $request - * @return array - */ protected function parseFilterFromRequest(Request $request): array { $arrayFilter = [ @@ -102,13 +96,10 @@ protected function parseFilterFromRequest(Request $request): array $arrayFilter['nodeType'] = $nodeTypes; } } + return $arrayFilter; } - /** - * @param Request $request - * @return array - */ protected function parseSortingFromRequest(Request $request): array { if ($request->query->has('sort-alpha')) { @@ -122,12 +113,6 @@ protected function parseSortingFromRequest(Request $request): array ]; } - /** - * @param Request $request - * @param array $criteria - * @param array $sorting - * @return array - */ protected function getNodeSearchResults(Request $request, array $criteria, array $sorting = []): array { /* @@ -144,6 +129,7 @@ protected function getNodeSearchResults(Request $request, array $criteria, array $nodes = $listManager->getEntities(); $nodesArray = $this->normalizeNodes($nodes); + return [ 'status' => 'confirm', 'statusCode' => 200, @@ -153,15 +139,9 @@ protected function getNodeSearchResults(Request $request, array $criteria, array ]; } - /** - * @param Request $request - * @param array $arrayFilter - * - * @return array - */ protected function getSolrSearchResults( Request $request, - array $arrayFilter + array $arrayFilter, ): array { $this->nodeSourceSearchHandler->boostByUpdateDate(); $currentPage = $request->get('page', 1); @@ -205,8 +185,6 @@ protected function getSolrSearchResults( /** * Get a Node list from an array of id. * - * @param Request $request - * @return JsonResponse * @throws NotSupported */ public function listAction(Request $request): JsonResponse @@ -219,7 +197,7 @@ public function listAction(Request $request): JsonResponse } $cleanNodeIds = array_filter($request->query->filter('ids', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])); $nodesArray = []; @@ -240,7 +218,7 @@ public function listAction(Request $request): JsonResponse return $this->createSerializedResponse([ 'status' => 'confirm', 'statusCode' => 200, - 'items' => $nodesArray + 'items' => $nodesArray, ]); } @@ -248,6 +226,7 @@ public function listAction(Request $request): JsonResponse * Normalize response Node list result. * * @param iterable $nodes + * * @return array */ private function normalizeNodes(iterable $nodes): array diff --git a/lib/Rozier/src/AjaxControllers/AjaxSearchNodesSourcesController.php b/lib/Rozier/src/AjaxControllers/AjaxSearchNodesSourcesController.php index 55ec1ec6..9ff6f537 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxSearchNodesSourcesController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxSearchNodesSourcesController.php @@ -11,11 +11,11 @@ use RZ\Roadiz\CoreBundle\SearchEngine\GlobalNodeSourceSearchHandler; use RZ\Roadiz\CoreBundle\Security\Authorization\Voter\NodeVoter; use RZ\Roadiz\Documents\UrlGenerators\DocumentUrlGeneratorInterface; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; -use Symfony\Bundle\SecurityBundle\Security; final class AjaxSearchNodesSourcesController extends AbstractAjaxController { @@ -24,7 +24,7 @@ final class AjaxSearchNodesSourcesController extends AbstractAjaxController public function __construct( private readonly DocumentUrlGeneratorInterface $documentUrlGenerator, private readonly Security $security, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -33,15 +33,13 @@ public function __construct( * Handle AJAX edition requests for Node * such as coming from node-tree widgets. * - * @param Request $request - * * @return Response JSON response */ public function searchAction(Request $request): Response { $this->denyAccessUnlessGranted(NodeVoter::SEARCH); - if (!$request->query->has('searchTerms') || $request->query->get('searchTerms') == '') { + if (!$request->query->has('searchTerms') || '' == $request->query->get('searchTerms')) { throw new BadRequestHttpException('searchTerms parameter is missing.'); } @@ -54,7 +52,7 @@ public function searchAction(Request $request): Response self::RESULT_COUNT ); - if (count($nodesSources) === 0) { + if (0 === count($nodesSources)) { return new JsonResponse([ 'statusCode' => Response::HTTP_OK, 'status' => 'success', @@ -67,14 +65,14 @@ public function searchAction(Request $request): Response 'statusCode' => Response::HTTP_OK, 'status' => 'success', 'data' => [], - 'responseText' => count($nodesSources) . ' results found.', + 'responseText' => count($nodesSources).' results found.', ]; foreach ($nodesSources as $source) { if ( - $source instanceof NodesSources && - $this->security->isGranted(NodeVoter::READ, $source) && - !key_exists($source->getNode()->getId(), $responseArray['data']) + $source instanceof NodesSources + && $this->security->isGranted(NodeVoter::READ, $source) + && !key_exists($source->getNode()->getId(), $responseArray['data']) ) { $responseArray['data'][$source->getNode()->getId()] = $this->getNodeSourceData($source); } @@ -96,16 +94,18 @@ protected function getNodeSourceData(NodesSources $source): array $translation = $source->getTranslation(); $displayableNSDoc = $source->getDocumentsByFields()->filter(function (NodesSourcesDocuments $nsDoc) { $doc = $nsDoc->getDocument(); + return !$doc->isPrivate() && ($doc->isImage() || $doc->isSvg()); })->first(); if (false !== $displayableNSDoc) { $thumbnail = $displayableNSDoc->getDocument(); $this->documentUrlGenerator->setDocument($thumbnail); $this->documentUrlGenerator->setOptions([ - "fit" => "60x60", - "quality" => 80 + 'fit' => '60x60', + 'quality' => 80, ]); } + return [ 'title' => $source->getTitle() ?? $source->getNode()->getNodeName(), 'parent' => $source->getParent() ? diff --git a/lib/Rozier/src/AjaxControllers/AjaxSessionMessages.php b/lib/Rozier/src/AjaxControllers/AjaxSessionMessages.php index 99d0bcaf..b56a6442 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxSessionMessages.php +++ b/lib/Rozier/src/AjaxControllers/AjaxSessionMessages.php @@ -17,7 +17,7 @@ public function getMessagesAction(Request $request): JsonResponse $responseArray = [ 'statusCode' => Response::HTTP_OK, - 'status' => 'success' + 'status' => 'success', ]; if ($request->hasPreviousSession()) { @@ -26,6 +26,7 @@ public function getMessagesAction(Request $request): JsonResponse $responseArray['messages'] = $session->getFlashBag()->all(); } } + return new JsonResponse( $responseArray ); diff --git a/lib/Rozier/src/AjaxControllers/AjaxTagTreeController.php b/lib/Rozier/src/AjaxControllers/AjaxTagTreeController.php index 67544e62..a1219982 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxTagTreeController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxTagTreeController.php @@ -15,7 +15,7 @@ final class AjaxTagTreeController extends AbstractAjaxController { public function __construct( private readonly TreeWidgetFactory $treeWidgetFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } @@ -28,7 +28,7 @@ public function getTreeAction(Request $request): JsonResponse /** @var TagTreeWidget|null $tagTree */ $tagTree = null; - switch ($request->get("_action")) { + switch ($request->get('_action')) { /* * Inner tag edit for tagTree */ @@ -48,9 +48,9 @@ public function getTreeAction(Request $request): JsonResponse $this->assignation['mainTagTree'] = false; break; - /* - * Main panel tree tagTree - */ + /* + * Main panel tree tagTree + */ case 'requestMainTagTree': $parent = null; $tagTree = $this->treeWidgetFactory->createTagTree($parent, $translation); diff --git a/lib/Rozier/src/AjaxControllers/AjaxTagsController.php b/lib/Rozier/src/AjaxControllers/AjaxTagsController.php index 995ae34c..29620ead 100644 --- a/lib/Rozier/src/AjaxControllers/AjaxTagsController.php +++ b/lib/Rozier/src/AjaxControllers/AjaxTagsController.php @@ -26,22 +26,17 @@ final class AjaxTagsController extends AbstractAjaxController public function __construct( private readonly ExplorerItemFactoryInterface $explorerItemFactory, private readonly HandlerFactoryInterface $handlerFactory, - SerializerInterface $serializer + SerializerInterface $serializer, ) { parent::__construct($serializer); } - /** - * @return TagRepository - */ protected function getRepository(): TagRepository { return $this->em()->getRepository(Tag::class); } /** - * @param Request $request - * * @return Response JSON response */ public function indexAction(Request $request): Response @@ -50,8 +45,8 @@ public function indexAction(Request $request): Response $onlyParents = false; if ( - $request->query->has('onlyParents') && - $request->query->get('onlyParents') + $request->query->has('onlyParents') + && $request->query->get('onlyParents') ) { $onlyParents = true; } @@ -71,9 +66,6 @@ public function indexAction(Request $request): Response /** * Get a Tag list from an array of node id. - * - * @param Request $request - * @return JsonResponse */ public function listArrayAction(Request $request): JsonResponse { @@ -84,7 +76,7 @@ public function listArrayAction(Request $request): JsonResponse } $cleanTagIds = array_filter($request->query->filter('ids', [], \FILTER_DEFAULT, [ - 'flags' => \FILTER_FORCE_ARRAY + 'flags' => \FILTER_FORCE_ARRAY, ])); $normalizedTags = []; @@ -101,13 +93,11 @@ public function listArrayAction(Request $request): JsonResponse return $this->createSerializedResponse([ 'status' => 'confirm', 'statusCode' => 200, - 'tags' => $normalizedTags + 'tags' => $normalizedTags, ]); } /** - * @param Request $request - * * @return Response JSON response */ public function explorerListAction(Request $request): Response @@ -115,10 +105,10 @@ public function explorerListAction(Request $request): Response $this->denyAccessUnlessGranted('ROLE_ACCESS_TAGS'); $arrayFilter = [ - 'translation' => $this->em()->getRepository(Translation::class)->findDefault() + 'translation' => $this->em()->getRepository(Translation::class)->findDefault(), ]; $defaultOrder = [ - 'createdAt' => 'DESC' + 'createdAt' => 'DESC', ]; if ($request->get('tagId') > 0) { @@ -159,12 +149,13 @@ public function explorerListAction(Request $request): Response /** * @param array|\Traversable|null $tags + * * @return array */ protected function normalizeTags($tags): array { $tagsArray = []; - if ($tags !== null) { + if (null !== $tags) { foreach ($tags as $tag) { $tagModel = $this->explorerItemFactory->createForEntity($tag); $tagsArray[] = $tagModel->toArray(); @@ -176,14 +167,11 @@ protected function normalizeTags($tags): array /** * @param Tag[]|null $tags - * @param bool $onlyParents - * - * @return array */ - protected function recurseTags(array $tags = null, bool $onlyParents = false): array + protected function recurseTags(?array $tags = null, bool $onlyParents = false): array { $tagsArray = []; - if ($tags !== null) { + if (null !== $tags) { foreach ($tags as $tag) { if ($onlyParents) { $children = $this->getRepository()->findByParentWithChildrenAndDefaultTranslation($tag); @@ -205,11 +193,6 @@ protected function recurseTags(array $tags = null, bool $onlyParents = false): a /** * Handle AJAX edition requests for Tag * such as coming from tag-tree widgets. - * - * @param Request $request - * @param int $tagId - * - * @return JsonResponse */ public function editAction(Request $request, int $tagId): JsonResponse { @@ -217,13 +200,13 @@ public function editAction(Request $request, int $tagId): JsonResponse $tag = $this->em()->find(Tag::class, (int) $tagId); - if ($tag === null) { - throw $this->createNotFoundException('Tag ' . $tagId . ' does not exists'); + if (null === $tag) { + throw $this->createNotFoundException('Tag '.$tagId.' does not exists'); } /* * Get the right update method against "_action" parameter */ - if ($request->get('_action') !== 'updatePosition') { + if ('updatePosition' !== $request->get('_action')) { throw new BadRequestHttpException('Action does not exist'); } @@ -233,16 +216,13 @@ public function editAction(Request $request, int $tagId): JsonResponse [ 'statusCode' => '200', 'status' => 'success', - 'responseText' => ('Tag ' . $tagId . ' edited '), + 'responseText' => ('Tag '.$tagId.' edited '), ], Response::HTTP_PARTIAL_CONTENT ); } /** - * @param Request $request - * - * @return JsonResponse * @throws \Exception */ public function searchAction(Request $request): JsonResponse @@ -257,7 +237,7 @@ public function searchAction(Request $request): JsonResponse $pattern = strip_tags($request->get('search')); $tags = $this->getRepository()->searchBy($pattern, [], [], 10); - if (count($tags) === 0) { + if (0 === count($tags)) { /* * Try again using tag slug */ @@ -265,7 +245,7 @@ public function searchAction(Request $request): JsonResponse $tags = $this->getRepository()->searchBy($pattern, [], [], 10); } - if (count($tags) === 0) { + if (0 === count($tags)) { throw $this->createNotFoundException('No tags found.'); } @@ -279,22 +259,18 @@ public function searchAction(Request $request): JsonResponse ); } - /** - * @param array $parameters - * @param Tag $tag - */ protected function updatePosition(array $parameters, Tag $tag): void { /* * First, we set the new parent */ if ( - !empty($parameters['newParent']) && - is_numeric($parameters['newParent']) && - $parameters['newParent'] > 0 + !empty($parameters['newParent']) + && is_numeric($parameters['newParent']) + && $parameters['newParent'] > 0 ) { $parent = $this->em()->find(Tag::class, (int) $parameters['newParent']); - if ($parent !== null) { + if (null !== $parent) { $tag->setParent($parent); } } else { @@ -305,19 +281,19 @@ protected function updatePosition(array $parameters, Tag $tag): void * Then compute new position */ if ( - !empty($parameters['nextTagId']) && - $parameters['nextTagId'] > 0 + !empty($parameters['nextTagId']) + && $parameters['nextTagId'] > 0 ) { $nextTag = $this->em()->find(Tag::class, (int) $parameters['nextTagId']); - if ($nextTag !== null) { + if (null !== $nextTag) { $tag->setPosition($nextTag->getPosition() - 0.5); } } elseif ( - !empty($parameters['prevTagId']) && - $parameters['prevTagId'] > 0 + !empty($parameters['prevTagId']) + && $parameters['prevTagId'] > 0 ) { $prevTag = $this->em()->find(Tag::class, (int) $parameters['prevTagId']); - if ($prevTag !== null) { + if (null !== $prevTag) { $tag->setPosition($prevTag->getPosition() + 0.5); } } @@ -339,8 +315,6 @@ protected function updatePosition(array $parameters, Tag $tag): void /** * Create a new Tag. * - * @param Request $request - * @return JsonResponse * @throws ORMException * @throws OptimisticLockException */ @@ -352,7 +326,7 @@ public function createAction(Request $request): JsonResponse throw new InvalidParameterException('tagName should be provided to create a new Tag'); } - if ($request->getMethod() != Request::METHOD_POST) { + if (Request::METHOD_POST != $request->getMethod()) { throw new BadRequestHttpException(); } @@ -362,7 +336,7 @@ public function createAction(Request $request): JsonResponse return new JsonResponse( [ - 'tag' => $tagModel->toArray() + 'tag' => $tagModel->toArray(), ], Response::HTTP_CREATED ); diff --git a/lib/Rozier/src/Controllers/AbstractAdminController.php b/lib/Rozier/src/Controllers/AbstractAdminController.php index 2d73a9ba..50aa51bf 100644 --- a/lib/Rozier/src/Controllers/AbstractAdminController.php +++ b/lib/Rozier/src/Controllers/AbstractAdminController.php @@ -25,21 +25,15 @@ abstract class AbstractAdminController extends RozierApp public function __construct( protected readonly SerializerInterface $serializer, - protected readonly UrlGeneratorInterface $urlGenerator + protected readonly UrlGeneratorInterface $urlGenerator, ) { } - /** - * @return string - */ protected function getThemeDirectory(): string { return RozierApp::getThemeDir(); } - /** - * @return string - */ protected function getTemplateNamespace(): string { return '@RoadizRozier'; @@ -60,9 +54,6 @@ protected function getRepository(): ObjectRepository return $this->em()->getRepository($this->getEntityClass()); } - /** - * @return string - */ protected function getRequiredDeletionRole(): string { return $this->getRequiredRole(); @@ -89,8 +80,6 @@ protected function getRequiredExportRole(): string } /** - * @param Request $request - * @return Response|null * @throws \Twig\Error\RuntimeError */ public function defaultAction(Request $request): ?Response @@ -107,7 +96,7 @@ public function defaultAction(Request $request): ?Response /* * Stored item per pages in session */ - $sessionListFilter = new SessionListFilters($this->getNamespace() . '_item_per_page'); + $sessionListFilter = new SessionListFilters($this->getNamespace().'_item_per_page'); $sessionListFilter->handleItemPerPage($request, $elm); $elm->handle(); @@ -115,7 +104,7 @@ public function defaultAction(Request $request): ?Response $this->assignation['filters'] = $elm->getAssignation(); return $this->render( - $this->getTemplateFolder() . '/list.html.twig', + $this->getTemplateFolder().'/list.html.twig', $this->assignation, null, $this->getTemplateNamespace() @@ -123,8 +112,6 @@ public function defaultAction(Request $request): ?Response } /** - * @param Request $request - * @return Response|null * @throws \Twig\Error\RuntimeError */ public function addAction(Request $request): ?Response @@ -155,7 +142,7 @@ public function addAction(Request $request): ?Response '%namespace%.%item%.was_created', [ '%item%' => $this->getEntityName($item), - '%namespace%' => $this->getTranslator()->trans($this->getNamespace()) + '%namespace%' => $this->getTranslator()->trans($this->getNamespace()), ] ); $this->publishConfirmMessage($request, $msg, $item); @@ -167,7 +154,7 @@ public function addAction(Request $request): ?Response $this->assignation['item'] = $item; return $this->render( - $this->getTemplateFolder() . '/add.html.twig', + $this->getTemplateFolder().'/add.html.twig', $this->assignation, null, $this->getTemplateNamespace() @@ -175,9 +162,8 @@ public function addAction(Request $request): ?Response } /** - * @param Request $request * @param int|string $id Numeric ID or UUID - * @return Response|null + * * @throws \Twig\Error\RuntimeError */ public function editAction(Request $request, $id): ?Response @@ -216,7 +202,7 @@ public function editAction(Request $request, $id): ?Response '%namespace%.%item%.was_updated', [ '%item%' => $this->getEntityName($item), - '%namespace%' => $this->getTranslator()->trans($this->getNamespace()) + '%namespace%' => $this->getTranslator()->trans($this->getNamespace()), ] ); $this->publishConfirmMessage($request, $msg, $item); @@ -228,7 +214,7 @@ public function editAction(Request $request, $id): ?Response $this->assignation['item'] = $item; return $this->render( - $this->getTemplateFolder() . '/edit.html.twig', + $this->getTemplateFolder().'/edit.html.twig', $this->assignation, null, $this->getTemplateNamespace() @@ -261,9 +247,8 @@ public function exportAction(Request $request): JsonResponse } /** - * @param Request $request * @param int|string $id Numeric ID or UUID - * @return Response|null + * * @throws \Twig\Error\RuntimeError */ public function deleteAction(Request $request, $id): ?Response @@ -301,7 +286,7 @@ public function deleteAction(Request $request, $id): ?Response '%namespace%.%item%.was_deleted', [ '%item%' => $this->getEntityName($item), - '%namespace%' => $this->getTranslator()->trans($this->getNamespace()) + '%namespace%' => $this->getTranslator()->trans($this->getNamespace()), ] ); $this->publishConfirmMessage($request, $msg, $item); @@ -313,38 +298,24 @@ public function deleteAction(Request $request, $id): ?Response $this->assignation['item'] = $item; return $this->render( - $this->getTemplateFolder() . '/delete.html.twig', + $this->getTemplateFolder().'/delete.html.twig', $this->assignation, null, $this->getTemplateNamespace() ); } - /** - * @param PersistableInterface $item - * @return bool - */ abstract protected function supports(PersistableInterface $item): bool; /** - * @return string Namespace is used for composing messages and translations. + * @return string namespace is used for composing messages and translations */ abstract protected function getNamespace(): string; - /** - * @param Request $request - * @return PersistableInterface - */ abstract protected function createEmptyItem(Request $request): PersistableInterface; - /** - * @return string - */ abstract protected function getTemplateFolder(): string; - /** - * @return string - */ abstract protected function getRequiredRole(): string; /** @@ -358,7 +329,6 @@ abstract protected function getEntityClass(): string; abstract protected function getFormType(): string; /** - * @param Request $request * @return class-string */ protected function getFormTypeFromRequest(Request $request): string @@ -370,6 +340,7 @@ protected function getFormTypeFromRequest(Request $request): string if (!class_exists($type)) { throw new InvalidConfigurationException(\sprintf('Route uses non-existent %s form type class.', $type)); } + return (string) $type; } @@ -377,27 +348,16 @@ protected function getFormTypeFromRequest(Request $request): string return $this->getFormType(); } - /** - * @param Request $request - * @return array - */ protected function getDefaultCriteria(Request $request): array { return []; } - /** - * @param Request $request - * @return array - */ protected function getDefaultOrder(Request $request): array { return []; } - /** - * @return string - */ abstract protected function getDefaultRouteName(): string; /** @@ -408,21 +368,12 @@ protected function getDefaultRouteParameters(): array return []; } - /** - * @return string - */ abstract protected function getEditRouteName(): string; - /** - * @param PersistableInterface $item - * @param bool $forceDefaultEditRoute - * @param Request|null $request - * @return Response - */ protected function getPostSubmitResponse( PersistableInterface $item, bool $forceDefaultEditRoute = false, - ?Request $request = null + ?Request $request = null, ): Response { if (null === $request) { // Redirect to default route if no request provided @@ -439,9 +390,9 @@ protected function getPostSubmitResponse( * Force redirect to avoid resending form when refreshing page */ if ( - \is_string($referrer) && - $referrer !== '' && - (new UnicodeString($referrer))->trim()->startsWith('/') + \is_string($referrer) + && '' !== $referrer + && (new UnicodeString($referrer))->trim()->startsWith('/') ) { return $this->redirect($referrer); } @@ -450,9 +401,9 @@ protected function getPostSubmitResponse( * Try to redirect to same route as defined in Request attribute */ if ( - false === $forceDefaultEditRoute && - \is_string($route) && - $route !== '' + false === $forceDefaultEditRoute + && \is_string($route) + && '' !== $route ) { return $this->redirect($this->urlGenerator->generate( $route, @@ -466,21 +417,13 @@ protected function getPostSubmitResponse( )); } - /** - * @param PersistableInterface $item - * @return array - */ protected function getEditRouteParameters(PersistableInterface $item): array { return [ - 'id' => $item->getId() + 'id' => $item->getId(), ]; } - /** - * @param PersistableInterface $item - * @return Response - */ protected function getPostDeleteResponse(PersistableInterface $item): Response { return $this->redirect($this->urlGenerator->generate( @@ -491,7 +434,9 @@ protected function getPostDeleteResponse(PersistableInterface $item): Response /** * @template T of object|Event + * * @param T|iterable|array|null $event + * * @return T|iterable|array|null */ protected function dispatchSingleOrMultipleEvent(mixed $event): object|array|null @@ -512,13 +457,13 @@ protected function dispatchSingleOrMultipleEvent(mixed $event): object|array|nul $events[] = $returningEvent; } } + return $events; } throw new \InvalidArgumentException('Event must be null, Event or array of Event'); } /** - * @param PersistableInterface $item * @return Event|Event[]|null */ protected function createCreateEvent(PersistableInterface $item) @@ -527,7 +472,6 @@ protected function createCreateEvent(PersistableInterface $item) } /** - * @param PersistableInterface $item * @return Event|Event[]|null */ protected function createPostCreateEvent(PersistableInterface $item) @@ -536,7 +480,6 @@ protected function createPostCreateEvent(PersistableInterface $item) } /** - * @param PersistableInterface $item * @return Event|Event[]|null */ protected function createUpdateEvent(PersistableInterface $item) @@ -545,7 +488,6 @@ protected function createUpdateEvent(PersistableInterface $item) } /** - * @param PersistableInterface $item * @return Event|Event[]|null */ protected function createPostUpdateEvent(PersistableInterface $item) @@ -554,7 +496,6 @@ protected function createPostUpdateEvent(PersistableInterface $item) } /** - * @param PersistableInterface $item * @return Event|Event[]|null */ protected function createDeleteEvent(PersistableInterface $item) @@ -563,7 +504,6 @@ protected function createDeleteEvent(PersistableInterface $item) } /** - * @param PersistableInterface $item * @return Event|Event[]|null */ protected function createPostDeleteEvent(PersistableInterface $item) @@ -571,15 +511,8 @@ protected function createPostDeleteEvent(PersistableInterface $item) return null; } - /** - * @param PersistableInterface $item - * @return string - */ abstract protected function getEntityName(PersistableInterface $item): string; - /** - * @param PersistableInterface $item - */ protected function denyAccessUnlessItemGranted(PersistableInterface $item): void { // Do nothing diff --git a/lib/Rozier/src/Controllers/AbstractAdminWithBulkController.php b/lib/Rozier/src/Controllers/AbstractAdminWithBulkController.php index 1efa45a5..4b349cff 100644 --- a/lib/Rozier/src/Controllers/AbstractAdminWithBulkController.php +++ b/lib/Rozier/src/Controllers/AbstractAdminWithBulkController.php @@ -20,7 +20,7 @@ abstract class AbstractAdminWithBulkController extends AbstractAdminController public function __construct( protected readonly FormFactoryInterface $formFactory, SerializerInterface $serializer, - UrlGeneratorInterface $urlGenerator + UrlGeneratorInterface $urlGenerator, ) { parent::__construct($serializer, $urlGenerator); } @@ -63,17 +63,18 @@ protected function getBulkPublishRouteName(): ?string { return null; } + protected function getBulkUnpublishRouteName(): ?string { return null; } + protected function getBulkDeleteRouteName(): ?string { return null; } /** - * @param FormInterface|null $form * @return array */ protected function parseFormBulkIds(?FormInterface $form): array @@ -99,16 +100,9 @@ protected function parseFormBulkIds(?FormInterface $form): array } /** - * @param Request $request - * @param string $requiredRole - * @param FormInterface $bulkForm - * @param FormInterface $form - * @param callable(string): FormInterface $createBulkFormWithIds - * @param string $templatePath - * @param string $confirmMessageTemplate + * @param callable(string): FormInterface $createBulkFormWithIds * @param callable(PersistableInterface, FormInterface): void $alterItemCallable - * @param string $bulkFormName - * @return Response + * * @throws \Twig\Error\RuntimeError */ protected function bulkAction( @@ -120,7 +114,7 @@ protected function bulkAction( string $templatePath, string $confirmMessageTemplate, callable $alterItemCallable, - string $bulkFormName + string $bulkFormName, ): Response { $this->denyAccessUnlessGranted($requiredRole); $bulkForm->handleRequest($request); @@ -164,13 +158,14 @@ protected function bulkAction( $confirmMessageTemplate, [ '%item%' => $this->getEntityName($item), - '%namespace%' => $this->getTranslator()->trans($this->getNamespace()) + '%namespace%' => $this->getTranslator()->trans($this->getNamespace()), ] ); $this->publishConfirmMessage($request, $msg, $item); } } $this->em()->flush(); + return $this->redirect($this->urlGenerator->generate( $this->getDefaultRouteName(), $this->getDefaultRouteParameters() @@ -191,6 +186,7 @@ protected function bulkAction( public function bulkDeleteAction(Request $request): Response { $this->additionalAssignation($request); + return $this->bulkAction( $request, $this->getRequiredDeletionRole(), @@ -201,7 +197,7 @@ function (string $ids) { 'id' => $ids, ]); }, - $this->getTemplateFolder() . '/bulk_delete.html.twig', + $this->getTemplateFolder().'/bulk_delete.html.twig', '%namespace%.%item%.was_deleted', function (PersistableInterface $item) { $this->removeItem($item); @@ -213,6 +209,7 @@ function (PersistableInterface $item) { public function bulkPublishAction(Request $request): Response { $this->additionalAssignation($request); + return $this->bulkAction( $request, $this->getRequiredRole(), @@ -223,7 +220,7 @@ function (string $ids) { 'id' => $ids, ]); }, - $this->getTemplateFolder() . '/bulk_publish.html.twig', + $this->getTemplateFolder().'/bulk_publish.html.twig', '%namespace%.%item%.was_published', function (PersistableInterface $item) { $this->setPublishedAt($item, new \DateTime('now')); @@ -235,6 +232,7 @@ function (PersistableInterface $item) { public function bulkUnpublishAction(Request $request): Response { $this->additionalAssignation($request); + return $this->bulkAction( $request, $this->getRequiredRole(), @@ -245,7 +243,7 @@ function (string $ids) { 'id' => $ids, ]); }, - $this->getTemplateFolder() . '/bulk_unpublish.html.twig', + $this->getTemplateFolder().'/bulk_unpublish.html.twig', '%namespace%.%item%.was_unpublished', function (PersistableInterface $item) { $this->setPublishedAt($item, null); @@ -258,7 +256,7 @@ protected function createBulkForm( ?string $routeName, string $formName, bool $get = false, - ?array $data = null + ?array $data = null, ): FormInterface { if (null === $routeName) { throw new \RuntimeException('Bulk delete route name is not defined.'); @@ -275,11 +273,12 @@ protected function createBulkForm( 'method' => 'POST', ]; } + return $this->formFactory->createNamedBuilder($formName, FormType::class, $data, $options) ->add('id', HiddenType::class, [ 'attr' => [ - 'class' => 'bulk-form-value' - ] + 'class' => 'bulk-form-value', + ], ])->getForm(); } diff --git a/lib/Rozier/src/Controllers/Attributes/AttributeController.php b/lib/Rozier/src/Controllers/Attributes/AttributeController.php index 49883ec6..19b5baa7 100644 --- a/lib/Rozier/src/Controllers/Attributes/AttributeController.php +++ b/lib/Rozier/src/Controllers/Attributes/AttributeController.php @@ -25,14 +25,11 @@ public function __construct( private readonly AttributeImporter $attributeImporter, FormFactoryInterface $formFactory, SerializerInterface $serializer, - UrlGeneratorInterface $urlGenerator + UrlGeneratorInterface $urlGenerator, ) { parent::__construct($formFactory, $serializer, $urlGenerator); } - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof Attribute; @@ -43,68 +40,44 @@ protected function getBulkDeleteRouteName(): ?string return 'attributesBulkDeletePage'; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'attribute'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { $item = new Attribute(); $item->setCode('new_attribute'); + return $item; } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizRozier/attributes'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_ATTRIBUTES'; } - /** - * @inheritDoc - */ protected function getRequiredDeletionRole(): string { return 'ROLE_ACCESS_ATTRIBUTES_DELETE'; } - - /** - * @inheritDoc - */ protected function getEntityClass(): string { return Attribute::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return AttributeType::class; } - /** - * @inheritDoc - */ protected function getDefaultOrder(Request $request): array { return [ @@ -113,36 +86,25 @@ protected function getDefaultOrder(Request $request): array ]; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'attributesHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'attributesEditPage'; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { if ($item instanceof Attribute) { return $item->getCode(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } /** - * @param Request $request - * @return Response * @throws RuntimeError */ public function importAction(Request $request): Response @@ -168,10 +130,11 @@ public function importAction(Request $request): Response $msg = $this->getTranslator()->trans( '%namespace%.imported', [ - '%namespace%' => $this->getTranslator()->trans($this->getNamespace()) + '%namespace%' => $this->getTranslator()->trans($this->getNamespace()), ] ); $this->publishConfirmMessage($request, $msg); + return $this->redirectToRoute('attributesHomePage'); } $form->addError(new FormError($this->getTranslator()->trans('file.not_uploaded'))); diff --git a/lib/Rozier/src/Controllers/Attributes/AttributeGroupController.php b/lib/Rozier/src/Controllers/Attributes/AttributeGroupController.php index 5fc541c3..b4e7b3d5 100644 --- a/lib/Rozier/src/Controllers/Attributes/AttributeGroupController.php +++ b/lib/Rozier/src/Controllers/Attributes/AttributeGroupController.php @@ -12,92 +12,59 @@ class AttributeGroupController extends AbstractAdminController { - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof AttributeGroup; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'attribute_group'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { return new AttributeGroup(); } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizRozier/attributes/groups'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_ATTRIBUTES'; } - /** - * @inheritDoc - */ protected function getEntityClass(): string { return AttributeGroup::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return AttributeGroupType::class; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'attributeGroupsHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'attributeGroupsEditPage'; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { if ($item instanceof AttributeGroup) { return $item->getName(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } - /** - * @inheritDoc - */ protected function getDefaultOrder(Request $request): array { return ['canonicalName' => 'ASC']; diff --git a/lib/Rozier/src/Controllers/CacheController.php b/lib/Rozier/src/Controllers/CacheController.php index 0020827d..60fb3d74 100644 --- a/lib/Rozier/src/Controllers/CacheController.php +++ b/lib/Rozier/src/Controllers/CacheController.php @@ -16,7 +16,7 @@ final class CacheController extends RozierApp { public function __construct( private readonly CacheClearerInterface $cacheClearer, - private readonly LoggerInterface $logger + private readonly LoggerInterface $logger, ) { } @@ -54,9 +54,6 @@ public function deleteDoctrineCache(Request $request): Response } /** - * @param Request $request - * - * @return Response * @throws \Twig\Error\RuntimeError */ public function deleteAssetsCache(Request $request): Response diff --git a/lib/Rozier/src/Controllers/CustomForms/CustomFormAnswersController.php b/lib/Rozier/src/Controllers/CustomForms/CustomFormAnswersController.php index 7aea9cfe..7d6a1f0c 100644 --- a/lib/Rozier/src/Controllers/CustomForms/CustomFormAnswersController.php +++ b/lib/Rozier/src/Controllers/CustomForms/CustomFormAnswersController.php @@ -21,10 +21,6 @@ class CustomFormAnswersController extends RozierApp /** * List every node-types. * - * @param Request $request - * @param int $customFormId - * - * @return Response * @throws RuntimeError */ public function listAction(Request $request, int $customFormId): Response @@ -41,8 +37,8 @@ public function listAction(Request $request, int $customFormId): Response $listManager = $this->createEntityListManager( CustomFormAnswer::class, - ["customForm" => $customForm], - ["submittedAt" => "DESC"] + ['customForm' => $customForm], + ['submittedAt' => 'DESC'] ); $listManager->setDisplayingNotPublishedNodes(true); $listManager->handle(); @@ -56,10 +52,6 @@ public function listAction(Request $request, int $customFormId): Response /** * Return a deletion form for requested node-type. * - * @param Request $request - * @param int $customFormAnswerId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $customFormAnswerId): Response @@ -77,20 +69,21 @@ public function deleteAction(Request $request, int $customFormAnswerId): Respons $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() + $form->isSubmitted() + && $form->isValid() ) { $this->em()->remove($customFormAnswer); $this->em()->flush(); $msg = $this->getTranslator()->trans('customFormAnswer.%id%.deleted', ['%id%' => $customFormAnswer->getId()]); $this->publishConfirmMessage($request, $msg, $customFormAnswer); + /* * Redirect to update schema page */ return $this->redirectToRoute( 'customFormAnswersHomePage', - ["customFormId" => $customFormAnswer->getCustomForm()->getId()] + ['customFormId' => $customFormAnswer->getCustomForm()->getId()] ); } @@ -99,11 +92,6 @@ public function deleteAction(Request $request, int $customFormAnswerId): Respons return $this->render('@RoadizRozier/custom-form-answers/delete.html.twig', $this->assignation); } - /** - * @param CustomFormAnswer $customFormAnswer - * - * @return FormInterface - */ private function buildDeleteForm(CustomFormAnswer $customFormAnswer): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldAttributesController.php b/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldAttributesController.php index e5747a84..eb066ec6 100644 --- a/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldAttributesController.php +++ b/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldAttributesController.php @@ -16,10 +16,6 @@ class CustomFormFieldAttributesController extends RozierApp /** * List every node-types. * - * @param Request $request - * @param int $customFormAnswerId - * - * @return Response * @throws RuntimeError */ public function listAction(Request $request, int $customFormAnswerId): Response @@ -40,10 +36,6 @@ public function listAction(Request $request, int $customFormAnswerId): Response return $this->render('@RoadizRozier/custom-form-field-attributes/list.html.twig', $this->assignation); } - /** - * @param iterable $answers - * @return array - */ protected function getAnswersByGroups(iterable $answers): array { $fieldsArray = []; @@ -51,7 +43,7 @@ protected function getAnswersByGroups(iterable $answers): array /** @var CustomFormFieldAttribute $answer */ foreach ($answers as $answer) { $groupName = $answer->getCustomFormField()->getGroupName(); - if (\is_string($groupName) && $groupName !== '') { + if (\is_string($groupName) && '' !== $groupName) { if (!isset($fieldsArray[$groupName]) || !\is_array($fieldsArray[$groupName])) { $fieldsArray[$groupName] = []; } diff --git a/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldsController.php b/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldsController.php index 66e63255..d47935e3 100644 --- a/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldsController.php +++ b/lib/Rozier/src/Controllers/CustomForms/CustomFormFieldsController.php @@ -4,7 +4,6 @@ namespace Themes\Rozier\Controllers\CustomForms; -use Exception; use RZ\Roadiz\CoreBundle\Entity\CustomForm; use RZ\Roadiz\CoreBundle\Entity\CustomFormField; use Symfony\Component\Form\Extension\Core\Type\HiddenType; @@ -23,9 +22,6 @@ class CustomFormFieldsController extends RozierApp /** * List every node-type-fields. * - * @param int $customFormId - * - * @return Response * @throws RuntimeError */ public function listAction(int $customFormId): Response @@ -34,7 +30,7 @@ public function listAction(int $customFormId): Response $customForm = $this->em()->find(CustomForm::class, $customFormId); - if ($customForm !== null) { + if (null !== $customForm) { $fields = $customForm->getFields(); $this->assignation['customForm'] = $customForm; @@ -49,10 +45,6 @@ public function listAction(int $customFormId): Response /** * Return an edition form for requested node-type. * - * @param Request $request - * @param int $customFormFieldId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $customFormFieldId): Response @@ -62,7 +54,7 @@ public function editAction(Request $request, int $customFormFieldId): Response /** @var CustomFormField|null $field */ $field = $this->em()->find(CustomFormField::class, $customFormFieldId); - if ($field === null) { + if (null === $field) { throw new ResourceNotFoundException(); } @@ -96,10 +88,6 @@ public function editAction(Request $request, int $customFormFieldId): Response /** * Return a creation form for requested node-type. * - * @param Request $request - * @param int $customFormId - * - * @return Response * @throws RuntimeError */ public function addAction(Request $request, int $customFormId): Response @@ -107,7 +95,7 @@ public function addAction(Request $request, int $customFormId): Response $this->denyAccessUnlessGranted('ROLE_ACCESS_CUSTOMFORMS'); $customForm = $this->em()->find(CustomForm::class, $customFormId); - if ($customForm === null) { + if (null === $customForm) { throw new ResourceNotFoundException(); } @@ -139,9 +127,10 @@ public function addAction(Request $request, int $customFormId): Response 'customFormId' => $customFormId, ] ); - } catch (Exception $e) { + } catch (\Exception $e) { $msg = $e->getMessage(); $this->publishErrorMessage($request, $msg, $field); + /* * Redirect to add page */ @@ -160,10 +149,6 @@ public function addAction(Request $request, int $customFormId): Response /** * Return a deletion form for requested node. * - * @param Request $request - * @param int $customFormFieldId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $customFormFieldId): Response @@ -172,7 +157,7 @@ public function deleteAction(Request $request, int $customFormFieldId): Response $field = $this->em()->find(CustomFormField::class, $customFormFieldId); - if ($field === null) { + if (null === $field) { throw new ResourceNotFoundException(); } @@ -181,9 +166,9 @@ public function deleteAction(Request $request, int $customFormFieldId): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - $form->getData()['customFormFieldId'] == $field->getId() + $form->isSubmitted() + && $form->isValid() + && $form->getData()['customFormFieldId'] == $field->getId() ) { $customFormId = $field->getCustomForm()->getId(); @@ -215,11 +200,6 @@ public function deleteAction(Request $request, int $customFormFieldId): Response return $this->render('@RoadizRozier/custom-form-fields/delete.html.twig', $this->assignation); } - /** - * @param CustomFormField $field - * - * @return FormInterface - */ private function buildDeleteForm(CustomFormField $field): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/CustomForms/CustomFormsController.php b/lib/Rozier/src/Controllers/CustomForms/CustomFormsController.php index 042983c8..b5fe1e3e 100644 --- a/lib/Rozier/src/Controllers/CustomForms/CustomFormsController.php +++ b/lib/Rozier/src/Controllers/CustomForms/CustomFormsController.php @@ -67,7 +67,7 @@ protected function getEntityName(PersistableInterface $item): string if ($item instanceof CustomForm) { return $item->getName(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } protected function getBulkDeleteRouteName(): ?string diff --git a/lib/Rozier/src/Controllers/CustomForms/CustomFormsUtilsController.php b/lib/Rozier/src/Controllers/CustomForms/CustomFormsUtilsController.php index 535da55d..7b61a6d1 100644 --- a/lib/Rozier/src/Controllers/CustomForms/CustomFormsUtilsController.php +++ b/lib/Rozier/src/Controllers/CustomForms/CustomFormsUtilsController.php @@ -22,17 +22,13 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly TranslatorInterface $translator, private readonly CustomFormAnswerSerializer $customFormAnswerSerializer, - private readonly SerializerInterface $serializer + private readonly SerializerInterface $serializer, ) { } /** * Export all custom form's answers in a CSV file. * - * @param Request $request - * @param int $id - * - * @return Response * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ @@ -53,12 +49,12 @@ public function exportAction(Request $request, int $id): Response $keys = [ 'ip', 'submitted.date', - ...$fields + ...$fields, ]; $response = new StreamedResponse(function () use ($answersArray, $keys) { echo $this->serializer->serialize($answersArray, 'csv', [ - 'csv_headers' => $keys + 'csv_headers' => $keys, ]); }); $response->headers->set('Content-Type', 'text/csv'); @@ -66,7 +62,7 @@ public function exportAction(Request $request, int $id): Response 'Content-Disposition', $response->headers->makeDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT, - $customForm->getName() . '.csv' + $customForm->getName().'.csv' ) ); @@ -76,11 +72,7 @@ public function exportAction(Request $request, int $id): Response } /** - * Duplicate custom form by ID - * - * @param Request $request - * @param int $id - * @return Response + * Duplicate custom form by ID. */ public function duplicateAction(Request $request, int $id): Response { @@ -103,7 +95,7 @@ public function duplicateAction(Request $request, int $id): Response $em->persist($newCustomForm); $em->flush(); - $msg = $this->translator->trans("duplicated.custom.form.%name%", [ + $msg = $this->translator->trans('duplicated.custom.form.%name%', [ '%name%' => $existingCustomForm->getDisplayName(), ]); @@ -111,12 +103,12 @@ public function duplicateAction(Request $request, int $id): Response return $this->redirectToRoute( 'customFormsEditPage', - ["id" => $newCustomForm->getId()] + ['id' => $newCustomForm->getId()] ); } catch (\Exception $e) { $this->publishErrorMessage( $request, - $this->translator->trans("impossible.duplicate.custom.form.%name%", [ + $this->translator->trans('impossible.duplicate.custom.form.%name%', [ '%name%' => $existingCustomForm->getDisplayName(), ]), $newCustomForm @@ -125,7 +117,7 @@ public function duplicateAction(Request $request, int $id): Response return $this->redirectToRoute( 'customFormsEditPage', - ["id" => $existingCustomForm->getId()] + ['id' => $existingCustomForm->getId()] ); } } diff --git a/lib/Rozier/src/Controllers/DashboardController.php b/lib/Rozier/src/Controllers/DashboardController.php index 5a28614c..d9ebf051 100644 --- a/lib/Rozier/src/Controllers/DashboardController.php +++ b/lib/Rozier/src/Controllers/DashboardController.php @@ -13,9 +13,8 @@ class DashboardController extends RozierApp { /** - * @param Request $request - * * @return Response $response + * * @throws RuntimeError */ public function indexAction(Request $request): Response @@ -28,7 +27,6 @@ public function indexAction(Request $request): Response ->getRepository(Log::class) ->findLatestByNodesSources(8); - return $this->render('@RoadizRozier/dashboard/index.html.twig', $this->assignation); } } diff --git a/lib/Rozier/src/Controllers/Documents/DocumentTranslationsController.php b/lib/Rozier/src/Controllers/Documents/DocumentTranslationsController.php index e8c1138f..69c20484 100644 --- a/lib/Rozier/src/Controllers/Documents/DocumentTranslationsController.php +++ b/lib/Rozier/src/Controllers/Documents/DocumentTranslationsController.php @@ -4,7 +4,6 @@ namespace Themes\Rozier\Controllers\Documents; -use Exception; use RZ\Roadiz\Core\AbstractEntities\PersistableInterface; use RZ\Roadiz\Core\AbstractEntities\TranslationInterface; use RZ\Roadiz\CoreBundle\Entity\Document; @@ -28,11 +27,6 @@ class DocumentTranslationsController extends RozierApp use VersionedControllerTrait; /** - * @param Request $request - * @param int $documentId - * @param int|null $translationId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $documentId, ?int $translationId = null): Response @@ -59,11 +53,11 @@ public function editAction(Request $request, int $documentId, ?int $translationI ->getRepository(DocumentTranslation::class) ->findOneBy(['document' => $documentId, 'translation' => $translationId]); - if ($documentTr === null && $document !== null && $translation !== null) { + if (null === $documentTr && null !== $document && null !== $translation) { $documentTr = $this->createDocumentTranslation($document, $translation); } - if ($documentTr === null || $document === null) { + if (null === $documentTr || null === $document) { throw new ResourceNotFoundException(); } @@ -71,7 +65,7 @@ public function editAction(Request $request, int $documentId, ?int $translationI $this->assignation['translation'] = $translation; $this->assignation['documentTr'] = $documentTr; - /** + /* * Versioning */ if ($this->isGranted('ROLE_ACCESS_VERSIONS')) { @@ -99,7 +93,7 @@ public function editAction(Request $request, int $documentId, ?int $translationI if ($form->get('referer')->getData()) { $routeParams = array_merge($routeParams, [ - 'referer' => $form->get('referer')->getData() + 'referer' => $form->get('referer')->getData(), ]); } @@ -120,7 +114,7 @@ public function editAction(Request $request, int $documentId, ?int $translationI protected function createDocumentTranslation( Document $document, - TranslationInterface $translation + TranslationInterface $translation, ): DocumentTranslation { $dt = new DocumentTranslation(); $dt->setDocument($document); @@ -134,11 +128,6 @@ protected function createDocumentTranslation( /** * Return an deletion form for requested document. * - * @param Request $request - * @param int $documentId - * @param int $translationId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $documentId, int $translationId): Response @@ -152,8 +141,8 @@ public function deleteAction(Request $request, int $documentId, int $translation ->find(Document::class, $documentId); if ( - $documentTr !== null && - $document !== null + null !== $documentTr + && null !== $document ) { $this->assignation['documentTr'] = $documentTr; $this->assignation['document'] = $document; @@ -161,9 +150,9 @@ public function deleteAction(Request $request, int $documentId, int $translation $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - $form->getData()['documentId'] == $documentTr->getId() + $form->isSubmitted() + && $form->isValid() + && $form->getData()['documentId'] == $documentTr->getId() ) { try { $this->em()->remove($documentTr); @@ -174,13 +163,14 @@ public function deleteAction(Request $request, int $documentId, int $translation ['%name%' => (string) $document] ); $this->publishConfirmMessage($request, $msg, $document); - } catch (Exception $e) { + } catch (\Exception $e) { $msg = $this->getTranslator()->trans( 'document.translation.%name%.cannot_delete', ['%name%' => (string) $document] ); $this->publishErrorMessage($request, $msg, $document); } + /* * Force redirect to avoid resending form when refreshing page */ @@ -235,14 +225,15 @@ protected function onPostUpdate(PersistableInterface $entity, Request $request): protected function getPostUpdateRedirection(PersistableInterface $entity): ?Response { if ( - $entity instanceof DocumentTranslation && - $entity->getDocument() instanceof Document && - $entity->getTranslation() instanceof Translation + $entity instanceof DocumentTranslation + && $entity->getDocument() instanceof Document + && $entity->getTranslation() instanceof Translation ) { $routeParams = [ 'documentId' => $entity->getDocument()->getId(), 'translationId' => $entity->getTranslation()->getId(), ]; + /* * Force redirect to avoid resending form when refreshing page */ @@ -251,6 +242,7 @@ protected function getPostUpdateRedirection(PersistableInterface $entity): ?Resp $routeParams ); } + return null; } } diff --git a/lib/Rozier/src/Controllers/Documents/DocumentsController.php b/lib/Rozier/src/Controllers/Documents/DocumentsController.php index 47dac637..26356da6 100644 --- a/lib/Rozier/src/Controllers/Documents/DocumentsController.php +++ b/lib/Rozier/src/Controllers/Documents/DocumentsController.php @@ -75,14 +75,11 @@ public function __construct( private readonly RandomImageFinder $randomImageFinder, private readonly DocumentFactory $documentFactory, private readonly ?string $googleServerId = null, - private readonly ?string $soundcloudClientId = null + private readonly ?string $soundcloudClientId = null, ) { } /** - * @param Request $request - * @param int|null $folderId - * @return Response * @throws RuntimeError */ public function indexAction(Request $request, ?int $folderId = null): Response @@ -99,8 +96,8 @@ public function indexAction(Request $request, ?int $folderId = null): Response ]; if ( - null !== $folderId && - $folderId > 0 + null !== $folderId + && $folderId > 0 ) { $folder = $this->em() ->find(Folder::class, $folderId); @@ -110,13 +107,13 @@ public function indexAction(Request $request, ?int $folderId = null): Response } $type = $request->query->get('type', null); - if (\is_string($type) && trim($type) !== '') { + if (\is_string($type) && '' !== trim($type)) { $prefilters['mimeType'] = trim($type); $this->assignation['mimeType'] = trim($type); } $embedPlatform = $request->query->get('embedPlatform', null); - if (\is_string($embedPlatform) && trim($embedPlatform) !== '') { + if (\is_string($embedPlatform) && '' !== trim($embedPlatform)) { $prefilters['embedPlatform'] = trim($embedPlatform); $this->assignation['embedPlatform'] = trim($embedPlatform); } @@ -176,9 +173,6 @@ public function indexAction(Request $request, ?int $folderId = null): Response } /** - * @param Request $request - * @param int $documentId - * @return Response * @throws RuntimeError * @throws FilesystemException */ @@ -188,7 +182,7 @@ public function adjustAction(Request $request, int $documentId): Response /** @var Document|null $document */ $document = $this->em()->find(Document::class, $documentId); - if ($document === null) { + if (null === $document) { throw new ResourceNotFoundException(); } if (!$document->isLocal()) { @@ -222,7 +216,7 @@ public function adjustAction(Request $request, int $documentId): Response * Prefix document filename with unique id to avoid overriding original * if already existing. */ - $cloneDocument->setFilename('original_' . uniqid() . '_' . $cloneDocument); + $cloneDocument->setFilename('original_'.uniqid().'_'.$cloneDocument); $newPath = $cloneDocument->getMountPath(); $this->documentsStorage->move($oldPath, $newPath); @@ -253,7 +247,7 @@ public function adjustAction(Request $request, int $documentId): Response return new JsonResponse([ 'message' => $msg, - 'path' => $this->documentsStorage->publicUrl($document->getMountPath()) . '?' . \random_int(10, 999), + 'path' => $this->documentsStorage->publicUrl($document->getMountPath()).'?'.\random_int(10, 999), ]); } @@ -264,9 +258,6 @@ public function adjustAction(Request $request, int $documentId): Response } /** - * @param Request $request - * @param int $documentId - * @return Response * @throws FilesystemException * @throws RuntimeError */ @@ -276,7 +267,7 @@ public function editAction(Request $request, int $documentId): Response /** @var Document|null $document */ $document = $this->em()->find(Document::class, $documentId); - if ($document === null) { + if (null === $document) { throw new ResourceNotFoundException(); } @@ -308,7 +299,7 @@ public function editAction(Request $request, int $documentId): Response } $msg = $this->getTranslator()->trans('document.%name%.updated', [ - '%name%' => (string) $document, + '%name%' => (string) $document, ]); $this->publishConfirmMessage($request, $msg, $document); $this->em()->flush(); @@ -322,9 +313,10 @@ public function editAction(Request $request, int $documentId): Response if ($form->get('referer')->getData()) { $routeParams = array_merge($routeParams, [ - 'referer' => $form->get('referer')->getData(), + 'referer' => $form->get('referer')->getData(), ]); } + /* * Force redirect to avoid resending form when refreshing page */ @@ -349,9 +341,6 @@ public function editAction(Request $request, int $documentId): Response /** * Return an deletion form for requested document. * - * @param Request $request - * @param int $documentId - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $documentId): Response @@ -361,7 +350,7 @@ public function deleteAction(Request $request, int $documentId): Response /** @var Document|null $document */ $document = $this->em()->find(Document::class, $documentId); - if ($document === null) { + if (null === $document) { throw new ResourceNotFoundException(); } @@ -370,9 +359,9 @@ public function deleteAction(Request $request, int $documentId): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - $form->getData()['documentId'] == $document->getId() + $form->isSubmitted() + && $form->isValid() + && $form->getData()['documentId'] == $document->getId() ) { try { $this->dispatchEvent( @@ -381,16 +370,17 @@ public function deleteAction(Request $request, int $documentId): Response $this->em()->remove($document); $this->em()->flush(); $msg = $this->getTranslator()->trans('document.%name%.deleted', [ - '%name%' => (string) $document + '%name%' => (string) $document, ]); $this->publishConfirmMessage($request, $msg, $document); } catch (\Exception $e) { $msg = $this->getTranslator()->trans('document.%name%.cannot_delete', [ - '%name%' => (string) $document + '%name%' => (string) $document, ]); $this->logger->error($e->getMessage()); $this->publishErrorMessage($request, $msg, $document); } + /* * Force redirect to avoid resending form when refreshing page */ @@ -405,8 +395,6 @@ public function deleteAction(Request $request, int $documentId): Response /** * Return an deletion form for multiple docs. * - * @param Request $request - * @return Response * @throws RuntimeError */ public function bulkDeleteAction(Request $request): Response @@ -448,7 +436,7 @@ public function bulkDeleteAction(Request $request): Response return $this->redirectToRoute('documentsHomePage'); } $this->assignation['form'] = $form->createView(); - $this->assignation['action'] = '?' . http_build_query(['documents' => $documentsIds]); + $this->assignation['action'] = '?'.http_build_query(['documents' => $documentsIds]); $this->assignation['thumbnailFormat'] = $this->thumbnailFormat; return $this->render('@RoadizRozier/documents/bulkDelete.html.twig', $this->assignation); @@ -457,9 +445,6 @@ public function bulkDeleteAction(Request $request): Response /** * Embed external document page. * - * @param Request $request - * @param int|null $folderId - * @return Response * @throws RuntimeError */ public function embedAction(Request $request, ?int $folderId = null): Response @@ -503,12 +488,13 @@ public function embedAction(Request $request, ?int $folderId = null): Response new DocumentCreatedEvent($document) ); } + /* * Force redirect to avoid resending form when refreshing page */ return $this->redirectToRoute('documentsHomePage', ['folderId' => $folderId]); } catch (RequestException $e) { - $this->logger->error($e->getRequest()->getUri() . ' failed.'); + $this->logger->error($e->getRequest()->getUri().' failed.'); if (null !== $e->getResponse() && in_array($e->getResponse()->getStatusCode(), [401, 403, 404])) { $form->addError(new FormError( $this->getTranslator()->trans('document.media_not_found_or_private') @@ -533,9 +519,6 @@ public function embedAction(Request $request, ?int $folderId = null): Response /** * Get random external document page. * - * @param Request $request - * @param int|null $folderId - * @return Response * @throws FilesystemException */ public function randomAction(Request $request, ?int $folderId = null): Response @@ -559,6 +542,7 @@ public function randomAction(Request $request, ?int $folderId = null): Response $this->getTranslator()->trans($e->getMessage()) ); } + /* * Force redirect to avoid resending form when refreshing page */ @@ -568,9 +552,6 @@ public function randomAction(Request $request, ?int $folderId = null): Response /** * Download document file. * - * @param Request $request - * @param int $documentId - * @return Response * @throws FilesystemException */ public function downloadAction(Request $request, int $documentId): Response @@ -580,7 +561,7 @@ public function downloadAction(Request $request, int $documentId): Response /** @var Document|null $document */ $document = $this->em()->find(Document::class, $documentId); - if ($document !== null) { + if (null !== $document) { /** @var DocumentHandler $handler */ $handler = $this->handlerFactory->getHandler($document); @@ -593,9 +574,6 @@ public function downloadAction(Request $request, int $documentId): Response /** * Download document file inline. * - * @param Request $request - * @param int $documentId - * @return Response * @throws FilesystemException */ public function downloadInlineAction(Request $request, int $documentId): Response @@ -605,7 +583,7 @@ public function downloadInlineAction(Request $request, int $documentId): Respons /** @var Document|null $document */ $document = $this->em()->find(Document::class, $documentId); - if ($document !== null) { + if (null !== $document) { /** @var DocumentHandler $handler */ $handler = $this->handlerFactory->getHandler($document); @@ -616,10 +594,6 @@ public function downloadInlineAction(Request $request, int $documentId): Respons } /** - * @param Request $request - * @param int|null $folderId - * @param string $_format - * @return Response * @throws RuntimeError */ public function uploadAction(Request $request, ?int $folderId = null, string $_format = 'html'): Response @@ -653,10 +627,11 @@ public function uploadAction(Request $request, ?int $folderId = null, string $_f new DocumentCreatedEvent($document) ); - if ($_format === 'json' || $request->isXmlHttpRequest()) { + if ('json' === $_format || $request->isXmlHttpRequest()) { $documentModel = $this->explorerItemFactory->createForEntity( $document ); + return new JsonResponse([ 'success' => true, 'document' => $documentModel->toArray(), @@ -668,13 +643,13 @@ public function uploadAction(Request $request, ?int $folderId = null, string $_f $msg = $this->getTranslator()->trans('document.cannot_persist'); $this->publishErrorMessage($request, $msg, $document); - if ($_format === 'json' || $request->isXmlHttpRequest()) { + if ('json' === $_format || $request->isXmlHttpRequest()) { throw $this->createNotFoundException($msg); } else { return $this->redirectToRoute('documentsHomePage', ['folderId' => $folderId]); } } - } elseif ($_format === 'json' || $request->isXmlHttpRequest()) { + } elseif ('json' === $_format || $request->isXmlHttpRequest()) { /* * Bad form submitted */ @@ -688,9 +663,10 @@ public function uploadAction(Request $request, ?int $folderId = null, string $_f } } } + return new JsonResponse( [ - "errors" => $errorPerForm, + 'errors' => $errorPerForm, ], Response::HTTP_BAD_REQUEST ); @@ -705,9 +681,6 @@ public function uploadAction(Request $request, ?int $folderId = null, string $_f /** * Return a node list using this document. * - * @param Request $request - * @param int $documentId - * @return Response * @throws RuntimeError */ public function usageAction(Request $request, int $documentId): Response @@ -716,7 +689,7 @@ public function usageAction(Request $request, int $documentId): Response /** @var Document|null $document */ $document = $this->em()->find(Document::class, $documentId); - if ($document === null) { + if (null === $document) { throw new ResourceNotFoundException(); } @@ -734,10 +707,6 @@ public function usageAction(Request $request, int $documentId): Response return $this->render('@RoadizRozier/documents/usage.html.twig', $this->assignation); } - /** - * @param Document $doc - * @return FormInterface - */ private function buildDeleteForm(Document $doc): FormInterface { $defaults = [ @@ -755,17 +724,13 @@ private function buildDeleteForm(Document $doc): FormInterface return $builder->getForm(); } - /** - * @param array $documentsIds - * @return FormInterface - */ private function buildBulkDeleteForm(array $documentsIds): FormInterface { $defaults = [ 'checksum' => md5(serialize($documentsIds)), ]; $builder = $this->createFormBuilder($defaults, [ - 'action' => '?' . http_build_query(['documents' => $documentsIds]), + 'action' => '?'.http_build_query(['documents' => $documentsIds]), ]) ->add('checksum', HiddenType::class, [ 'constraints' => [ @@ -777,9 +742,6 @@ private function buildBulkDeleteForm(array $documentsIds): FormInterface return $builder->getForm(); } - /** - * @return FormInterface - */ private function buildFileForm(): FormInterface { $defaults = [ @@ -798,15 +760,11 @@ private function buildFileForm(): FormInterface return $builder->getForm(); } - /** - * @param int|null $folderId - * @return FormInterface - */ private function buildUploadForm(?int $folderId = null): FormInterface { $builder = $this->createFormBuilder([], [ - 'csrf_protection' => false, - ]) + 'csrf_protection' => false, + ]) ->add('attachment', FileType::class, [ 'label' => 'choose.documents.to_upload', 'constraints' => [ @@ -815,8 +773,8 @@ private function buildUploadForm(?int $folderId = null): FormInterface ]); if ( - null !== $folderId && - $folderId > 0 + null !== $folderId + && $folderId > 0 ) { $builder->add('folderId', HiddenType::class, [ 'data' => $folderId, @@ -826,9 +784,6 @@ private function buildUploadForm(?int $folderId = null): FormInterface return $builder->getForm(); } - /** - * @return FormInterface - */ private function buildLinkFoldersForm(): FormInterface { $builder = $this->createNamedFormBuilder('folderForm') @@ -855,7 +810,7 @@ private function buildLinkFoldersForm(): FormInterface 'attr' => [ 'class' => 'uk-button uk-button-primary', 'title' => 'link.folders', - 'data-uk-tooltip' => "{animation:true}", + 'data-uk-tooltip' => '{animation:true}', ], ]) ->add('submitUnfolder', SubmitType::class, [ @@ -863,7 +818,7 @@ private function buildLinkFoldersForm(): FormInterface 'attr' => [ 'class' => 'uk-button', 'title' => 'unlink.folders', - 'data-uk-tooltip' => "{animation:true}", + 'data-uk-tooltip' => '{animation:true}', ], ]); @@ -872,6 +827,7 @@ private function buildLinkFoldersForm(): FormInterface /** * @param array $data + * * @return string Status message */ private function joinFolder($data): string @@ -879,8 +835,8 @@ private function joinFolder($data): string $msg = $this->getTranslator()->trans('no_documents.linked_to.folders'); if ( - !empty($data['documentsId']) && - !empty($data['folderPaths']) + !empty($data['documentsId']) + && !empty($data['folderPaths']) ) { $documentsIds = explode(',', $data['documentsId']); @@ -925,6 +881,7 @@ private function joinFolder($data): string /** * @param array $data + * * @return string Status message */ private function leaveFolder($data): string @@ -932,8 +889,8 @@ private function leaveFolder($data): string $msg = $this->getTranslator()->trans('no_documents.removed_from.folders'); if ( - !empty($data['documentsId']) && - !empty($data['folderPaths']) + !empty($data['documentsId']) + && !empty($data['folderPaths']) ) { $documentsIds = explode(',', $data['documentsId']); @@ -978,10 +935,10 @@ private function leaveFolder($data): string } /** - * @param array $data - * @param int|null $folderId + * @param array $data * * @return DocumentInterface|array + * * @throws \Exception * @throws EntityAlreadyExistsException */ @@ -990,9 +947,9 @@ private function embedDocument($data, ?int $folderId = null) $handlers = $this->documentPlatforms; if ( - isset($data['embedId']) && - isset($data['embedPlatform']) && - in_array($data['embedPlatform'], array_keys($handlers)) + isset($data['embedId']) + && isset($data['embedPlatform']) + && in_array($data['embedPlatform'], array_keys($handlers)) ) { $class = $handlers[$data['embedPlatform']]; @@ -1009,18 +966,16 @@ private function embedDocument($data, ?int $folderId = null) $finder->setKey($this->soundcloudClientId); } $finder->setEmbedId($data['embedId']); + return $this->createDocumentFromFinder($finder, $folderId); } else { - throw new \RuntimeException("bad.request", 1); + throw new \RuntimeException('bad.request', 1); } } /** * Download a random document. * - * @param int|null $folderId - * - * @return DocumentInterface|null * @throws FilesystemException */ private function randomDocument(?int $folderId = null): ?DocumentInterface @@ -1033,15 +988,15 @@ private function randomDocument(?int $folderId = null): ?DocumentInterface if (is_array($document) && isset($document[0])) { return $document[0]; } + return null; } - throw new \RuntimeException('Random image finder must be instance of ' . AbstractEmbedFinder::class); + throw new \RuntimeException('Random image finder must be instance of '.AbstractEmbedFinder::class); } /** - * @param AbstractEmbedFinder $finder - * @param int|null $folderId * @return DocumentInterface|array + * * @throws FilesystemException */ private function createDocumentFromFinder(AbstractEmbedFinder $finder, ?int $folderId = null): DocumentInterface|array @@ -1071,9 +1026,6 @@ private function createDocumentFromFinder(AbstractEmbedFinder $finder, ?int $fol /** * Handle upload form data to create a Document. * - * @param FormInterface $data - * @param int|null $folderId - * @return DocumentInterface|null * @throws FilesystemException */ private function uploadDocument(FormInterface $data, ?int $folderId = null): ?DocumentInterface @@ -1092,6 +1044,7 @@ private function uploadDocument(FormInterface $data, ?int $folderId = null): ?Do if (null !== $document = $this->documentFactory->getDocument()) { $this->em()->flush(); + return $document; } } @@ -1101,9 +1054,10 @@ private function uploadDocument(FormInterface $data, ?int $folderId = null): ?Do private function getListingTemplate(Request $request): string { - if ($request->query->get('list') === '1') { + if ('1' === $request->query->get('list')) { return '@RoadizRozier/documents/list-table.html.twig'; } + return '@RoadizRozier/documents/list.html.twig'; } } diff --git a/lib/Rozier/src/Controllers/FoldersController.php b/lib/Rozier/src/Controllers/FoldersController.php index c3e866b5..0451e41f 100644 --- a/lib/Rozier/src/Controllers/FoldersController.php +++ b/lib/Rozier/src/Controllers/FoldersController.php @@ -48,10 +48,6 @@ public function indexAction(Request $request): Response /** * Return a creation form for requested folder. * - * @param Request $request - * @param int|null $parentFolderId - * - * @return Response * @throws RuntimeError */ public function addAction(Request $request, ?int $parentFolderId = null): Response @@ -106,10 +102,6 @@ public function addAction(Request $request, ?int $parentFolderId = null): Respon /** * Return a deletion form for requested folder. * - * @param Request $request - * @param int $folderId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $folderId): Response @@ -158,10 +150,6 @@ public function deleteAction(Request $request, int $folderId): Response /** * Return an edition form for requested folder. * - * @param Request $request - * @param int $folderId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $folderId): Response @@ -171,7 +159,7 @@ public function editAction(Request $request, int $folderId): Response /** @var Folder|null $folder */ $folder = $this->em()->find(Folder::class, $folderId); - if ($folder === null) { + if (null === $folder) { throw new ResourceNotFoundException(); } @@ -212,11 +200,6 @@ public function editAction(Request $request, int $folderId): Response } /** - * @param Request $request - * @param int $folderId - * @param int $translationId - * - * @return Response * @throws RuntimeError */ public function editTranslationAction(Request $request, int $folderId, int $translationId): Response @@ -261,9 +244,9 @@ public function editTranslationAction(Request $request, int $folderId, int $tran $newFolderName = StringHandler::slugify($folderTranslation->getName()); if ($folder->getFolderName() !== $newFolderName) { if ( - !$folder->isLocked() && - $translation->isDefaultTranslation() && - !$this->folderNameExists($newFolderName) + !$folder->isLocked() + && $translation->isDefaultTranslation() + && !$this->folderNameExists($newFolderName) ) { $folder->setFolderName($folderTranslation->getName()); } @@ -300,23 +283,15 @@ public function editTranslationAction(Request $request, int $folderId, int $tran return $this->render('@RoadizRozier/folders/edit.html.twig', $this->assignation); } - /** - * @param string $name - * - * @return bool - */ protected function folderNameExists(string $name): bool { $entity = $this->em()->getRepository(Folder::class)->findOneByFolderName($name); - return (null !== $entity); + + return null !== $entity; } /** * Return a ZipArchive of requested folder. - * - * @param int $folderId - * - * @return Response */ public function downloadAction(int $folderId): Response { @@ -325,7 +300,7 @@ public function downloadAction(int $folderId): Response /** @var Folder|null $folder */ $folder = $this->em()->find(Folder::class, $folderId); - if ($folder === null) { + if (null === $folder) { throw new ResourceNotFoundException(); } @@ -337,7 +312,7 @@ public function downloadAction(int $folderId): Response return $this->documentArchiver->archiveAndServe( $documents, - $folder->getFolderName() . '_' . date('YmdHi'), + $folder->getFolderName().'_'.date('YmdHi'), true ); } diff --git a/lib/Rozier/src/Controllers/GroupsController.php b/lib/Rozier/src/Controllers/GroupsController.php index c4b9e949..0608e899 100644 --- a/lib/Rozier/src/Controllers/GroupsController.php +++ b/lib/Rozier/src/Controllers/GroupsController.php @@ -22,92 +22,59 @@ class GroupsController extends AbstractAdminController { - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof Group; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'group'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { return new Group(); } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizRozier/groups'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_GROUPS'; } - /** - * @inheritDoc - */ protected function getEntityClass(): string { return Group::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return GroupType::class; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'groupsHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'groupsEditPage'; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { if ($item instanceof Group) { return $item->getName(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } - /** - * @inheritDoc - */ protected function denyAccessUnlessItemGranted(PersistableInterface $item): void { $this->denyAccessUnlessGranted($item); @@ -116,9 +83,6 @@ protected function denyAccessUnlessItemGranted(PersistableInterface $item): void /** * Return an edition form for requested group. * - * @param Request $request - * @param int $id - * @return Response * @throws RuntimeError */ public function editRolesAction(Request $request, int $id): Response @@ -140,7 +104,7 @@ public function editRolesAction(Request $request, int $id): Response if ($form->isSubmitted() && $form->isValid()) { $role = $this->em()->find(Role::class, (int) $form->get('roleId')->getData()); - if ($role !== null) { + if (null !== $role) { $item->addRoleEntity($role); $this->em()->flush(); $msg = $this->getTranslator()->trans('role.%role%.linked_group.%group%', [ @@ -163,11 +127,6 @@ public function editRolesAction(Request $request, int $id): Response } /** - * @param Request $request - * @param int $id - * @param int $roleId - * - * @return Response * @throws RuntimeError */ public function removeRolesAction(Request $request, int $id, int $roleId): Response @@ -217,10 +176,6 @@ public function removeRolesAction(Request $request, int $id, int $roleId): Respo } /** - * @param Request $request - * @param int $id - * - * @return Response * @throws RuntimeError */ public function editUsersAction(Request $request, int $id): Response @@ -244,7 +199,7 @@ public function editUsersAction(Request $request, int $id): Response /** @var User|null $user */ $user = $this->em()->find(User::class, (int) $form->get('userId')->getData()); - if ($user !== null) { + if (null !== $user) { $user->addGroup($item); $this->em()->flush(); $msg = $this->getTranslator()->trans('user.%user%.linked.group.%group%', [ @@ -267,11 +222,6 @@ public function editUsersAction(Request $request, int $id): Response } /** - * @param Request $request - * @param int $id - * @param int $userId - * - * @return Response * @throws RuntimeError */ public function removeUsersAction(Request $request, int $id, int $userId): Response @@ -311,7 +261,7 @@ public function removeUsersAction(Request $request, int $id, int $userId): Respo return $this->redirectToRoute( 'groupsEditUsersPage', [ - 'id' => $item->getId() + 'id' => $item->getId(), ] ); } @@ -321,11 +271,6 @@ public function removeUsersAction(Request $request, int $id, int $userId): Respo return $this->render('@RoadizRozier/groups/removeUser.html.twig', $this->assignation); } - /** - * @param Group $group - * - * @return FormInterface - */ private function buildEditRolesForm(Group $group): FormInterface { $builder = $this->createFormBuilder() @@ -342,11 +287,6 @@ private function buildEditRolesForm(Group $group): FormInterface return $builder->getForm(); } - /** - * @param Group $group - * - * @return FormInterface - */ private function buildEditUsersForm(Group $group): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/GroupsUtilsController.php b/lib/Rozier/src/Controllers/GroupsUtilsController.php index 25e6be3e..8d15f5dc 100644 --- a/lib/Rozier/src/Controllers/GroupsUtilsController.php +++ b/lib/Rozier/src/Controllers/GroupsUtilsController.php @@ -22,16 +22,12 @@ class GroupsUtilsController extends RozierApp { public function __construct( private readonly SerializerInterface $serializer, - private readonly GroupsImporter $groupsImporter + private readonly GroupsImporter $groupsImporter, ) { } /** * Export all Group data and roles in a Json file (.json). - * - * @param Request $request - * - * @return Response */ public function exportAllAction(Request $request): Response { @@ -49,7 +45,7 @@ public function exportAllAction(Request $request): Response ), Response::HTTP_OK, [ - 'Content-Disposition' => sprintf('attachment; filename="%s"', 'group-all-' . date("YmdHis") . '.json'), + 'Content-Disposition' => sprintf('attachment; filename="%s"', 'group-all-'.date('YmdHis').'.json'), ], true ); @@ -57,11 +53,6 @@ public function exportAllAction(Request $request): Response /** * Export a Group in a Json file (.json). - * - * @param Request $request - * @param int $id - * - * @return Response */ public function exportAction(Request $request, int $id): Response { @@ -81,7 +72,7 @@ public function exportAction(Request $request, int $id): Response ), Response::HTTP_OK, [ - 'Content-Disposition' => sprintf('attachment; filename="%s"', 'group-' . $existingGroup->getName() . '-' . date("YmdHis") . '.json'), + 'Content-Disposition' => sprintf('attachment; filename="%s"', 'group-'.$existingGroup->getName().'-'.date('YmdHis').'.json'), ], true ); @@ -90,9 +81,6 @@ public function exportAction(Request $request, int $id): Response /** * Import a Json file (.rzt) containing Group datas and roles. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function importJsonFileAction(Request $request): Response @@ -104,9 +92,9 @@ public function importJsonFileAction(Request $request): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - !empty($form['group_file']) + $form->isSubmitted() + && $form->isValid() + && !empty($form['group_file']) ) { /** @var UploadedFile $file */ $file = $form['group_file']->getData(); @@ -140,9 +128,6 @@ public function importJsonFileAction(Request $request): Response return $this->render('@RoadizRozier/groups/import.html.twig', $this->assignation); } - /** - * @return FormInterface - */ private function buildImportJsonFileForm(): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/HistoryController.php b/lib/Rozier/src/Controllers/HistoryController.php index acc480ca..6e39db01 100644 --- a/lib/Rozier/src/Controllers/HistoryController.php +++ b/lib/Rozier/src/Controllers/HistoryController.php @@ -19,22 +19,19 @@ class HistoryController extends RozierApp { public static array $levelToHuman = [ - Logger::EMERGENCY => "emergency", - Logger::CRITICAL => "critical", - Logger::ALERT => "alert", - Logger::ERROR => "error", - Logger::WARNING => "warning", - Logger::NOTICE => "notice", - Logger::INFO => "info", - Logger::DEBUG => "debug", + Logger::EMERGENCY => 'emergency', + Logger::CRITICAL => 'critical', + Logger::ALERT => 'alert', + Logger::ERROR => 'error', + Logger::WARNING => 'warning', + Logger::NOTICE => 'notice', + Logger::INFO => 'info', + Logger::DEBUG => 'debug', ]; /** * List all logs action. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function indexAction(Request $request): Response @@ -63,10 +60,6 @@ public function indexAction(Request $request): Response /** * List user logs action. * - * @param Request $request - * @param int|string $userId - * - * @return Response * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException diff --git a/lib/Rozier/src/Controllers/LoginController.php b/lib/Rozier/src/Controllers/LoginController.php index 7dea01cb..0b9f906f 100644 --- a/lib/Rozier/src/Controllers/LoginController.php +++ b/lib/Rozier/src/Controllers/LoginController.php @@ -18,7 +18,7 @@ class LoginController extends RozierApp public function __construct( private readonly DocumentUrlGeneratorInterface $documentUrlGenerator, private readonly RandomImageFinder $randomImageFinder, - private readonly Settings $settingsBag + private readonly Settings $settingsBag, ) { } @@ -30,9 +30,9 @@ public function imageAction(Request $request): Response if (null !== $document = $this->settingsBag->getDocument('login_image')) { if ( - $document instanceof Document && - !$document->isPrivate() && - $document->isProcessable() + $document instanceof Document + && !$document->isPrivate() + && $document->isProcessable() ) { $this->documentUrlGenerator->setDocument($document); $this->documentUrlGenerator->setOptions([ @@ -41,8 +41,9 @@ public function imageAction(Request $request): Response 'quality' => 80, 'sharpen' => 5, ]); + return $response->setData([ - 'url' => $this->documentUrlGenerator->getUrl() + 'url' => $this->documentUrlGenerator->getUrl(), ]); } } @@ -53,8 +54,9 @@ public function imageAction(Request $request): Response if (null !== $feed) { $url = $feed['url'] ?? $feed['urls']['regular'] ?? $feed['urls']['full'] ?? $feed['urls']['raw'] ?? null; } + return $response->setData([ - 'url' => $url ?? '/themes/Rozier/static/assets/img/default_login.jpg' + 'url' => $url ?? '/themes/Rozier/static/assets/img/default_login.jpg', ]); } } diff --git a/lib/Rozier/src/Controllers/LoginResetController.php b/lib/Rozier/src/Controllers/LoginResetController.php index d3cd05e1..67de8312 100644 --- a/lib/Rozier/src/Controllers/LoginResetController.php +++ b/lib/Rozier/src/Controllers/LoginResetController.php @@ -16,10 +16,6 @@ class LoginResetController extends RozierApp use LoginResetTrait; /** - * @param Request $request - * @param string $token - * - * @return Response * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException */ diff --git a/lib/Rozier/src/Controllers/NodeTypeFieldsController.php b/lib/Rozier/src/Controllers/NodeTypeFieldsController.php index 4bdcd44b..1138dd2d 100644 --- a/lib/Rozier/src/Controllers/NodeTypeFieldsController.php +++ b/lib/Rozier/src/Controllers/NodeTypeFieldsController.php @@ -4,7 +4,6 @@ namespace Themes\Rozier\Controllers; -use Exception; use RZ\Roadiz\CoreBundle\Entity\NodeType; use RZ\Roadiz\CoreBundle\Entity\NodeTypeField; use RZ\Roadiz\CoreBundle\Message\UpdateNodeTypeSchemaMessage; @@ -23,15 +22,11 @@ class NodeTypeFieldsController extends RozierApp { public function __construct( private readonly bool $allowNodeTypeEdition, - private readonly MessageBusInterface $messageBus + private readonly MessageBusInterface $messageBus, ) { } /** - * @param Request $request - * @param int $nodeTypeId - * - * @return Response * @throws RuntimeError */ public function listAction(Request $request, int $nodeTypeId): Response @@ -41,7 +36,7 @@ public function listAction(Request $request, int $nodeTypeId): Response /** @var NodeType|null $nodeType */ $nodeType = $this->em()->find(NodeType::class, $nodeTypeId); - if ($nodeType === null) { + if (null === $nodeType) { throw new ResourceNotFoundException(); } @@ -54,10 +49,6 @@ public function listAction(Request $request, int $nodeTypeId): Response } /** - * @param Request $request - * @param int $nodeTypeFieldId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $nodeTypeFieldId): Response @@ -67,7 +58,7 @@ public function editAction(Request $request, int $nodeTypeFieldId): Response /** @var NodeTypeField|null $field */ $field = $this->em()->find(NodeTypeField::class, $nodeTypeFieldId); - if ($field === null) { + if (null === $field) { throw new ResourceNotFoundException(); } @@ -105,10 +96,6 @@ public function editAction(Request $request, int $nodeTypeFieldId): Response } /** - * @param Request $request - * @param int $nodeTypeId - * - * @return Response * @throws RuntimeError */ public function addAction(Request $request, int $nodeTypeId): Response @@ -119,7 +106,7 @@ public function addAction(Request $request, int $nodeTypeId): Response /** @var NodeType|null $nodeType */ $nodeType = $this->em()->find(NodeType::class, $nodeTypeId); - if ($nodeType === null) { + if (null === $nodeType) { throw new ResourceNotFoundException(); } @@ -134,7 +121,7 @@ public function addAction(Request $request, int $nodeTypeId): Response $this->assignation['field'] = $field; $form = $this->createForm(NodeTypeFieldType::class, $field, [ - 'disabled' => !$this->allowNodeTypeEdition + 'disabled' => !$this->allowNodeTypeEdition, ]); $form->handleRequest($request); @@ -161,7 +148,7 @@ public function addAction(Request $request, int $nodeTypeId): Response 'nodeTypeId' => $nodeTypeId, ] ); - } catch (Exception $e) { + } catch (\Exception $e) { $form->addError(new FormError($e->getMessage())); } } @@ -173,10 +160,6 @@ public function addAction(Request $request, int $nodeTypeId): Response } /** - * @param Request $request - * @param int $nodeTypeFieldId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $nodeTypeFieldId): Response @@ -186,7 +169,7 @@ public function deleteAction(Request $request, int $nodeTypeFieldId): Response /** @var NodeTypeField|null $field */ $field = $this->em()->find(NodeTypeField::class, $nodeTypeFieldId); - if ($field === null) { + if (null === $field) { throw new ResourceNotFoundException(); } diff --git a/lib/Rozier/src/Controllers/NodeTypes/NodeTypesController.php b/lib/Rozier/src/Controllers/NodeTypes/NodeTypesController.php index 58720914..1f5f68ef 100644 --- a/lib/Rozier/src/Controllers/NodeTypes/NodeTypesController.php +++ b/lib/Rozier/src/Controllers/NodeTypes/NodeTypesController.php @@ -23,7 +23,7 @@ class NodeTypesController extends RozierApp { public function __construct( private readonly bool $allowNodeTypeEdition, - private readonly MessageBusInterface $messageBus + private readonly MessageBusInterface $messageBus, ) { } @@ -55,9 +55,6 @@ public function indexAction(Request $request): Response } /** - * @param Request $request - * @param int $nodeTypeId - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $nodeTypeId): Response @@ -83,7 +80,7 @@ public function editAction(Request $request, int $nodeTypeId): Response $this->publishConfirmMessage($request, $msg, $nodeType); return $this->redirectToRoute('nodeTypesEditPage', [ - 'nodeTypeId' => $nodeTypeId + 'nodeTypeId' => $nodeTypeId, ]); } catch (EntityAlreadyExistsException $e) { $form->addError(new FormError($e->getMessage())); @@ -97,9 +94,6 @@ public function editAction(Request $request, int $nodeTypeId): Response } /** - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function addAction(Request $request): Response @@ -108,7 +102,7 @@ public function addAction(Request $request): Response $nodeType = new NodeType(); $form = $this->createForm(NodeTypeType::class, $nodeType, [ - 'disabled' => !$this->allowNodeTypeEdition + 'disabled' => !$this->allowNodeTypeEdition, ]); $form->handleRequest($request); @@ -126,7 +120,7 @@ public function addAction(Request $request): Response $this->publishConfirmMessage($request, $msg, $nodeType); return $this->redirectToRoute('nodeTypesEditPage', [ - 'nodeTypeId' => $nodeType->getId() + 'nodeTypeId' => $nodeType->getId(), ]); } catch (EntityAlreadyExistsException $e) { $form->addError(new FormError($e->getMessage())); @@ -141,10 +135,6 @@ public function addAction(Request $request): Response } /** - * @param Request $request - * @param int $nodeTypeId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $nodeTypeId): Response diff --git a/lib/Rozier/src/Controllers/NodeTypes/NodeTypesUtilsController.php b/lib/Rozier/src/Controllers/NodeTypes/NodeTypesUtilsController.php index 059a6b13..91d2689c 100644 --- a/lib/Rozier/src/Controllers/NodeTypes/NodeTypesUtilsController.php +++ b/lib/Rozier/src/Controllers/NodeTypes/NodeTypesUtilsController.php @@ -33,17 +33,12 @@ public function __construct( private readonly SerializerInterface $serializer, private readonly NodeTypes $nodeTypesBag, private readonly NodeTypesImporter $nodeTypesImporter, - private readonly MessageBusInterface $messageBus + private readonly MessageBusInterface $messageBus, ) { } /** * Export a Json file containing NodeType data and fields. - * - * @param Request $request - * @param int $nodeTypeId - * - * @return JsonResponse */ public function exportJsonFileAction(Request $request, int $nodeTypeId): JsonResponse { @@ -64,15 +59,13 @@ public function exportJsonFileAction(Request $request, int $nodeTypeId): JsonRes ), Response::HTTP_OK, [ - 'Content-Disposition' => sprintf('attachment; filename="%s"', $nodeType->getName() . '.json'), + 'Content-Disposition' => sprintf('attachment; filename="%s"', $nodeType->getName().'.json'), ], true ); } /** - * @param Request $request - * @return BinaryFileResponse * @throws RuntimeError */ public function exportDocumentationAction(Request $request): BinaryFileResponse @@ -81,14 +74,14 @@ public function exportDocumentationAction(Request $request): BinaryFileResponse $documentationGenerator = new DocumentationGenerator($this->nodeTypesBag, $this->getTranslator()); - $tmpfname = tempnam(sys_get_temp_dir(), date('Y-m-d-H-i-s') . '.zip'); + $tmpfname = tempnam(sys_get_temp_dir(), date('Y-m-d-H-i-s').'.zip'); if (false === $tmpfname) { throw new RuntimeError('Unable to create temporary file.'); } unlink($tmpfname); // Deprecated: ZipArchive::open(): Using empty file as ZipArchive is deprecated - $zipArchive = new ZipArchive(); - $zipArchive->open($tmpfname, ZipArchive::CREATE); + $zipArchive = new \ZipArchive(); + $zipArchive->open($tmpfname, \ZipArchive::CREATE); $zipArchive->addFromString( '_sidebar.md', @@ -113,18 +106,13 @@ public function exportDocumentationAction(Request $request): BinaryFileResponse $response = new BinaryFileResponse($tmpfname); $response->setContentDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT, - 'documentation-' . date('Y-m-d-H-i-s') . '.zip' + 'documentation-'.date('Y-m-d-H-i-s').'.zip' ); $response->deleteFileAfterSend(true); return $response; } - /** - * @param Request $request - * - * @return Response - */ public function exportTypeScriptDeclarationAction(Request $request): Response { $this->denyAccessUnlessGranted('ROLE_ACCESS_NODETYPES'); @@ -133,12 +121,13 @@ public function exportTypeScriptDeclarationAction(Request $request): Response new DeclarationGeneratorFactory($this->nodeTypesBag) ); - $fileName = 'roadiz-app-' . date('Ymd-His') . '.d.ts'; + $fileName = 'roadiz-app-'.date('Ymd-His').'.d.ts'; $response = new Response($documentationGenerator->getContents(), Response::HTTP_OK, [ 'Content-type' => 'application/x-typescript', - 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Disposition' => 'attachment; filename="'.$fileName.'"', ]); $response->prepare($request); + return $response; } @@ -150,18 +139,18 @@ public function exportAllAction(Request $request): BinaryFileResponse ->getRepository(NodeType::class) ->findAll(); - $zipArchive = new ZipArchive(); - $tmpfname = tempnam(sys_get_temp_dir(), date('Y-m-d-H-i-s') . '.zip'); + $zipArchive = new \ZipArchive(); + $tmpfname = tempnam(sys_get_temp_dir(), date('Y-m-d-H-i-s').'.zip'); if (false === $tmpfname) { throw new RuntimeError('Unable to create temporary file.'); } unlink($tmpfname); // Deprecated: ZipArchive::open(): Using empty file as ZipArchive is deprecated - $zipArchive->open($tmpfname, ZipArchive::CREATE); + $zipArchive->open($tmpfname, \ZipArchive::CREATE); /** @var NodeType $nodeType */ foreach ($nodeTypes as $nodeType) { $zipArchive->addFromString( - $nodeType->getName() . '.json', + $nodeType->getName().'.json', $this->serializer->serialize( $nodeType, 'json', @@ -174,7 +163,7 @@ public function exportAllAction(Request $request): BinaryFileResponse $response = new BinaryFileResponse($tmpfname); $response->setContentDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT, - 'nodetypes-' . date('Y-m-d-H-i-s') . '.zip' + 'nodetypes-'.date('Y-m-d-H-i-s').'.zip' ); $response->deleteFileAfterSend(true); @@ -184,9 +173,6 @@ public function exportAllAction(Request $request): BinaryFileResponse /** * Import a Json file (.json) containing NodeType datas and fields. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function importJsonFileAction(Request $request): Response @@ -198,9 +184,9 @@ public function importJsonFileAction(Request $request): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - !empty($form['node_type_file']) + $form->isSubmitted() + && $form->isValid() + && !empty($form['node_type_file']) ) { $file = $form['node_type_file']->getData(); @@ -232,9 +218,6 @@ public function importJsonFileAction(Request $request): Response return $this->render('@RoadizRozier/node-types/import.html.twig', $this->assignation); } - /** - * @return FormInterface - */ private function buildImportJsonFileForm(): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/Nodes/ExportController.php b/lib/Rozier/src/Controllers/Nodes/ExportController.php index 3b1f02ef..4f4e5c02 100644 --- a/lib/Rozier/src/Controllers/Nodes/ExportController.php +++ b/lib/Rozier/src/Controllers/Nodes/ExportController.php @@ -19,17 +19,12 @@ class ExportController extends RozierApp { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly SerializerInterface $serializer + private readonly SerializerInterface $serializer, ) { } /** * Export all Node in a CSV file. - * - * @param int $translationId - * @param int|null $parentNodeId - * - * @return Response */ public function exportAllAction(int $translationId, ?int $parentNodeId = null): Response { @@ -42,9 +37,9 @@ public function exportAllAction(int $translationId, ?int $parentNodeId = null): ->getRepository(Translation::class) ->findDefault(); } - $criteria = ["translation" => $translation]; + $criteria = ['translation' => $translation]; $order = ['node.nodeType' => 'ASC']; - $filename = 'nodes-' . date("YmdHis") . '.' . $translation->getLocale() . '.csv'; + $filename = 'nodes-'.date('YmdHis').'.'.$translation->getLocale().'.csv'; if (null !== $parentNodeId) { /** @var Node|null $parentNode */ @@ -56,7 +51,7 @@ public function exportAllAction(int $translationId, ?int $parentNodeId = null): } $this->denyAccessUnlessGranted(NodeVoter::READ, $parentNode); $criteria['node.parent'] = $parentNode; - $filename = $parentNode->getNodeName() . '-' . date("YmdHis") . '.' . $translation->getLocale() . '.csv'; + $filename = $parentNode->getNodeName().'-'.date('YmdHis').'.'.$translation->getLocale().'.csv'; } else { $this->denyAccessUnlessGranted(NodeVoter::READ_AT_ROOT); } diff --git a/lib/Rozier/src/Controllers/Nodes/HistoryController.php b/lib/Rozier/src/Controllers/Nodes/HistoryController.php index 6915d67e..2c4ad7b4 100644 --- a/lib/Rozier/src/Controllers/Nodes/HistoryController.php +++ b/lib/Rozier/src/Controllers/Nodes/HistoryController.php @@ -20,9 +20,6 @@ class HistoryController extends RozierApp { /** - * @param Request $request - * @param int $nodeId - * @return Response * @throws RuntimeError */ public function historyAction(Request $request, int $nodeId): Response @@ -45,7 +42,7 @@ public function historyAction(Request $request, int $nodeId): Response $queryBuilder->expr()->like('obj.message', ':search'), $queryBuilder->expr()->like('obj.channel', ':search') )); - $queryBuilder->setParameter('search', '%' . $search . '%'); + $queryBuilder->setParameter('search', '%'.$search.'%'); }); $listManager->setDisplayingNotPublishedNodes(true); $listManager->setDisplayingAllNodesStatuses(true); diff --git a/lib/Rozier/src/Controllers/Nodes/NodesAttributesController.php b/lib/Rozier/src/Controllers/Nodes/NodesAttributesController.php index f1dfe96e..f500034e 100644 --- a/lib/Rozier/src/Controllers/Nodes/NodesAttributesController.php +++ b/lib/Rozier/src/Controllers/Nodes/NodesAttributesController.php @@ -29,16 +29,11 @@ class NodesAttributesController extends RozierApp { public function __construct( private readonly FormFactoryInterface $formFactory, - private readonly FormErrorSerializer $formErrorSerializer + private readonly FormErrorSerializer $formErrorSerializer, ) { } /** - * @param Request $request - * @param int $nodeId - * @param int $translationId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $nodeId, int $translationId): Response @@ -74,9 +69,9 @@ public function editAction(Request $request, int $nodeId, int $translationId): R } $isJson = - $request->isXmlHttpRequest() || - $request->getRequestFormat('html') === 'json' || - \in_array( + $request->isXmlHttpRequest() + || 'json' === $request->getRequestFormat('html') + || \in_array( 'application/json', $request->getAcceptableContentTypes() ); @@ -93,7 +88,7 @@ public function editAction(Request $request, int $nodeId, int $translationId): R ); /** @var AttributeValue $attributeValue */ foreach ($attributeValues as $attributeValue) { - $name = $node->getNodeName() . '_attribute_' . $attributeValue->getId(); + $name = $node->getNodeName().'_attribute_'.$attributeValue->getId(); $attributeValueTranslation = $attributeValue->getAttributeValueTranslation($translation); if (null === $attributeValueTranslation) { $attributeValueTranslation = new AttributeValueTranslation(); @@ -132,6 +127,7 @@ public function editAction(Request $request, int $nodeId, int $translationId): R 'message' => $msg, ], Response::HTTP_ACCEPTED); } + return $this->redirectToRoute('nodesEditAttributesPage', [ 'nodeId' => $node->getId(), 'translationId' => $translation->getId(), @@ -180,16 +176,10 @@ protected function isAttributable(Node $node): bool if ($nodeType instanceof NodeType) { return $nodeType->isAttributable(); } + return false; } - /** - * @param Request $request - * @param Node $node - * @param Translation $translation - * - * @return RedirectResponse|null - */ protected function handleAddAttributeForm(Request $request, Node $node, Translation $translation): ?RedirectResponse { if (!$this->isAttributable($node)) { @@ -232,19 +222,13 @@ protected function handleAddAttributeForm(Request $request, Node $node, Translat } /** - * @param Request $request - * @param int $nodeId - * @param int $translationId - * @param int $attributeValueId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $nodeId, int $translationId, int $attributeValueId): Response { /** @var AttributeValue|null $item */ $item = $this->em()->find(AttributeValue::class, $attributeValueId); - if ($item === null) { + if (null === $item) { throw $this->createNotFoundException('AttributeValue does not exist.'); } /** @var Translation|null $translation */ @@ -305,11 +289,6 @@ public function deleteAction(Request $request, int $nodeId, int $translationId, } /** - * @param Request $request - * @param int $nodeId - * @param int $translationId - * @param int $attributeValueId - * @return Response * @throws RuntimeError */ public function resetAction(Request $request, int $nodeId, int $translationId, int $attributeValueId): Response @@ -319,9 +298,9 @@ public function resetAction(Request $request, int $nodeId, int $translationId, i ->getRepository(AttributeValueTranslation::class) ->findOneBy([ 'attributeValue' => $attributeValueId, - 'translation' => $translationId + 'translation' => $translationId, ]); - if ($item === null) { + if (null === $item) { throw $this->createNotFoundException('AttributeValueTranslation does not exist.'); } /** @var Translation|null $translation */ diff --git a/lib/Rozier/src/Controllers/Nodes/NodesController.php b/lib/Rozier/src/Controllers/Nodes/NodesController.php index 482e097f..38b652fe 100644 --- a/lib/Rozier/src/Controllers/Nodes/NodesController.php +++ b/lib/Rozier/src/Controllers/Nodes/NodesController.php @@ -44,13 +44,6 @@ final class NodesController extends RozierApp use NodesTrait; /** - * @param NodeChrootResolver $nodeChrootResolver - * @param NodeMover $nodeMover - * @param Registry $workflowRegistry - * @param HandlerFactoryInterface $handlerFactory - * @param UniqueNodeGenerator $uniqueNodeGenerator - * @param NodeFactory $nodeFactory - * @param NodeOffspringResolverInterface $nodeOffspringResolver * @param class-string $nodeFormTypeClass * @param class-string $addNodeFormTypeClass */ @@ -63,7 +56,7 @@ public function __construct( private readonly NodeFactory $nodeFactory, private readonly NodeOffspringResolverInterface $nodeOffspringResolver, private readonly string $nodeFormTypeClass, - private readonly string $addNodeFormTypeClass + private readonly string $addNodeFormTypeClass, ) { } @@ -75,10 +68,6 @@ protected function getNodeFactory(): NodeFactory /** * List every node. * - * @param Request $request - * @param string|null $filter - * - * @return Response * @throws RuntimeError */ public function indexAction(Request $request, ?string $filter = null): Response @@ -121,7 +110,7 @@ public function indexAction(Request $request, ?string $filter = null): Response } if (null !== $user) { - $arrayFilter["chroot"] = $this->nodeChrootResolver->getChroot($user); + $arrayFilter['chroot'] = $this->nodeChrootResolver->getChroot($user); } /* @@ -159,11 +148,6 @@ public function indexAction(Request $request, ?string $filter = null): Response /** * Return an edition form for requested node. * - * @param Request $request - * @param int $nodeId - * @param int|null $translationId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $nodeId, ?int $translationId = null): Response @@ -194,6 +178,7 @@ public function editAction(Request $request, int $nodeId, ?int $translationId = ] ); $this->publishConfirmMessage($request, $msg, $node); + return $this->redirectToRoute( 'nodesEditPage', ['nodeId' => $node->getId()] @@ -235,6 +220,7 @@ public function editAction(Request $request, int $nodeId, ?int $translationId = '%name%' => $node->getNodeName(), ]); $this->publishConfirmMessage($request, $msg, $node->getNodeSources()->first() ?: $node); + return $this->redirectToRoute( 'nodesEditPage', ['nodeId' => $node->getId()] @@ -261,12 +247,6 @@ public function editAction(Request $request, int $nodeId, ?int $translationId = return $this->render('@RoadizRozier/nodes/edit.html.twig', $this->assignation); } - /** - * @param Request $request - * @param int $nodeId - * @param int $typeId - * @return Response - */ public function removeStackTypeAction(Request $request, int $nodeId, int $typeId): Response { /** @var Node|null $node */ @@ -300,11 +280,6 @@ public function removeStackTypeAction(Request $request, int $nodeId, int $typeId /** * Handle node creation pages. * - * @param Request $request - * @param int $nodeTypeId - * @param int|null $translationId - * - * @return Response * @throws RuntimeError * @throws ORMException * @throws OptimisticLockException @@ -315,17 +290,17 @@ public function addAction(Request $request, int $nodeTypeId, ?int $translationId /** @var NodeType|null $type */ $type = $this->em()->find(NodeType::class, $nodeTypeId); - if ($type === null) { + if (null === $type) { throw new ResourceNotFoundException(sprintf('Node-type #%s does not exist.', $nodeTypeId)); } /** @var Translation|null $translation */ $translation = $this->em()->getRepository(Translation::class)->findDefault(); - if ($translationId !== null) { + if (null !== $translationId) { $translation = $this->em()->find(Translation::class, $translationId); } - if ($translation === null) { + if (null === $translation) { throw new ResourceNotFoundException(sprintf('Translation #%s does not exist.', $translationId)); } @@ -363,7 +338,7 @@ public function addAction(Request $request, int $nodeTypeId, ?int $translationId 'nodesEditSourcePage', [ 'nodeId' => $node->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] ); } catch (EntityAlreadyExistsException $e) { @@ -384,11 +359,6 @@ public function addAction(Request $request, int $nodeTypeId, ?int $translationId /** * Handle node creation pages. * - * @param Request $request - * @param int|null $nodeId - * @param int|null $translationId - * - * @return Response * @throws ORMException * @throws OptimisticLockException * @throws RuntimeError @@ -453,7 +423,7 @@ public function addChildAction(Request $request, ?int $nodeId = null, ?int $tran 'nodesEditSourcePage', [ 'nodeId' => $node->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] ); } catch (EntityAlreadyExistsException $e) { @@ -474,10 +444,6 @@ public function addChildAction(Request $request, ?int $nodeId = null, ?int $tran /** * Return an deletion form for requested node. * - * @param Request $request - * @param int $nodeId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $nodeId): Response @@ -494,11 +460,12 @@ public function deleteAction(Request $request, int $nodeId): Response $workflow = $this->workflowRegistry->get($node); if (!$workflow->can($node, 'delete')) { $this->publishErrorMessage($request, sprintf('Node #%s cannot be deleted.', $nodeId), $node); + return $this->redirectToRoute( 'nodesEditSourcePage', [ 'nodeId' => $node->getId(), - 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId() + 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId(), ] ); } @@ -508,9 +475,9 @@ public function deleteAction(Request $request, int $nodeId): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - $form->getData()['nodeId'] == $node->getId() + $form->isSubmitted() + && $form->isValid() + && $form->getData()['nodeId'] == $node->getId() ) { /** @var Node|null $parent */ $parent = $node->getParent(); @@ -532,8 +499,8 @@ public function deleteAction(Request $request, int $nodeId): Response $referrer = $request->query->get('referer'); if ( - \is_string($referrer) && - (new UnicodeString($referrer))->trim()->startsWith('/') + \is_string($referrer) + && (new UnicodeString($referrer))->trim()->startsWith('/') ) { return $this->redirect($referrer); } @@ -542,22 +509,21 @@ public function deleteAction(Request $request, int $nodeId): Response 'nodesEditSourcePage', [ 'nodeId' => $parent->getId(), - 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId() + 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId(), ] ); } + return $this->redirectToRoute('nodesHomePage'); } $this->assignation['form'] = $form->createView(); + return $this->render('@RoadizRozier/nodes/delete.html.twig', $this->assignation); } /** * Empty trash action. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function emptyTrashAction(Request $request): Response @@ -571,8 +537,8 @@ public function emptyTrashAction(Request $request): Response $criteria = ['status' => Node::DELETED]; /** @var Node|null $chroot */ $chroot = $this->nodeChrootResolver->getChroot($this->getUser()); - if ($chroot !== null) { - $criteria["parent"] = $this->nodeOffspringResolver->getAllOffspringIds($chroot); + if (null !== $chroot) { + $criteria['parent'] = $this->nodeOffspringResolver->getAllOffspringIds($chroot); } $nodes = $this->em() @@ -606,10 +572,6 @@ public function emptyTrashAction(Request $request): Response /** * Return an deletion form for requested node. * - * @param Request $request - * @param int $nodeId - * - * @return Response * @throws RuntimeError */ public function undeleteAction(Request $request, int $nodeId): Response @@ -626,11 +588,12 @@ public function undeleteAction(Request $request, int $nodeId): Response $workflow = $this->workflowRegistry->get($node); if (!$workflow->can($node, 'undelete')) { $this->publishErrorMessage($request, sprintf('Node #%s cannot be undeleted.', $nodeId), $node); + return $this->redirectToRoute( 'nodesEditSourcePage', [ 'nodeId' => $node->getId(), - 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId() + 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId(), ] ); } @@ -652,6 +615,7 @@ public function undeleteAction(Request $request, int $nodeId): Response ['%name%' => $node->getNodeName()] ); $this->publishConfirmMessage($request, $msg, $node->getNodeSources()->first() ?: $node); + /* * Force redirect to avoid resending form when refreshing page */ @@ -665,10 +629,6 @@ public function undeleteAction(Request $request, int $nodeId): Response return $this->render('@RoadizRozier/nodes/undelete.html.twig', $this->assignation); } - /** - * @param Request $request - * @return RedirectResponse - */ public function generateAndAddNodeAction(Request $request): RedirectResponse { $this->denyAccessUnlessGranted('ROLE_ACCESS_NODES'); @@ -686,7 +646,7 @@ public function generateAndAddNodeAction(Request $request): RedirectResponse 'nodesEditSourcePage', [ 'nodeId' => $source->getNode()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] ); } catch (\Exception $e) { @@ -696,9 +656,6 @@ public function generateAndAddNodeAction(Request $request): RedirectResponse } /** - * @param Request $request - * @param int $nodeId - * @return Response * @throws RuntimeError */ public function publishAllAction(Request $request, int $nodeId): Response @@ -714,11 +671,12 @@ public function publishAllAction(Request $request, int $nodeId): Response $workflow = $this->workflowRegistry->get($node); if (!$workflow->can($node, 'publish')) { $this->publishErrorMessage($request, sprintf('Node #%s cannot be published.', $nodeId), $node); + return $this->redirectToRoute( 'nodesEditSourcePage', [ 'nodeId' => $node->getId(), - 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId() + 'translationId' => $this->em()->getRepository(Translation::class)->findDefault()->getId(), ] ); } diff --git a/lib/Rozier/src/Controllers/Nodes/NodesSourcesController.php b/lib/Rozier/src/Controllers/Nodes/NodesSourcesController.php index 980ed5f3..eed80d0f 100644 --- a/lib/Rozier/src/Controllers/Nodes/NodesSourcesController.php +++ b/lib/Rozier/src/Controllers/Nodes/NodesSourcesController.php @@ -36,18 +36,13 @@ class NodesSourcesController extends RozierApp public function __construct( private readonly JwtExtension $jwtExtension, - private readonly FormErrorSerializer $formErrorSerializer + private readonly FormErrorSerializer $formErrorSerializer, ) { } /** * Return an edition form for requested node. * - * @param Request $request - * @param int $nodeId - * @param int $translationId - * - * @return Response * @throws RuntimeError */ public function editSourceAction(Request $request, int $nodeId, int $translationId): Response @@ -86,7 +81,7 @@ public function editSourceAction(Request $request, int $nodeId, int $translation $node = $source->getNode(); - /** + /* * Versioning */ if ($this->isGranted('ROLE_ACCESS_VERSIONS')) { @@ -108,8 +103,8 @@ public function editSourceAction(Request $request, int $nodeId, int $translation ); $form->handleRequest($request); $isJsonRequest = - $request->isXmlHttpRequest() || - \in_array('application/json', $request->getAcceptableContentTypes()) + $request->isXmlHttpRequest() + || \in_array('application/json', $request->getAcceptableContentTypes()) ; if ($form->isSubmitted()) { @@ -126,31 +121,31 @@ public function editSourceAction(Request $request, int $nodeId, int $translation $previewUrl = $this->generateUrl($source, [ 'canonicalScheme' => $this->getSettingsBag()->get('custom_preview_scheme'), 'token' => $jwtToken, - NodeRouter::NO_CACHE_PARAMETER => true + NodeRouter::NO_CACHE_PARAMETER => true, ], UrlGeneratorInterface::ABSOLUTE_URL); } elseif ($this->getSettingsBag()->get('custom_public_scheme')) { $previewUrl = $this->generateUrl($source, [ 'canonicalScheme' => $this->getSettingsBag()->get('custom_public_scheme'), '_preview' => 1, 'token' => $jwtToken, - NodeRouter::NO_CACHE_PARAMETER => true + NodeRouter::NO_CACHE_PARAMETER => true, ], UrlGeneratorInterface::ABSOLUTE_URL); } else { $previewUrl = $this->generateUrl($source, [ '_preview' => 1, 'token' => $jwtToken, - NodeRouter::NO_CACHE_PARAMETER => true + NodeRouter::NO_CACHE_PARAMETER => true, ]); } if ($this->getSettingsBag()->get('custom_public_scheme')) { $publicUrl = $this->generateUrl($source, [ 'canonicalScheme' => $this->getSettingsBag()->get('custom_public_scheme'), - NodeRouter::NO_CACHE_PARAMETER => true + NodeRouter::NO_CACHE_PARAMETER => true, ], UrlGeneratorInterface::ABSOLUTE_URL); } else { $publicUrl = $this->generateUrl($source, [ - NodeRouter::NO_CACHE_PARAMETER => true + NodeRouter::NO_CACHE_PARAMETER => true, ]); } @@ -171,6 +166,7 @@ public function editSourceAction(Request $request, int $nodeId, int $translation */ if ($isJsonRequest) { $errors = $this->formErrorSerializer->getErrorsAsArray($form); + return new JsonResponse([ 'status' => 'fail', 'errors' => $errors, @@ -196,10 +192,6 @@ public function editSourceAction(Request $request, int $nodeId, int $translation /** * Return a remove form for requested nodeSource. * - * @param Request $request - * @param int $nodeSourceId - * - * @return Response * @throws RuntimeError */ public function removeAction(Request $request, int $nodeSourceId): Response @@ -262,11 +254,11 @@ public function removeAction(Request $request, int $nodeSourceId): Response return $this->redirectToRoute( 'nodesEditSourcePage', - ['nodeId' => $node->getId(), "translationId" => $ns->getTranslation()->getId()] + ['nodeId' => $node->getId(), 'translationId' => $ns->getTranslation()->getId()] ); } - $this->assignation["nodeSource"] = $ns; + $this->assignation['nodeSource'] = $ns; $this->assignation['form'] = $form->createView(); return $this->render('@RoadizRozier/nodes/deleteSource.html.twig', $this->assignation); @@ -301,11 +293,12 @@ protected function getPostUpdateRedirection(PersistableInterface $entity): ?Resp /** @var Translation $translation */ $translation = $entity->getTranslation(); + return $this->redirectToRoute( 'nodesEditSourcePage', [ 'nodeId' => $entity->getNode()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] ); } diff --git a/lib/Rozier/src/Controllers/Nodes/NodesTreesController.php b/lib/Rozier/src/Controllers/Nodes/NodesTreesController.php index 7604d5b6..6bd770a5 100644 --- a/lib/Rozier/src/Controllers/Nodes/NodesTreesController.php +++ b/lib/Rozier/src/Controllers/Nodes/NodesTreesController.php @@ -37,16 +37,11 @@ public function __construct( private readonly TreeWidgetFactory $treeWidgetFactory, private readonly FormFactoryInterface $formFactory, private readonly HandlerFactoryInterface $handlerFactory, - private readonly Registry $workflowRegistry + private readonly Registry $workflowRegistry, ) { } /** - * @param Request $request - * @param int|null $nodeId - * @param int|null $translationId - * - * @return Response * @throws RuntimeError */ public function treeAction(Request $request, ?int $nodeId = null, ?int $translationId = null): Response @@ -83,8 +78,8 @@ public function treeAction(Request $request, ?int $nodeId = null, ?int $translat $widget = $this->treeWidgetFactory->createNodeTree($node, $translation); if ( - $request->get('tagId') && - $request->get('tagId') > 0 + $request->get('tagId') + && $request->get('tagId') > 0 ) { $filterTag = $this->em()->find(Tag::class, (int) $request->get('tagId')); $this->assignation['filterTag'] = $filterTag; @@ -92,7 +87,7 @@ public function treeAction(Request $request, ?int $nodeId = null, ?int $translat } $widget->setStackTree(true); - $widget->getNodes(); //pre-fetch nodes for enable filters + $widget->getNodes(); // pre-fetch nodes for enable filters if (null !== $node) { $this->assignation['node'] = $node; @@ -159,8 +154,6 @@ public function treeAction(Request $request, ?int $nodeId = null, ?int $translat } /** - * @param Request $request - * @return Response * @throws RuntimeError */ public function bulkDeleteAction(Request $request): Response @@ -181,7 +174,7 @@ public function bulkDeleteAction(Request $request): Response 'id' => $nodesIds, ]); - if (count($nodes) === 0) { + if (0 === count($nodes)) { throw new ResourceNotFoundException(); } @@ -216,9 +209,6 @@ public function bulkDeleteAction(Request $request): Response } /** - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function bulkStatusAction(Request $request): Response @@ -239,7 +229,7 @@ public function bulkStatusAction(Request $request): Response 'id' => $nodesIds, ]); - if (count($nodes) === 0) { + if (0 === count($nodes)) { throw new ResourceNotFoundException(); } @@ -276,15 +266,9 @@ public function bulkStatusAction(Request $request): Response return $this->render('@RoadizRozier/nodes/bulkStatus.html.twig', $this->assignation); } - /** - * @param null|string $referer - * @param array $nodesIds - * - * @return FormInterface - */ private function buildBulkDeleteForm( ?string $referer = null, - array $nodesIds = [] + array $nodesIds = [], ): FormInterface { /** @var FormBuilder $builder */ $builder = $this->formFactory @@ -308,8 +292,6 @@ private function buildBulkDeleteForm( } /** - * @param array $data - * * @return string */ private function bulkDeleteNodes(array $data) @@ -364,6 +346,7 @@ private function bulkStatusNodes(array $data): string } } $this->em()->flush(); + return $this->getTranslator()->trans('nodes.bulk.status.changed'); } @@ -398,7 +381,7 @@ private function buildBulkTagForm(): FormInterface 'attr' => [ 'class' => 'uk-button uk-button-primary', 'title' => 'link.tags', - 'data-uk-tooltip' => "{animation:true}", + 'data-uk-tooltip' => '{animation:true}', ], ]) ->add('submitUntag', SubmitType::class, [ @@ -406,7 +389,7 @@ private function buildBulkTagForm(): FormInterface 'attr' => [ 'class' => 'uk-button', 'title' => 'unlink.tags', - 'data-uk-tooltip' => "{animation:true}", + 'data-uk-tooltip' => '{animation:true}', ], ]) ; @@ -415,7 +398,6 @@ private function buildBulkTagForm(): FormInterface } /** - * @param array $data * @return string */ private function tagNodes(array $data) @@ -423,8 +405,8 @@ private function tagNodes(array $data) $msg = $this->getTranslator()->trans('nodes.bulk.not_tagged'); if ( - !empty($data['tagsPaths']) && - !empty($data['nodesIds']) + !empty($data['tagsPaths']) + && !empty($data['nodesIds']) ) { $nodesIds = explode(',', $data['nodesIds']); $nodesIds = array_filter($nodesIds); @@ -458,7 +440,6 @@ private function tagNodes(array $data) } /** - * @param array $data * @return string */ private function untagNodes(array $data) @@ -466,8 +447,8 @@ private function untagNodes(array $data) $msg = $this->getTranslator()->trans('nodes.bulk.not_untagged'); if ( - !empty($data['tagsPaths']) && - !empty($data['nodesIds']) + !empty($data['tagsPaths']) + && !empty($data['nodesIds']) ) { $nodesIds = explode(',', $data['nodesIds']); $nodesIds = array_filter($nodesIds); @@ -502,17 +483,10 @@ private function untagNodes(array $data) return $msg; } - /** - * @param null|string $referer - * @param array $nodesIds - * @param string $status - * - * @return FormInterface - */ private function buildBulkStatusForm( ?string $referer = null, array $nodesIds = [], - string $status = 'reject' + string $status = 'reject', ): FormInterface { /** @var FormBuilder $builder */ $builder = $this->formFactory diff --git a/lib/Rozier/src/Controllers/Nodes/NodesUtilsController.php b/lib/Rozier/src/Controllers/Nodes/NodesUtilsController.php index cf73e9fc..227f534b 100644 --- a/lib/Rozier/src/Controllers/Nodes/NodesUtilsController.php +++ b/lib/Rozier/src/Controllers/Nodes/NodesUtilsController.php @@ -21,12 +21,7 @@ public function __construct(private readonly NodeNamePolicyInterface $nodeNamePo } /** - * Duplicate node by ID - * - * @param Request $request - * @param int $nodeId - * - * @return Response + * Duplicate node by ID. */ public function duplicateAction(Request $request, int $nodeId): Response { @@ -53,7 +48,7 @@ public function duplicateAction(Request $request, int $nodeId): Response $this->dispatchEvent(new NodeCreatedEvent($newNode)); $this->dispatchEvent(new NodeDuplicatedEvent($newNode)); - $msg = $this->getTranslator()->trans("duplicated.node.%name%", [ + $msg = $this->getTranslator()->trans('duplicated.node.%name%', [ '%name%' => $existingNode->getNodeName(), ]); @@ -61,12 +56,12 @@ public function duplicateAction(Request $request, int $nodeId): Response return $this->redirectToRoute( 'nodesEditPage', - ["nodeId" => $newNode->getId()] + ['nodeId' => $newNode->getId()] ); } catch (\Exception $e) { $this->publishErrorMessage( $request, - $this->getTranslator()->trans("impossible.duplicate.node.%name%", [ + $this->getTranslator()->trans('impossible.duplicate.node.%name%', [ '%name%' => $existingNode->getNodeName(), ]), $existingNode @@ -74,7 +69,7 @@ public function duplicateAction(Request $request, int $nodeId): Response return $this->redirectToRoute( 'nodesEditPage', - ["nodeId" => $existingNode->getId()] + ['nodeId' => $existingNode->getId()] ); } } diff --git a/lib/Rozier/src/Controllers/Nodes/TranstypeController.php b/lib/Rozier/src/Controllers/Nodes/TranstypeController.php index 7e3326ae..25264f51 100644 --- a/lib/Rozier/src/Controllers/Nodes/TranstypeController.php +++ b/lib/Rozier/src/Controllers/Nodes/TranstypeController.php @@ -24,10 +24,6 @@ public function __construct(private readonly NodeTranstyper $nodeTranstyper) } /** - * @param Request $request - * @param int $nodeId - * - * @return Response * @throws RuntimeError * @throws \Exception */ diff --git a/lib/Rozier/src/Controllers/RedirectionsController.php b/lib/Rozier/src/Controllers/RedirectionsController.php index b2819ef5..fbf2bcbd 100644 --- a/lib/Rozier/src/Controllers/RedirectionsController.php +++ b/lib/Rozier/src/Controllers/RedirectionsController.php @@ -15,92 +15,59 @@ class RedirectionsController extends AbstractAdminWithBulkController { - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof Redirection; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'redirection'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { return new Redirection(); } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizRozier/redirections'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_REDIRECTIONS'; } - /** - * @inheritDoc - */ protected function getEntityClass(): string { return Redirection::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return RedirectionType::class; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'redirectionsHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'redirectionsEditPage'; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { if ($item instanceof Redirection) { return (string) $item->getQuery(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } - /** - * @inheritDoc - */ protected function getDefaultOrder(Request $request): array { return ['query' => 'ASC']; @@ -109,24 +76,27 @@ protected function getDefaultOrder(Request $request): array protected function createPostCreateEvent(PersistableInterface $item): RedirectionEvent { if (!($item instanceof Redirection)) { - throw new \InvalidArgumentException('Item should be instance of ' . Redirection::class); + throw new \InvalidArgumentException('Item should be instance of '.Redirection::class); } + return new PostCreatedRedirectionEvent($item); } protected function createPostUpdateEvent(PersistableInterface $item): RedirectionEvent { if (!($item instanceof Redirection)) { - throw new \InvalidArgumentException('Item should be instance of ' . Redirection::class); + throw new \InvalidArgumentException('Item should be instance of '.Redirection::class); } + return new PostUpdatedRedirectionEvent($item); } protected function createDeleteEvent(PersistableInterface $item): RedirectionEvent { if (!($item instanceof Redirection)) { - throw new \InvalidArgumentException('Item should be instance of ' . Redirection::class); + throw new \InvalidArgumentException('Item should be instance of '.Redirection::class); } + return new PostDeletedRedirectionEvent($item); } diff --git a/lib/Rozier/src/Controllers/RolesController.php b/lib/Rozier/src/Controllers/RolesController.php index 06a6c78e..f0cb580c 100644 --- a/lib/Rozier/src/Controllers/RolesController.php +++ b/lib/Rozier/src/Controllers/RolesController.php @@ -15,100 +15,64 @@ class RolesController extends AbstractAdminController { - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof Role; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'role'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { return new Role('ROLE_EXAMPLE'); } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizRozier/roles'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_ROLES'; } - /** - * @inheritDoc - */ protected function getEntityClass(): string { return Role::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return RoleType::class; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'rolesHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'rolesEditPage'; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { if ($item instanceof Role) { return $item->getRole(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } - /** - * @inheritDoc - */ protected function getDefaultOrder(Request $request): array { return ['name' => 'ASC']; } - /** - * @inheritDoc - */ protected function denyAccessUnlessItemGranted(PersistableInterface $item): void { if ($item instanceof Role) { @@ -116,36 +80,30 @@ protected function denyAccessUnlessItemGranted(PersistableInterface $item): void } } - /** - * @inheritDoc - */ protected function createCreateEvent(PersistableInterface $item): ?Event { if ($item instanceof Role) { return new PreCreatedRoleEvent($item); } + return null; } - /** - * @inheritDoc - */ protected function createUpdateEvent(PersistableInterface $item): ?Event { if ($item instanceof Role) { return new PreUpdatedRoleEvent($item); } + return null; } - /** - * @inheritDoc - */ protected function createDeleteEvent(PersistableInterface $item): ?Event { if ($item instanceof Role) { return new PreDeletedRoleEvent($item); } + return null; } } diff --git a/lib/Rozier/src/Controllers/RolesUtilsController.php b/lib/Rozier/src/Controllers/RolesUtilsController.php index 4cc08dc7..9b4aa6aa 100644 --- a/lib/Rozier/src/Controllers/RolesUtilsController.php +++ b/lib/Rozier/src/Controllers/RolesUtilsController.php @@ -7,8 +7,8 @@ use Doctrine\Common\Cache\CacheProvider; use JMS\Serializer\SerializationContext; use JMS\Serializer\SerializerInterface; -use RZ\Roadiz\CoreBundle\Importer\RolesImporter; use RZ\Roadiz\CoreBundle\Entity\Role; +use RZ\Roadiz\CoreBundle\Importer\RolesImporter; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; @@ -22,17 +22,12 @@ class RolesUtilsController extends RozierApp { public function __construct( private readonly SerializerInterface $serializer, - private readonly RolesImporter $rolesImporter + private readonly RolesImporter $rolesImporter, ) { } /** - * Export a Role in a Json file - * - * @param Request $request - * @param int $id - * - * @return Response + * Export a Role in a Json file. */ public function exportAction(Request $request, int $id): Response { @@ -53,7 +48,7 @@ public function exportAction(Request $request, int $id): Response ), Response::HTTP_OK, [ - 'Content-Disposition' => sprintf('attachment; filename="%s"', 'role-' . $existingRole->getName() . '-' . date("YmdHis") . '.json'), + 'Content-Disposition' => sprintf('attachment; filename="%s"', 'role-'.$existingRole->getName().'-'.date('YmdHis').'.json'), ], true ); @@ -62,9 +57,6 @@ public function exportAction(Request $request, int $id): Response /** * Import a Json file containing Roles. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function importJsonFileAction(Request $request): Response @@ -75,9 +67,9 @@ public function importJsonFileAction(Request $request): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - !empty($form['role_file']) + $form->isSubmitted() + && $form->isValid() + && !empty($form['role_file']) ) { $file = $form['role_file']->getData(); @@ -117,9 +109,6 @@ public function importJsonFileAction(Request $request): Response return $this->render('@RoadizRozier/roles/import.html.twig', $this->assignation); } - /** - * @return FormInterface - */ private function buildImportJsonFileForm(): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/SearchController.php b/lib/Rozier/src/Controllers/SearchController.php index 34529eb9..943acdad 100644 --- a/lib/Rozier/src/Controllers/SearchController.php +++ b/lib/Rozier/src/Controllers/SearchController.php @@ -4,7 +4,6 @@ namespace Themes\Rozier\Controllers; -use DateTime; use Doctrine\Persistence\ManagerRegistry; use RZ\Roadiz\Core\AbstractEntities\AbstractField; use RZ\Roadiz\CoreBundle\Entity\Node; @@ -48,159 +47,135 @@ class SearchController extends RozierApp public function __construct( protected readonly ManagerRegistry $managerRegistry, protected readonly FormFactoryInterface $formFactory, - protected readonly SerializerInterface $serializer + protected readonly SerializerInterface $serializer, ) { } - /** - * @param mixed $var - * @return bool - */ public function isBlank(mixed $var): bool { return empty($var) && !is_numeric($var); } - /** - * @param mixed $var - * @return bool - */ public function notBlank(mixed $var): bool { return !$this->isBlank($var); } - /** - * @param array $data - * @param string $fieldName - * - * @return array - */ protected function appendDateTimeCriteria(array &$data, string $fieldName): array { $date = $data[$fieldName]['compareDatetime']; - if ($date instanceof DateTime) { + if ($date instanceof \DateTime) { $date = $date->format('Y-m-d H:i:s'); } $data[$fieldName] = [ $data[$fieldName]['compareOp'], $date, ]; + return $data; } - /** - * @param array $data - * @param string $prefix - * @return array - */ - protected function processCriteria(array $data, string $prefix = ""): array + protected function processCriteria(array $data, string $prefix = ''): array { - if (!empty($data[$prefix . "nodeName"])) { - if (!isset($data[$prefix . "nodeName_exact"]) || $data[$prefix . "nodeName_exact"] !== true) { - $data[$prefix . "nodeName"] = ["LIKE", "%" . $data[$prefix . "nodeName"] . "%"]; + if (!empty($data[$prefix.'nodeName'])) { + if (!isset($data[$prefix.'nodeName_exact']) || true !== $data[$prefix.'nodeName_exact']) { + $data[$prefix.'nodeName'] = ['LIKE', '%'.$data[$prefix.'nodeName'].'%']; } } - if (key_exists($prefix . "nodeName_exact", $data)) { - unset($data[$prefix . "nodeName_exact"]); + if (key_exists($prefix.'nodeName_exact', $data)) { + unset($data[$prefix.'nodeName_exact']); } - if (isset($data[$prefix . 'parent']) && !$this->isBlank($data[$prefix . "parent"])) { - if ($data[$prefix . "parent"] == "null" || $data[$prefix . "parent"] == 0) { - $data[$prefix . "parent"] = null; + if (isset($data[$prefix.'parent']) && !$this->isBlank($data[$prefix.'parent'])) { + if ('null' == $data[$prefix.'parent'] || 0 == $data[$prefix.'parent']) { + $data[$prefix.'parent'] = null; } } - if (isset($data[$prefix . 'visible'])) { - $data[$prefix . 'visible'] = (bool) $data[$prefix . 'visible']; + if (isset($data[$prefix.'visible'])) { + $data[$prefix.'visible'] = (bool) $data[$prefix.'visible']; } - if (isset($data[$prefix . 'createdAt'])) { - $this->appendDateTimeCriteria($data, $prefix . 'createdAt'); + if (isset($data[$prefix.'createdAt'])) { + $this->appendDateTimeCriteria($data, $prefix.'createdAt'); } - if (isset($data[$prefix . 'updatedAt'])) { - $this->appendDateTimeCriteria($data, $prefix . 'updatedAt'); + if (isset($data[$prefix.'updatedAt'])) { + $this->appendDateTimeCriteria($data, $prefix.'updatedAt'); } - if (isset($data[$prefix . "limitResult"])) { + if (isset($data[$prefix.'limitResult'])) { $this->pagination = false; - $this->itemPerPage = (int) $data[$prefix . "limitResult"]; - unset($data[$prefix . "limitResult"]); + $this->itemPerPage = (int) $data[$prefix.'limitResult']; + unset($data[$prefix.'limitResult']); } /* * no need to prefix tags */ - if (isset($data["tags"])) { - $data["tags"] = array_map('trim', explode(',', $data["tags"])); - foreach ($data["tags"] as $key => $value) { - $data["tags"][$key] = $this->managerRegistry->getRepository(Tag::class)->findByPath($value); + if (isset($data['tags'])) { + $data['tags'] = array_map('trim', explode(',', $data['tags'])); + foreach ($data['tags'] as $key => $value) { + $data['tags'][$key] = $this->managerRegistry->getRepository(Tag::class)->findByPath($value); } - array_filter($data["tags"]); + array_filter($data['tags']); } return $data; } - /** - * @param array $data - * @param NodeType $nodetype - * @return array - */ protected function processCriteriaNodetype(array $data, NodeType $nodetype): array { $fields = $nodetype->getFields(); foreach ($data as $key => $value) { - if ($key === 'title') { - $data['title'] = ["LIKE", "%" . $value . "%"]; - if (isset($data[$key . '_exact'])) { - if ($data[$key . '_exact'] === true) { + if ('title' === $key) { + $data['title'] = ['LIKE', '%'.$value.'%']; + if (isset($data[$key.'_exact'])) { + if (true === $data[$key.'_exact']) { $data['title'] = $value; } } - } elseif ($key === 'publishedAt') { + } elseif ('publishedAt' === $key) { $this->appendDateTimeCriteria($data, 'publishedAt'); } else { /** @var NodeTypeField $field */ foreach ($fields as $field) { if ($key == $field->getName()) { if ( - $field->getType() === AbstractField::MARKDOWN_T - || $field->getType() === AbstractField::STRING_T - || $field->getType() === AbstractField::YAML_T - || $field->getType() === AbstractField::JSON_T - || $field->getType() === AbstractField::TEXT_T - || $field->getType() === AbstractField::EMAIL_T - || $field->getType() === AbstractField::CSS_T + AbstractField::MARKDOWN_T === $field->getType() + || AbstractField::STRING_T === $field->getType() + || AbstractField::YAML_T === $field->getType() + || AbstractField::JSON_T === $field->getType() + || AbstractField::TEXT_T === $field->getType() + || AbstractField::EMAIL_T === $field->getType() + || AbstractField::CSS_T === $field->getType() ) { - $data[$field->getVarName()] = ["LIKE", "%" . $value . "%"]; - if (isset($data[$key . '_exact']) && $data[$key . '_exact'] === true) { + $data[$field->getVarName()] = ['LIKE', '%'.$value.'%']; + if (isset($data[$key.'_exact']) && true === $data[$key.'_exact']) { $data[$field->getVarName()] = $value; } - } elseif ($field->getType() === AbstractField::BOOLEAN_T) { + } elseif (AbstractField::BOOLEAN_T === $field->getType()) { $data[$field->getVarName()] = (bool) $value; - } elseif ($field->getType() === AbstractField::MULTIPLE_T) { - $data[$field->getVarName()] = implode(",", $value); - } elseif ($field->getType() === AbstractField::DATETIME_T) { + } elseif (AbstractField::MULTIPLE_T === $field->getType()) { + $data[$field->getVarName()] = implode(',', $value); + } elseif (AbstractField::DATETIME_T === $field->getType()) { $this->appendDateTimeCriteria($data, $key); - } elseif ($field->getType() === AbstractField::DATE_T) { + } elseif (AbstractField::DATE_T === $field->getType()) { $this->appendDateTimeCriteria($data, $key); } } } } - if (key_exists($key . '_exact', $data)) { - unset($data[$key . '_exact']); + if (key_exists($key.'_exact', $data)) { + unset($data[$key.'_exact']); } } + return $data; } /** - * @param Request $request - * @return Response * @throws RuntimeError */ public function searchNodeAction(Request $request): Response @@ -217,6 +192,7 @@ public function searchNodeAction(Request $request): Response if (null !== $response = $this->handleNodeTypeForm($nodeTypeForm)) { $response->prepare($request); + return $response->send(); } @@ -224,8 +200,8 @@ public function searchNodeAction(Request $request): Response $data = []; foreach ($form->getData() as $key => $value) { if ( - (!is_array($value) && $this->notBlank($value)) || - (is_array($value) && isset($value["compareDatetime"])) + (!is_array($value) && $this->notBlank($value)) + || (is_array($value) && isset($value['compareDatetime'])) ) { $data[$key] = $value; } @@ -238,7 +214,7 @@ public function searchNodeAction(Request $request): Response $listManager->setDisplayingNotPublishedNodes(true); $listManager->setDisplayingAllNodesStatuses(true); - if ($this->pagination === false) { + if (false === $this->pagination) { $listManager->setItemPerPage($this->itemPerPage ?? 999); $listManager->disablePagination(); } @@ -256,10 +232,6 @@ public function searchNodeAction(Request $request): Response } /** - * @param Request $request - * @param int $nodetypeId - * - * @return Response * @throws RuntimeError */ public function searchNodeSourceAction(Request $request, int $nodetypeId): Response @@ -267,7 +239,7 @@ public function searchNodeSourceAction(Request $request, int $nodetypeId): Respo /** @var NodeType|null $nodetype */ $nodetype = $this->managerRegistry->getRepository(NodeType::class)->find($nodetypeId); - $builder = $this->buildSimpleForm("__node__"); + $builder = $this->buildSimpleForm('__node__'); $this->extendForm($builder, $nodetype); $this->addButtons($builder, true); @@ -295,19 +267,16 @@ public function searchNodeSourceAction(Request $request, int $nodetypeId): Respo /** * Build node-type selection form. - * - * @param int|null $nodetypeId - * @return FormBuilderInterface */ protected function buildNodeTypeForm(?int $nodetypeId = null): FormBuilderInterface { - $builderNodeType = $this->formFactory->createNamedBuilder('nodeTypeForm', FormType::class, [], ["method" => "get"]); + $builderNodeType = $this->formFactory->createNamedBuilder('nodeTypeForm', FormType::class, [], ['method' => 'get']); $builderNodeType->add( - "nodetype", + 'nodetype', NodeTypesType::class, [ 'label' => 'nodeType', - 'placeholder' => "ignore", + 'placeholder' => 'ignore', 'required' => false, 'data' => $nodetypeId, 'showInvisible' => true, @@ -317,12 +286,6 @@ protected function buildNodeTypeForm(?int $nodetypeId = null): FormBuilderInterf return $builderNodeType; } - /** - * @param FormBuilderInterface $builder - * @param bool $export - * - * @return FormBuilderInterface - */ protected function addButtons(FormBuilderInterface $builder, bool $export = false): FormBuilderInterface { $builder->add('search', SubmitType::class, [ @@ -344,11 +307,6 @@ protected function addButtons(FormBuilderInterface $builder, bool $export = fals return $builder; } - /** - * @param FormInterface $nodeTypeForm - * - * @return null|RedirectResponse - */ protected function handleNodeTypeForm(FormInterface $nodeTypeForm): ?RedirectResponse { if ($nodeTypeForm->isSubmitted() && $nodeTypeForm->isValid()) { @@ -358,7 +316,7 @@ protected function handleNodeTypeForm(FormInterface $nodeTypeForm): ?RedirectRes return $this->redirectToRoute( 'searchNodeSourcePage', [ - "nodetypeId" => $nodeTypeForm->getData()['nodetype'], + 'nodetypeId' => $nodeTypeForm->getData()['nodetype'], ] ); } @@ -367,12 +325,6 @@ protected function handleNodeTypeForm(FormInterface $nodeTypeForm): ?RedirectRes return null; } - /** - * @param FormInterface $form - * @param NodeType $nodetype - * - * @return null|Response - */ protected function handleNodeForm(FormInterface $form, NodeType $nodetype): ?Response { if (!$form->isSubmitted() || !$form->isValid()) { @@ -382,20 +334,20 @@ protected function handleNodeForm(FormInterface $form, NodeType $nodetype): ?Res foreach ($form->getData() as $key => $value) { if ( (!is_array($value) && $this->notBlank($value)) - || (is_array($value) && isset($value["compareDatetime"])) - || (is_array($value) && isset($value["compareDate"])) - || (is_array($value) && $value != [] && !isset($value["compareOp"])) + || (is_array($value) && isset($value['compareDatetime'])) + || (is_array($value) && isset($value['compareDate'])) + || (is_array($value) && [] != $value && !isset($value['compareOp'])) ) { - if (\is_string($key) & \str_contains($key, "__node__")) { + if (\is_string($key) & \str_contains($key, '__node__')) { /** @var string $newKey */ - $newKey = \str_replace("__node__", "node.", $key); + $newKey = \str_replace('__node__', 'node.', $key); $data[$newKey] = $value; } else { $data[$key] = $value; } } } - $data = $this->processCriteria($data, "node."); + $data = $this->processCriteria($data, 'node.'); $data = $this->processCriteriaNodetype($data, $nodetype); $listManager = $this->createEntityListManager( @@ -404,7 +356,7 @@ protected function handleNodeForm(FormInterface $form, NodeType $nodetype): ?Res ); $listManager->setDisplayingNotPublishedNodes(true); $listManager->setDisplayingAllNodesStatuses(true); - if ($this->pagination === false) { + if (false === $this->pagination) { $listManager->setItemPerPage($this->itemPerPage ?? 999); $listManager->disablePagination(); } @@ -421,7 +373,7 @@ protected function handleNodeForm(FormInterface $form, NodeType $nodetype): ?Res */ $button = $form->get('export'); if ($button instanceof ClickableInterface && $button->isClicked()) { - $filename = 'search-' . $nodetype->getName() . '-' . date("YmdHis") . '.csv'; + $filename = 'search-'.$nodetype->getName().'-'.date('YmdHis').'.csv'; $response = new StreamedResponse(function () use ($entities) { echo $this->serializer->serialize($entities, 'csv', [ 'groups' => [ @@ -440,6 +392,7 @@ protected function handleNodeForm(FormInterface $form, NodeType $nodetype): ?Res $filename ) ); + return $response; } @@ -450,16 +403,12 @@ protected function handleNodeForm(FormInterface $form, NodeType $nodetype): ?Res return null; } - /** - * @param string $prefix - * @return FormBuilderInterface - */ protected function buildSimpleForm(string $prefix = ''): FormBuilderInterface { /** @var FormBuilder $builder */ - $builder = $this->createFormBuilder([], ["method" => "get"]); + $builder = $this->createFormBuilder([], ['method' => 'get']); - $builder->add($prefix . 'status', NodeStatesType::class, [ + $builder->add($prefix.'status', NodeStatesType::class, [ 'label' => 'node.status', 'required' => false, ]); @@ -472,37 +421,37 @@ protected function buildSimpleForm(string $prefix = ''): FormBuilderInterface 'class' => 'form-col-status-group', ], ]) - ->add($prefix . 'visible', ExtendedBooleanType::class, [ + ->add($prefix.'visible', ExtendedBooleanType::class, [ 'label' => 'visible', ]) - ->add($prefix . 'locked', ExtendedBooleanType::class, [ + ->add($prefix.'locked', ExtendedBooleanType::class, [ 'label' => 'locked', ]) - ->add($prefix . 'sterile', ExtendedBooleanType::class, [ + ->add($prefix.'sterile', ExtendedBooleanType::class, [ 'label' => 'sterile-status', ]) - ->add($prefix . 'hideChildren', ExtendedBooleanType::class, [ + ->add($prefix.'hideChildren', ExtendedBooleanType::class, [ 'label' => 'hiding-children', ]) ); $builder->add( - $this->createTextSearchForm($builder, $prefix . 'nodeName', 'nodeName') + $this->createTextSearchForm($builder, $prefix.'nodeName', 'nodeName') ); - $builder->add($prefix . 'parent', TextType::class, [ - 'label' => 'node.id.parent', - 'required' => false, - ]) - ->add($prefix . 'createdAt', CompareDatetimeType::class, [ + $builder->add($prefix.'parent', TextType::class, [ + 'label' => 'node.id.parent', + 'required' => false, + ]) + ->add($prefix.'createdAt', CompareDatetimeType::class, [ 'label' => 'created.at', 'inherit_data' => false, 'required' => false, ]) - ->add($prefix . 'updatedAt', CompareDatetimeType::class, [ + ->add($prefix.'updatedAt', CompareDatetimeType::class, [ 'label' => 'updated.at', 'inherit_data' => false, 'required' => false, ]) - ->add($prefix . 'limitResult', NumberType::class, [ + ->add($prefix.'limitResult', NumberType::class, [ 'label' => 'node.limit.result', 'required' => false, 'constraints' => [ @@ -525,51 +474,40 @@ protected function buildSimpleForm(string $prefix = ''): FormBuilderInterface return $builder; } - /** - * @param FormBuilderInterface $builder - * @param string $formName - * @param string $label - * - * @return FormBuilderInterface - */ protected function createTextSearchForm( FormBuilderInterface $builder, string $formName, - string $label + string $label, ): FormBuilderInterface { - return $builder->create($formName . '_group', FormType::class, [ - 'label' => false, - 'inherit_data' => true, - 'mapped' => false, - 'attr' => [ - 'class' => 'form-col-search-group', - ], - ]) + return $builder->create($formName.'_group', FormType::class, [ + 'label' => false, + 'inherit_data' => true, + 'mapped' => false, + 'attr' => [ + 'class' => 'form-col-search-group', + ], + ]) ->add($formName, TextType::class, [ 'label' => $label, 'required' => false, ]) - ->add($formName . '_exact', CheckboxType::class, [ + ->add($formName.'_exact', CheckboxType::class, [ 'label' => 'exact_search', 'required' => false, ]) ; } - /** - * @param FormBuilderInterface $builder - * @param NodeType $nodetype - */ private function extendForm(FormBuilderInterface $builder, NodeType $nodetype): void { $fields = $nodetype->getFields(); $builder->add( - "nodetypefield", + 'nodetypefield', SeparatorType::class, [ 'label' => 'nodetypefield', - 'attr' => ["class" => "label-separator"], + 'attr' => ['class' => 'label-separator'], ] ); $builder->add( @@ -577,7 +515,7 @@ private function extendForm(FormBuilderInterface $builder, NodeType $nodetype): ); if ($nodetype->isPublishable()) { $builder->add( - "publishedAt", + 'publishedAt', CompareDatetimeType::class, [ 'label' => 'publishedAt', @@ -587,7 +525,7 @@ private function extendForm(FormBuilderInterface $builder, NodeType $nodetype): } foreach ($fields as $field) { - $option = ["label" => $field->getLabel()]; + $option = ['label' => $field->getLabel()]; $option['required'] = false; if ($field->isVirtual()) { continue; @@ -596,56 +534,56 @@ private function extendForm(FormBuilderInterface $builder, NodeType $nodetype): * Prevent searching on complex fields */ if ( - $field->isMultipleProvider() || - $field->isSingleProvider() || - $field->isCollection() || - $field->isManyToMany() || - $field->isManyToOne() + $field->isMultipleProvider() + || $field->isSingleProvider() + || $field->isCollection() + || $field->isManyToMany() + || $field->isManyToOne() ) { continue; } - if ($field->getType() === AbstractField::ENUM_T) { + if (AbstractField::ENUM_T === $field->getType()) { $choices = explode(',', $field->getDefaultValues() ?? ''); $choices = array_map('trim', $choices); $choices = array_combine(array_values($choices), array_values($choices)); $type = ChoiceType::class; $option['placeholder'] = 'ignore'; $option['required'] = false; - $option["expanded"] = false; + $option['expanded'] = false; if (count($choices) < 4) { - $option["expanded"] = true; + $option['expanded'] = true; } - $option["choices"] = $choices; - } elseif ($field->getType() === AbstractField::MULTIPLE_T) { + $option['choices'] = $choices; + } elseif (AbstractField::MULTIPLE_T === $field->getType()) { $choices = explode(',', $field->getDefaultValues() ?? ''); $choices = array_map('trim', $choices); $choices = array_combine(array_values($choices), array_values($choices)); $type = ChoiceType::class; - $option["choices"] = $choices; + $option['choices'] = $choices; $option['placeholder'] = 'ignore'; $option['required'] = false; - $option["multiple"] = true; - $option["expanded"] = false; + $option['multiple'] = true; + $option['expanded'] = false; if (count($choices) < 4) { - $option["expanded"] = true; + $option['expanded'] = true; } - } elseif ($field->getType() === AbstractField::DATETIME_T) { + } elseif (AbstractField::DATETIME_T === $field->getType()) { $type = CompareDatetimeType::class; - } elseif ($field->getType() === AbstractField::DATE_T) { + } elseif (AbstractField::DATE_T === $field->getType()) { $type = CompareDateType::class; } else { $type = NodeSourceType::getFormTypeFromFieldType($field); } if ( - $field->getType() === AbstractField::MARKDOWN_T || - $field->getType() === AbstractField::STRING_T || - $field->getType() === AbstractField::TEXT_T || - $field->getType() === AbstractField::EMAIL_T || - $field->getType() === AbstractField::JSON_T || - $field->getType() === AbstractField::YAML_T || - $field->getType() === AbstractField::CSS_T + AbstractField::MARKDOWN_T === $field->getType() + || AbstractField::STRING_T === $field->getType() + || AbstractField::TEXT_T === $field->getType() + || AbstractField::EMAIL_T === $field->getType() + || AbstractField::JSON_T === $field->getType() + || AbstractField::YAML_T === $field->getType() + || AbstractField::CSS_T === $field->getType() ) { $builder->add( $this->createTextSearchForm($builder, $field->getVarName(), $field->getLabel()) diff --git a/lib/Rozier/src/Controllers/SettingGroupsController.php b/lib/Rozier/src/Controllers/SettingGroupsController.php index 5f87b52d..18bf442b 100644 --- a/lib/Rozier/src/Controllers/SettingGroupsController.php +++ b/lib/Rozier/src/Controllers/SettingGroupsController.php @@ -11,92 +11,59 @@ class SettingGroupsController extends AbstractAdminController { - /** - * @inheritDoc - */ protected function supports(PersistableInterface $item): bool { return $item instanceof SettingGroup; } - /** - * @inheritDoc - */ protected function getNamespace(): string { return 'settingGroup'; } - /** - * @inheritDoc - */ protected function createEmptyItem(Request $request): PersistableInterface { return new SettingGroup(); } - /** - * @inheritDoc - */ protected function getTemplateFolder(): string { return '@RoadizRozier/settingGroups'; } - /** - * @inheritDoc - */ protected function getRequiredRole(): string { return 'ROLE_ACCESS_SETTINGS'; } - /** - * @inheritDoc - */ protected function getEntityClass(): string { return SettingGroup::class; } - /** - * @inheritDoc - */ protected function getFormType(): string { return SettingGroupType::class; } - /** - * @inheritDoc - */ protected function getDefaultRouteName(): string { return 'settingGroupsHomePage'; } - /** - * @inheritDoc - */ protected function getEditRouteName(): string { return 'settingGroupsEditPage'; } - /** - * @inheritDoc - */ protected function getEntityName(PersistableInterface $item): string { if ($item instanceof SettingGroup) { return $item->getName(); } - throw new \InvalidArgumentException('Item should be instance of ' . $this->getEntityClass()); + throw new \InvalidArgumentException('Item should be instance of '.$this->getEntityClass()); } - /** - * @inheritDoc - */ protected function getDefaultOrder(Request $request): array { return ['name' => 'ASC']; diff --git a/lib/Rozier/src/Controllers/SettingsController.php b/lib/Rozier/src/Controllers/SettingsController.php index 4a12ba8d..92d68df5 100644 --- a/lib/Rozier/src/Controllers/SettingsController.php +++ b/lib/Rozier/src/Controllers/SettingsController.php @@ -30,16 +30,13 @@ class SettingsController extends RozierApp { public function __construct( private readonly FormFactoryInterface $formFactory, - private readonly FormErrorSerializer $formErrorSerializer + private readonly FormErrorSerializer $formErrorSerializer, ) { } /** * List every setting. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function indexAction(Request $request): Response @@ -54,10 +51,6 @@ public function indexAction(Request $request): Response } /** - * @param Request $request - * @param int $settingGroupId - * - * @return Response * @throws RuntimeError */ public function byGroupAction(Request $request, int $settingGroupId): Response @@ -67,7 +60,7 @@ public function byGroupAction(Request $request, int $settingGroupId): Response /** @var SettingGroup|null $settingGroup */ $settingGroup = $this->em()->find(SettingGroup::class, $settingGroupId); - if ($settingGroup === null) { + if (null === $settingGroup) { throw new ResourceNotFoundException(); } @@ -80,13 +73,7 @@ public function byGroupAction(Request $request, int $settingGroupId): Response return $this->render('@RoadizRozier/settings/list.html.twig', $this->assignation); } - /** - * @param Request $request - * @param SettingGroup|null $settingGroup - * - * @return Response|null - */ - protected function commonSettingList(Request $request, SettingGroup $settingGroup = null): ?Response + protected function commonSettingList(Request $request, ?SettingGroup $settingGroup = null): ?Response { $criteria = []; if (null !== $settingGroup) { @@ -114,9 +101,9 @@ protected function commonSettingList(Request $request, SettingGroup $settingGrou $settings = $listManager->getEntities(); $this->assignation['settings'] = []; $isJson = - $request->isXmlHttpRequest() || - $request->getRequestFormat('html') === 'json' || - \in_array( + $request->isXmlHttpRequest() + || 'json' === $request->getRequestFormat('html') + || \in_array( 'application/json', $request->getAcceptableContentTypes() ); @@ -176,7 +163,7 @@ protected function commonSettingList(Request $request, SettingGroup $settingGrou } $document = null; - if ($setting->getType() == AbstractField::DOCUMENTS_T) { + if (AbstractField::DOCUMENTS_T == $setting->getType()) { $document = $this->getSettingsBag()->getDocument($setting->getName()); } @@ -193,10 +180,6 @@ protected function commonSettingList(Request $request, SettingGroup $settingGrou /** * Return an edition form for requested setting. * - * @param Request $request - * @param int $settingId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $settingId): Response @@ -205,14 +188,14 @@ public function editAction(Request $request, int $settingId): Response /** @var Setting|null $setting */ $setting = $this->em()->find(Setting::class, $settingId); - if ($setting === null) { + if (null === $setting) { throw $this->createNotFoundException(); } $this->assignation['setting'] = $setting; $form = $this->createForm(SettingType::class, $setting, [ - 'shortEdit' => false + 'shortEdit' => false, ]); $form->handleRequest($request); @@ -223,6 +206,7 @@ public function editAction(Request $request, int $settingId): Response $this->em()->flush(); $msg = $this->getTranslator()->trans('setting.%name%.updated', ['%name%' => $setting->getName()]); $this->publishConfirmMessage($request, $msg, $setting); + /* * Force redirect to avoid resending form when refreshing page */ @@ -252,9 +236,6 @@ protected function resetSettingsCache(): void /** * Return a creation form for requested setting. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function addAction(Request $request): Response @@ -293,10 +274,6 @@ public function addAction(Request $request): Response /** * Return a deletion form for requested setting. * - * @param Request $request - * @param int $settingId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $settingId): Response diff --git a/lib/Rozier/src/Controllers/SettingsUtilsController.php b/lib/Rozier/src/Controllers/SettingsUtilsController.php index 8d963eb4..5ebba989 100644 --- a/lib/Rozier/src/Controllers/SettingsUtilsController.php +++ b/lib/Rozier/src/Controllers/SettingsUtilsController.php @@ -23,17 +23,12 @@ class SettingsUtilsController extends RozierApp { public function __construct( private readonly SerializerInterface $serializer, - private readonly SettingsImporter $settingsImporter + private readonly SettingsImporter $settingsImporter, ) { } /** * Export all settings in a Json file. - * - * @param Request $request - * @param int|null $settingGroupId - * - * @return Response */ public function exportAllAction(Request $request, ?int $settingGroupId = null): Response { @@ -45,12 +40,12 @@ public function exportAllAction(Request $request, ?int $settingGroupId = null): if (null === $group) { throw $this->createNotFoundException(); } - $fileName = 'settings-' . \mb_strtolower(StringHandler::cleanForFilename($group->getName())) . '-' . date("YmdHis") . '.json'; + $fileName = 'settings-'.\mb_strtolower(StringHandler::cleanForFilename($group->getName())).'-'.date('YmdHis').'.json'; $settings = $this->em() ->getRepository(Setting::class) ->findBySettingGroup($group); } else { - $fileName = 'settings-' . date("YmdHis") . '.json'; + $fileName = 'settings-'.date('YmdHis').'.json'; $settings = $this->em() ->getRepository(Setting::class) ->findAll(); @@ -73,9 +68,6 @@ public function exportAllAction(Request $request, ?int $settingGroupId = null): /** * Import a Json file (.rzt) containing setting and setting group. * - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function importJsonFileAction(Request $request): Response @@ -87,9 +79,9 @@ public function importJsonFileAction(Request $request): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - !empty($form['setting_file']) + $form->isSubmitted() + && $form->isValid() + && !empty($form['setting_file']) ) { $file = $form['setting_file']->getData(); @@ -123,9 +115,6 @@ public function importJsonFileAction(Request $request): Response return $this->render('@RoadizRozier/settings/import.html.twig', $this->assignation); } - /** - * @return FormInterface - */ private function buildImportJsonFileForm(): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/Tags/TagMultiCreationController.php b/lib/Rozier/src/Controllers/Tags/TagMultiCreationController.php index fa8632b9..4298dc73 100644 --- a/lib/Rozier/src/Controllers/Tags/TagMultiCreationController.php +++ b/lib/Rozier/src/Controllers/Tags/TagMultiCreationController.php @@ -22,9 +22,6 @@ public function __construct(private readonly TagFactory $tagFactory) } /** - * @param Request $request - * @param int $parentTagId - * @return Response * @throws \Twig\Error\RuntimeError */ public function addChildAction(Request $request, int $parentTagId): Response diff --git a/lib/Rozier/src/Controllers/Tags/TagsController.php b/lib/Rozier/src/Controllers/Tags/TagsController.php index 9a766e71..740a40bd 100644 --- a/lib/Rozier/src/Controllers/Tags/TagsController.php +++ b/lib/Rozier/src/Controllers/Tags/TagsController.php @@ -44,16 +44,12 @@ public function __construct( private readonly FormFactoryInterface $formFactory, private readonly FormErrorSerializer $formErrorSerializer, private readonly HandlerFactoryInterface $handlerFactory, - private readonly TreeWidgetFactory $treeWidgetFactory + private readonly TreeWidgetFactory $treeWidgetFactory, ) { } /** * List every tags. - * - * @param Request $request - * - * @return Response */ public function indexAction(Request $request): Response { @@ -85,11 +81,6 @@ public function indexAction(Request $request): Response /** * Return an edition form for current translated tag. * - * @param Request $request - * @param int $tagId - * @param int|null $translationId - * - * @return Response * @throws RuntimeError */ public function editTranslatedAction(Request $request, int $tagId, ?int $translationId = null): Response @@ -133,13 +124,13 @@ public function editTranslatedAction(Request $request, int $tagId, ?int $transla if (false !== $baseTranslation) { $tagTranslation->setName($baseTranslation->getName()); } else { - $tagTranslation->setName('tag_' . $tag->getId()); + $tagTranslation->setName('tag_'.$tag->getId()); } $this->em()->persist($tagTranslation); $this->em()->flush(); } - /** + /* * Versioning */ if ($this->isGranted('ROLE_ACCESS_VERSIONS')) { @@ -154,8 +145,8 @@ public function editTranslatedAction(Request $request, int $tagId, ?int $transla ]); $form->handleRequest($request); $isJsonRequest = - $request->isXmlHttpRequest() || - \in_array('application/json', $request->getAcceptableContentTypes()) + $request->isXmlHttpRequest() + || \in_array('application/json', $request->getAcceptableContentTypes()) ; if ($form->isSubmitted()) { @@ -167,9 +158,9 @@ public function editTranslatedAction(Request $request, int $tagId, ?int $transla $newTagName = StringHandler::slugify($tagTranslation->getName()); if ($tag->getTagName() !== $newTagName) { if ( - !$tag->isLocked() && - $translation->isDefaultTranslation() && - !$this->tagNameExists($newTagName) + !$tag->isLocked() + && $translation->isDefaultTranslation() + && !$this->tagNameExists($newTagName) ) { $tag->setTagName($tagTranslation->getName()); } @@ -205,6 +196,7 @@ public function editTranslatedAction(Request $request, int $tagId, ?int $transla */ if ($isJsonRequest) { $errors = $this->formErrorSerializer->getErrorsAsArray($form); + return new JsonResponse([ 'status' => 'fail', 'errors' => $errors, @@ -226,22 +218,14 @@ public function editTranslatedAction(Request $request, int $tagId, ?int $transla return $this->render('@RoadizRozier/tags/edit.html.twig', $this->assignation); } - /** - * @param string $name - * - * @return bool - */ protected function tagNameExists(string $name): bool { $entity = $this->em()->getRepository(Tag::class)->findOneByTagName($name); - return (null !== $entity); + return null !== $entity; } /** - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function bulkDeleteAction(Request $request): Response @@ -293,8 +277,6 @@ public function bulkDeleteAction(Request $request): Response } /** - * @param Request $request - * @return Response * @throws RuntimeError */ public function addAction(Request $request): Response @@ -304,7 +286,7 @@ public function addAction(Request $request): Response $tag = new Tag(); $translation = $this->em()->getRepository(Translation::class)->findDefault(); - if ($translation !== null) { + if (null !== $translation) { $this->assignation['tag'] = $tag; $form = $this->createForm(TagType::class, $tag); $form->handleRequest($request); @@ -332,6 +314,7 @@ public function addAction(Request $request): Response $msg = $this->getTranslator()->trans('tag.%name%.created', ['%name%' => $tag->getTagName()]); $this->publishConfirmMessage($request, $msg, $tag); + /* * Force redirect to avoid resending form when refreshing page */ @@ -347,10 +330,6 @@ public function addAction(Request $request): Response } /** - * @param Request $request - * @param int $tagId - * - * @return Response * @throws RuntimeError */ public function editSettingsAction(Request $request, int $tagId): Response @@ -362,7 +341,7 @@ public function editSettingsAction(Request $request, int $tagId): Response /** @var Tag|null $tag */ $tag = $this->em()->find(Tag::class, $tagId); - if ($tag === null) { + if (null === $tag) { throw new ResourceNotFoundException(); } @@ -372,8 +351,8 @@ public function editSettingsAction(Request $request, int $tagId): Response $form->handleRequest($request); $isJsonRequest = - $request->isXmlHttpRequest() || - \in_array('application/json', $request->getAcceptableContentTypes()) + $request->isXmlHttpRequest() + || \in_array('application/json', $request->getAcceptableContentTypes()) ; if ($form->isSubmitted()) { @@ -400,6 +379,7 @@ public function editSettingsAction(Request $request, int $tagId): Response */ if ($isJsonRequest) { $errors = $this->formErrorSerializer->getErrorsAsArray($form); + return new JsonResponse([ 'status' => 'fail', 'errors' => $errors, @@ -416,11 +396,6 @@ public function editSettingsAction(Request $request, int $tagId): Response } /** - * @param Request $request - * @param int $tagId - * @param int|null $translationId - * - * @return Response * @throws RuntimeError */ public function treeAction(Request $request, int $tagId, ?int $translationId = null): Response @@ -452,10 +427,6 @@ public function treeAction(Request $request, int $tagId, ?int $translationId = n /** * Return a deletion form for requested tag. * - * @param Request $request - * @param int $tagId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $tagId): Response @@ -466,8 +437,8 @@ public function deleteAction(Request $request, int $tagId): Response $tag = $this->em()->find(Tag::class, $tagId); if ( - $tag !== null && - !$tag->isLocked() + null !== $tag + && !$tag->isLocked() ) { $this->assignation['tag'] = $tag; @@ -475,9 +446,9 @@ public function deleteAction(Request $request, int $tagId): Response $form->handleRequest($request); if ( - $form->isSubmitted() && - $form->isValid() && - $form->getData()['tagId'] == $tag->getId() + $form->isSubmitted() + && $form->isValid() + && $form->getData()['tagId'] == $tag->getId() ) { /* * Dispatch event @@ -511,11 +482,6 @@ public function deleteAction(Request $request, int $tagId): Response /** * Handle tag creation pages. * - * @param Request $request - * @param int $tagId - * @param int|null $translationId - * - * @return Response * @throws RuntimeError */ public function addChildAction(Request $request, int $tagId, ?int $translationId = null): Response @@ -524,7 +490,7 @@ public function addChildAction(Request $request, int $tagId, ?int $translationId $translation = $this->em()->getRepository(Translation::class)->findDefault(); - if ($translationId !== null) { + if (null !== $translationId) { $translation = $this->em()->find(Translation::class, $translationId); } $parentTag = $this->em()->find(Tag::class, $tagId); @@ -532,8 +498,8 @@ public function addChildAction(Request $request, int $tagId, ?int $translationId $tag->setParent($parentTag); if ( - $translation !== null && - $parentTag !== null + null !== $translation + && null !== $parentTag ) { $form = $this->createForm(TagType::class, $tag); $form->handleRequest($request); @@ -584,10 +550,6 @@ public function addChildAction(Request $request, int $tagId, ?int $translationId /** * Handle tag nodes page. * - * @param Request $request - * @param int $tagId - * - * @return Response * @throws RuntimeError */ public function editNodesAction(Request $request, int $tagId): Response @@ -623,11 +585,6 @@ public function editNodesAction(Request $request, int $tagId): Response throw new ResourceNotFoundException(); } - /** - * @param Tag $tag - * - * @return FormInterface - */ private function buildDeleteForm(Tag $tag): FormInterface { $builder = $this->createFormBuilder() @@ -642,15 +599,9 @@ private function buildDeleteForm(Tag $tag): FormInterface return $builder->getForm(); } - /** - * @param null|string $referer - * @param array $tagsIds - * - * @return FormInterface - */ private function buildBulkDeleteForm( ?string $referer = null, - array $tagsIds = [] + array $tagsIds = [], ): FormInterface { $builder = $this->formFactory ->createNamedBuilder('deleteForm') @@ -672,11 +623,6 @@ private function buildBulkDeleteForm( return $builder->getForm(); } - /** - * @param array $data - * - * @return string - */ private function bulkDeleteTags(array $data): string { if (!empty($data['tagsIds'])) { @@ -730,14 +676,16 @@ protected function getPostUpdateRedirection(PersistableInterface $entity): ?Resp if ($entity instanceof TagTranslation) { /** @var Translation $translation */ $translation = $entity->getTranslation(); + return $this->redirectToRoute( 'tagsEditTranslatedPage', [ 'tagId' => $entity->getTag()->getId(), - 'translationId' => $translation->getId() + 'translationId' => $translation->getId(), ] ); } + return null; } } diff --git a/lib/Rozier/src/Controllers/Tags/TagsUtilsController.php b/lib/Rozier/src/Controllers/Tags/TagsUtilsController.php index 71f96693..e6c5e4ed 100644 --- a/lib/Rozier/src/Controllers/Tags/TagsUtilsController.php +++ b/lib/Rozier/src/Controllers/Tags/TagsUtilsController.php @@ -19,11 +19,7 @@ public function __construct(private readonly SerializerInterface $serializer) } /** - * Export a Tag in a Json file - * - * @param Request $request - * @param int $tagId - * @return JsonResponse + * Export a Tag in a Json file. */ public function exportAction(Request $request, int $tagId): JsonResponse { @@ -41,7 +37,7 @@ public function exportAction(Request $request, int $tagId): JsonResponse [ 'Content-Disposition' => sprintf( 'attachment; filename="%s"', - 'tag-' . $existingTag->getTagName() . '-' . date("YmdHis") . '.json' + 'tag-'.$existingTag->getTagName().'-'.date('YmdHis').'.json' ), ], true @@ -49,12 +45,7 @@ public function exportAction(Request $request, int $tagId): JsonResponse } /** - * Export a Tag in a Json file - * - * @param Request $request - * @param int $tagId - * - * @return JsonResponse + * Export a Tag in a Json file. */ public function exportAllAction(Request $request, int $tagId): JsonResponse { @@ -62,7 +53,7 @@ public function exportAllAction(Request $request, int $tagId): JsonResponse $existingTags = $this->em() ->getRepository(Tag::class) - ->findBy(["parent" => null]); + ->findBy(['parent' => null]); return new JsonResponse( $this->serializer->serialize( @@ -74,7 +65,7 @@ public function exportAllAction(Request $request, int $tagId): JsonResponse [ 'Content-Disposition' => sprintf( 'attachment; filename="%s"', - 'tag-all-' . date("YmdHis") . '.json' + 'tag-all-'.date('YmdHis').'.json' ), ], true diff --git a/lib/Rozier/src/Controllers/TranslationsController.php b/lib/Rozier/src/Controllers/TranslationsController.php index 601c24b1..93b5006c 100644 --- a/lib/Rozier/src/Controllers/TranslationsController.php +++ b/lib/Rozier/src/Controllers/TranslationsController.php @@ -28,9 +28,6 @@ public function __construct(private readonly HandlerFactoryInterface $handlerFac } /** - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function indexAction(Request $request): Response @@ -51,7 +48,7 @@ public function indexAction(Request $request): Response /** @var Translation $translation */ foreach ($translations as $translation) { // Make default forms - $form = $this->createNamedFormBuilder('default_trans_' . $translation->getId(), $translation)->getForm(); + $form = $this->createNamedFormBuilder('default_trans_'.$translation->getId(), $translation)->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { /** @var TranslationHandler $handler */ @@ -60,6 +57,7 @@ public function indexAction(Request $request): Response $msg = $this->getTranslator()->trans('translation.%name%.made_default', ['%name%' => $translation->getName()]); $this->publishConfirmMessage($request, $msg, $translation); $this->dispatchEvent(new TranslationUpdatedEvent($translation)); + /* * Force redirect to avoid resending form when refreshing page */ @@ -78,10 +76,6 @@ public function indexAction(Request $request): Response } /** - * @param Request $request - * @param int $translationId - * - * @return Response * @throws RuntimeError */ public function editAction(Request $request, int $translationId): Response @@ -91,7 +85,7 @@ public function editAction(Request $request, int $translationId): Response /** @var Translation|null $translation */ $translation = $this->em()->find(Translation::class, $translationId); - if ($translation === null) { + if (null === $translation) { throw new ResourceNotFoundException(); } @@ -106,6 +100,7 @@ public function editAction(Request $request, int $translationId): Response $this->publishConfirmMessage($request, $msg, $translation); $this->dispatchEvent(new TranslationUpdatedEvent($translation)); + /* * Force redirect to avoid resending form when refreshing page */ @@ -121,9 +116,6 @@ public function editAction(Request $request, int $translationId): Response } /** - * @param Request $request - * - * @return Response * @throws RuntimeError */ public function addAction(Request $request): Response @@ -144,6 +136,7 @@ public function addAction(Request $request): Response $this->publishConfirmMessage($request, $msg, $translation); $this->dispatchEvent(new TranslationCreatedEvent($translation)); + /* * Force redirect to avoid resending form when refreshing page */ @@ -156,10 +149,6 @@ public function addAction(Request $request): Response } /** - * @param Request $request - * @param int $translationId - * - * @return Response * @throws RuntimeError */ public function deleteAction(Request $request, int $translationId): Response diff --git a/lib/Rozier/src/Controllers/Users/UsersController.php b/lib/Rozier/src/Controllers/Users/UsersController.php index a2ded208..2403de25 100644 --- a/lib/Rozier/src/Controllers/Users/UsersController.php +++ b/lib/Rozier/src/Controllers/Users/UsersController.php @@ -24,12 +24,11 @@ public function __construct( FormFactoryInterface $formFactory, SerializerInterface $serializer, UrlGeneratorInterface $urlGenerator, - private readonly bool $useGravatar + private readonly bool $useGravatar, ) { parent::__construct($formFactory, $serializer, $urlGenerator); } - protected function supports(PersistableInterface $item): bool { return $item instanceof User; @@ -44,6 +43,7 @@ protected function createEmptyItem(Request $request): User { $user = new User(); $user->sendCreationConfirmationEmail(true); + return $user; } @@ -104,14 +104,14 @@ protected function denyAccessUnlessItemGranted(PersistableInterface $item): void $requestUser = $this->getUser(); if ( !( - $this->isGranted('ROLE_ACCESS_USERS') || - ($requestUser instanceof User && $requestUser->getId() === $item->getId()) + $this->isGranted('ROLE_ACCESS_USERS') + || ($requestUser instanceof User && $requestUser->getId() === $item->getId()) ) ) { throw $this->createAccessDeniedException("You don't have access to this page: ROLE_ACCESS_USERS"); } if (!$this->isGranted(Role::ROLE_SUPERADMIN) && $item->isSuperAdmin()) { - throw $this->createAccessDeniedException("You cannot edit a super admin."); + throw $this->createAccessDeniedException('You cannot edit a super admin.'); } } @@ -120,6 +120,7 @@ protected function getEntityName(PersistableInterface $item): string if (!$item instanceof User) { throw new \RuntimeException('Invalid item type.'); } + return $item->getUsername(); } @@ -136,7 +137,7 @@ protected function createUpdateEvent(PersistableInterface $item) /* * If pictureUrl is empty, use default Gravatar image. */ - if ($item->getPictureUrl() == '' && $this->useGravatar) { + if ('' == $item->getPictureUrl() && $this->useGravatar) { $item->setPictureUrl($item->getGravatarUrl()); } @@ -144,10 +145,6 @@ protected function createUpdateEvent(PersistableInterface $item) } /** - * @param Request $request - * @param int $id - * - * @return Response * @throws RuntimeError */ public function editDetailsAction(Request $request, int $id): Response @@ -186,7 +183,7 @@ public function editDetailsAction(Request $request, int $id): Response '%namespace%.%item%.was_updated', [ '%item%' => $this->getEntityName($item), - '%namespace%' => $this->getTranslator()->trans($this->getNamespace()) + '%namespace%' => $this->getTranslator()->trans($this->getNamespace()), ] ); $this->publishConfirmMessage($request, $msg, $item); @@ -204,15 +201,13 @@ public function editDetailsAction(Request $request, int $id): Response $this->assignation['item'] = $item; return $this->render( - $this->getTemplateFolder() . '/editDetails.html.twig', + $this->getTemplateFolder().'/editDetails.html.twig', $this->assignation, null, $this->getTemplateNamespace() ); } - - protected function additionalAssignation(Request $request): void { parent::additionalAssignation($request); @@ -276,7 +271,7 @@ function (string $ids) { 'id' => $ids, ]); }, - $this->getTemplateFolder() . '/bulk_enable.html.twig', + $this->getTemplateFolder().'/bulk_enable.html.twig', '%namespace%.%item%.was_enabled', function (PersistableInterface $item) { if (!$item instanceof User) { @@ -300,7 +295,7 @@ function (string $ids) { 'id' => $ids, ]); }, - $this->getTemplateFolder() . '/bulk_disable.html.twig', + $this->getTemplateFolder().'/bulk_disable.html.twig', '%namespace%.%item%.was_disabled', function (PersistableInterface $item) { if (!$item instanceof User) { diff --git a/lib/Rozier/src/Controllers/Users/UsersGroupsController.php b/lib/Rozier/src/Controllers/Users/UsersGroupsController.php index 62103ffc..5180e3d1 100644 --- a/lib/Rozier/src/Controllers/Users/UsersGroupsController.php +++ b/lib/Rozier/src/Controllers/Users/UsersGroupsController.php @@ -27,7 +27,7 @@ public function editGroupsAction(Request $request, int $userId): Response /** @var User|null $user */ $user = $this->em()->find(User::class, $userId); - if ($user === null) { + if (null === $user) { throw new ResourceNotFoundException(); } @@ -47,7 +47,7 @@ public function editGroupsAction(Request $request, int $userId): Response $group = null; } - if ($group !== null) { + if (null !== $group) { $user->addGroup($group); $this->em()->flush(); @@ -84,10 +84,10 @@ public function removeGroupAction(Request $request, int $userId, int $groupId): /** @var Group|null $group */ $group = $this->em()->find(Group::class, $groupId); - if ($user === null) { + if (null === $user) { throw new ResourceNotFoundException(); } - if ($group === null) { + if (null === $group) { throw new ResourceNotFoundException(); } @@ -127,11 +127,6 @@ public function removeGroupAction(Request $request, int $userId, int $groupId): return $this->render('@RoadizRozier/users/removeGroup.html.twig', $this->assignation); } - /** - * @param User $user - * - * @return FormInterface - */ private function buildEditGroupsForm(User $user): FormInterface { $defaults = [ @@ -153,7 +148,7 @@ private function buildEditGroupsForm(User $user): FormInterface 'group', GroupsType::class, [ - 'label' => 'Group' + 'label' => 'Group', ] ) ; diff --git a/lib/Rozier/src/Controllers/Users/UsersRolesController.php b/lib/Rozier/src/Controllers/Users/UsersRolesController.php index ba80f0af..aa402279 100644 --- a/lib/Rozier/src/Controllers/Users/UsersRolesController.php +++ b/lib/Rozier/src/Controllers/Users/UsersRolesController.php @@ -19,10 +19,6 @@ class UsersRolesController extends RozierApp { /** - * @param Request $request - * @param int $userId - * - * @return Response * @throws RuntimeError */ public function editRolesAction(Request $request, int $userId): Response @@ -32,7 +28,7 @@ public function editRolesAction(Request $request, int $userId): Response /** @var User|null $user */ $user = $this->em()->find(User::class, $userId); - if ($user === null) { + if (null === $user) { throw new ResourceNotFoundException(); } @@ -74,11 +70,6 @@ public function editRolesAction(Request $request, int $userId): Response /** * Return a deletion form for requested role depending on the user. * - * @param Request $request - * @param int $userId - * @param int $roleId - * - * @return Response * @throws RuntimeError */ public function removeRoleAction(Request $request, int $userId, int $roleId): Response @@ -87,13 +78,13 @@ public function removeRoleAction(Request $request, int $userId, int $roleId): Re /** @var User|null $user */ $user = $this->em()->find(User::class, $userId); - if ($user === null) { + if (null === $user) { throw new ResourceNotFoundException(); } /** @var Role|null $role */ $role = $this->em()->find(Role::class, $roleId); - if ($role === null) { + if (null === $role) { throw new ResourceNotFoundException(); } @@ -130,11 +121,6 @@ public function removeRoleAction(Request $request, int $userId, int $roleId): Re return $this->render('@RoadizRozier/users/removeRole.html.twig', $this->assignation); } - /** - * @param User $user - * - * @return FormInterface - */ private function buildEditRolesForm(User $user): FormInterface { $builder = $this->createFormBuilder() diff --git a/lib/Rozier/src/Controllers/Users/UsersSecurityController.php b/lib/Rozier/src/Controllers/Users/UsersSecurityController.php index 35949690..df84e8e7 100644 --- a/lib/Rozier/src/Controllers/Users/UsersSecurityController.php +++ b/lib/Rozier/src/Controllers/Users/UsersSecurityController.php @@ -15,10 +15,6 @@ class UsersSecurityController extends RozierApp { /** - * @param Request $request - * @param int $userId - * - * @return Response * @throws RuntimeError */ public function securityAction(Request $request, int $userId): Response @@ -28,13 +24,13 @@ public function securityAction(Request $request, int $userId): Response /** @var User|null $user */ $user = $this->em()->find(User::class, $userId); - if ($user === null) { + if (null === $user) { throw new ResourceNotFoundException(); } $this->assignation['user'] = $user; $form = $this->createForm(UserSecurityType::class, $user, [ - 'canChroot' => $this->isGranted("ROLE_SUPERADMIN") + 'canChroot' => $this->isGranted('ROLE_SUPERADMIN'), ]); $form->handleRequest($request); diff --git a/lib/Rozier/src/Controllers/WebhookController.php b/lib/Rozier/src/Controllers/WebhookController.php index 60bccc70..c5930fb8 100644 --- a/lib/Rozier/src/Controllers/WebhookController.php +++ b/lib/Rozier/src/Controllers/WebhookController.php @@ -23,7 +23,7 @@ public function __construct( private readonly WebhookDispatcher $webhookDispatcher, FormFactoryInterface $formFactory, SerializerInterface $serializer, - UrlGeneratorInterface $urlGenerator + UrlGeneratorInterface $urlGenerator, ) { parent::__construct($formFactory, $serializer, $urlGenerator); } @@ -64,7 +64,7 @@ public function triggerAction(Request $request, string $id): Response )); } catch (TooManyWebhookTriggeredException $e) { $form->addError(new FormError('webhook.too_many_triggered_in_period', null, [ - '%time%' => $e->getDoNotTriggerBefore()->format('H:i:s') + '%time%' => $e->getDoNotTriggerBefore()->format('H:i:s'), ], null, $e)); } } @@ -73,7 +73,7 @@ public function triggerAction(Request $request, string $id): Response $this->assignation['item'] = $item; return $this->render( - $this->getTemplateFolder() . '/trigger.html.twig', + $this->getTemplateFolder().'/trigger.html.twig', $this->assignation, null, $this->getTemplateNamespace() @@ -130,8 +130,10 @@ protected function getEntityName(PersistableInterface $item): string if ($item instanceof Webhook) { return (string) $item; } + return ''; } + protected function getBulkDeleteRouteName(): ?string { return 'webhooksBulkDeletePage'; diff --git a/lib/Rozier/src/Explorer/ConfigurableExplorerItem.php b/lib/Rozier/src/Explorer/ConfigurableExplorerItem.php index 754e9d45..b5c83ca2 100644 --- a/lib/Rozier/src/Explorer/ConfigurableExplorerItem.php +++ b/lib/Rozier/src/Explorer/ConfigurableExplorerItem.php @@ -18,17 +18,11 @@ public function __construct( ) { } - /** - * @inheritDoc - */ public function getId(): int|string { return $this->entity->getId() ?? throw new \RuntimeException('Entity must have an ID'); } - /** - * @inheritDoc - */ public function getAlternativeDisplayable(): ?string { $alt = $this->configuration['classname']; @@ -41,12 +35,10 @@ public function getAlternativeDisplayable(): ?string } } } + return (new UnicodeString($alt ?? ''))->truncate(30, '…')->toString(); } - /** - * @inheritDoc - */ public function getDisplayable(): string { $displayableCallable = [$this->entity, $this->configuration['displayable']]; @@ -56,12 +48,10 @@ public function getDisplayable(): string $displayable = $displayable->format('c'); } } + return (new UnicodeString($displayable ?? ''))->truncate(30, '…')->toString(); } - /** - * @inheritDoc - */ public function getOriginal(): PersistableInterface { return $this->entity; diff --git a/lib/Rozier/src/Explorer/CustomFormExplorerItem.php b/lib/Rozier/src/Explorer/CustomFormExplorerItem.php index 915f169b..93f37f10 100644 --- a/lib/Rozier/src/Explorer/CustomFormExplorerItem.php +++ b/lib/Rozier/src/Explorer/CustomFormExplorerItem.php @@ -14,7 +14,7 @@ final class CustomFormExplorerItem extends AbstractExplorerItem public function __construct( private readonly CustomForm $customForm, private readonly UrlGeneratorInterface $urlGenerator, - private readonly TranslatorInterface $translator + private readonly TranslatorInterface $translator, ) { } @@ -28,7 +28,7 @@ public function getAlternativeDisplayable(): ?string return strip_tags($this->translator->trans( '{0} no.customFormField|{1} 1.customFormField|]1,Inf] %count%.customFormFields', [ - '%count%' => $this->customForm->getFields()->count() + '%count%' => $this->customForm->getFields()->count(), ] )); } @@ -46,7 +46,7 @@ public function getOriginal(): CustomForm protected function getEditItemPath(): ?string { return $this->urlGenerator->generate('customFormsEditPage', [ - 'id' => $this->customForm->getId() + 'id' => $this->customForm->getId(), ]); } diff --git a/lib/Rozier/src/Explorer/DocumentExplorerItem.php b/lib/Rozier/src/Explorer/DocumentExplorerItem.php index 19c81b9b..0870b7e4 100644 --- a/lib/Rozier/src/Explorer/DocumentExplorerItem.php +++ b/lib/Rozier/src/Explorer/DocumentExplorerItem.php @@ -18,17 +18,17 @@ final class DocumentExplorerItem extends AbstractExplorerItem { public static array $thumbnail80Array = [ - "fit" => "80x80", - "quality" => 50, - "sharpen" => 5, - "inline" => false, + 'fit' => '80x80', + 'quality' => 50, + 'sharpen' => 5, + 'inline' => false, ]; public static array $previewArray = [ - "width" => 1440, - "quality" => 80, - "inline" => false, - "picture" => true, - "embed" => true, + 'width' => 1440, + 'quality' => 80, + 'inline' => false, + 'picture' => true, + 'embed' => true, ]; public function __construct( @@ -36,7 +36,7 @@ public function __construct( private readonly RendererInterface $renderer, private readonly DocumentUrlGeneratorInterface $documentUrlGenerator, private readonly UrlGeneratorInterface $urlGenerator, - private readonly ?EmbedFinderFactory $embedFinderFactory = null + private readonly ?EmbedFinderFactory $embedFinderFactory = null, ) { } @@ -45,6 +45,7 @@ public function getId(): string|int if ($this->document instanceof PersistableInterface) { return $this->document->getId(); } + return 0; } @@ -56,12 +57,13 @@ public function getAlternativeDisplayable(): ?string public function getDisplayable(): string { if ( - $this->document instanceof Document && - $this->document->getDocumentTranslations()->first() && - $this->document->getDocumentTranslations()->first()->getName() + $this->document instanceof Document + && $this->document->getDocumentTranslations()->first() + && $this->document->getDocumentTranslations()->first()->getName() ) { return $this->document->getDocumentTranslations()->first()->getName(); } + return (string) $this->document; } @@ -75,8 +77,9 @@ protected function getEditItemPath(): ?string if (!($this->document instanceof PersistableInterface)) { return null; } + return $this->urlGenerator->generate('documentsEditPage', [ - 'documentId' => $this->document->getId() + 'documentId' => $this->document->getId(), ]); } @@ -85,10 +88,10 @@ protected function getColor(): ?string if ($this->document instanceof AdvancedDocumentInterface) { return $this->document->getImageAverageColor(); } + return null; } - public function toArray(): array { $thumbnail80Url = null; @@ -97,10 +100,10 @@ public function toArray(): array $hasThumbnail = false; if ( - $this->document instanceof HasThumbnailInterface && - $this->document->needsThumbnail() && - $this->document->hasThumbnails() && - false !== $thumbnail = $this->document->getThumbnails()->first() + $this->document instanceof HasThumbnailInterface + && $this->document->needsThumbnail() + && $this->document->hasThumbnails() + && false !== $thumbnail = $this->document->getThumbnails()->first() ) { $this->documentUrlGenerator->setDocument($thumbnail); $hasThumbnail = true; @@ -121,7 +124,7 @@ public function toArray(): array ...parent::toArray(), 'hasThumbnail' => $hasThumbnail, 'isImage' => $this->document->isImage(), - 'isWebp' => $this->document->getMimeType() === 'image/webp', + 'isWebp' => 'image/webp' === $this->document->getMimeType(), 'isVideo' => $this->document->isVideo(), 'isSvg' => $this->document->isSvg(), 'isEmbed' => $this->document->isEmbed(), diff --git a/lib/Rozier/src/Explorer/ExplorerItemFactory.php b/lib/Rozier/src/Explorer/ExplorerItemFactory.php index 4b5b2627..6582e6d4 100644 --- a/lib/Rozier/src/Explorer/ExplorerItemFactory.php +++ b/lib/Rozier/src/Explorer/ExplorerItemFactory.php @@ -22,15 +22,15 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Contracts\Translation\TranslatorInterface; -final class ExplorerItemFactory implements ExplorerItemFactoryInterface +final readonly class ExplorerItemFactory implements ExplorerItemFactoryInterface { public function __construct( - private readonly RendererInterface $renderer, - private readonly DocumentUrlGeneratorInterface $documentUrlGenerator, - private readonly UrlGeneratorInterface $urlGenerator, - private readonly EmbedFinderFactory $embedFinderFactory, - private readonly Security $security, - private readonly TranslatorInterface $translator + private RendererInterface $renderer, + private DocumentUrlGeneratorInterface $documentUrlGenerator, + private UrlGeneratorInterface $urlGenerator, + private EmbedFinderFactory $embedFinderFactory, + private Security $security, + private TranslatorInterface $translator, ) { } diff --git a/lib/Rozier/src/Explorer/FolderExplorerItem.php b/lib/Rozier/src/Explorer/FolderExplorerItem.php index f2ffe508..4cc25a9d 100644 --- a/lib/Rozier/src/Explorer/FolderExplorerItem.php +++ b/lib/Rozier/src/Explorer/FolderExplorerItem.php @@ -12,21 +12,15 @@ final class FolderExplorerItem extends AbstractExplorerItem { public function __construct( private readonly Folder $folder, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { } - /** - * @inheritDoc - */ public function getId(): int|string { return $this->folder->getId() ?? throw new \RuntimeException('Entity must have an ID'); } - /** - * @inheritDoc - */ public function getAlternativeDisplayable(): ?string { /** @var Folder|null $parent */ @@ -36,12 +30,10 @@ public function getAlternativeDisplayable(): ?string $parent->getTranslatedFolders()->first()->getName() : $parent->getName(); } + return ''; } - /** - * @inheritDoc - */ public function getDisplayable(): string { return $this->folder->getTranslatedFolders()->first() ? @@ -49,9 +41,6 @@ public function getDisplayable(): string $this->folder->getName(); } - /** - * @inheritDoc - */ public function getOriginal(): Folder { return $this->folder; @@ -60,7 +49,7 @@ public function getOriginal(): Folder protected function getEditItemPath(): ?string { return $this->urlGenerator->generate('foldersEditPage', [ - 'folderId' => $this->folder->getId() + 'folderId' => $this->folder->getId(), ]); } } diff --git a/lib/Rozier/src/Explorer/FoldersProvider.php b/lib/Rozier/src/Explorer/FoldersProvider.php index e1f58a41..9d7cb0e3 100644 --- a/lib/Rozier/src/Explorer/FoldersProvider.php +++ b/lib/Rozier/src/Explorer/FoldersProvider.php @@ -24,10 +24,7 @@ protected function getDefaultOrdering(): array return ['folderName' => 'ASC']; } - /** - * @inheritDoc - */ - public function supports($item): bool + public function supports(mixed $item): bool { if ($item instanceof Folder) { return true; diff --git a/lib/Rozier/src/Explorer/NodeExplorerItem.php b/lib/Rozier/src/Explorer/NodeExplorerItem.php index bfaefe87..90946545 100644 --- a/lib/Rozier/src/Explorer/NodeExplorerItem.php +++ b/lib/Rozier/src/Explorer/NodeExplorerItem.php @@ -19,7 +19,7 @@ final class NodeExplorerItem extends AbstractExplorerItem public function __construct( private readonly Node $node, private readonly UrlGeneratorInterface $urlGenerator, - private readonly Security $security + private readonly Security $security, ) { } @@ -55,6 +55,7 @@ public function getDisplayable(): string { /** @var NodesSources|false $nodeSource */ $nodeSource = $this->node->getNodeSources()->first(); + return false !== $nodeSource ? ($nodeSource->getTitle() ?? $this->node->getNodeName()) : $this->node->getNodeName(); @@ -76,6 +77,7 @@ public function getEditItemPath(): ?string 'nodeId' => $this->node->getId(), ]); } + return null; } @@ -88,6 +90,7 @@ public function getEditItemPath(): ?string 'translationId' => $translation->getId(), ]); } + return null; } @@ -97,6 +100,7 @@ public function getThumbnail(): ?DocumentInterface $nodeSource = $this->node->getNodeSources()->first(); /** @var NodesSourcesDocuments|false $thumbnail */ $thumbnail = false !== $nodeSource ? $nodeSource->getDocumentsByFields()->first() : false; + return $thumbnail ? $thumbnail->getDocument() : null; } diff --git a/lib/Rozier/src/Explorer/NodeSourceExplorerItem.php b/lib/Rozier/src/Explorer/NodeSourceExplorerItem.php index 3d2dbd38..f52e0d22 100644 --- a/lib/Rozier/src/Explorer/NodeSourceExplorerItem.php +++ b/lib/Rozier/src/Explorer/NodeSourceExplorerItem.php @@ -18,7 +18,7 @@ final class NodeSourceExplorerItem extends AbstractExplorerItem public function __construct( private readonly NodesSources $nodeSource, private readonly UrlGeneratorInterface $urlGenerator, - private readonly Security $security + private readonly Security $security, ) { } @@ -67,6 +67,7 @@ public function getEditItemPath(): ?string 'translationId' => $translation->getId(), ]); } + return null; } @@ -74,6 +75,7 @@ public function getThumbnail(): ?DocumentInterface { /** @var NodesSourcesDocuments|false $thumbnail */ $thumbnail = $this->nodeSource->getDocumentsByFields()->first(); + return $thumbnail ? $thumbnail->getDocument() : null; } diff --git a/lib/Rozier/src/Explorer/NodeTypeExplorerItem.php b/lib/Rozier/src/Explorer/NodeTypeExplorerItem.php index 91607473..e6a280b9 100644 --- a/lib/Rozier/src/Explorer/NodeTypeExplorerItem.php +++ b/lib/Rozier/src/Explorer/NodeTypeExplorerItem.php @@ -12,7 +12,7 @@ final class NodeTypeExplorerItem extends AbstractExplorerItem { public function __construct( private readonly NodeType $nodeType, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { } @@ -39,7 +39,7 @@ public function getOriginal(): NodeType protected function getEditItemPath(): ?string { return $this->urlGenerator->generate('nodeTypesEditPage', [ - 'nodeTypeId' => $this->nodeType->getId() + 'nodeTypeId' => $this->nodeType->getId(), ]); } diff --git a/lib/Rozier/src/Explorer/SettingExplorerItem.php b/lib/Rozier/src/Explorer/SettingExplorerItem.php index 9145f861..16d336eb 100644 --- a/lib/Rozier/src/Explorer/SettingExplorerItem.php +++ b/lib/Rozier/src/Explorer/SettingExplorerItem.php @@ -12,40 +12,29 @@ final class SettingExplorerItem extends AbstractExplorerItem { public function __construct( private readonly Setting $setting, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { } - /** - * @inheritDoc - */ public function getId(): int|string { return $this->setting->getId() ?? throw new \RuntimeException('Entity must have an ID'); } - /** - * @inheritDoc - */ public function getAlternativeDisplayable(): ?string { if (null !== $this->setting->getSettingGroup()) { return $this->setting->getSettingGroup()->getName(); } + return ''; } - /** - * @inheritDoc - */ public function getDisplayable(): string { return $this->setting->getName(); } - /** - * @inheritDoc - */ public function getOriginal(): Setting { return $this->setting; @@ -54,7 +43,7 @@ public function getOriginal(): Setting protected function getEditItemPath(): ?string { return $this->urlGenerator->generate('settingsEditPage', [ - 'settingId' => $this->setting->getId() + 'settingId' => $this->setting->getId(), ]); } } diff --git a/lib/Rozier/src/Explorer/SettingsProvider.php b/lib/Rozier/src/Explorer/SettingsProvider.php index f6809cc3..860b7f64 100644 --- a/lib/Rozier/src/Explorer/SettingsProvider.php +++ b/lib/Rozier/src/Explorer/SettingsProvider.php @@ -24,10 +24,7 @@ protected function getDefaultOrdering(): array return ['name' => 'ASC']; } - /** - * @inheritDoc - */ - public function supports($item): bool + public function supports(mixed $item): bool { if ($item instanceof Setting) { return true; diff --git a/lib/Rozier/src/Explorer/TagExplorerItem.php b/lib/Rozier/src/Explorer/TagExplorerItem.php index b69ec482..3765c297 100644 --- a/lib/Rozier/src/Explorer/TagExplorerItem.php +++ b/lib/Rozier/src/Explorer/TagExplorerItem.php @@ -12,14 +12,14 @@ final class TagExplorerItem extends AbstractExplorerItem { public function __construct( private readonly Tag $tag, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { } protected function getEditItemPath(): ?string { return $this->urlGenerator->generate('tagsEditPage', [ - 'tagId' => $this->tag->getId() + 'tagId' => $this->tag->getId(), ]); } @@ -55,11 +55,6 @@ public function getOriginal(): Tag return $this->tag; } - /** - * @param Tag $tag - * @param bool $slash - * @return string - */ private function getTagParents(Tag $tag, bool $slash = false): string { $result = ''; @@ -74,7 +69,7 @@ private function getTagParents(Tag $tag, bool $slash = false): string $name = $firstTrans->getName(); } - $result = $superParent . $name; + $result = $superParent.$name; if ($slash) { $result .= ' / '; diff --git a/lib/Rozier/src/Explorer/UserExplorerItem.php b/lib/Rozier/src/Explorer/UserExplorerItem.php index 60b1a32a..1bee803b 100644 --- a/lib/Rozier/src/Explorer/UserExplorerItem.php +++ b/lib/Rozier/src/Explorer/UserExplorerItem.php @@ -12,45 +12,34 @@ final class UserExplorerItem extends AbstractExplorerItem { public function __construct( private readonly User $user, - private readonly UrlGeneratorInterface $urlGenerator + private readonly UrlGeneratorInterface $urlGenerator, ) { } - /** - * @inheritDoc - */ public function getId(): int|string { return $this->user->getId() ?? throw new \RuntimeException('Entity must have an ID'); } - /** - * @inheritDoc - */ public function getAlternativeDisplayable(): ?string { return $this->user->getEmail(); } - /** - * @inheritDoc - */ public function getDisplayable(): string { $fullName = trim( - ($this->user->getFirstName() ?? '') . - ' ' . + ($this->user->getFirstName() ?? ''). + ' '. ($this->user->getLastName() ?? '') ); - if ($fullName !== '') { + if ('' !== $fullName) { return $fullName; } + return $this->user->getUsername(); } - /** - * @inheritDoc - */ public function getOriginal(): User { return $this->user; @@ -59,7 +48,7 @@ public function getOriginal(): User protected function getEditItemPath(): ?string { return $this->urlGenerator->generate('usersEditPage', [ - 'id' => $this->user->getId() + 'id' => $this->user->getId(), ]); } } diff --git a/lib/Rozier/src/Explorer/UsersProvider.php b/lib/Rozier/src/Explorer/UsersProvider.php index 102252a0..48578772 100644 --- a/lib/Rozier/src/Explorer/UsersProvider.php +++ b/lib/Rozier/src/Explorer/UsersProvider.php @@ -24,10 +24,7 @@ protected function getDefaultOrdering(): array return ['username' => 'ASC']; } - /** - * @inheritDoc - */ - public function supports($item): bool + public function supports(mixed $item): bool { if ($item instanceof User) { return true; diff --git a/lib/Rozier/src/Forms/AddUserType.php b/lib/Rozier/src/Forms/AddUserType.php index 2cbff0d7..63cc27e0 100644 --- a/lib/Rozier/src/Forms/AddUserType.php +++ b/lib/Rozier/src/Forms/AddUserType.php @@ -14,11 +14,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void parent::buildForm($builder, $options); $builder->add('groups', GroupsType::class, [ - 'label' => 'user.groups', - 'required' => false, - 'multiple' => true, - 'expanded' => true, - ]) + 'label' => 'user.groups', + 'required' => false, + 'multiple' => true, + 'expanded' => true, + ]) ; } diff --git a/lib/Rozier/src/Forms/CustomFormFieldType.php b/lib/Rozier/src/Forms/CustomFormFieldType.php index f0e25cd8..957404c4 100644 --- a/lib/Rozier/src/Forms/CustomFormFieldType.php +++ b/lib/Rozier/src/Forms/CustomFormFieldType.php @@ -19,12 +19,11 @@ class CustomFormFieldType extends AbstractType { public function __construct( - private readonly CustomFormFieldRepository $customFormFieldRepository + private readonly CustomFormFieldRepository $customFormFieldRepository, ) { } /** - * @param CustomFormField $field * @return string[] */ protected function getAllGroupsNames(CustomFormField $field): array @@ -35,9 +34,9 @@ protected function getAllGroupsNames(CustomFormField $field): array public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('label', TextType::class, [ - 'label' => 'label', - 'empty_data' => '', - ]) + 'label' => 'label', + 'empty_data' => '', + ]) ->add('description', MarkdownType::class, [ 'label' => 'description', 'required' => false, @@ -115,7 +114,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ], 'placeholder' => 'autocomplete.no_autocomplete', 'choice_label' => function ($choice, $key, $value) { - return 'autocomplete.' . $value; + return 'autocomplete.'.$value; }, 'required' => false, ]); diff --git a/lib/Rozier/src/Forms/CustomFormType.php b/lib/Rozier/src/Forms/CustomFormType.php index 57858f3b..cf805eed 100644 --- a/lib/Rozier/src/Forms/CustomFormType.php +++ b/lib/Rozier/src/Forms/CustomFormType.php @@ -23,9 +23,6 @@ class CustomFormType extends AbstractType { protected Security $security; - /** - * @param Security $security - */ public function __construct(Security $security) { $this->security = $security; @@ -66,7 +63,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'label' => 'customForm.retentionTime', 'help' => 'customForm.retentionTime.help', 'required' => false, - 'placeholder' => 'customForm.retentionTime.always', + 'placeholder' => 'customForm.retentionTime.always', 'choices' => [ 'customForm.retentionTime.one_week' => 'P7D', 'customForm.retentionTime.two_weeks' => 'P14D', @@ -75,13 +72,13 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'customForm.retentionTime.six_months' => 'P6M', 'customForm.retentionTime.one_year' => 'P1Y', 'customForm.retentionTime.two_years' => 'P2Y', - ] + ], ]); } $builder->add('open', CheckboxType::class, [ - 'label' => 'customForm.open', - 'required' => false, - ]) + 'label' => 'customForm.open', + 'required' => false, + ]) ->add('closeDate', DateTimeType::class, [ 'label' => 'customForm.closeDate', 'required' => false, diff --git a/lib/Rozier/src/Forms/DataTransformer/TagTransformer.php b/lib/Rozier/src/Forms/DataTransformer/TagTransformer.php index f90162b2..0d9fad58 100644 --- a/lib/Rozier/src/Forms/DataTransformer/TagTransformer.php +++ b/lib/Rozier/src/Forms/DataTransformer/TagTransformer.php @@ -13,9 +13,6 @@ class TagTransformer implements DataTransformerInterface { private ObjectManager $manager; - /** - * @param ObjectManager $manager - */ public function __construct(ObjectManager $manager) { $this->manager = $manager; @@ -23,6 +20,7 @@ public function __construct(ObjectManager $manager) /** * @param iterable|null $tags + * * @return array|string */ public function transform($tags) @@ -35,11 +33,13 @@ public function transform($tags) foreach ($tags as $tag) { $ids[] = $tag->getId(); } + return $ids; } /** * @param string|array $tagIds + * * @return array */ public function reverseTransform($tagIds) @@ -61,10 +61,7 @@ public function reverseTransform($tagIds) ->find($tagId) ; if (null === $tag) { - throw new TransformationFailedException(sprintf( - 'A tag with id "%s" does not exist!', - $tagId - )); + throw new TransformationFailedException(sprintf('A tag with id "%s" does not exist!', $tagId)); } $tags[] = $tag; diff --git a/lib/Rozier/src/Forms/DocumentEditType.php b/lib/Rozier/src/Forms/DocumentEditType.php index b016ee93..a5f19d06 100644 --- a/lib/Rozier/src/Forms/DocumentEditType.php +++ b/lib/Rozier/src/Forms/DocumentEditType.php @@ -8,6 +8,7 @@ use RZ\Roadiz\CoreBundle\Form\ColorType; use RZ\Roadiz\CoreBundle\Form\Constraint\UniqueFilename; use RZ\Roadiz\CoreBundle\Form\DocumentCollectionType; +use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; @@ -17,7 +18,6 @@ use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; -use Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Validator\Constraints\LessThanOrEqual; use Symfony\Component\Validator\Constraints\NotBlank; @@ -33,9 +33,6 @@ public function __construct(Security $security) $this->security = $security; } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { /** @var Document $document */ @@ -54,8 +51,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void new NotBlank(), new Regex([ 'pattern' => '/\.[a-z0-9]+$/i', - 'htmlPattern' => ".[a-z0-9]+$", - 'message' => 'value_is_not_a_valid_filename' + 'htmlPattern' => '.[a-z0-9]+$', + 'message' => 'value_is_not_a_valid_filename', ]), new UniqueFilename([ 'document' => $document, @@ -80,13 +77,13 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } $builder->add('newDocument', FileType::class, [ - 'label' => 'overwrite.document', - 'required' => false, - 'mapped' => false, - 'constraints' => [ - new File() - ], - ]) + 'label' => 'overwrite.document', + 'required' => false, + 'mapped' => false, + 'constraints' => [ + new File(), + ], + ]) ->add('embed', DocumentEmbedType::class, [ 'label' => 'document.embed', 'required' => false, @@ -103,18 +100,18 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if ($document->isImage() || $document->isVideo() || $document->isEmbed()) { $builder->add('imageWidth', IntegerType::class, [ 'label' => 'document.width', - 'required' => false + 'required' => false, ]); $builder->add('imageHeight', IntegerType::class, [ 'label' => 'document.height', - 'required' => false + 'required' => false, ]); } if ($document->isAudio() || $document->isVideo() || $document->isEmbed()) { $builder->add('mediaDuration', IntegerType::class, [ 'label' => 'document.duration', - 'required' => false + 'required' => false, ]); } @@ -133,14 +130,14 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->add('thumbnails', DocumentCollectionType::class, [ 'label' => 'document.thumbnails', 'multiple' => true, - 'required' => false + 'required' => false, ]); } $builder->add('folders', FolderCollectionType::class, [ 'label' => 'folders', 'multiple' => true, - 'required' => false + 'required' => false, ]); if ($this->security->isGranted('ROLE_ACCESS_DOCUMENTS_CREATION_DATE')) { @@ -160,18 +157,15 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'constraints' => [ new LessThanOrEqual($builder->getData()->getUpdatedAt()), new LessThanOrEqual('now'), - ] + ], ]); } } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ - 'data_class' => Document::class + 'data_class' => Document::class, ]); $resolver->setRequired('referer'); @@ -181,10 +175,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('document_platforms', ['array']); } - - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'document_edit'; diff --git a/lib/Rozier/src/Forms/DocumentEmbedType.php b/lib/Rozier/src/Forms/DocumentEmbedType.php index 74073030..660533c7 100644 --- a/lib/Rozier/src/Forms/DocumentEmbedType.php +++ b/lib/Rozier/src/Forms/DocumentEmbedType.php @@ -12,9 +12,6 @@ class DocumentEmbedType extends AbstractType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $services = []; @@ -32,18 +29,15 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'label' => 'document.platform', 'required' => true, 'choices' => $services, - 'placeholder' => 'document.no_embed_platform' + 'placeholder' => 'document.no_embed_platform', ]) ; - if ($options['required'] === false) { + if (false === $options['required']) { $builder->get('embedId')->setRequired(false); $builder->get('embedPlatform')->setRequired(false); } } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('required', true); @@ -51,10 +45,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('document_platforms', ['array']); } - - /** - * @inheritDoc - */ public function getBlockPrefix(): string { return 'document_embed'; diff --git a/lib/Rozier/src/Forms/DocumentTranslationType.php b/lib/Rozier/src/Forms/DocumentTranslationType.php index ea1fd10a..b9a1c4d9 100644 --- a/lib/Rozier/src/Forms/DocumentTranslationType.php +++ b/lib/Rozier/src/Forms/DocumentTranslationType.php @@ -17,9 +17,9 @@ class DocumentTranslationType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('referer', HiddenType::class, [ - 'data' => $options['referer'], - 'mapped' => false, - ]) + 'data' => $options['referer'], + 'mapped' => false, + ]) ->add('name', TextType::class, [ 'label' => 'name', 'required' => false, @@ -38,13 +38,10 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ - 'data_class' => DocumentTranslation::class + 'data_class' => DocumentTranslation::class, ]); $resolver->setRequired('referer'); diff --git a/lib/Rozier/src/Forms/DynamicType.php b/lib/Rozier/src/Forms/DynamicType.php index dbaf6999..000e8994 100644 --- a/lib/Rozier/src/Forms/DynamicType.php +++ b/lib/Rozier/src/Forms/DynamicType.php @@ -11,24 +11,16 @@ class DynamicType extends AbstractType { - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextareaType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'dynamic'; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -37,8 +29,8 @@ public function configureOptions(OptionsResolver $resolver): void 'class' => 'dynamic_textarea', ], 'constraints' => [ - new ValidYaml() - ] + new ValidYaml(), + ], ]); } } diff --git a/lib/Rozier/src/Forms/FolderCollectionType.php b/lib/Rozier/src/Forms/FolderCollectionType.php index c580bf84..51d0cf08 100644 --- a/lib/Rozier/src/Forms/FolderCollectionType.php +++ b/lib/Rozier/src/Forms/FolderCollectionType.php @@ -7,7 +7,7 @@ use Doctrine\Persistence\ManagerRegistry; use RZ\Roadiz\CoreBundle\Entity\Folder; use RZ\Roadiz\CoreBundle\Form\DataTransformer\FolderCollectionTransformer; -use Symfony\Component\Form\AbstractType as AbstractType; +use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; @@ -21,11 +21,6 @@ public function __construct(private readonly ManagerRegistry $managerRegistry) { } - /** - * @param FormView $view - * @param FormInterface $form - * @param array $options - */ public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); @@ -33,9 +28,6 @@ public function buildView(FormView $view, FormInterface $form, array $options): $view->vars['provider_class'] = FoldersProvider::class; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -46,12 +38,6 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - /** - * {@inheritdoc} - * - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addModelTransformer(new FolderCollectionTransformer( @@ -60,17 +46,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void )); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'folders'; diff --git a/lib/Rozier/src/Forms/GeoJsonType.php b/lib/Rozier/src/Forms/GeoJsonType.php index 7cefd14c..49c8ec55 100644 --- a/lib/Rozier/src/Forms/GeoJsonType.php +++ b/lib/Rozier/src/Forms/GeoJsonType.php @@ -20,9 +20,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void })); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'geojson'; diff --git a/lib/Rozier/src/Forms/GroupType.php b/lib/Rozier/src/Forms/GroupType.php index 51e21a2c..b91e59b8 100644 --- a/lib/Rozier/src/Forms/GroupType.php +++ b/lib/Rozier/src/Forms/GroupType.php @@ -12,9 +12,6 @@ class GroupType extends AbstractType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('name', TextType::class, [ @@ -23,9 +20,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ diff --git a/lib/Rozier/src/Forms/ImageCropAlignmentType.php b/lib/Rozier/src/Forms/ImageCropAlignmentType.php index 5a79bd2d..dce7100b 100644 --- a/lib/Rozier/src/Forms/ImageCropAlignmentType.php +++ b/lib/Rozier/src/Forms/ImageCropAlignmentType.php @@ -27,7 +27,7 @@ public function configureOptions(OptionsResolver $resolver): void 'image_crop_alignment.bottom-left' => 'bottom-left', 'image_crop_alignment.bottom' => 'bottom', 'image_crop_alignment.bottom-right' => 'bottom-right', - ] + ], ]); } @@ -36,7 +36,6 @@ public function getBlockPrefix(): string return 'image_crop_alignment'; } - public function getParent(): string { return ChoiceType::class; diff --git a/lib/Rozier/src/Forms/LoginType.php b/lib/Rozier/src/Forms/LoginType.php index 3f88811c..52e94899 100644 --- a/lib/Rozier/src/Forms/LoginType.php +++ b/lib/Rozier/src/Forms/LoginType.php @@ -22,25 +22,18 @@ class LoginType extends AbstractType protected UrlGeneratorInterface $urlGenerator; protected RequestStack $requestStack; - /** - * @param UrlGeneratorInterface $urlGenerator - * @param RequestStack $requestStack - */ public function __construct(UrlGeneratorInterface $urlGenerator, RequestStack $requestStack) { $this->urlGenerator = $urlGenerator; $this->requestStack = $requestStack; } - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('_username', TextType::class, [ 'label' => 'username', 'attr' => [ - 'autocomplete' => 'username' + 'autocomplete' => 'username', ], 'constraints' => [ new NotNull(), @@ -50,7 +43,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ->add('_password', PasswordType::class, [ 'label' => 'password', 'attr' => [ - 'autocomplete' => 'current-password' + 'autocomplete' => 'current-password', ], 'constraints' => [ new NotNull(), @@ -61,20 +54,17 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'label' => 'keep_me_logged_in', 'required' => false, 'attr' => [ - 'checked' => true + 'checked' => true, ], ]); if ($this->requestStack->getMainRequest()?->query->has('_home')) { $builder->add('_target_path', HiddenType::class, [ - 'data' => $this->urlGenerator->generate('adminHomePage') + 'data' => $this->urlGenerator->generate('adminHomePage'), ]); } } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setNormalizer('action', function (Options $options) { @@ -82,9 +72,6 @@ public function configureOptions(OptionsResolver $resolver): void }); } - /** - * @inheritDoc - */ public function getBlockPrefix(): string { /* diff --git a/lib/Rozier/src/Forms/Node/AddNodeType.php b/lib/Rozier/src/Forms/Node/AddNodeType.php index ffc863f6..886aacd0 100644 --- a/lib/Rozier/src/Forms/Node/AddNodeType.php +++ b/lib/Rozier/src/Forms/Node/AddNodeType.php @@ -24,18 +24,11 @@ class AddNodeType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('title', TextType::class, [ @@ -46,12 +39,12 @@ public function buildForm(FormBuilderInterface $builder, array $options): void new NotNull(), new NotBlank(), new Length([ - 'max' => 255 - ]) + 'max' => 255, + ]), ], ]); - if ($options['showNodeType'] === true) { + if (true === $options['showNodeType']) { $builder->add('nodeType', NodeTypesType::class, [ 'label' => 'nodeType', 'constraints' => [ @@ -112,17 +105,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void }); } - /** - * @return string - */ public function getBlockPrefix(): string { return 'childnode'; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ diff --git a/lib/Rozier/src/Forms/NodeSource/AbstractConfigurableNodeSourceFieldType.php b/lib/Rozier/src/Forms/NodeSource/AbstractConfigurableNodeSourceFieldType.php index 752fe133..928ee059 100644 --- a/lib/Rozier/src/Forms/NodeSource/AbstractConfigurableNodeSourceFieldType.php +++ b/lib/Rozier/src/Forms/NodeSource/AbstractConfigurableNodeSourceFieldType.php @@ -6,17 +6,9 @@ use Symfony\Component\Yaml\Yaml; -/** - * @package RZ\Roadiz\CMS\Forms\NodeSource - */ abstract class AbstractConfigurableNodeSourceFieldType extends AbstractNodeSourceFieldType { - /** - * @param array $options - * - * @return mixed - */ - protected function getFieldConfiguration(array $options) + protected function getFieldConfiguration(array $options): mixed { return Yaml::parse($options['nodeTypeField']->getDefaultValues() ?? ''); } diff --git a/lib/Rozier/src/Forms/NodeSource/AbstractNodeSourceFieldType.php b/lib/Rozier/src/Forms/NodeSource/AbstractNodeSourceFieldType.php index b8ad2c6d..5b16afb9 100644 --- a/lib/Rozier/src/Forms/NodeSource/AbstractNodeSourceFieldType.php +++ b/lib/Rozier/src/Forms/NodeSource/AbstractNodeSourceFieldType.php @@ -17,9 +17,6 @@ abstract class AbstractNodeSourceFieldType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; @@ -27,10 +24,6 @@ public function __construct(ManagerRegistry $managerRegistry) /** * Pass nodeSource to form twig template. - * - * @param FormView $view - * @param FormInterface $form - * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options): void { @@ -40,9 +33,6 @@ public function buildView(FormView $view, FormInterface $form, array $options): $view->vars['nodeTypeField'] = $options['nodeTypeField']; } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -56,10 +46,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('nodeTypeField', [NodeTypeField::class]); } - - /** - * {@inheritdoc} - */ public function getParent(): ?string { return HiddenType::class; diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceBaseType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceBaseType.php index 755a2f78..4ca983f4 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceBaseType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceBaseType.php @@ -15,10 +15,6 @@ final class NodeSourceBaseType extends AbstractType { - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('title', TextType::class, [ @@ -26,24 +22,24 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'empty_data' => '', 'required' => false, 'attr' => [ - 'data-dev-name' => '{{ nodeSource.' . StringHandler::camelCase('title') . ' }}', + 'data-dev-name' => '{{ nodeSource.'.StringHandler::camelCase('title').' }}', 'lang' => \mb_strtolower(str_replace('_', '-', $options['translation']->getLocale())), 'dir' => $options['translation']->isRtl() ? 'rtl' : 'ltr', ], 'constraints' => [ new Length([ 'max' => 255, - ]) - ] + ]), + ], ]); - if ($options['publishable'] === true) { + if (true === $options['publishable']) { $builder->add('publishedAt', DateTimeType::class, [ 'label' => 'publishedAt', 'required' => false, 'attr' => [ 'class' => 'rz-datetime-field', - 'data-dev-name' => '{{ nodeSource.' . StringHandler::camelCase('publishedAt') . ' }}', + 'data-dev-name' => '{{ nodeSource.'.StringHandler::camelCase('publishedAt').' }}', ], 'date_widget' => 'single_text', 'date_format' => 'yyyy-MM-dd', @@ -55,17 +51,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'nodesourcebase'; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceCollectionType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceCollectionType.php index 583d01e6..7a548399 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceCollectionType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceCollectionType.php @@ -11,9 +11,6 @@ final class NodeSourceCollectionType extends CollectionType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { parent::buildForm($builder, $options); diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceCustomFormType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceCustomFormType.php index be552197..5e9fb0f9 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceCustomFormType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceCustomFormType.php @@ -14,22 +14,15 @@ use Symfony\Component\Form\FormEvents; use Symfony\Component\OptionsResolver\OptionsResolver; -/** - * @package RZ\Roadiz\CMS\Forms\NodeSource - */ final class NodeSourceCustomFormType extends AbstractNodeSourceFieldType { public function __construct( ManagerRegistry $managerRegistry, - private readonly NodeHandler $nodeHandler + private readonly NodeHandler $nodeHandler, ) { parent::__construct($managerRegistry); } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener( @@ -43,9 +36,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -59,17 +49,11 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'custom_forms'; } - /** - * @param FormEvent $event - */ public function onPreSetData(FormEvent $event): void { /** @var NodesSources $nodeSource */ @@ -83,9 +67,6 @@ public function onPreSetData(FormEvent $event): void ->findByNodeAndFieldName($nodeSource->getNode(), $nodeTypeField->getName())); } - /** - * @param FormEvent $event - */ public function onPostSubmit(FormEvent $event): void { /** @var NodesSources $nodeSource */ @@ -104,11 +85,11 @@ public function onPostSubmit(FormEvent $event): void /** @var CustomForm|null $tempCForm */ $tempCForm = $manager->find(CustomForm::class, (int) $customFormId); - if ($tempCForm !== null) { + if (null !== $tempCForm) { $this->nodeHandler->addCustomFormForField($tempCForm, $nodeTypeField, false, $position); - $position++; + ++$position; } else { - throw new \RuntimeException('Custom form #' . $customFormId . ' was not found during relationship creation.'); + throw new \RuntimeException('Custom form #'.$customFormId.' was not found during relationship creation.'); } } } diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceDocumentType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceDocumentType.php index efcce674..48eff69e 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceDocumentType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceDocumentType.php @@ -14,22 +14,15 @@ use Symfony\Component\Form\FormEvents; use Symfony\Component\OptionsResolver\OptionsResolver; -/** - * @package RZ\Roadiz\CMS\Forms\NodeSource - */ final class NodeSourceDocumentType extends AbstractNodeSourceFieldType { public function __construct( ManagerRegistry $managerRegistry, - private readonly NodesSourcesHandler $nodesSourcesHandler + private readonly NodesSourcesHandler $nodesSourcesHandler, ) { parent::__construct($managerRegistry); } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener( @@ -43,9 +36,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -63,17 +53,11 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'documents'; } - /** - * @param FormEvent $event - */ public function onPreSetData(FormEvent $event): void { /** @var NodesSources $nodeSource */ @@ -90,8 +74,6 @@ public function onPreSetData(FormEvent $event): void } /** - * @param FormEvent $event - * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException @@ -113,11 +95,11 @@ public function onPostSubmit(FormEvent $event): void /** @var Document|null $tempDoc */ $tempDoc = $manager->find(Document::class, (int) $documentId); - if ($tempDoc !== null) { + if (null !== $tempDoc) { $this->nodesSourcesHandler->addDocumentForField($tempDoc, $nodeTypeField, false, $position); - $position++; + ++$position; } else { - throw new \RuntimeException('Document #' . $documentId . ' was not found during relationship creation.'); + throw new \RuntimeException('Document #'.$documentId.' was not found during relationship creation.'); } } } diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceJoinType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceJoinType.php index b7810c44..88da3918 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceJoinType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceJoinType.php @@ -14,9 +14,6 @@ final class NodeSourceJoinType extends AbstractConfigurableNodeSourceFieldType { - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -27,10 +24,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefault('multiple', true); } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $configuration = $this->getFieldConfiguration($options); @@ -44,10 +37,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void /** * Pass data to form twig template. - * - * @param FormView $view - * @param FormInterface $form - * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options): void { @@ -93,9 +82,6 @@ public function buildView(FormView $view, FormInterface $form, array $options): $view->vars['data'] = $displayableData; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'join'; diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceNodeType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceNodeType.php index 779badd0..d59bed96 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceNodeType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceNodeType.php @@ -15,9 +15,6 @@ use Symfony\Component\Form\FormEvents; use Symfony\Component\OptionsResolver\OptionsResolver; -/** - * @package RZ\Roadiz\CMS\Forms\NodeSource - */ final class NodeSourceNodeType extends AbstractNodeSourceFieldType { public function __construct(ManagerRegistry $managerRegistry, private readonly NodeHandler $nodeHandler) @@ -25,10 +22,6 @@ public function __construct(ManagerRegistry $managerRegistry, private readonly N parent::__construct($managerRegistry); } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener( @@ -42,9 +35,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -58,17 +48,11 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'nodes'; } - /** - * @param FormEvent $event - */ public function onPreSetData(FormEvent $event): void { /** @var NodesSources $nodeSource */ @@ -87,9 +71,6 @@ public function onPreSetData(FormEvent $event): void )); } - /** - * @param FormEvent $event - */ public function onPostSubmit(FormEvent $event): void { /** @var NodesSources $nodeSource */ @@ -108,11 +89,11 @@ public function onPostSubmit(FormEvent $event): void /** @var Node|null $tempNode */ $tempNode = $manager->find(Node::class, (int) $nodeId); - if ($tempNode !== null) { + if (null !== $tempNode) { $this->nodeHandler->addNodeForField($tempNode, $nodeTypeField, false, $position); - $position++; + ++$position; } else { - throw new \RuntimeException('Node #' . $nodeId . ' was not found during relationship creation.'); + throw new \RuntimeException('Node #'.$nodeId.' was not found during relationship creation.'); } } } diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceProviderType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceProviderType.php index 7d3a1c63..acaee5e3 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceProviderType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceProviderType.php @@ -23,9 +23,6 @@ public function __construct(ManagerRegistry $managerRegistry, private readonly C parent::__construct($managerRegistry); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -40,14 +37,11 @@ public function configureOptions(OptionsResolver $resolver): void if ($nodeTypeField->isMultipleProvider()) { return true; } + return false; }); } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $configuration = $this->getFieldConfiguration($options); @@ -74,10 +68,6 @@ protected function getProvider(array $configuration, array $options): ExplorerPr /** * Pass data to form twig template. - * - * @param FormView $view - * @param FormInterface $form - * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options): void { @@ -126,9 +116,6 @@ public function buildView(FormView $view, FormInterface $form, array $options): } } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'provider'; diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceSeoType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceSeoType.php index c102d487..6bb9c28f 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceSeoType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceSeoType.php @@ -13,30 +13,23 @@ use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\Length; -/** - * @package RZ\Roadiz\CMS\Forms\NodeSource - */ final class NodeSourceSeoType extends AbstractType { - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('metaTitle', TextType::class, [ - 'label' => 'metaTitle', - 'help' => 'nodeSource.metaTitle.help', - 'required' => false, - 'attr' => [ - 'data-max-length' => 80, - ], - 'constraints' => [ - new Length([ - 'max' => 80 - ]) - ] - ]) + 'label' => 'metaTitle', + 'help' => 'nodeSource.metaTitle.help', + 'required' => false, + 'attr' => [ + 'data-max-length' => 80, + ], + 'constraints' => [ + new Length([ + 'max' => 80, + ]), + ], + ]) ->add('metaDescription', TextareaType::class, [ 'label' => 'metaDescription', 'help' => 'nodeSource.metaDescription.help', @@ -50,9 +43,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ diff --git a/lib/Rozier/src/Forms/NodeSource/NodeSourceType.php b/lib/Rozier/src/Forms/NodeSource/NodeSourceType.php index 22aab62a..c2417880 100644 --- a/lib/Rozier/src/Forms/NodeSource/NodeSourceType.php +++ b/lib/Rozier/src/Forms/NodeSource/NodeSourceType.php @@ -43,20 +43,18 @@ final class NodeSourceType extends AbstractType { public function __construct( private readonly ManagerRegistry $managerRegistry, - private readonly Security $security + private readonly Security $security, ) { } /** - * @param FormBuilderInterface $builder - * @param array $options * @throws \ReflectionException */ public function buildForm(FormBuilderInterface $builder, array $options): void { $fields = $this->getFieldsForSource($builder->getData(), $options['nodeType']); - if ($options['withTitle'] === true) { + if (true === $options['withTitle']) { $builder->add('base', NodeSourceBaseType::class, [ 'publishable' => $options['nodeType']->isPublishable(), 'translation' => $builder->getData()->getTranslation(), @@ -67,7 +65,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if (!$this->security->isGranted(NodeTypeFieldVoter::VIEW, $field)) { continue; } - if ($options['withVirtual'] === true || !$field->isVirtual()) { + if (true === $options['withVirtual'] || !$field->isVirtual()) { $builder->add( $field->getVarName(), self::getFormTypeFromFieldType($field), @@ -77,9 +75,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -97,17 +92,12 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('class', 'string'); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'source'; } /** - * @param NodesSources $source - * @param NodeType $nodeType * @return array */ private function getFieldsForSource(NodesSources $source, NodeType $nodeType): array @@ -128,19 +118,11 @@ private function getFieldsForSource(NodesSources $source, NodeType $nodeType): a return $this->managerRegistry->getRepository(NodeTypeField::class)->findBy($criteria, $position); } - /** - * @param NodesSources $source - * @return bool - */ private function needsUniversalFields(NodesSources $source): bool { - return ($source->getTranslation()->isDefaultTranslation() || !$this->hasDefaultTranslation($source)); + return $source->getTranslation()->isDefaultTranslation() || !$this->hasDefaultTranslation($source); } - /** - * @param NodesSources $source - * @return bool - */ private function hasDefaultTranslation(NodesSources $source): bool { /** @var Translation $defaultTranslation */ @@ -155,13 +137,12 @@ private function hasDefaultTranslation(NodesSources $source): bool 'translation' => $defaultTranslation, ]); - return $sourceCount === 1; + return 1 === $sourceCount; } /** * Returns a Symfony Form type according to a node-type field. * - * @param AbstractField $field * @return class-string */ public static function getFormTypeFromFieldType(AbstractField $field): string @@ -256,10 +237,8 @@ public static function getFormTypeFromFieldType(AbstractField $field): string * Returns an option array for creating a Symfony Form * according to a node-type field. * - * @param NodesSources $nodeSource - * @param NodeTypeField $field - * @param array $formOptions * @return array + * * @throws \ReflectionException */ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeField $field, array &$formOptions) @@ -287,7 +266,7 @@ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeFi 'data-nodetypes' => json_encode(explode( ',', $field->getDefaultValues() ?? '' - )) + )), ], ]); break; @@ -327,8 +306,8 @@ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeFi 'constraints' => [ new Email(), new Length([ - 'max' => 255 - ]) + 'max' => 255, + ]), ], ]); break; @@ -336,8 +315,8 @@ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeFi $options = array_merge_recursive($options, [ 'constraints' => [ new Length([ - 'max' => 255 - ]) + 'max' => 255, + ]), ], ]); break; @@ -366,7 +345,7 @@ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeFi case AbstractField::CHILDREN_T: $options = array_merge_recursive($options, [ 'nodeSource' => $nodeSource, - 'nodeTypeField' => $field + 'nodeTypeField' => $field, ]); break; case AbstractField::COUNTRY_T: @@ -376,7 +355,7 @@ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeFi if ('' !== $field->getPlaceholder()) { $options['placeholder'] = $field->getPlaceholder(); } - if ($field->getDefaultValues() !== '') { + if ('' !== $field->getDefaultValues()) { $countries = explode(',', $field->getDefaultValues() ?? ''); $countries = array_map('trim', $countries); $options = array_merge_recursive($options, [ @@ -390,11 +369,11 @@ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeFi 'allow_add' => true, 'allow_delete' => true, 'attr' => [ - 'class' => 'rz-collection-form-type' + 'class' => 'rz-collection-form-type', ], 'entry_options' => [ 'label' => false, - ] + ], ]; if (isset($configuration['entry_type'])) { $reflectionClass = new \ReflectionClass($configuration['entry_type']); @@ -411,16 +390,11 @@ public function getFormOptionsFromFieldType(NodesSources $nodeSource, NodeTypeFi /** * Get common options for your node-type field form components. - * - * @param NodesSources $nodeSource - * @param NodeTypeField $field - * @param array $formOptions - * @return array */ public function getDefaultOptions(NodesSources $nodeSource, NodeTypeField $field, array &$formOptions): array { $label = $field->getLabel(); - $devName = '{{ nodeSource.' . $field->getVarName() . ' }}'; + $devName = '{{ nodeSource.'.$field->getVarName().' }}'; $options = [ 'label' => $label, 'required' => false, @@ -429,8 +403,8 @@ public function getDefaultOptions(NodesSources $nodeSource, NodeTypeField $field $field->getGroupName() : 'default', 'data-field-group-canonical' => ( - null !== $field->getGroupNameCanonical() && - '' != $field->getGroupNameCanonical() + null !== $field->getGroupNameCanonical() + && '' != $field->getGroupNameCanonical() ) ? $field->getGroupNameCanonical() : 'default', 'data-dev-name' => $devName, 'autocomplete' => 'off', @@ -454,22 +428,22 @@ public function getDefaultOptions(NodesSources $nodeSource, NodeTypeField $field $options['attr']['data-max-length'] = $field->getMaxLength(); } if ( - $field->isVirtual() && - $field->getType() !== AbstractField::MANY_TO_ONE_T && - $field->getType() !== AbstractField::MANY_TO_MANY_T + $field->isVirtual() + && AbstractField::MANY_TO_ONE_T !== $field->getType() + && AbstractField::MANY_TO_MANY_T !== $field->getType() ) { $options['mapped'] = false; } if ( in_array($field->getType(), [ - AbstractField::MANY_TO_ONE_T, - AbstractField::MANY_TO_MANY_T, - AbstractField::DOCUMENTS_T, - AbstractField::NODES_T, - AbstractField::CUSTOM_FORMS_T, - AbstractField::MULTI_PROVIDER_T, - AbstractField::SINGLE_PROVIDER_T, + AbstractField::MANY_TO_ONE_T, + AbstractField::MANY_TO_MANY_T, + AbstractField::DOCUMENTS_T, + AbstractField::NODES_T, + AbstractField::CUSTOM_FORMS_T, + AbstractField::MULTI_PROVIDER_T, + AbstractField::SINGLE_PROVIDER_T, ]) ) { $options['nodeTypeField'] = $field; @@ -477,7 +451,7 @@ public function getDefaultOptions(NodesSources $nodeSource, NodeTypeField $field unset($options['attr']['dir']); } - if ($field->getType() === AbstractField::CHILDREN_T) { + if (AbstractField::CHILDREN_T === $field->getType()) { unset($options['attr']['dir']); } diff --git a/lib/Rozier/src/Forms/NodeTreeType.php b/lib/Rozier/src/Forms/NodeTreeType.php index b1cbc3d9..71bded78 100644 --- a/lib/Rozier/src/Forms/NodeTreeType.php +++ b/lib/Rozier/src/Forms/NodeTreeType.php @@ -32,17 +32,11 @@ class NodeTreeType extends AbstractType protected ManagerRegistry $managerRegistry; protected TreeWidgetFactory $treeWidgetFactory; - /** - * @param AuthorizationCheckerInterface $authorizationChecker - * @param RequestStack $requestStack - * @param ManagerRegistry $managerRegistry - * @param TreeWidgetFactory $treeWidgetFactory - */ public function __construct( AuthorizationCheckerInterface $authorizationChecker, RequestStack $requestStack, ManagerRegistry $managerRegistry, - TreeWidgetFactory $treeWidgetFactory + TreeWidgetFactory $treeWidgetFactory, ) { $this->authorizationChecker = $authorizationChecker; $this->requestStack = $requestStack; @@ -50,19 +44,12 @@ public function __construct( $this->managerRegistry = $managerRegistry; } - /** - * {@inheritdoc} - * - * @param FormView $view - * @param FormInterface $form - * @param array $options - */ public function finishView(FormView $view, FormInterface $form, array $options): void { parent::finishView($view, $form, $options); - if ($options['nodeTypeField']->getType() !== AbstractField::CHILDREN_T) { - throw new \RuntimeException("Given field is not a NodeTypeField::CHILDREN_T field.", 1); + if (AbstractField::CHILDREN_T !== $options['nodeTypeField']->getType()) { + throw new \RuntimeException('Given field is not a NodeTypeField::CHILDREN_T field.', 1); } $view->vars['authorizationChecker'] = $this->authorizationChecker; @@ -97,7 +84,7 @@ public function finishView(FormView $view, FormInterface $form, array $options): */ if (is_array($nodeTypes) && count($nodeTypes) > 0) { $nodeTree->setAdditionalCriteria([ - 'nodeType' => $nodeTypes + 'nodeType' => $nodeTypes, ]); } @@ -110,24 +97,17 @@ public function finishView(FormView $view, FormInterface $form, array $options): Node::getStatusLabel(Node::DELETED) => Node::DELETED, ]; } - /** - * {@inheritdoc} - */ + public function getParent(): ?string { return HiddenType::class; } - /** - * {@inheritdoc} - */ + public function getBlockPrefix(): string { return 'childrennodes'; } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired([ diff --git a/lib/Rozier/src/Forms/NodeType.php b/lib/Rozier/src/Forms/NodeType.php index 9cf491af..0f394e2a 100644 --- a/lib/Rozier/src/Forms/NodeType.php +++ b/lib/Rozier/src/Forms/NodeType.php @@ -18,10 +18,10 @@ class NodeType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('nodeName', TextType::class, [ - 'label' => 'nodeName', - 'empty_data' => '', - 'help' => 'node.nodeName.help', - ]) + 'label' => 'nodeName', + 'empty_data' => '', + 'help' => 'node.nodeName.help', + ]) ->add('dynamicNodeName', CheckboxType::class, [ 'label' => 'node.dynamicNodeName', 'required' => false, @@ -41,9 +41,9 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } $builder->add('childrenOrder', ChoiceType::class, [ - 'label' => 'node.childrenOrder', - 'choices' => Node::$orderingFields, - ]) + 'label' => 'node.childrenOrder', + 'choices' => Node::$orderingFields, + ]) ->add('childrenOrderDirection', ChoiceType::class, [ 'label' => 'node.childrenOrderDirection', 'choices' => [ diff --git a/lib/Rozier/src/Forms/NodeTypeFieldSerializationType.php b/lib/Rozier/src/Forms/NodeTypeFieldSerializationType.php index 38079b02..c151f0c3 100644 --- a/lib/Rozier/src/Forms/NodeTypeFieldSerializationType.php +++ b/lib/Rozier/src/Forms/NodeTypeFieldSerializationType.php @@ -17,9 +17,6 @@ final class NodeTypeFieldSerializationType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('excludedFromSerialization', CheckboxType::class, [ @@ -35,8 +32,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ], 'constraints' => [ new GreaterThan([ - 'value' => 0 - ]) + 'value' => 0, + ]), ], ]) ->add('serializationExclusionExpression', TextareaType::class, [ @@ -45,7 +42,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'help' => 'exclude_this_field_from_api_serialization_if_expression_result_is_true', 'attr' => [ 'placeholder' => 'enter_symfony_expression_language_with_object_as_var_name', - ] + ], ]) ->add('serializationGroups', CollectionType::class, [ 'label' => 'nodeTypeField.serializationGroups', @@ -53,12 +50,12 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'allow_add' => true, 'allow_delete' => true, 'attr' => [ - 'class' => 'rz-collection-form-type' + 'class' => 'rz-collection-form-type', ], 'entry_options' => [ 'label' => false, ], - 'entry_type' => TextType::class + 'entry_type' => TextType::class, ]); } @@ -70,17 +67,11 @@ public function configureOptions(OptionsResolver $resolver): void ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return ''; } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return FormType::class; diff --git a/lib/Rozier/src/Forms/NodeTypeFieldType.php b/lib/Rozier/src/Forms/NodeTypeFieldType.php index 2d779998..d8192854 100644 --- a/lib/Rozier/src/Forms/NodeTypeFieldType.php +++ b/lib/Rozier/src/Forms/NodeTypeFieldType.php @@ -113,7 +113,7 @@ public function configureOptions(OptionsResolver $resolver): void 'data_class' => NodeTypeField::class, 'attr' => [ 'class' => 'uk-form node-type-field-form', - ] + ], ]); } } diff --git a/lib/Rozier/src/Forms/RedirectionType.php b/lib/Rozier/src/Forms/RedirectionType.php index 1839e8ce..278b6f41 100644 --- a/lib/Rozier/src/Forms/RedirectionType.php +++ b/lib/Rozier/src/Forms/RedirectionType.php @@ -20,11 +20,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->add('query', TextType::class, [ 'label' => (!$options['only_query']) ? 'redirection.query' : false, 'attr' => [ - 'placeholder' => $options['placeholder'] + 'placeholder' => $options['placeholder'], ], 'empty_data' => '', ]); - if ($options['only_query'] === false) { + if (false === $options['only_query']) { $builder->add('redirectUri', TextareaType::class, [ 'label' => 'redirection.redirect_uri', 'required' => false, @@ -34,7 +34,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'choices' => [ 'redirection.moved_permanently' => Response::HTTP_MOVED_PERMANENTLY, 'redirection.moved_temporarily' => Response::HTTP_FOUND, - ] + ], ]); } } @@ -52,7 +52,7 @@ public function configureOptions(OptionsResolver $resolver): void 'placeholder' => null, 'attr' => [ 'class' => 'uk-form redirection-form', - ] + ], ]); } } diff --git a/lib/Rozier/src/Forms/RoleType.php b/lib/Rozier/src/Forms/RoleType.php index 5fcebdca..a485ed8c 100644 --- a/lib/Rozier/src/Forms/RoleType.php +++ b/lib/Rozier/src/Forms/RoleType.php @@ -12,9 +12,6 @@ class RoleType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('name', TextType::class, [ @@ -23,17 +20,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', Role::class); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'role'; diff --git a/lib/Rozier/src/Forms/SettingGroupType.php b/lib/Rozier/src/Forms/SettingGroupType.php index 9badaa0c..4fde99b8 100644 --- a/lib/Rozier/src/Forms/SettingGroupType.php +++ b/lib/Rozier/src/Forms/SettingGroupType.php @@ -13,9 +13,6 @@ class SettingGroupType extends AbstractType { - /** - * @inheritDoc - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add( @@ -36,9 +33,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ); } - /** - * @inheritDoc - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', SettingGroup::class); diff --git a/lib/Rozier/src/Forms/TagTranslationType.php b/lib/Rozier/src/Forms/TagTranslationType.php index da47e861..8030002c 100644 --- a/lib/Rozier/src/Forms/TagTranslationType.php +++ b/lib/Rozier/src/Forms/TagTranslationType.php @@ -20,17 +20,17 @@ class TagTranslationType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('name', TextType::class, [ - 'label' => 'name', - 'empty_data' => '', - 'constraints' => [ - new NotNull(), - new NotBlank(), - // Allow users to rename Tag the same, but tag slug must be different! - new Length([ - 'max' => 255, - ]) - ], - ]) + 'label' => 'name', + 'empty_data' => '', + 'constraints' => [ + new NotNull(), + new NotBlank(), + // Allow users to rename Tag the same, but tag slug must be different! + new Length([ + 'max' => 255, + ]), + ], + ]) ->add('description', MarkdownType::class, [ 'label' => 'description', 'required' => false, diff --git a/lib/Rozier/src/Forms/TagType.php b/lib/Rozier/src/Forms/TagType.php index 914520cb..df3a9085 100644 --- a/lib/Rozier/src/Forms/TagType.php +++ b/lib/Rozier/src/Forms/TagType.php @@ -48,8 +48,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ->add('childrenOrderDirection', ChoiceType::class, [ 'label' => 'tag.childrenOrderDirection', 'choices' => [ - 'ascendant' => 'ASC', - 'descendant' => 'DESC', + 'ascendant' => 'ASC', + 'descendant' => 'DESC', ], ]); } diff --git a/lib/Rozier/src/Forms/TranslationType.php b/lib/Rozier/src/Forms/TranslationType.php index b19592dd..f8333b36 100644 --- a/lib/Rozier/src/Forms/TranslationType.php +++ b/lib/Rozier/src/Forms/TranslationType.php @@ -31,7 +31,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]) ->add('overrideLocale', TextType::class, [ 'label' => 'overrideLocale', - 'required' => false + 'required' => false, ]); } diff --git a/lib/Rozier/src/Forms/TranstypeType.php b/lib/Rozier/src/Forms/TranstypeType.php index bb32d3b5..0c502d76 100644 --- a/lib/Rozier/src/Forms/TranstypeType.php +++ b/lib/Rozier/src/Forms/TranstypeType.php @@ -18,18 +18,11 @@ class TranstypeType extends AbstractType { protected ManagerRegistry $managerRegistry; - /** - * @param ManagerRegistry $managerRegistry - */ public function __construct(ManagerRegistry $managerRegistry) { $this->managerRegistry = $managerRegistry; } - /** - * @param FormBuilderInterface $builder - * @param array $options - */ public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add( @@ -46,17 +39,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ); } - /** - * @return string - */ public function getBlockPrefix(): string { return 'transtype'; } - /** - * @param OptionsResolver $resolver - */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ @@ -74,10 +61,6 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('currentType', NodeType::class); } - /** - * @param NodeType $currentType - * @return array - */ protected function getAvailableTypes(NodeType $currentType): array { $qb = $this->managerRegistry->getManager()->createQueryBuilder(); diff --git a/lib/Rozier/src/Forms/UserDetailsType.php b/lib/Rozier/src/Forms/UserDetailsType.php index b2add740..81c6c733 100644 --- a/lib/Rozier/src/Forms/UserDetailsType.php +++ b/lib/Rozier/src/Forms/UserDetailsType.php @@ -25,15 +25,15 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]) ->add('firstName', TextType::class, [ 'label' => 'firstName', - 'required' => false + 'required' => false, ]) ->add('lastName', TextType::class, [ 'label' => 'lastName', - 'required' => false + 'required' => false, ]) ->add('phone', TextType::class, [ 'label' => 'phone', - 'required' => false + 'required' => false, ]) ->add('facebookName', TextType::class, [ 'label' => 'facebookName', @@ -41,18 +41,18 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]) ->add('company', TextType::class, [ 'label' => 'company', - 'required' => false + 'required' => false, ]) ->add('job', TextType::class, [ 'label' => 'job', - 'required' => false + 'required' => false, ]) ->add('birthday', DateType::class, [ 'label' => 'birthday', 'placeholder' => [ 'year' => 'year', 'month' => 'month', - 'day' => 'day' + 'day' => 'day', ], 'required' => false, 'years' => range(1920, ((int) date('Y')) - 6), @@ -64,13 +64,13 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ]) ->add('pictureUrl', TextType::class, [ 'label' => 'pictureUrl', - 'required' => false + 'required' => false, ]) ->add('locale', ChoiceType::class, [ 'label' => 'user.backoffice.language', 'required' => false, 'choices' => RozierApp::$backendLanguages, - 'placeholder' => 'use.website.default_language' + 'placeholder' => 'use.website.default_language', ]) ; } diff --git a/lib/Rozier/src/Forms/UserSecurityType.php b/lib/Rozier/src/Forms/UserSecurityType.php index df26f076..c92e181b 100644 --- a/lib/Rozier/src/Forms/UserSecurityType.php +++ b/lib/Rozier/src/Forms/UserSecurityType.php @@ -19,9 +19,9 @@ class UserSecurityType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('enabled', CheckboxType::class, [ - 'label' => 'user.enabled', - 'required' => false, - ]) + 'label' => 'user.enabled', + 'required' => false, + ]) ->add('locked', CheckboxType::class, [ 'label' => 'user.locked', 'required' => false, @@ -55,7 +55,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ], ]); - if ($options['canChroot'] === true) { + if (true === $options['canChroot']) { $builder->add('chroot', NodesType::class, [ 'label' => 'chroot', 'required' => false, @@ -65,12 +65,14 @@ function (mixed $mixedEntities) { if ($mixedEntities instanceof Node) { return [$mixedEntities]; } + return []; }, function (mixed $mixedIds) { - if (\is_array($mixedIds) && count($mixedIds) === 1) { + if (\is_array($mixedIds) && 1 === count($mixedIds)) { return $mixedIds[0]; } + return null; } )); diff --git a/lib/Rozier/src/Forms/UserType.php b/lib/Rozier/src/Forms/UserType.php index 0f4f8c9b..1920b596 100644 --- a/lib/Rozier/src/Forms/UserType.php +++ b/lib/Rozier/src/Forms/UserType.php @@ -17,9 +17,9 @@ class UserType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('email', EmailType::class, [ - 'label' => 'email', - 'empty_data' => '', - ]) + 'label' => 'email', + 'empty_data' => '', + ]) ->add('username', TextType::class, [ 'label' => 'username', 'empty_data' => '', @@ -45,7 +45,7 @@ public function configureOptions(OptionsResolver $resolver): void 'data_class' => User::class, 'attr' => [ 'class' => 'uk-form user-form', - ] + ], ]); } } diff --git a/lib/Rozier/src/Models/ModelInterface.php b/lib/Rozier/src/Models/ModelInterface.php index c058a827..ea573e0f 100644 --- a/lib/Rozier/src/Models/ModelInterface.php +++ b/lib/Rozier/src/Models/ModelInterface.php @@ -5,14 +5,12 @@ namespace Themes\Rozier\Models; /** - * @deprecated Use RZ\Roadiz\CoreBundle\Explorer\ExplorerItemInterface instead. + * @deprecated use RZ\Roadiz\CoreBundle\Explorer\ExplorerItemInterface instead */ interface ModelInterface { /** * Return a structured array of data. - * - * @return array */ public function toArray(): array; } diff --git a/lib/Rozier/src/RozierApp.php b/lib/Rozier/src/RozierApp.php index 5eef7c8d..ea7376fc 100644 --- a/lib/Rozier/src/RozierApp.php +++ b/lib/Rozier/src/RozierApp.php @@ -25,7 +25,7 @@ use Twig\Error\RuntimeError; /** - * Rozier main theme application + * Rozier main theme application. */ class RozierApp extends AppController { @@ -68,9 +68,6 @@ public static function getSubscribedServices(): array ]); } - /** - * @inheritDoc - */ public function createEntityListManager(string $entity, array $criteria = [], array $ordering = []): EntityListManagerInterface { return parent::createEntityListManager($entity, $criteria, $ordering) @@ -79,19 +76,15 @@ public function createEntityListManager(string $entity, array $criteria = [], ar /** * Returns a fully qualified view path for Twig rendering. - * - * @param string $view - * @param string $namespace - * @return string */ protected function getNamespacedView(string $view, string $namespace = ''): string { - if ($namespace !== "" && $namespace !== "/") { - $view = '@' . $namespace . '/' . $view; - } elseif ($namespace !== "/") { + if ('' !== $namespace && '/' !== $namespace) { + $view = '@'.$namespace.'/'.$view; + } elseif ('/' !== $namespace) { // when no namespace is used // use current theme directory - $view = '@RoadizRozier/' . $view; + $view = '@RoadizRozier/'.$view; } return $view; @@ -111,9 +104,9 @@ public function prepareBaseAssignation(): static * Switch this to true to use uncompressed JS and CSS files */ $this->assignation['head']['backDevMode'] = false; - $this->assignation['head']['siteTitle'] = $this->getSettingsBag()->get('site_name') . ' backstage'; + $this->assignation['head']['siteTitle'] = $this->getSettingsBag()->get('site_name').' backstage'; $this->assignation['head']['mapsLocation'] = $this->getSettingsBag()->get('maps_default_location') ? $this->getSettingsBag()->get('maps_default_location') : null; - $this->assignation['head']['googleClientId'] = $this->getSettingsBag()->get('google_client_id', ""); + $this->assignation['head']['googleClientId'] = $this->getSettingsBag()->get('google_client_id', ''); $this->assignation['head']['themeName'] = static::$themeName; $this->assignation['head']['ajaxToken'] = $tokenManager->getToken(static::AJAX_TOKEN_INTENTION); /** @var UserActionsMenuEvent $userActionsMenuEvent */ @@ -132,8 +125,8 @@ public function prepareBaseAssignation(): static } /** - * @param Request $request * @return Response $response + * * @throws RuntimeError */ public function indexAction(Request $request): Response diff --git a/lib/Rozier/src/RozierServiceRegistry.php b/lib/Rozier/src/RozierServiceRegistry.php index 3adc5264..0a5eb340 100644 --- a/lib/Rozier/src/RozierServiceRegistry.php +++ b/lib/Rozier/src/RozierServiceRegistry.php @@ -27,7 +27,7 @@ public function __construct( private readonly ManagerRegistry $managerRegistry, private readonly TreeWidgetFactory $treeWidgetFactory, private readonly NodeChrootResolver $chrootResolver, - private readonly array $backofficeMenuEntries + private readonly array $backofficeMenuEntries, ) { } @@ -50,6 +50,7 @@ public function getSettingGroups(): array ['name' => 'ASC'] ); } + return $this->settingGroups; } @@ -58,6 +59,7 @@ public function getTagTree(): TagTreeWidget if (null === $this->tagTree) { $this->tagTree = $this->treeWidgetFactory->createTagTree(); } + return $this->tagTree; } @@ -66,6 +68,7 @@ public function getFolderTree(): FolderTreeWidget if (null === $this->folderTree) { $this->folderTree = $this->treeWidgetFactory->createFolderTree(); } + return $this->folderTree; } @@ -76,6 +79,7 @@ public function getNodeTree(mixed $user): NodeTreeWidget $this->chrootResolver->getChroot($user) ); } + return $this->nodeTree; } diff --git a/lib/Rozier/src/Serialization/DocumentThumbnailSerializeSubscriber.php b/lib/Rozier/src/Serialization/DocumentThumbnailSerializeSubscriber.php index a8e81000..bdf237f0 100644 --- a/lib/Rozier/src/Serialization/DocumentThumbnailSerializeSubscriber.php +++ b/lib/Rozier/src/Serialization/DocumentThumbnailSerializeSubscriber.php @@ -32,12 +32,12 @@ public function onPostSerialize(ObjectEvent $event): void $context = $event->getContext(); if ( - $visitor instanceof SerializationVisitorInterface && - $document instanceof Document && - !$document->isPrivate() && - $context->hasAttribute('groups') && - \is_array($context->getAttribute('groups')) && - in_array('explorer_thumbnail', $context->getAttribute('groups')) + $visitor instanceof SerializationVisitorInterface + && $document instanceof Document + && !$document->isPrivate() + && $context->hasAttribute('groups') + && \is_array($context->getAttribute('groups')) + && in_array('explorer_thumbnail', $context->getAttribute('groups')) ) { $visitor->visitProperty( new StaticPropertyMetadata('boolean', 'processable', []), diff --git a/lib/Rozier/src/Traits/NodesTrait.php b/lib/Rozier/src/Traits/NodesTrait.php index 672baad0..45aff99d 100644 --- a/lib/Rozier/src/Traits/NodesTrait.php +++ b/lib/Rozier/src/Traits/NodesTrait.php @@ -19,19 +19,11 @@ trait NodesTrait { abstract protected function getNodeFactory(): NodeFactory; - /** - * @param string $title - * @param TranslationInterface $translation - * @param Node|null $node - * @param NodeTypeInterface|null $type - * - * @return Node - */ protected function createNode( string $title, TranslationInterface $translation, - Node $node = null, - NodeTypeInterface $type = null + ?Node $node = null, + ?NodeTypeInterface $type = null, ): Node { $factory = $this->getNodeFactory(); $node = $factory->create($title, $type, $translation, $node); @@ -44,15 +36,12 @@ protected function createNode( /** * @param array $data - * @param Node $node - * - * @return NodeType|null */ public function addStackType($data, Node $node): ?NodeType { if ( - $data['nodeId'] == $node->getId() && - !empty($data['nodeTypeId']) + $data['nodeId'] == $node->getId() + && !empty($data['nodeTypeId']) ) { $nodeType = $this->em()->find(NodeType::class, (int) $data['nodeTypeId']); @@ -67,11 +56,6 @@ public function addStackType($data, Node $node): ?NodeType return null; } - /** - * @param Node $node - * - * @return FormInterface|null - */ public function buildStackTypesForm(Node $node): ?FormInterface { if ($node->isHidingChildren()) { @@ -95,14 +79,9 @@ public function buildStackTypesForm(Node $node): ?FormInterface } } - /** - * @param Node $node - * - * @return FormInterface - */ protected function buildDeleteForm(Node $node): FormInterface { - $builder = $this->createNamedFormBuilder('delete_node_' . $node->getId()) + $builder = $this->createNamedFormBuilder('delete_node_'.$node->getId()) ->add('nodeId', HiddenType::class, [ 'data' => $node->getId(), 'constraints' => [ @@ -114,12 +93,10 @@ protected function buildDeleteForm(Node $node): FormInterface return $builder->getForm(); } - /** - * @return FormInterface - */ protected function buildEmptyTrashForm(): FormInterface { $builder = $this->createFormBuilder(); + return $builder->getForm(); } } diff --git a/lib/Rozier/src/Traits/VersionedControllerTrait.php b/lib/Rozier/src/Traits/VersionedControllerTrait.php index 7319702c..b7dab54d 100644 --- a/lib/Rozier/src/Traits/VersionedControllerTrait.php +++ b/lib/Rozier/src/Traits/VersionedControllerTrait.php @@ -17,16 +17,12 @@ trait VersionedControllerTrait { protected bool $isReadOnly = false; - /** - * @return bool - */ public function isReadOnly(): bool { return $this->isReadOnly; } /** - * @param bool $isReadOnly * @return self */ public function setIsReadOnly(bool $isReadOnly) @@ -44,8 +40,8 @@ protected function handleVersions(Request $request, PersistableInterface $entity $versionNumber = $request->get('version', null); if ( - \is_numeric($versionNumber) && - intval($versionNumber) > 0 + \is_numeric($versionNumber) + && intval($versionNumber) > 0 ) { try { $versionNumber = intval($versionNumber); diff --git a/lib/Rozier/src/Widgets/AbstractWidget.php b/lib/Rozier/src/Widgets/AbstractWidget.php index f9e48096..915f6eea 100644 --- a/lib/Rozier/src/Widgets/AbstractWidget.php +++ b/lib/Rozier/src/Widgets/AbstractWidget.php @@ -21,25 +21,20 @@ abstract class AbstractWidget public function __construct( protected RequestStack $requestStack, - protected ManagerRegistry $managerRegistry + protected ManagerRegistry $managerRegistry, ) { } - /** - * @return Request - */ protected function getRequest(): Request { $request = $this->requestStack->getCurrentRequest() ?? $this->requestStack->getMainRequest(); if (null === $request) { throw new \RuntimeException('Request cannot be found.'); } + return $request; } - /** - * @return ManagerRegistry - */ protected function getManagerRegistry(): ManagerRegistry { return $this->managerRegistry; diff --git a/lib/Rozier/src/Widgets/FolderTreeWidget.php b/lib/Rozier/src/Widgets/FolderTreeWidget.php index 08bad9d7..5efe6bfd 100644 --- a/lib/Rozier/src/Widgets/FolderTreeWidget.php +++ b/lib/Rozier/src/Widgets/FolderTreeWidget.php @@ -25,19 +25,13 @@ public function __construct( parent::__construct($requestStack, $managerRegistry); } - /** - * @param Folder $parent - * @return array - */ public function getChildrenFolders(Folder $parent): array { return $this->folders = $this->getManagerRegistry() ->getRepository(Folder::class) ->findByParentAndTranslation($parent, $this->getTranslation()); } - /** - * @return Folder|null - */ + public function getRootFolder(): ?Folder { return $this->parentFolder; @@ -53,12 +47,10 @@ public function getFolders(): iterable ->getRepository(Folder::class) ->findByParentAndTranslation($this->getRootFolder(), $this->getTranslation()); } + return $this->folders; } - /** - * @return TranslationInterface - */ public function getTranslation(): TranslationInterface { return $this->translation ?? parent::getTranslation(); diff --git a/lib/Rozier/src/Widgets/NodeTreeWidget.php b/lib/Rozier/src/Widgets/NodeTreeWidget.php index f863cd51..31c070ef 100644 --- a/lib/Rozier/src/Widgets/NodeTreeWidget.php +++ b/lib/Rozier/src/Widgets/NodeTreeWidget.php @@ -33,33 +33,25 @@ final class NodeTreeWidget extends AbstractWidget private array $additionalCriteria = []; /** - * @param RequestStack $requestStack - * @param ManagerRegistry $managerRegistry - * @param Node|null $parentNode Entry point of NodeTreeWidget, set null if it's root + * @param Node|null $parentNode Entry point of NodeTreeWidget, set null if it's root * @param TranslationInterface|null $translation NodeTree translation - * @param bool $includeRootNode */ public function __construct( RequestStack $requestStack, ManagerRegistry $managerRegistry, private readonly ?Node $parentNode = null, private readonly ?TranslationInterface $translation = null, - private readonly bool $includeRootNode = false + private readonly bool $includeRootNode = false, ) { parent::__construct($requestStack, $managerRegistry); } - /** - * @return Tag|null - */ public function getTag(): ?Tag { return $this->tag; } /** - * @param Tag|null $tag - * * @return $this */ public function setTag(?Tag $tag): NodeTreeWidget @@ -69,17 +61,12 @@ public function setTag(?Tag $tag): NodeTreeWidget return $this; } - /** - * @return bool - */ public function isStackTree(): bool { return $this->stackTree; } /** - * @param bool $stackTree - * * @return $this */ public function setStackTree(bool $stackTree): NodeTreeWidget @@ -91,6 +78,7 @@ public function setStackTree(bool $stackTree): NodeTreeWidget /** * Fill twig assignation array with NodeTree entities. + * * @throws \ReflectionException */ protected function getRootListManager(): NodeTreeDtoListManager @@ -101,31 +89,18 @@ protected function getRootListManager(): NodeTreeDtoListManager return $this->getListManager($this->parentNode, false, $this->additionalCriteria); } - /** - * @return array - */ public function getAdditionalCriteria(): array { return $this->additionalCriteria; } - /** - * @param array $additionalCriteria - * - * @return NodeTreeWidget - */ public function setAdditionalCriteria(array $additionalCriteria): NodeTreeWidget { $this->additionalCriteria = $additionalCriteria; + return $this; } - /** - * @param NodeInterface|null $parent - * @param bool $subRequest - * - * @return bool - */ protected function canOrderByParent(?NodeInterface $parent = null, bool $subRequest = false): bool { if (true === $subRequest || null === $parent) { @@ -133,9 +108,9 @@ protected function canOrderByParent(?NodeInterface $parent = null, bool $subRequ } if ( - $parent->getChildrenOrder() !== 'position' && - in_array($parent->getChildrenOrder(), Node::$orderingFields) && - in_array($parent->getChildrenOrderDirection(), ['ASC', 'DESC']) + 'position' !== $parent->getChildrenOrder() + && in_array($parent->getChildrenOrder(), Node::$orderingFields) + && in_array($parent->getChildrenOrderDirection(), ['ASC', 'DESC']) ) { return true; } @@ -144,16 +119,15 @@ protected function canOrderByParent(?NodeInterface $parent = null, bool $subRequ } /** - * @param NodeInterface|null $parent - * @param bool $subRequest Default: false + * @param bool $subRequest Default: false * @param array $additionalCriteria Default: [] - * @return NodeTreeDtoListManager + * * @throws \ReflectionException */ protected function getListManager( ?NodeInterface $parent = null, bool $subRequest = false, - array $additionalCriteria = [] + array $additionalCriteria = [], ): NodeTreeDtoListManager { $criteria = array_merge($additionalCriteria, [ 'parent' => $parent?->getId() ?? null, @@ -206,20 +180,22 @@ protected function getListManager( } /** - * @param NodeInterface|null $parent * @param bool $subRequest Default: false + * * @return array + * * @throws \ReflectionException */ - public function getChildrenNodes(NodeInterface|null $parent = null, bool $subRequest = false): array + public function getChildrenNodes(?NodeInterface $parent = null, bool $subRequest = false): array { return $this->getListManager($parent, $subRequest)->getEntities(); } /** - * @param NodeInterface|null $parent * @param bool $subRequest Default: false + * * @return array + * * @throws \ReflectionException */ public function getReachableChildrenNodes(?NodeInterface $parent = null, bool $subRequest = false): array @@ -229,9 +205,6 @@ public function getReachableChildrenNodes(?NodeInterface $parent = null, bool $s ])->getEntities(); } - /** - * @return Node|null - */ public function getRootNode(): ?Node { return $this->parentNode; @@ -241,17 +214,12 @@ public function getRootNode(): ?Node * Get entity list manager filters. * * Call getNodes() first to populate this. - * - * @return array|null */ public function getFilters(): ?array { return $this->filters; } - /** - * @return TranslationInterface - */ public function getTranslation(): TranslationInterface { return $this->translation ?? parent::getTranslation(); @@ -272,6 +240,7 @@ public function getAvailableTranslations(): array /** * @return array + * * @throws \ReflectionException */ public function getNodes(): array @@ -296,8 +265,9 @@ public function getTags(?NodeInterface $node): array if (null === $node) { return []; } + return $this->managerRegistry->getRepository(Tag::class)->findByAsTagTreeDto([ - "nodes" => $node->getId(), + 'nodes' => $node->getId(), ], [ 'position' => 'ASC', ], null, null, $this->getTranslation()); @@ -315,8 +285,6 @@ public function getOneDisplayableDocument(NodeTreeDto $node): ?Document /** * Gets the value of canReorder. - * - * @return bool */ public function getCanReorder(): bool { diff --git a/lib/Rozier/src/Widgets/TagTreeWidget.php b/lib/Rozier/src/Widgets/TagTreeWidget.php index 0821b38c..7a5e8a42 100644 --- a/lib/Rozier/src/Widgets/TagTreeWidget.php +++ b/lib/Rozier/src/Widgets/TagTreeWidget.php @@ -23,7 +23,7 @@ public function __construct( ManagerRegistry $managerRegistry, private readonly ?Tag $parentTag = null, private readonly ?TranslationInterface $translation = null, - private readonly bool $forceTranslation = false + private readonly bool $forceTranslation = false, ) { parent::__construct($requestStack, $managerRegistry); } @@ -37,9 +37,9 @@ protected function getTagTreeAssignationForParent(): void 'position' => 'ASC', ]; if ( - null !== $this->parentTag && - $this->parentTag->getChildrenOrder() !== 'order' && - $this->parentTag->getChildrenOrder() !== 'position' + null !== $this->parentTag + && 'order' !== $this->parentTag->getChildrenOrder() + && 'position' !== $this->parentTag->getChildrenOrder() ) { $ordering = [ $this->parentTag->getChildrenOrder() => $this->parentTag->getChildrenOrderDirection(), @@ -56,19 +56,17 @@ protected function getTagTreeAssignationForParent(): void } /** - * @param Tag|null $parent - * * @return iterable|null */ public function getChildrenTags(?Tag $parent): ?iterable { - if ($parent !== null) { + if (null !== $parent) { $ordering = [ 'position' => 'ASC', ]; if ( - $parent->getChildrenOrder() !== 'order' && - $parent->getChildrenOrder() !== 'position' + 'order' !== $parent->getChildrenOrder() + && 'position' !== $parent->getChildrenOrder() ) { $ordering = [ $parent->getChildrenOrder() => $parent->getChildrenOrderDirection(), @@ -89,9 +87,7 @@ public function getChildrenTags(?Tag $parent): ?iterable return null; } - /** - * @return Tag|null - */ + public function getRootTag(): ?Tag { return $this->parentTag; @@ -102,15 +98,13 @@ public function getRootTag(): ?Tag */ public function getTags(): iterable { - if ($this->tags === null) { + if (null === $this->tags) { $this->getTagTreeAssignationForParent(); } + return $this->tags; } - /** - * @return TagRepository - */ protected function getTagRepository(): TagRepository { return $this->getManagerRegistry()->getRepository(Tag::class); @@ -118,17 +112,12 @@ protected function getTagRepository(): TagRepository /** * Gets the value of canReorder. - * - * @return bool */ public function getCanReorder(): bool { return $this->canReorder; } - /** - * @return TranslationInterface - */ public function getTranslation(): TranslationInterface { return $this->translation ?? parent::getTranslation(); diff --git a/lib/Rozier/src/Widgets/TreeWidgetFactory.php b/lib/Rozier/src/Widgets/TreeWidgetFactory.php index 818f6cce..c2a1bc84 100644 --- a/lib/Rozier/src/Widgets/TreeWidgetFactory.php +++ b/lib/Rozier/src/Widgets/TreeWidgetFactory.php @@ -15,7 +15,7 @@ final class TreeWidgetFactory { public function __construct( private readonly RequestStack $requestStack, - private readonly ManagerRegistry $managerRegistry + private readonly ManagerRegistry $managerRegistry, ) { } diff --git a/monorepo-builder.php b/monorepo-builder.php index 0bd10414..8b19044a 100644 --- a/monorepo-builder.php +++ b/monorepo-builder.php @@ -11,7 +11,7 @@ return static function (MBConfig $mbConfig): void { $mbConfig->packageAliasFormat('..x-dev'); - $mbConfig->packageDirectories([__DIR__ . '/lib']); + $mbConfig->packageDirectories([__DIR__.'/lib']); // Using packageDirectoriesExcludes does not work with bower_components $parameters = $mbConfig->parameters(); diff --git a/public/index.php b/public/index.php index 9982c218..97e228df 100644 --- a/public/index.php +++ b/public/index.php @@ -1,5 +1,7 @@ paths([ - __DIR__ . '/src', - __DIR__ . '/lib/DocGenerator/src', - __DIR__ . '/lib/Documents/src', - __DIR__ . '/lib/DtsGenerator/src', - __DIR__ . '/lib/EntityGenerator/src', - __DIR__ . '/lib/Jwt/src', - __DIR__ . '/lib/Markdown/src', - __DIR__ . '/lib/Models/src', - __DIR__ . '/lib/OpenId/src', - __DIR__ . '/lib/Random/src', - __DIR__ . '/lib/RoadizCompatBundle/src', - __DIR__ . '/lib/RoadizCoreBundle/src', - __DIR__ . '/lib/RoadizFontBundle/src', - __DIR__ . '/lib/RoadizRozierBundle/src', - __DIR__ . '/lib/RoadizTwoFactorBundle/src', - __DIR__ . '/lib/RoadizUserBundle/src', - __DIR__ . '/lib/Rozier/src', + __DIR__.'/src', + __DIR__.'/lib/DocGenerator/src', + __DIR__.'/lib/Documents/src', + __DIR__.'/lib/DtsGenerator/src', + __DIR__.'/lib/EntityGenerator/src', + __DIR__.'/lib/Jwt/src', + __DIR__.'/lib/Markdown/src', + __DIR__.'/lib/Models/src', + __DIR__.'/lib/OpenId/src', + __DIR__.'/lib/Random/src', + __DIR__.'/lib/RoadizCompatBundle/src', + __DIR__.'/lib/RoadizCoreBundle/src', + __DIR__.'/lib/RoadizFontBundle/src', + __DIR__.'/lib/RoadizRozierBundle/src', + __DIR__.'/lib/RoadizTwoFactorBundle/src', + __DIR__.'/lib/RoadizUserBundle/src', + __DIR__.'/lib/Rozier/src', ]); // define sets of rules diff --git a/src/Api/Model/CommonContent.php b/src/Api/Model/CommonContent.php index 8893dd6b..55ee3174 100644 --- a/src/Api/Model/CommonContent.php +++ b/src/Api/Model/CommonContent.php @@ -14,12 +14,12 @@ final class CommonContent #[ApiProperty(identifier: true)] public string $id = 'unique'; - #[Groups(["common_content"])] + #[Groups(['common_content'])] public ?NodesSources $home = null; - #[Groups(["common_content"])] + #[Groups(['common_content'])] public ?NodesSourcesHeadInterface $head = null; - #[Groups(["common_content"])] + #[Groups(['common_content'])] public ?array $menus = null; } diff --git a/src/Controller/ContactFormController.php b/src/Controller/ContactFormController.php index e5e97bcf..5fd0d58c 100644 --- a/src/Controller/ContactFormController.php +++ b/src/Controller/ContactFormController.php @@ -20,7 +20,7 @@ final class ContactFormController public function __construct( private readonly ContactFormManagerFactory $contactFormManagerFactory, private readonly RateLimiterFactory $contactFormLimiter, - private readonly LiformInterface $liform + private readonly LiformInterface $liform, ) { } @@ -81,6 +81,7 @@ public function formAction(Request $request): Response if (null !== $response = $contactFormManager->handle()) { $response->headers->add($headers); + return $response; } throw new BadRequestHttpException('Form has not been submitted.'); diff --git a/src/Controller/GetCommonContentController.php b/src/Controller/GetCommonContentController.php index ff19ecd6..7c3408f2 100644 --- a/src/Controller/GetCommonContentController.php +++ b/src/Controller/GetCommonContentController.php @@ -31,7 +31,7 @@ public function __construct( ManagerRegistry $managerRegistry, NodesSourcesHeadFactoryInterface $nodesSourcesHeadFactory, PreviewResolverInterface $previewResolver, - TreeWalkerGenerator $treeWalkerGenerator + TreeWalkerGenerator $treeWalkerGenerator, ) { $this->requestStack = $requestStack; $this->managerRegistry = $managerRegistry; @@ -57,6 +57,7 @@ public function __invoke(): ?CommonContent $translation, 3 ); + return $resource; } catch (ResourceNotFoundException $exception) { throw new NotFoundHttpException($exception->getMessage(), $exception); @@ -90,8 +91,9 @@ protected function getTranslationFromRequest(?Request $request): TranslationInte ->findOneAvailableByLocaleOrOverrideLocale((string) $locale); } if (null === $translation) { - throw new NotFoundHttpException('No translation for locale ' . $locale); + throw new NotFoundHttpException('No translation for locale '.$locale); } + return $translation; } @@ -99,11 +101,9 @@ protected function getTranslationRepository(): TranslationRepository { $repository = $this->managerRegistry->getRepository(TranslationInterface::class); if (!$repository instanceof TranslationRepository) { - throw new \RuntimeException( - 'Translation repository must be instance of ' . - TranslationRepository::class - ); + throw new \RuntimeException('Translation repository must be instance of '.TranslationRepository::class); } + return $repository; } } diff --git a/src/Controller/PageController.php b/src/Controller/PageController.php index ce70bdd7..24187f54 100644 --- a/src/Controller/PageController.php +++ b/src/Controller/PageController.php @@ -13,7 +13,7 @@ class PageController extends AbstractController public function indexAction(NodesSources $nodeSource): Response { return $this->render('nodeSource/page.html.twig', [ - 'nodeSource' => $nodeSource + 'nodeSource' => $nodeSource, ]); } } diff --git a/src/DataFixtures/AppFixtures.php b/src/DataFixtures/AppFixtures.php index 3755b6c2..dcc73157 100644 --- a/src/DataFixtures/AppFixtures.php +++ b/src/DataFixtures/AppFixtures.php @@ -1,5 +1,7 @@ setPublishedAt(new \DateTime()); $manager->flush(); - for ($i = 0; $i < 50; $i++) { + for ($i = 0; $i < 50; ++$i) { $article = $this->uniqueNodeGenerator->generate( // @phpstan-ignore-next-line nodeType: $this->getReference(NodeTypeFixtures::NS_ARTICLE), diff --git a/src/DataFixtures/NodeTypeFixtures.php b/src/DataFixtures/NodeTypeFixtures.php index a01395eb..0165344a 100644 --- a/src/DataFixtures/NodeTypeFixtures.php +++ b/src/DataFixtures/NodeTypeFixtures.php @@ -1,5 +1,7 @@ nodeTypesImporter->import( - file_get_contents(__DIR__ . '/../Resources/node-types/ArticleContainer.json') ?: + file_get_contents(__DIR__.'/../Resources/node-types/ArticleContainer.json') ?: throw new \RuntimeException('Node type JSON file does not exist.') ); $this->nodeTypesImporter->import( - file_get_contents(__DIR__ . '/../Resources/node-types/Article.json') ?: + file_get_contents(__DIR__.'/../Resources/node-types/Article.json') ?: throw new \RuntimeException('Node type JSON file does not exist.') ); $this->nodeTypesImporter->import( - file_get_contents(__DIR__ . '/../Resources/node-types/Offer.json') ?: + file_get_contents(__DIR__.'/../Resources/node-types/Offer.json') ?: throw new \RuntimeException('Node type JSON file does not exist.') ); $this->nodeTypesImporter->import( - file_get_contents(__DIR__ . '/../Resources/node-types/Neutral.json') ?: + file_get_contents(__DIR__.'/../Resources/node-types/Neutral.json') ?: throw new \RuntimeException('Node type JSON file does not exist.') ); diff --git a/src/DataFixtures/OfferFixtures.php b/src/DataFixtures/OfferFixtures.php index f1ffcd68..732eb9c8 100644 --- a/src/DataFixtures/OfferFixtures.php +++ b/src/DataFixtures/OfferFixtures.php @@ -1,5 +1,7 @@ getNode()->setStatus(Node::PUBLISHED); $offerContainer->setPublishedAt(new \DateTime()); - for ($i = 0; $i < 50; $i++) { + for ($i = 0; $i < 50; ++$i) { /** @var NSOffer $offer */ $offer = $this->uniqueNodeGenerator->generate( // @phpstan-ignore-next-line diff --git a/src/Doctrine/ProjectVersionComparator.php b/src/Doctrine/ProjectVersionComparator.php index 91608832..04341647 100644 --- a/src/Doctrine/ProjectVersionComparator.php +++ b/src/Doctrine/ProjectVersionComparator.php @@ -12,6 +12,7 @@ class ProjectVersionComparator implements Comparator private function getClassname(Version $version): string { $tokens = explode('\\', (string) $version); + return $tokens[count($tokens) - 1]; } @@ -19,6 +20,7 @@ public function compare(Version $a, Version $b): int { $classA = $this->getClassname($a); $classB = $this->getClassname($b); + /* * Only compare class-name timestamp */ diff --git a/src/Entity/PositionedPageUser.php b/src/Entity/PositionedPageUser.php index 197cba35..069f390f 100644 --- a/src/Entity/PositionedPageUser.php +++ b/src/Entity/PositionedPageUser.php @@ -7,64 +7,45 @@ use App\GeneratedEntity\NSPage; use Doctrine\ORM\Mapping as ORM; use RZ\Roadiz\Core\AbstractEntities\AbstractPositioned; -use RZ\Roadiz\CoreBundle\Entity\NodesSources; use RZ\Roadiz\CoreBundle\Entity\User; #[ ORM\Entity(), - ORM\Table(name: "positioned_page_user"), - ORM\Index(columns: ["position"], name: "ppu_position"), - ORM\Index(columns: ["node_source_id", "position"], name: "ppu_node_source_id_position"), + ORM\Table(name: 'positioned_page_user'), + ORM\Index(columns: ['position'], name: 'ppu_position'), + ORM\Index(columns: ['node_source_id', 'position'], name: 'ppu_node_source_id_position'), ] class PositionedPageUser extends AbstractPositioned { - /** - * @var NSPage|null - */ #[ORM\ManyToOne(targetEntity: '\App\GeneratedEntity\NSPage', inversedBy: 'usersProxy')] #[ORM\JoinColumn(name: 'node_source_id', onDelete: 'CASCADE')] private ?NSPage $nodeSource; - /** - * @var User|null - */ #[ORM\ManyToOne(targetEntity: '\RZ\Roadiz\CoreBundle\Entity\User')] #[ORM\JoinColumn(name: 'user_id', onDelete: 'CASCADE')] private ?User $user; - /** - * @return NSPage|null - */ public function getNodeSource(): ?NSPage { return $this->nodeSource; } - /** - * @param NSPage|null $nodeSource - * @return PositionedPageUser - */ public function setNodeSource(?NSPage $nodeSource): PositionedPageUser { $this->nodeSource = $nodeSource; + return $this; } - /** - * @return User|null - */ public function getUser(): ?User { return $this->user; } - /** - * @param User|null $user - * @return PositionedPageUser - */ public function setUser(?User $user): PositionedPageUser { $this->user = $user; + return $this; } } diff --git a/src/Form/ContactFormType.php b/src/Form/ContactFormType.php index 36a0bbb7..6eb3841a 100644 --- a/src/Form/ContactFormType.php +++ b/src/Form/ContactFormType.php @@ -23,15 +23,15 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'label' => 'contact_form.last_name', 'required' => true, 'constraints' => [ - new NotNull() - ] + new NotNull(), + ], ]) ->add('first_name', TextType::class, [ 'label' => 'contact_form.first_name', 'required' => true, 'constraints' => [ - new NotNull() - ] + new NotNull(), + ], ]) ->add('email', EmailType::class, [ 'label' => 'contact_form.email', @@ -39,18 +39,18 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'constraints' => [ new NotNull(), new Email(), - ] + ], ]) ->add('message', TextareaType::class, [ 'label' => 'contact_form.message', 'required' => true, 'constraints' => [ - new NotNull() - ] + new NotNull(), + ], ]) ->add('file', FileType::class, [ 'label' => 'contact_form.file', - 'required' => false + 'required' => false, ]) ; } diff --git a/src/GeneratedEntity/NSArticle.php b/src/GeneratedEntity/NSArticle.php index bd3e839b..1131a037 100644 --- a/src/GeneratedEntity/NSArticle.php +++ b/src/GeneratedEntity/NSArticle.php @@ -13,19 +13,17 @@ use ApiPlatform\Metadata\ApiFilter; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; /** * Article node-source entity. - * Article + * Article. */ #[Gedmo\Loggable(logEntryClass: UserLogEntry::class)] #[ORM\Entity(repositoryClass: Repository\NSArticleRepository::class)] @@ -96,9 +94,6 @@ class NSArticle extends NodesSources #[JMS\Type('string')] private ?string $onlyOnWebresponse = null; - /** - * @return string|null - */ public function getContent(): ?string { return $this->content; @@ -112,12 +107,10 @@ public function setContent(?string $content): static $this->content = null !== $content ? (string) $content : null; + return $this; } - /** - * @return string|null - */ public function getRealmBSecret(): ?string { return $this->realmBSecret; @@ -131,12 +124,10 @@ public function setRealmBSecret(?string $realmBSecret): static $this->realmBSecret = null !== $realmBSecret ? (string) $realmBSecret : null; + return $this; } - /** - * @return string|null - */ public function getRealmASecret(): ?string { return $this->realmASecret; @@ -150,12 +141,10 @@ public function setRealmASecret(?string $realmASecret): static $this->realmASecret = null !== $realmASecret ? (string) $realmASecret : null; + return $this; } - /** - * @return \DateTime|null - */ public function getUnpublishedAt(): ?\DateTime { return $this->unpublishedAt; @@ -167,12 +156,10 @@ public function getUnpublishedAt(): ?\DateTime public function setUnpublishedAt(?\DateTime $unpublishedAt): static { $this->unpublishedAt = $unpublishedAt; + return $this; } - /** - * @return string|null - */ public function getOnlyOnWebresponse(): ?string { return $this->onlyOnWebresponse; @@ -186,6 +173,7 @@ public function setOnlyOnWebresponse(?string $onlyOnWebresponse): static $this->onlyOnWebresponse = null !== $onlyOnWebresponse ? (string) $onlyOnWebresponse : null; + return $this; } @@ -201,6 +189,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -211,6 +200,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -221,6 +211,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSArticle] ' . parent::__toString(); + return '[NSArticle] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSArticleContainer.php b/src/GeneratedEntity/NSArticleContainer.php index 5de3d8f0..0e93fd18 100644 --- a/src/GeneratedEntity/NSArticleContainer.php +++ b/src/GeneratedEntity/NSArticleContainer.php @@ -9,17 +9,13 @@ namespace App\GeneratedEntity; -use ApiPlatform\Doctrine\Orm\Filter; use ApiPlatform\Metadata\ApiFilter; -use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; @@ -44,6 +40,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -54,6 +51,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -64,6 +62,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSArticleContainer] ' . parent::__toString(); + return '[NSArticleContainer] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSArticleFeedBlock.php b/src/GeneratedEntity/NSArticleFeedBlock.php index 26c86fee..f649e6c3 100644 --- a/src/GeneratedEntity/NSArticleFeedBlock.php +++ b/src/GeneratedEntity/NSArticleFeedBlock.php @@ -9,17 +9,14 @@ namespace App\GeneratedEntity; -use ApiPlatform\Doctrine\Orm\Filter; use ApiPlatform\Metadata\ApiFilter; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; @@ -44,9 +41,6 @@ class NSArticleFeedBlock extends NodesSources #[JMS\Type('int')] private int|float|null $listingCount = null; - /** - * @return int|float|null - */ public function getListingCount(): int|float|null { return $this->listingCount; @@ -60,6 +54,7 @@ public function setListingCount(int|float|null $listingCount): static $this->listingCount = null !== $listingCount ? (int) $listingCount : null; + return $this; } @@ -75,6 +70,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -85,6 +81,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -95,6 +92,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSArticleFeedBlock] ' . parent::__toString(); + return '[NSArticleFeedBlock] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSBasicBlock.php b/src/GeneratedEntity/NSBasicBlock.php index fd896d4f..61eb875b 100644 --- a/src/GeneratedEntity/NSBasicBlock.php +++ b/src/GeneratedEntity/NSBasicBlock.php @@ -9,17 +9,14 @@ namespace App\GeneratedEntity; -use ApiPlatform\Doctrine\Orm\Filter; use ApiPlatform\Metadata\ApiFilter; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; @@ -58,7 +55,7 @@ class NSBasicBlock extends NodesSources /** * Image. - * (Virtual field, this var is a buffer) + * (Virtual field, this var is a buffer). */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'image')] @@ -67,9 +64,6 @@ class NSBasicBlock extends NodesSources #[Serializer\MaxDepth(2)] private ?array $image = null; - /** - * @return string|null - */ public function getContent(): ?string { return $this->content; @@ -83,12 +77,10 @@ public function setContent(?string $content): static $this->content = null !== $content ? (string) $content : null; + return $this; } - /** - * @return bool - */ public function getBooleanField(): bool { return $this->booleanField; @@ -100,6 +92,7 @@ public function getBooleanField(): bool public function setBooleanField(bool $booleanField): static { $this->booleanField = $booleanField; + return $this; } @@ -125,6 +118,7 @@ public function getImage(): array $this->image = []; } } + return $this->image; } @@ -146,6 +140,7 @@ public function addImage(\RZ\Roadiz\CoreBundle\Entity\Document $document): stati $this->addDocumentsByFields($nodeSourceDocument); $this->image = null; } + return $this; } @@ -161,6 +156,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -171,6 +167,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -181,6 +178,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSBasicBlock] ' . parent::__toString(); + return '[NSBasicBlock] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSGroupBlock.php b/src/GeneratedEntity/NSGroupBlock.php index 0dd2a2fa..372bbb15 100644 --- a/src/GeneratedEntity/NSGroupBlock.php +++ b/src/GeneratedEntity/NSGroupBlock.php @@ -9,17 +9,13 @@ namespace App\GeneratedEntity; -use ApiPlatform\Doctrine\Orm\Filter; use ApiPlatform\Metadata\ApiFilter; -use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; @@ -44,6 +40,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -54,6 +51,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -64,6 +62,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSGroupBlock] ' . parent::__toString(); + return '[NSGroupBlock] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSMenu.php b/src/GeneratedEntity/NSMenu.php index 8881e09a..77146074 100644 --- a/src/GeneratedEntity/NSMenu.php +++ b/src/GeneratedEntity/NSMenu.php @@ -9,17 +9,13 @@ namespace App\GeneratedEntity; -use ApiPlatform\Doctrine\Orm\Filter; use ApiPlatform\Metadata\ApiFilter; -use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; @@ -44,6 +40,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -54,6 +51,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -64,6 +62,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSMenu] ' . parent::__toString(); + return '[NSMenu] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSMenuLink.php b/src/GeneratedEntity/NSMenuLink.php index 83809bbf..bc86a214 100644 --- a/src/GeneratedEntity/NSMenuLink.php +++ b/src/GeneratedEntity/NSMenuLink.php @@ -9,17 +9,14 @@ namespace App\GeneratedEntity; -use ApiPlatform\Doctrine\Orm\Filter; use ApiPlatform\Metadata\ApiFilter; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; @@ -46,10 +43,11 @@ class NSMenuLink extends NodesSources /** * linkInternalReferenceSources NodesSources direct field buffer. + * * @var \RZ\Roadiz\CoreBundle\Entity\NodesSources[]|null - * Référence au nœud (Page ou Bloc de page). - * Default values: - * Page, Article, ArticleContainer, Offer + * Référence au nœud (Page ou Bloc de page). + * Default values: + * Page, Article, ArticleContainer, Offer */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'linkInternalReference')] @@ -60,7 +58,7 @@ class NSMenuLink extends NodesSources /** * Image. - * (Virtual field, this var is a buffer) + * (Virtual field, this var is a buffer). */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'image')] @@ -69,9 +67,6 @@ class NSMenuLink extends NodesSources #[Serializer\MaxDepth(2)] private ?array $image = null; - /** - * @return string|null - */ public function getLinkExternalUrl(): ?string { return $this->linkExternalUrl; @@ -85,6 +80,7 @@ public function setLinkExternalUrl(?string $linkExternalUrl): static $this->linkExternalUrl = null !== $linkExternalUrl ? (string) $linkExternalUrl : null; + return $this; } @@ -101,7 +97,7 @@ public function getLinkInternalReferenceSources(): array if (null === $this->linkInternalReferenceSources) { if (null !== $this->objectManager) { $this->linkInternalReferenceSources = $this->objectManager - ->getRepository(\RZ\Roadiz\CoreBundle\Entity\NodesSources::class) + ->getRepository(NodesSources::class) ->findByNodesSourcesAndFieldNameAndTranslation( $this, 'link_internal_reference' @@ -110,16 +106,19 @@ public function getLinkInternalReferenceSources(): array $this->linkInternalReferenceSources = []; } } + return $this->linkInternalReferenceSources; } /** * @param \RZ\Roadiz\CoreBundle\Entity\NodesSources[]|null $linkInternalReferenceSources + * * @return $this */ public function setLinkInternalReferenceSources(?array $linkInternalReferenceSources): static { $this->linkInternalReferenceSources = $linkInternalReferenceSources; + return $this; } @@ -145,6 +144,7 @@ public function getImage(): array $this->image = []; } } + return $this->image; } @@ -166,6 +166,7 @@ public function addImage(\RZ\Roadiz\CoreBundle\Entity\Document $document): stati $this->addDocumentsByFields($nodeSourceDocument); $this->image = null; } + return $this; } @@ -181,6 +182,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -191,6 +193,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -201,6 +204,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSMenuLink] ' . parent::__toString(); + return '[NSMenuLink] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSNeutral.php b/src/GeneratedEntity/NSNeutral.php index f1d1d528..452cd0f7 100644 --- a/src/GeneratedEntity/NSNeutral.php +++ b/src/GeneratedEntity/NSNeutral.php @@ -13,19 +13,17 @@ use ApiPlatform\Metadata\ApiFilter; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; /** * Neutral node-source entity. - * Neutral + * Neutral. */ #[Gedmo\Loggable(logEntryClass: UserLogEntry::class)] #[ORM\Entity(repositoryClass: Repository\NSNeutralRepository::class)] @@ -49,9 +47,6 @@ class NSNeutral extends NodesSources #[JMS\Type('int')] private int|float|null $number = null; - /** - * @return int|float|null - */ public function getNumber(): int|float|null { return $this->number; @@ -65,6 +60,7 @@ public function setNumber(int|float|null $number): static $this->number = null !== $number ? (int) $number : null; + return $this; } @@ -80,6 +76,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -90,6 +87,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -100,6 +98,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSNeutral] ' . parent::__toString(); + return '[NSNeutral] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSOffer.php b/src/GeneratedEntity/NSOffer.php index 3db366ce..bc21fab6 100644 --- a/src/GeneratedEntity/NSOffer.php +++ b/src/GeneratedEntity/NSOffer.php @@ -13,19 +13,17 @@ use ApiPlatform\Metadata\ApiFilter; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Serializer\Filter\PropertyFilter; -use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation as JMS; use RZ\Roadiz\CoreBundle\Entity\Node; use RZ\Roadiz\CoreBundle\Entity\NodesSources; -use RZ\Roadiz\CoreBundle\Entity\Translation; use RZ\Roadiz\CoreBundle\Entity\UserLogEntry; use Symfony\Component\Serializer\Attribute as Serializer; /** * Offer node-source entity. - * Offer + * Offer. */ #[Gedmo\Loggable(logEntryClass: UserLogEntry::class)] #[ORM\Entity(repositoryClass: Repository\NSOfferRepository::class)] @@ -87,7 +85,7 @@ class NSOffer extends NodesSources /** * Layout. * Default values: - * dark + * dark. */ #[Serializer\SerializedName(serializedName: 'layout')] #[Serializer\Groups(['nodes_sources', 'nodes_sources_default'])] @@ -102,9 +100,6 @@ class NSOffer extends NodesSources #[JMS\Type('string')] private ?string $layout = null; - /** - * @return int|float|null - */ public function getPrice(): int|float|null { return $this->price; @@ -118,12 +113,10 @@ public function setPrice(int|float|null $price): static $this->price = null !== $price ? (int) $price : null; + return $this; } - /** - * @return int|float|null - */ public function getVat(): int|float|null { return $this->vat; @@ -135,12 +128,10 @@ public function getVat(): int|float|null public function setVat(int|float|null $vat): static { $this->vat = $vat; + return $this; } - /** - * @return mixed - */ public function getGeolocation(): mixed { return $this->geolocation; @@ -152,12 +143,10 @@ public function getGeolocation(): mixed public function setGeolocation(mixed $geolocation): static { $this->geolocation = $geolocation; + return $this; } - /** - * @return mixed - */ public function getMultiGeolocation(): mixed { return $this->multiGeolocation; @@ -169,12 +158,10 @@ public function getMultiGeolocation(): mixed public function setMultiGeolocation(mixed $multiGeolocation): static { $this->multiGeolocation = $multiGeolocation; + return $this; } - /** - * @return string|null - */ public function getLayout(): ?string { return $this->layout; @@ -188,6 +175,7 @@ public function setLayout(?string $layout): static $this->layout = null !== $layout ? (string) $layout : null; + return $this; } @@ -203,6 +191,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -213,6 +202,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -223,6 +213,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSOffer] ' . parent::__toString(); + return '[NSOffer] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/NSPage.php b/src/GeneratedEntity/NSPage.php index 7a515b1e..fceb3515 100644 --- a/src/GeneratedEntity/NSPage.php +++ b/src/GeneratedEntity/NSPage.php @@ -25,7 +25,7 @@ /** * Page node-source entity. - * Page + * Page. */ #[Gedmo\Loggable(logEntryClass: UserLogEntry::class)] #[ORM\Entity(repositoryClass: Repository\NSPageRepository::class)] @@ -77,7 +77,7 @@ class NSPage extends NodesSources /** * Images. - * (Virtual field, this var is a buffer) + * (Virtual field, this var is a buffer). */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'images')] @@ -89,7 +89,7 @@ class NSPage extends NodesSources /** * Header image. * Group: Images. - * (Virtual field, this var is a buffer) + * (Virtual field, this var is a buffer). */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'headerImage')] @@ -114,7 +114,7 @@ class NSPage extends NodesSources * Pictures. * Picture for website. * Group: Images. - * (Virtual field, this var is a buffer) + * (Virtual field, this var is a buffer). */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'pictures')] @@ -125,10 +125,11 @@ class NSPage extends NodesSources /** * nodeReferencesSources NodesSources direct field buffer. + * * @var \App\GeneratedEntity\NSPage[]|null - * References. - * Default values: - * Page + * References. + * Default values: + * Page */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'nodeReferences')] @@ -173,7 +174,7 @@ class NSPage extends NodesSources /** * Custom form. - * (Virtual field, this var is a buffer) + * (Virtual field, this var is a buffer). */ #[JMS\Exclude] #[Serializer\SerializedName(serializedName: 'customForm')] @@ -185,6 +186,7 @@ class NSPage extends NodesSources /** * Buffer var to get referenced entities (documents, nodes, cforms, doctrine entities) * Reference to users. + * * @var \Doctrine\Common\Collections\Collection */ #[JMS\Exclude] @@ -221,7 +223,8 @@ class NSPage extends NodesSources * # # This order will preserve position * # orderBy: * # - field: position - * # direction: ASC + * # direction: ASC. + * * @var \Doctrine\Common\Collections\Collection */ #[Serializer\SerializedName(serializedName: 'folderReferences')] @@ -265,7 +268,7 @@ class NSPage extends NodesSources /** * Settings. * Default values: - * classname: Themes\Rozier\Explorer\SettingsProvider + * classname: Themes\Rozier\Explorer\SettingsProvider. */ #[Serializer\SerializedName(serializedName: 'settings')] #[Serializer\Groups(['nodes_sources', 'nodes_sources_default'])] @@ -280,7 +283,7 @@ class NSPage extends NodesSources /** * Folder simple. * Default values: - * classname: Themes\Rozier\Explorer\FoldersProvider + * classname: Themes\Rozier\Explorer\FoldersProvider. */ #[Serializer\SerializedName(serializedName: 'folder')] #[Serializer\Groups(['nodes_sources', 'nodes_sources_default'])] @@ -332,7 +335,7 @@ class NSPage extends NodesSources /** * Layout. * Default values: - * dark, transparent + * dark, transparent. */ #[Serializer\SerializedName(serializedName: 'layout')] #[Serializer\Groups(['nodes_sources', 'nodes_sources_default'])] @@ -369,7 +372,7 @@ class NSPage extends NodesSources * # This order will only be used for explorer * orderBy: * - field: email - * direction: ASC + * direction: ASC. */ #[Serializer\SerializedName(serializedName: 'mainUser')] #[Serializer\Groups(['nodes_sources', 'nodes_sources_default'])] @@ -382,9 +385,6 @@ class NSPage extends NodesSources #[JMS\MaxDepth(2)] private ?\RZ\Roadiz\CoreBundle\Entity\User $mainUser = null; - /** - * @return string|null - */ public function getContent(): ?string { return $this->content; @@ -398,12 +398,10 @@ public function setContent(?string $content): static $this->content = null !== $content ? (string) $content : null; + return $this; } - /** - * @return string|null - */ public function getSubTitle(): ?string { return $this->subTitle; @@ -417,12 +415,10 @@ public function setSubTitle(?string $subTitle): static $this->subTitle = null !== $subTitle ? (string) $subTitle : null; + return $this; } - /** - * @return string|null - */ public function getColor(): ?string { return $this->color; @@ -436,6 +432,7 @@ public function setColor(?string $color): static $this->color = null !== $color ? (string) $color : null; + return $this; } @@ -461,6 +458,7 @@ public function getImages(): array $this->images = []; } } + return $this->images; } @@ -482,6 +480,7 @@ public function addImages(\RZ\Roadiz\CoreBundle\Entity\Document $document): stat $this->addDocumentsByFields($nodeSourceDocument); $this->images = null; } + return $this; } @@ -507,6 +506,7 @@ public function getHeaderImage(): array $this->headerImage = []; } } + return $this->headerImage; } @@ -528,12 +528,10 @@ public function addHeaderImage(\RZ\Roadiz\CoreBundle\Entity\Document $document): $this->addDocumentsByFields($nodeSourceDocument); $this->headerImage = null; } + return $this; } - /** - * @return string|null - */ public function getOverTitle(): ?string { return $this->overTitle; @@ -547,6 +545,7 @@ public function setOverTitle(?string $overTitle): static $this->overTitle = null !== $overTitle ? (string) $overTitle : null; + return $this; } @@ -572,6 +571,7 @@ public function getPictures(): array $this->pictures = []; } } + return $this->pictures; } @@ -593,6 +593,7 @@ public function addPictures(\RZ\Roadiz\CoreBundle\Entity\Document $document): st $this->addDocumentsByFields($nodeSourceDocument); $this->pictures = null; } + return $this; } @@ -609,7 +610,7 @@ public function getNodeReferencesSources(): array if (null === $this->nodeReferencesSources) { if (null !== $this->objectManager) { $this->nodeReferencesSources = $this->objectManager - ->getRepository(\App\GeneratedEntity\NSPage::class) + ->getRepository(NSPage::class) ->findByNodesSourcesAndFieldNameAndTranslation( $this, 'node_references' @@ -618,22 +619,22 @@ public function getNodeReferencesSources(): array $this->nodeReferencesSources = []; } } + return $this->nodeReferencesSources; } /** * @param \App\GeneratedEntity\NSPage[]|null $nodeReferencesSources + * * @return $this */ public function setNodeReferencesSources(?array $nodeReferencesSources): static { $this->nodeReferencesSources = $nodeReferencesSources; + return $this; } - /** - * @return bool - */ public function getSticky(): bool { return $this->sticky; @@ -645,12 +646,10 @@ public function getSticky(): bool public function setSticky(bool $sticky): static { $this->sticky = $sticky; + return $this; } - /** - * @return bool - */ public function getStickytest(): bool { return $this->stickytest; @@ -662,6 +661,7 @@ public function getStickytest(): bool public function setStickytest(bool $stickytest): static { $this->stickytest = $stickytest; + return $this; } @@ -686,6 +686,7 @@ public function getCustomForm(): array $this->customForm = []; } } + return $this->customForm; } @@ -704,6 +705,7 @@ public function addCustomForm(\RZ\Roadiz\CoreBundle\Entity\CustomForm $customFor $this->getNode()->addCustomForm($nodeCustomForm); $this->customForm = null; } + return $this; } @@ -731,11 +733,13 @@ public function getUsers(): array /** * @param \Doctrine\Common\Collections\Collection $usersProxy + * * @return $this */ public function setUsersProxy(Collection $usersProxy): static { $this->usersProxy = $usersProxy; + return $this; } @@ -775,21 +779,20 @@ public function getFolderReferences(): Collection /** * @param \Doctrine\Common\Collections\Collection|array<\RZ\Roadiz\CoreBundle\Entity\Folder> $folderReferences + * * @return $this */ public function setFolderReferences(Collection|array $folderReferences): static { - if ($folderReferences instanceof \Doctrine\Common\Collections\Collection) { + if ($folderReferences instanceof Collection) { $this->folderReferences = $folderReferences; } else { $this->folderReferences = new \Doctrine\Common\Collections\ArrayCollection($folderReferences); } + return $this; } - /** - * @return int|float|null - */ public function getAmount(): int|float|null { return $this->amount; @@ -801,12 +804,10 @@ public function getAmount(): int|float|null public function setAmount(int|float|null $amount): static { $this->amount = $amount; + return $this; } - /** - * @return string|null - */ public function getEmailTest(): ?string { return $this->emailTest; @@ -820,12 +821,10 @@ public function setEmailTest(?string $emailTest): static $this->emailTest = null !== $emailTest ? (string) $emailTest : null; + return $this; } - /** - * @return mixed - */ public function getSettings(): mixed { return $this->settings; @@ -837,12 +836,10 @@ public function getSettings(): mixed public function setSettings(mixed $settings): static { $this->settings = $settings; + return $this; } - /** - * @return mixed - */ public function getFolder(): mixed { return $this->folder; @@ -854,12 +851,10 @@ public function getFolder(): mixed public function setFolder(mixed $folder): static { $this->folder = $folder; + return $this; } - /** - * @return string|null - */ public function getCountry(): ?string { return $this->country; @@ -873,12 +868,10 @@ public function setCountry(?string $country): static $this->country = null !== $country ? (string) $country : null; + return $this; } - /** - * @return mixed - */ public function getGeolocation(): mixed { return $this->geolocation; @@ -890,12 +883,10 @@ public function getGeolocation(): mixed public function setGeolocation(mixed $geolocation): static { $this->geolocation = $geolocation; + return $this; } - /** - * @return mixed - */ public function getMultiGeolocation(): mixed { return $this->multiGeolocation; @@ -907,12 +898,10 @@ public function getMultiGeolocation(): mixed public function setMultiGeolocation(mixed $multiGeolocation): static { $this->multiGeolocation = $multiGeolocation; + return $this; } - /** - * @return string|null - */ public function getLayout(): ?string { return $this->layout; @@ -926,6 +915,7 @@ public function setLayout(?string $layout): static $this->layout = null !== $layout ? (string) $layout : null; + return $this; } @@ -940,6 +930,7 @@ public function getMainUser(): ?\RZ\Roadiz\CoreBundle\Entity\User public function setMainUser(?\RZ\Roadiz\CoreBundle\Entity\User $mainUser): static { $this->mainUser = $mainUser; + return $this; } @@ -976,6 +967,7 @@ public function getNodeTypeName(): string /** * $this->nodeType->isReachable() proxy. + * * @return bool Does this nodeSource is reachable over network? */ #[JMS\VirtualProperty] @@ -986,6 +978,7 @@ public function isReachable(): bool /** * $this->nodeType->isPublishable() proxy. + * * @return bool Does this nodeSource is publishable with date and time? */ #[JMS\VirtualProperty] @@ -996,6 +989,6 @@ public function isPublishable(): bool public function __toString(): string { - return '[NSPage] ' . parent::__toString(); + return '[NSPage] '.parent::__toString(); } } diff --git a/src/GeneratedEntity/Repository/NSArticleContainerRepository.php b/src/GeneratedEntity/Repository/NSArticleContainerRepository.php index a86ec6d4..18e5a6de 100644 --- a/src/GeneratedEntity/Repository/NSArticleContainerRepository.php +++ b/src/GeneratedEntity/Repository/NSArticleContainerRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSArticleContainer|null find($id, $lockMode = null, $lockVersion = null) * @method NSArticleContainer|null findOneBy(array $criteria, array $orderBy = null) * @method NSArticleContainer[] findAll() diff --git a/src/GeneratedEntity/Repository/NSArticleFeedBlockRepository.php b/src/GeneratedEntity/Repository/NSArticleFeedBlockRepository.php index fb87311a..b0e545a2 100644 --- a/src/GeneratedEntity/Repository/NSArticleFeedBlockRepository.php +++ b/src/GeneratedEntity/Repository/NSArticleFeedBlockRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSArticleFeedBlock|null find($id, $lockMode = null, $lockVersion = null) * @method NSArticleFeedBlock|null findOneBy(array $criteria, array $orderBy = null) * @method NSArticleFeedBlock[] findAll() diff --git a/src/GeneratedEntity/Repository/NSArticleRepository.php b/src/GeneratedEntity/Repository/NSArticleRepository.php index 96f4a8d5..568878f3 100644 --- a/src/GeneratedEntity/Repository/NSArticleRepository.php +++ b/src/GeneratedEntity/Repository/NSArticleRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSArticle|null find($id, $lockMode = null, $lockVersion = null) * @method NSArticle|null findOneBy(array $criteria, array $orderBy = null) * @method NSArticle[] findAll() diff --git a/src/GeneratedEntity/Repository/NSBasicBlockRepository.php b/src/GeneratedEntity/Repository/NSBasicBlockRepository.php index 8fa1304c..7c8a4fb9 100644 --- a/src/GeneratedEntity/Repository/NSBasicBlockRepository.php +++ b/src/GeneratedEntity/Repository/NSBasicBlockRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSBasicBlock|null find($id, $lockMode = null, $lockVersion = null) * @method NSBasicBlock|null findOneBy(array $criteria, array $orderBy = null) * @method NSBasicBlock[] findAll() diff --git a/src/GeneratedEntity/Repository/NSGroupBlockRepository.php b/src/GeneratedEntity/Repository/NSGroupBlockRepository.php index a7e9c274..210687b4 100644 --- a/src/GeneratedEntity/Repository/NSGroupBlockRepository.php +++ b/src/GeneratedEntity/Repository/NSGroupBlockRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSGroupBlock|null find($id, $lockMode = null, $lockVersion = null) * @method NSGroupBlock|null findOneBy(array $criteria, array $orderBy = null) * @method NSGroupBlock[] findAll() diff --git a/src/GeneratedEntity/Repository/NSMenuLinkRepository.php b/src/GeneratedEntity/Repository/NSMenuLinkRepository.php index 39cc7802..c6cb07d3 100644 --- a/src/GeneratedEntity/Repository/NSMenuLinkRepository.php +++ b/src/GeneratedEntity/Repository/NSMenuLinkRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSMenuLink|null find($id, $lockMode = null, $lockVersion = null) * @method NSMenuLink|null findOneBy(array $criteria, array $orderBy = null) * @method NSMenuLink[] findAll() diff --git a/src/GeneratedEntity/Repository/NSMenuRepository.php b/src/GeneratedEntity/Repository/NSMenuRepository.php index 0aaec016..399d7d86 100644 --- a/src/GeneratedEntity/Repository/NSMenuRepository.php +++ b/src/GeneratedEntity/Repository/NSMenuRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSMenu|null find($id, $lockMode = null, $lockVersion = null) * @method NSMenu|null findOneBy(array $criteria, array $orderBy = null) * @method NSMenu[] findAll() diff --git a/src/GeneratedEntity/Repository/NSNeutralRepository.php b/src/GeneratedEntity/Repository/NSNeutralRepository.php index d66e2bee..f71e0796 100644 --- a/src/GeneratedEntity/Repository/NSNeutralRepository.php +++ b/src/GeneratedEntity/Repository/NSNeutralRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSNeutral|null find($id, $lockMode = null, $lockVersion = null) * @method NSNeutral|null findOneBy(array $criteria, array $orderBy = null) * @method NSNeutral[] findAll() diff --git a/src/GeneratedEntity/Repository/NSOfferRepository.php b/src/GeneratedEntity/Repository/NSOfferRepository.php index eee4a855..c9a55923 100644 --- a/src/GeneratedEntity/Repository/NSOfferRepository.php +++ b/src/GeneratedEntity/Repository/NSOfferRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSOffer|null find($id, $lockMode = null, $lockVersion = null) * @method NSOffer|null findOneBy(array $criteria, array $orderBy = null) * @method NSOffer[] findAll() diff --git a/src/GeneratedEntity/Repository/NSPageRepository.php b/src/GeneratedEntity/Repository/NSPageRepository.php index 8bef5894..eb7db23c 100644 --- a/src/GeneratedEntity/Repository/NSPageRepository.php +++ b/src/GeneratedEntity/Repository/NSPageRepository.php @@ -19,6 +19,7 @@ /** * @extends NodesSourcesRepository + * * @method NSPage|null find($id, $lockMode = null, $lockVersion = null) * @method NSPage|null findOneBy(array $criteria, array $orderBy = null) * @method NSPage[] findAll() diff --git a/src/Kernel.php b/src/Kernel.php index cf4518d1..ccb1f388 100644 --- a/src/Kernel.php +++ b/src/Kernel.php @@ -1,5 +1,7 @@ import('../config/{packages}/*.yaml'); - $container->import('../config/{packages}/' . $this->environment . '/*.yaml'); + $container->import('../config/{packages}/'.$this->environment.'/*.yaml'); - if (is_file(\dirname(__DIR__) . '/config/services.yaml')) { + if (is_file(\dirname(__DIR__).'/config/services.yaml')) { $container->import('../config/services.yaml'); - $container->import('../config/{services}_' . $this->environment . '.yaml'); + $container->import('../config/{services}_'.$this->environment.'.yaml'); } else { $container->import('../config/{services}.php'); } @@ -26,10 +28,10 @@ protected function configureContainer(ContainerConfigurator $container): void protected function configureRoutes(RoutingConfigurator $routes): void { - $routes->import('../config/{routes}/' . $this->environment . '/*.yaml'); + $routes->import('../config/{routes}/'.$this->environment.'/*.yaml'); $routes->import('../config/{routes}/*.yaml'); - if (is_file(\dirname(__DIR__) . '/config/routes.yaml')) { + if (is_file(\dirname(__DIR__).'/config/routes.yaml')) { $routes->import('../config/routes.yaml'); } else { $routes->import('../config/{routes}.php'); diff --git a/src/Serializer/Normalizer/MenuLinkPathNormalizer.php b/src/Serializer/Normalizer/MenuLinkPathNormalizer.php index 6f521181..b4797774 100644 --- a/src/Serializer/Normalizer/MenuLinkPathNormalizer.php +++ b/src/Serializer/Normalizer/MenuLinkPathNormalizer.php @@ -11,10 +11,10 @@ final class MenuLinkPathNormalizer extends AbstractPathNormalizer { /** - * @param mixed $object * @param string|null $format - * @param array $context + * * @return array|\ArrayObject|bool|float|int|mixed|string|null + * * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface */ public function normalize($object, $format = null, array $context = []) @@ -26,12 +26,13 @@ public function normalize($object, $format = null, array $context = []) $actualUrl = $this->urlGenerator->generate( RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ - RouteObjectInterface::ROUTE_OBJECT => $object->getLinkInternalReferenceSources()[0] + RouteObjectInterface::ROUTE_OBJECT => $object->getLinkInternalReferenceSources()[0], ] ); } $data['url'] = $actualUrl; } + return $data; } } diff --git a/src/TreeWalker/Definition/ArticleFeedBlockDefinition.php b/src/TreeWalker/Definition/ArticleFeedBlockDefinition.php index 492ff6b9..a951afba 100644 --- a/src/TreeWalker/Definition/ArticleFeedBlockDefinition.php +++ b/src/TreeWalker/Definition/ArticleFeedBlockDefinition.php @@ -22,27 +22,24 @@ public function isStoppingCollectionOnceInvoked(): bool } /** - * @param NodesSources $source - * @param WalkerInterface $walker - * @return array * @throws \Exception */ public function __invoke(NodesSources $source, WalkerInterface $walker): array { if (!($this->context instanceof NodeSourceWalkerContext)) { - throw new \InvalidArgumentException('Context should be instance of ' . NodeSourceWalkerContext::class); + throw new \InvalidArgumentException('Context should be instance of '.NodeSourceWalkerContext::class); } $this->context->getStopwatch()->start(self::class); if (!$source instanceof NSArticleFeedBlock) { - throw new \InvalidArgumentException('Source must be instance of ' . NSArticleFeedBlock::class); + throw new \InvalidArgumentException('Source must be instance of '.NSArticleFeedBlock::class); } $criteria = [ 'node.visible' => true, 'publishedAt' => ['<=', new \DateTime()], 'translation' => $source->getTranslation(), - 'node.nodeType' => $this->context->getNodeTypesBag()->get('Article') + 'node.nodeType' => $this->context->getNodeTypesBag()->get('Article'), ]; // Prevent Article feed to list root Article again @@ -62,7 +59,7 @@ public function __invoke(NodesSources $source, WalkerInterface $walker): array $children = $this->context->getManagerRegistry() ->getRepository(NSArticle::class) ->findBy($criteria, [ - 'publishedAt' => 'DESC' + 'publishedAt' => 'DESC', ], $count); $this->context->getStopwatch()->stop(self::class); diff --git a/src/TreeWalker/Definition/ArticleFeedBlockDefinitionFactory.php b/src/TreeWalker/Definition/ArticleFeedBlockDefinitionFactory.php index ef026cc6..8d4b29d2 100644 --- a/src/TreeWalker/Definition/ArticleFeedBlockDefinitionFactory.php +++ b/src/TreeWalker/Definition/ArticleFeedBlockDefinitionFactory.php @@ -10,7 +10,7 @@ use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag; #[AutoconfigureTag( - name:'roadiz_core.tree_walker_definition_factory', + name: 'roadiz_core.tree_walker_definition_factory', attributes: ['classname' => NSArticleFeedBlock::class] )] final class ArticleFeedBlockDefinitionFactory implements DefinitionFactoryInterface diff --git a/src/TreeWalker/MenuNodeSourceWalker.php b/src/TreeWalker/MenuNodeSourceWalker.php index 3c0fc558..45ff59aa 100644 --- a/src/TreeWalker/MenuNodeSourceWalker.php +++ b/src/TreeWalker/MenuNodeSourceWalker.php @@ -11,9 +11,6 @@ use RZ\TreeWalker\AbstractCycleAwareWalker; use RZ\TreeWalker\Definition\ZeroChildrenDefinition; -/** - * @package App\TreeWalker - */ final class MenuNodeSourceWalker extends AbstractCycleAwareWalker { /** @@ -36,18 +33,13 @@ protected function initializeDefinitions(): void } /** - * @param NodeTypeInterface $nodeType - * @return callable * @throws InvalidArgumentException */ protected function createDefinitionForNodeType(NodeTypeInterface $nodeType): callable { $context = $this->getContext(); if (!$context instanceof NodeSourceWalkerContext) { - throw new \InvalidArgumentException( - 'TreeWalker context must be instance of ' . - NodeSourceWalkerContext::class - ); + throw new \InvalidArgumentException('TreeWalker context must be instance of '.NodeSourceWalkerContext::class); } $childrenNodeTypes = $context->getNodeTypeResolver()->getChildrenNodeTypeList($nodeType); if (count($childrenNodeTypes) > 0) { diff --git a/tests/ArticleTest.php b/tests/ArticleTest.php index 1fa55b68..37cdfe20 100644 --- a/tests/ArticleTest.php +++ b/tests/ArticleTest.php @@ -1,5 +1,7 @@ assertInstanceOf(NSArticle::class, $article); - static::createClient()->request('GET', '/api/articles/' . $article->getId()); + static::createClient()->request('GET', '/api/articles/'.$article->getId()); $this->assertResponseIsSuccessful(); $this->assertJsonContains([ '@context' => '/api/contexts/Article', - '@id' => '/api/articles/' . $article->getId(), + '@id' => '/api/articles/'.$article->getId(), '@type' => 'Article', 'title' => $article->getTitle(), 'url' => $urlGenerator->generate(RouteObjectInterface::OBJECT_BASED_ROUTE_NAME, [ diff --git a/tests/OfferTest.php b/tests/OfferTest.php index 3a4f9405..f6e1daa9 100644 --- a/tests/OfferTest.php +++ b/tests/OfferTest.php @@ -1,5 +1,7 @@ bootEnv(__DIR__ . '/../.env'); +(new Dotenv())->bootEnv(__DIR__.'/../.env'); $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']); $kernel->boot(); + return $kernel->getContainer()->get('doctrine')->getManager(); From e816f6ff97784691be65ebaef9e12736bfa0723d Mon Sep 17 00:00:00 2001 From: Ambroise Maupate Date: Wed, 6 Nov 2024 01:18:09 +0100 Subject: [PATCH 2/5] refactor: Removed squizlabs/php_codesniffer from all sub-packages --- .../.github/workflows/run-test.yml | 2 -- lib/DocGenerator/Makefile | 4 --- lib/DocGenerator/composer.json | 3 +-- lib/DocGenerator/phpcs.xml.dist | 17 ------------ lib/Documents/.github/workflows/run-test.yml | 2 -- lib/Documents/composer.json | 3 +-- lib/Documents/phpcs.xml.dist | 13 ---------- .../.github/workflows/run-test.yml | 2 -- lib/DtsGenerator/Makefile | 4 --- lib/DtsGenerator/composer.json | 3 +-- lib/DtsGenerator/phpcs.xml.dist | 17 ------------ .../.github/workflows/run-test.yml | 2 -- lib/EntityGenerator/composer.json | 1 - lib/Jwt/.github/workflows/run-test.yml | 2 -- lib/Jwt/Makefile | 4 --- lib/Jwt/composer.json | 3 +-- lib/Jwt/phpcs.xml.dist | 14 ---------- lib/Markdown/.github/workflows/run-test.yml | 2 -- lib/Markdown/Makefile | 3 --- lib/Markdown/composer.json | 3 +-- lib/Markdown/phpcs.xml.dist | 14 ---------- lib/Models/.github/workflows/run-test.yml | 2 -- lib/Models/composer.json | 3 +-- lib/Models/phpcs.xml.dist | 13 ---------- lib/OpenId/.github/workflows/run-test.yml | 2 -- lib/OpenId/Makefile | 4 --- lib/OpenId/composer.json | 3 +-- lib/OpenId/phpcs.xml.dist | 14 ---------- lib/Random/.github/workflows/run-test.yml | 2 -- lib/Random/Makefile | 3 --- lib/Random/composer.json | 3 +-- lib/Random/phpcs.xml.dist | 14 ---------- .../.github/workflows/run-test.yml | 2 -- lib/RoadizCompatBundle/Makefile | 3 --- lib/RoadizCompatBundle/composer.json | 3 +-- lib/RoadizCompatBundle/phpcs.xml.dist | 13 ---------- .../.github/workflows/run-test.yml | 2 -- lib/RoadizCoreBundle/composer.json | 1 - lib/RoadizCoreBundle/phpcs.xml.dist | 13 ---------- .../.github/workflows/run-test.yml | 2 -- lib/RoadizFontBundle/Makefile | 3 --- lib/RoadizFontBundle/composer.json | 1 - lib/RoadizFontBundle/phpcs.xml.dist | 13 ---------- .../.github/workflows/run-test.yml | 2 -- lib/RoadizRozierBundle/Makefile | 3 --- lib/RoadizRozierBundle/composer.json | 3 +-- lib/RoadizRozierBundle/phpcs.xml.dist | 13 ---------- .../.github/workflows/run-test.yml | 2 -- lib/RoadizTwoFactorBundle/composer.json | 1 - lib/RoadizTwoFactorBundle/phpcs.xml.dist | 13 ---------- .../.github/workflows/run-test.yml | 2 -- lib/RoadizUserBundle/.gitignore | 4 --- lib/RoadizUserBundle/Makefile | 3 --- lib/RoadizUserBundle/composer.json | 3 +-- lib/RoadizUserBundle/phpcs.xml.dist | 13 ---------- lib/Rozier/.github/workflows/run-test.yml | 2 -- lib/Rozier/Makefile | 5 ---- lib/Rozier/composer.json | 3 +-- lib/Rozier/phpcs.xml.dist | 26 ------------------- 59 files changed, 12 insertions(+), 323 deletions(-) delete mode 100644 lib/DocGenerator/Makefile delete mode 100644 lib/DocGenerator/phpcs.xml.dist delete mode 100644 lib/Documents/phpcs.xml.dist delete mode 100644 lib/DtsGenerator/Makefile delete mode 100644 lib/DtsGenerator/phpcs.xml.dist delete mode 100644 lib/Jwt/Makefile delete mode 100644 lib/Jwt/phpcs.xml.dist delete mode 100644 lib/Markdown/Makefile delete mode 100644 lib/Markdown/phpcs.xml.dist delete mode 100644 lib/Models/phpcs.xml.dist delete mode 100644 lib/OpenId/Makefile delete mode 100644 lib/OpenId/phpcs.xml.dist delete mode 100644 lib/Random/Makefile delete mode 100644 lib/Random/phpcs.xml.dist delete mode 100644 lib/RoadizCompatBundle/Makefile delete mode 100644 lib/RoadizCompatBundle/phpcs.xml.dist delete mode 100644 lib/RoadizCoreBundle/phpcs.xml.dist delete mode 100644 lib/RoadizFontBundle/Makefile delete mode 100644 lib/RoadizFontBundle/phpcs.xml.dist delete mode 100644 lib/RoadizRozierBundle/Makefile delete mode 100644 lib/RoadizRozierBundle/phpcs.xml.dist delete mode 100644 lib/RoadizTwoFactorBundle/phpcs.xml.dist delete mode 100644 lib/RoadizUserBundle/Makefile delete mode 100644 lib/RoadizUserBundle/phpcs.xml.dist delete mode 100644 lib/Rozier/Makefile delete mode 100644 lib/Rozier/phpcs.xml.dist diff --git a/lib/DocGenerator/.github/workflows/run-test.yml b/lib/DocGenerator/.github/workflows/run-test.yml index b8b2c629..2d69d181 100644 --- a/lib/DocGenerator/.github/workflows/run-test.yml +++ b/lib/DocGenerator/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/DocGenerator/Makefile b/lib/DocGenerator/Makefile deleted file mode 100644 index 79021819..00000000 --- a/lib/DocGenerator/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -test: - vendor/bin/phpcs --report=full --report-file=./report.txt -p ./ - vendor/bin/phpstan analyse -c phpstan.neon - diff --git a/lib/DocGenerator/composer.json b/lib/DocGenerator/composer.json index 3c4c1e6e..ca753e10 100644 --- a/lib/DocGenerator/composer.json +++ b/lib/DocGenerator/composer.json @@ -23,8 +23,7 @@ } }, "require-dev": { - "phpstan/phpstan": "^1.5.3", - "squizlabs/php_codesniffer": "^3.5" + "phpstan/phpstan": "^1.5.3" }, "extra": { "branch-alias": { diff --git a/lib/DocGenerator/phpcs.xml.dist b/lib/DocGenerator/phpcs.xml.dist deleted file mode 100644 index 97e3c88c..00000000 --- a/lib/DocGenerator/phpcs.xml.dist +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - ./src - */node_modules - */.AppleDouble - */vendor - diff --git a/lib/Documents/.github/workflows/run-test.yml b/lib/Documents/.github/workflows/run-test.yml index 41775f9e..99e3d46c 100644 --- a/lib/Documents/.github/workflows/run-test.yml +++ b/lib/Documents/.github/workflows/run-test.yml @@ -37,7 +37,5 @@ jobs: run: composer install --no-scripts --no-ansi --no-interaction --no-progress - name: Run Unit tests run: vendor/bin/phpunit -v --whitelist ./src tests - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/Documents/composer.json b/lib/Documents/composer.json index cadc080c..b4cb11c7 100644 --- a/lib/Documents/composer.json +++ b/lib/Documents/composer.json @@ -48,8 +48,7 @@ "php-coveralls/php-coveralls": "^2.4", "phpstan/phpstan": "^1.5.3", "phpstan/phpstan-doctrine": "^1.3", - "phpunit/phpunit": "^9.5", - "squizlabs/php_codesniffer": "^3.5" + "phpunit/phpunit": "^9.5" }, "autoload": { "psr-4": { diff --git a/lib/Documents/phpcs.xml.dist b/lib/Documents/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/Documents/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/DtsGenerator/.github/workflows/run-test.yml b/lib/DtsGenerator/.github/workflows/run-test.yml index f93c401f..7f2d3d7e 100644 --- a/lib/DtsGenerator/.github/workflows/run-test.yml +++ b/lib/DtsGenerator/.github/workflows/run-test.yml @@ -36,7 +36,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/DtsGenerator/Makefile b/lib/DtsGenerator/Makefile deleted file mode 100644 index 9ab639a6..00000000 --- a/lib/DtsGenerator/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -test: - vendor/bin/phpcbf --report=full --report-file=./report.txt -p ./ - vendor/bin/phpstan analyse -c phpstan.neon - diff --git a/lib/DtsGenerator/composer.json b/lib/DtsGenerator/composer.json index 6001ffa1..1d640f79 100644 --- a/lib/DtsGenerator/composer.json +++ b/lib/DtsGenerator/composer.json @@ -7,8 +7,7 @@ "symfony/http-foundation": "6.4.*" }, "require-dev": { - "phpstan/phpstan": "^1.5.3", - "squizlabs/php_codesniffer": "^3.5" + "phpstan/phpstan": "^1.5.3" }, "license": "MIT", "authors": [ diff --git a/lib/DtsGenerator/phpcs.xml.dist b/lib/DtsGenerator/phpcs.xml.dist deleted file mode 100644 index 97e3c88c..00000000 --- a/lib/DtsGenerator/phpcs.xml.dist +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - ./src - */node_modules - */.AppleDouble - */vendor - diff --git a/lib/EntityGenerator/.github/workflows/run-test.yml b/lib/EntityGenerator/.github/workflows/run-test.yml index d3db004b..9017ed17 100644 --- a/lib/EntityGenerator/.github/workflows/run-test.yml +++ b/lib/EntityGenerator/.github/workflows/run-test.yml @@ -35,8 +35,6 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs --extensions=php --warning-severity=0 --standard=PSR12 -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon - name: Run unit tests diff --git a/lib/EntityGenerator/composer.json b/lib/EntityGenerator/composer.json index bf55423f..3a6c069f 100644 --- a/lib/EntityGenerator/composer.json +++ b/lib/EntityGenerator/composer.json @@ -35,7 +35,6 @@ } }, "require-dev": { - "squizlabs/php_codesniffer": "^3.5", "phpstan/phpstan": "^1.5.3", "phpunit/phpunit": "^9.5", "api-platform/core": "~3.3.11" diff --git a/lib/Jwt/.github/workflows/run-test.yml b/lib/Jwt/.github/workflows/run-test.yml index d7371a17..2d69d181 100644 --- a/lib/Jwt/.github/workflows/run-test.yml +++ b/lib/Jwt/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs --extensions=php --warning-severity=0 --standard=PSR12 -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/Jwt/Makefile b/lib/Jwt/Makefile deleted file mode 100644 index 7e60d0ef..00000000 --- a/lib/Jwt/Makefile +++ /dev/null @@ -1,4 +0,0 @@ - -test: - vendor/bin/phpcs --report=full --report-file=./report.txt -p ./src - vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/Jwt/composer.json b/lib/Jwt/composer.json index 223312e9..a3780e3b 100644 --- a/lib/Jwt/composer.json +++ b/lib/Jwt/composer.json @@ -17,8 +17,7 @@ "symfony/http-client": "6.4.*" }, "require-dev": { - "phpstan/phpstan": "^1.5.3", - "squizlabs/php_codesniffer": "^3.5" + "phpstan/phpstan": "^1.5.3" }, "autoload": { "psr-4": { diff --git a/lib/Jwt/phpcs.xml.dist b/lib/Jwt/phpcs.xml.dist deleted file mode 100644 index da4bfdb5..00000000 --- a/lib/Jwt/phpcs.xml.dist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - ./src - diff --git a/lib/Markdown/.github/workflows/run-test.yml b/lib/Markdown/.github/workflows/run-test.yml index d7371a17..2d69d181 100644 --- a/lib/Markdown/.github/workflows/run-test.yml +++ b/lib/Markdown/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs --extensions=php --warning-severity=0 --standard=PSR12 -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/Markdown/Makefile b/lib/Markdown/Makefile deleted file mode 100644 index 5f4d6d24..00000000 --- a/lib/Markdown/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -test: - vendor/bin/phpcs --report=full --report-file=./report.txt -p ./src - vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/Markdown/composer.json b/lib/Markdown/composer.json index 003f3c47..fade4ff4 100644 --- a/lib/Markdown/composer.json +++ b/lib/Markdown/composer.json @@ -10,8 +10,7 @@ "twig/twig": "^3.1" }, "require-dev": { - "phpstan/phpstan": "^1.5.3", - "squizlabs/php_codesniffer": "^3.5" + "phpstan/phpstan": "^1.5.3" }, "license": "MIT", "authors": [ diff --git a/lib/Markdown/phpcs.xml.dist b/lib/Markdown/phpcs.xml.dist deleted file mode 100644 index da4bfdb5..00000000 --- a/lib/Markdown/phpcs.xml.dist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - ./src - diff --git a/lib/Models/.github/workflows/run-test.yml b/lib/Models/.github/workflows/run-test.yml index ec28386c..49e8d32b 100644 --- a/lib/Models/.github/workflows/run-test.yml +++ b/lib/Models/.github/workflows/run-test.yml @@ -37,7 +37,5 @@ jobs: run: composer install --no-scripts --no-ansi --no-interaction --no-progress - name: Run PHPUnit tests run: vendor/bin/phpunit -v --whitelist ./src tests - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/Models/composer.json b/lib/Models/composer.json index a81bf099..52e2dc2a 100644 --- a/lib/Models/composer.json +++ b/lib/Models/composer.json @@ -32,8 +32,7 @@ "doctrine/doctrine-bundle": "^2.8.1", "php-coveralls/php-coveralls": "^2.4", "phpstan/phpstan": "^1.5.3", - "phpunit/phpunit": "^9.5", - "squizlabs/php_codesniffer": "^3.5" + "phpunit/phpunit": "^9.5" }, "autoload": { "psr-4": { diff --git a/lib/Models/phpcs.xml.dist b/lib/Models/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/Models/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/OpenId/.github/workflows/run-test.yml b/lib/OpenId/.github/workflows/run-test.yml index d7371a17..2d69d181 100644 --- a/lib/OpenId/.github/workflows/run-test.yml +++ b/lib/OpenId/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs --extensions=php --warning-severity=0 --standard=PSR12 -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/OpenId/Makefile b/lib/OpenId/Makefile deleted file mode 100644 index 7e60d0ef..00000000 --- a/lib/OpenId/Makefile +++ /dev/null @@ -1,4 +0,0 @@ - -test: - vendor/bin/phpcs --report=full --report-file=./report.txt -p ./src - vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/OpenId/composer.json b/lib/OpenId/composer.json index 7992d6c6..2884ca38 100644 --- a/lib/OpenId/composer.json +++ b/lib/OpenId/composer.json @@ -30,8 +30,7 @@ "symfony/security-http": "6.4.*" }, "require-dev": { - "phpstan/phpstan": "^1.5.3", - "squizlabs/php_codesniffer": "^3.5" + "phpstan/phpstan": "^1.5.3" }, "autoload": { "psr-4": { diff --git a/lib/OpenId/phpcs.xml.dist b/lib/OpenId/phpcs.xml.dist deleted file mode 100644 index da4bfdb5..00000000 --- a/lib/OpenId/phpcs.xml.dist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - ./src - diff --git a/lib/Random/.github/workflows/run-test.yml b/lib/Random/.github/workflows/run-test.yml index d7371a17..2d69d181 100644 --- a/lib/Random/.github/workflows/run-test.yml +++ b/lib/Random/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs --extensions=php --warning-severity=0 --standard=PSR12 -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/Random/Makefile b/lib/Random/Makefile deleted file mode 100644 index 5f4d6d24..00000000 --- a/lib/Random/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -test: - vendor/bin/phpcs --report=full --report-file=./report.txt -p ./src - vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/Random/composer.json b/lib/Random/composer.json index a8819e19..a0e4a7f8 100644 --- a/lib/Random/composer.json +++ b/lib/Random/composer.json @@ -17,8 +17,7 @@ "ext-openssl": "*" }, "require-dev": { - "phpstan/phpstan": "^1.5.3", - "squizlabs/php_codesniffer": "^3.5" + "phpstan/phpstan": "^1.5.3" }, "autoload": { "psr-4": { diff --git a/lib/Random/phpcs.xml.dist b/lib/Random/phpcs.xml.dist deleted file mode 100644 index da4bfdb5..00000000 --- a/lib/Random/phpcs.xml.dist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - ./src - diff --git a/lib/RoadizCompatBundle/.github/workflows/run-test.yml b/lib/RoadizCompatBundle/.github/workflows/run-test.yml index 5b0323a5..3b9abf45 100644 --- a/lib/RoadizCompatBundle/.github/workflows/run-test.yml +++ b/lib/RoadizCompatBundle/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/RoadizCompatBundle/Makefile b/lib/RoadizCompatBundle/Makefile deleted file mode 100644 index 16ef8148..00000000 --- a/lib/RoadizCompatBundle/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -test: - php -d "memory_limit=-1" vendor/bin/phpcbf --report=full --report-file=./report.txt -p ./src - php -d "memory_limit=-1" vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/RoadizCompatBundle/composer.json b/lib/RoadizCompatBundle/composer.json index 32308cbe..3c2717ce 100644 --- a/lib/RoadizCompatBundle/composer.json +++ b/lib/RoadizCompatBundle/composer.json @@ -35,8 +35,7 @@ "roadiz/jwt": "2.4.x-dev", "roadiz/markdown": "2.4.x-dev", "roadiz/models": "2.4.x-dev", - "roadiz/random": "2.4.x-dev", - "squizlabs/php_codesniffer": "^3.5" + "roadiz/random": "2.4.x-dev" }, "config": { "optimize-autoloader": true, diff --git a/lib/RoadizCompatBundle/phpcs.xml.dist b/lib/RoadizCompatBundle/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/RoadizCompatBundle/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/RoadizCoreBundle/.github/workflows/run-test.yml b/lib/RoadizCoreBundle/.github/workflows/run-test.yml index c4d69727..a5e3045f 100644 --- a/lib/RoadizCoreBundle/.github/workflows/run-test.yml +++ b/lib/RoadizCoreBundle/.github/workflows/run-test.yml @@ -35,8 +35,6 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon - name: Run PHP Unit diff --git a/lib/RoadizCoreBundle/composer.json b/lib/RoadizCoreBundle/composer.json index 5f18d247..08642dfd 100644 --- a/lib/RoadizCoreBundle/composer.json +++ b/lib/RoadizCoreBundle/composer.json @@ -102,7 +102,6 @@ "phpstan/phpstan": "^1.5.3", "phpstan/phpstan-doctrine": "^1.3", "phpunit/phpunit": "^9.5", - "squizlabs/php_codesniffer": "^3.5", "symfony/browser-kit": "6.4.*", "symfony/phpunit-bridge": "^7.0", "symfony/stopwatch": "6.4.*" diff --git a/lib/RoadizCoreBundle/phpcs.xml.dist b/lib/RoadizCoreBundle/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/RoadizCoreBundle/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/RoadizFontBundle/.github/workflows/run-test.yml b/lib/RoadizFontBundle/.github/workflows/run-test.yml index 5b0323a5..3b9abf45 100644 --- a/lib/RoadizFontBundle/.github/workflows/run-test.yml +++ b/lib/RoadizFontBundle/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/RoadizFontBundle/Makefile b/lib/RoadizFontBundle/Makefile deleted file mode 100644 index 16ef8148..00000000 --- a/lib/RoadizFontBundle/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -test: - php -d "memory_limit=-1" vendor/bin/phpcbf --report=full --report-file=./report.txt -p ./src - php -d "memory_limit=-1" vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/RoadizFontBundle/composer.json b/lib/RoadizFontBundle/composer.json index fb9e8edd..5651230f 100644 --- a/lib/RoadizFontBundle/composer.json +++ b/lib/RoadizFontBundle/composer.json @@ -59,7 +59,6 @@ "roadiz/documents": "2.4.x-dev", "roadiz/entity-generator": "2.4.x-dev", "roadiz/rozier-bundle": "2.4.x-dev", - "squizlabs/php_codesniffer": "^3.5", "symfony/browser-kit": "6.4.*", "symfony/phpunit-bridge": "^7.0", "symfony/stopwatch": "6.4.*" diff --git a/lib/RoadizFontBundle/phpcs.xml.dist b/lib/RoadizFontBundle/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/RoadizFontBundle/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/RoadizRozierBundle/.github/workflows/run-test.yml b/lib/RoadizRozierBundle/.github/workflows/run-test.yml index 5b0323a5..3b9abf45 100644 --- a/lib/RoadizRozierBundle/.github/workflows/run-test.yml +++ b/lib/RoadizRozierBundle/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/RoadizRozierBundle/Makefile b/lib/RoadizRozierBundle/Makefile deleted file mode 100644 index 16ef8148..00000000 --- a/lib/RoadizRozierBundle/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -test: - php -d "memory_limit=-1" vendor/bin/phpcbf --report=full --report-file=./report.txt -p ./src - php -d "memory_limit=-1" vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/RoadizRozierBundle/composer.json b/lib/RoadizRozierBundle/composer.json index 997eeb28..ee08cb94 100644 --- a/lib/RoadizRozierBundle/composer.json +++ b/lib/RoadizRozierBundle/composer.json @@ -30,8 +30,7 @@ "php-coveralls/php-coveralls": "^2.4", "phpstan/phpstan": "^1.5.3", "phpstan/phpstan-doctrine": "^1.3", - "phpstan/phpstan-symfony": "^1.1.8", - "squizlabs/php_codesniffer": "^3.5" + "phpstan/phpstan-symfony": "^1.1.8" }, "config": { "optimize-autoloader": true, diff --git a/lib/RoadizRozierBundle/phpcs.xml.dist b/lib/RoadizRozierBundle/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/RoadizRozierBundle/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/RoadizTwoFactorBundle/.github/workflows/run-test.yml b/lib/RoadizTwoFactorBundle/.github/workflows/run-test.yml index 5b0323a5..3b9abf45 100644 --- a/lib/RoadizTwoFactorBundle/.github/workflows/run-test.yml +++ b/lib/RoadizTwoFactorBundle/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/RoadizTwoFactorBundle/composer.json b/lib/RoadizTwoFactorBundle/composer.json index 748ca3b0..e6be1612 100644 --- a/lib/RoadizTwoFactorBundle/composer.json +++ b/lib/RoadizTwoFactorBundle/composer.json @@ -43,7 +43,6 @@ "roadiz/entity-generator": "2.4.x-dev", "roadiz/jwt": "2.4.x-dev", "roadiz/random": "2.4.x-dev", - "squizlabs/php_codesniffer": "^3.5", "symfony/stopwatch": "6.4.*" }, "config": { diff --git a/lib/RoadizTwoFactorBundle/phpcs.xml.dist b/lib/RoadizTwoFactorBundle/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/RoadizTwoFactorBundle/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/RoadizUserBundle/.github/workflows/run-test.yml b/lib/RoadizUserBundle/.github/workflows/run-test.yml index 5b0323a5..3b9abf45 100644 --- a/lib/RoadizUserBundle/.github/workflows/run-test.yml +++ b/lib/RoadizUserBundle/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/RoadizUserBundle/.gitignore b/lib/RoadizUserBundle/.gitignore index e36c4c58..63e53f9f 100644 --- a/lib/RoadizUserBundle/.gitignore +++ b/lib/RoadizUserBundle/.gitignore @@ -118,9 +118,5 @@ modules.xml /lib/ /.data/ -###> squizlabs/php_codesniffer ### -/.phpcs-cache -/phpcs.xml -###< squizlabs/php_codesniffer ### /report.txt /composer.lock diff --git a/lib/RoadizUserBundle/Makefile b/lib/RoadizUserBundle/Makefile deleted file mode 100644 index 16ef8148..00000000 --- a/lib/RoadizUserBundle/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -test: - php -d "memory_limit=-1" vendor/bin/phpcbf --report=full --report-file=./report.txt -p ./src - php -d "memory_limit=-1" vendor/bin/phpstan analyse -c phpstan.neon diff --git a/lib/RoadizUserBundle/composer.json b/lib/RoadizUserBundle/composer.json index 466fd98d..cd33e818 100644 --- a/lib/RoadizUserBundle/composer.json +++ b/lib/RoadizUserBundle/composer.json @@ -35,8 +35,7 @@ "roadiz/doc-generator": "2.4.x-dev", "roadiz/entity-generator": "2.4.x-dev", "roadiz/jwt": "2.4.x-dev", - "roadiz/random": "2.4.x-dev", - "squizlabs/php_codesniffer": "^3.5" + "roadiz/random": "2.4.x-dev" }, "config": { "optimize-autoloader": true, diff --git a/lib/RoadizUserBundle/phpcs.xml.dist b/lib/RoadizUserBundle/phpcs.xml.dist deleted file mode 100644 index 19bff0cc..00000000 --- a/lib/RoadizUserBundle/phpcs.xml.dist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - src/ - diff --git a/lib/Rozier/.github/workflows/run-test.yml b/lib/Rozier/.github/workflows/run-test.yml index 5b0323a5..3b9abf45 100644 --- a/lib/Rozier/.github/workflows/run-test.yml +++ b/lib/Rozier/.github/workflows/run-test.yml @@ -35,7 +35,5 @@ jobs: ${{ runner.os }}-php-${{ matrix.php-version }}- - name: Install Dependencies run: composer install --no-scripts --no-ansi --no-interaction --no-progress - - name: Run PHP Code Sniffer - run: vendor/bin/phpcs -p ./src - name: Run PHPStan run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon diff --git a/lib/Rozier/Makefile b/lib/Rozier/Makefile deleted file mode 100644 index 865ab9a1..00000000 --- a/lib/Rozier/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - php -d "memory_limit=-1" vendor/bin/phpcs --report=full --report-file=./report.txt -p ./ - php -d "memory_limit=-1" vendor/bin/phpstan analyse -c phpstan.neon - diff --git a/lib/Rozier/composer.json b/lib/Rozier/composer.json index 84e8b005..cc99b80b 100644 --- a/lib/Rozier/composer.json +++ b/lib/Rozier/composer.json @@ -69,8 +69,7 @@ "phpstan/phpstan-doctrine": "^1.3", "roadiz/entity-generator": "2.4.x-dev", "roadiz/jwt": "2.4.x-dev", - "roadiz/random": "2.4.x-dev", - "squizlabs/php_codesniffer": "^3.5" + "roadiz/random": "2.4.x-dev" }, "autoload": { "psr-4": { diff --git a/lib/Rozier/phpcs.xml.dist b/lib/Rozier/phpcs.xml.dist deleted file mode 100644 index 8e43eb01..00000000 --- a/lib/Rozier/phpcs.xml.dist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - ./ - *.js - *.vue - */Resources/app - */node_modules - */.AppleDouble - */vendor - */cache - */gen-src - */tests - */bin - */themes - .data/* - From bad46f3d353f985de69b4c282dceeb0643ecdda9 Mon Sep 17 00:00:00 2001 From: Ambroise Maupate Date: Wed, 6 Nov 2024 01:19:37 +0100 Subject: [PATCH 3/5] refactor: Removed squizlabs/php_codesniffer files --- .phpcs.xml | 29 ----------------------------- 1 file changed, 29 deletions(-) delete mode 100644 .phpcs.xml diff --git a/.phpcs.xml b/.phpcs.xml deleted file mode 100644 index 694a396f..00000000 --- a/.phpcs.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - The coding standard for Roadiz monorepo. - - - - - - - */node_modules/* - */bower_components/* - - lib/DocGenerator/src - lib/Documents/src - lib/DtsGenerator/src - lib/EntityGenerator/src - lib/Jwt/src - lib/Markdown/src - lib/Models/src - lib/OpenId/src - lib/Random/src - lib/RoadizCompatBundle/src - lib/RoadizCoreBundle/src - lib/RoadizFontBundle/src - lib/RoadizRozierBundle/src - lib/RoadizUserBundle/src - lib/RoadizTwoFactorBundle/src - lib/Rozier/src - From 6be7822e12293f34cecd6fdd07e709124e2da8a9 Mon Sep 17 00:00:00 2001 From: Ambroise Maupate Date: Wed, 6 Nov 2024 01:24:11 +0100 Subject: [PATCH 4/5] chore: Ignore config/bundles.php in php-cs-fixer --- .php-cs-fixer.dist.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 3d2bdab8..0d815ddc 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -2,7 +2,7 @@ $finder = (new PhpCsFixer\Finder()) ->in(__DIR__) - ->exclude(['var', 'vendor', 'docker', 'lib/EntityGenerator/tests/Mocks']) + ->exclude(['var', 'vendor', 'docker', 'lib/EntityGenerator/tests/Mocks', 'config/bundles.php']) ; return (new PhpCsFixer\Config()) From a77a821ce2a06041af5f3e84971121104c4967e1 Mon Sep 17 00:00:00 2001 From: Ambroise Maupate Date: Wed, 6 Nov 2024 01:27:41 +0100 Subject: [PATCH 5/5] chore: Ignore config/bundles.php in php-cs-fixer --- .php-cs-fixer.dist.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 0d815ddc..95e3088c 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -2,7 +2,7 @@ $finder = (new PhpCsFixer\Finder()) ->in(__DIR__) - ->exclude(['var', 'vendor', 'docker', 'lib/EntityGenerator/tests/Mocks', 'config/bundles.php']) + ->exclude(['var', 'vendor', 'docker', 'lib/EntityGenerator/tests/Mocks', 'config']) ; return (new PhpCsFixer\Config())