diff --git a/.github/workflows/run-test.yml b/.github/workflows/run-test.yml
index 2fe1003b..a5e3045f 100644
--- a/.github/workflows/run-test.yml
+++ b/.github/workflows/run-test.yml
@@ -19,7 +19,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- php-version: ['8.1', '8.2', '8.3']
+ php-version: ['8.2', '8.3']
steps:
- uses: shivammathur/setup-php@v2
with:
@@ -34,9 +34,7 @@ jobs:
restore-keys: |
${{ 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
+ run: composer install --no-ansi --no-interaction --no-progress
- name: Run PHPStan
run: vendor/bin/phpstan analyse --no-progress -c phpstan.neon
- name: Run PHP Unit
diff --git a/composer.json b/composer.json
index d4ca8d28..9df8748e 100644
--- a/composer.json
+++ b/composer.json
@@ -18,54 +18,55 @@
"type": "symfony-bundle",
"prefer-stable": true,
"require": {
- "php": ">=8.1",
+ "php": ">=8.2",
"ext-ctype": "*",
"ext-iconv": "*",
"ext-zip": "*",
"ext-json": "*",
- "api-platform/core": "~3.2.14",
- "doctrine/annotations": "^1.0",
+ "ext-mbstring": "*",
+ "api-platform/core": "~3.3.11",
+ "doctrine/annotations": "^2.0",
"doctrine/doctrine-bundle": "^2.8.1",
"doctrine/doctrine-migrations-bundle": "^3.1",
- "doctrine/orm": "~2.19.0",
- "gedmo/doctrine-extensions": "^3.10.0",
+ "doctrine/orm": "~2.20.0",
+ "gedmo/doctrine-extensions": "^3.16.1",
"inlinestyle/inlinestyle": "~1.2.7",
"james-heinrich/getid3": "^1.9",
"jms/serializer": "^3.9.0",
"jms/serializer-bundle": "^4.2.0",
"league/flysystem": "^3.0",
"league/flysystem-bundle": "^3.0",
- "lexik/jwt-authentication-bundle": "^2.19",
+ "lexik/jwt-authentication-bundle": "^3.1.0",
"phpdocumentor/reflection-docblock": "^5.2",
"phpoffice/phpspreadsheet": "^1.15",
"ramsey/uuid": "^4.7",
- "rezozero/intervention-request-bundle": "~3.0.0",
- "rezozero/liform-bundle": "^0.19",
+ "rezozero/intervention-request-bundle": "~3.0.1",
+ "rezozero/liform-bundle": "^0.20.1",
"rezozero/tree-walker": "^1.5.0",
- "roadiz/doc-generator": "2.3.*",
- "roadiz/documents": "2.3.*",
- "roadiz/dts-generator": "2.3.*",
- "roadiz/entity-generator": "2.3.*",
- "roadiz/jwt": "2.3.*",
- "roadiz/markdown": "2.3.*",
- "roadiz/models": "2.3.*",
+ "roadiz/doc-generator": "2.4.*",
+ "roadiz/documents": "2.4.*",
+ "roadiz/dts-generator": "2.4.*",
+ "roadiz/entity-generator": "2.4.*",
+ "roadiz/jwt": "2.4.*",
+ "roadiz/markdown": "2.4.*",
+ "roadiz/models": "2.4.*",
"roadiz/nodetype-contracts": "~1.1.2",
- "roadiz/random": "2.3.*",
- "rollerworks/password-common-list": "^0.2.0",
- "rollerworks/password-strength-bundle": "^2.2",
+ "roadiz/random": "2.4.*",
+ "rollerworks/password-common-list": "^0.3.0",
+ "rollerworks/password-strength-bundle": "^3.0",
"scienta/doctrine-json-functions": "^4.2",
- "sensio/framework-extra-bundle": "^6.1",
- "solarium/solarium": "^6.0.4",
- "symfony-cmf/routing-bundle": "^3.0.2",
+ "solarium/solarium": "^6.3.6",
+ "symfony-cmf/routing-bundle": "^3.1.0",
"symfony/asset": "6.4.*",
"symfony/cache": "6.4.*",
"symfony/console": "6.4.*",
"symfony/dotenv": "6.4.*",
"symfony/expression-language": "6.4.*",
- "symfony/flex": "^2.2.3",
+ "symfony/flex": "^2.4.7",
"symfony/form": "6.4.*",
"symfony/framework-bundle": "6.4.*",
"symfony/http-client": "6.4.*",
+ "symfony/http-client-contracts": "^3.5",
"symfony/intl": "6.4.*",
"symfony/lock": "6.4.*",
"symfony/mailer": "6.4.*",
@@ -88,10 +89,10 @@
"symfony/web-link": "6.4.*",
"symfony/workflow": "6.4.*",
"symfony/yaml": "6.4.*",
- "twig/extra-bundle": "^3.0",
+ "twig/extra-bundle": "^3.16",
"twig/intl-extra": "*",
"twig/string-extra": "*",
- "twig/twig": "^3.1"
+ "twig/twig": "^3.16"
},
"replace": {
"roadiz/roadiz": "*"
@@ -101,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.*"
@@ -136,8 +136,8 @@
},
"extra": {
"branch-alias": {
- "dev-main": "2.3.x-dev",
- "dev-develop": "2.4.x-dev"
+ "dev-main": "2.4.x-dev",
+ "dev-develop": "2.5.x-dev"
}
}
}
diff --git a/config/packages/api_platform.yaml b/config/packages/api_platform.yaml
index f9551bd7..20c65cc5 100644
--- a/config/packages/api_platform.yaml
+++ b/config/packages/api_platform.yaml
@@ -1,17 +1,34 @@
+parameters:
+ env(HTTP_CACHE_STALE_WHILE_REVALIDATE): 3600
+ env(HTTP_CACHE_MAX_AGE): 60
+ env(HTTP_CACHE_SHARED_MAX_AGE): 600
+
api_platform:
- patch_formats:
- json: ['application/merge-patch+json']
- enable_swagger_ui: false
+ title: "%env(string:APP_TITLE)%"
+ description: "%env(string:APP_DESCRIPTION)%"
+ version: '%env(string:APP_VERSION)%'
+ enable_swagger_ui: true
enable_re_doc: true
+ # Symfony inflector wrongly pluralizes "nodes_sources" to "nodes_sourcess"
+ keep_legacy_inflector: true
+ use_symfony_listeners: true
+ formats:
+ jsonld: ['application/ld+json']
+ json: ['application/json']
+ x-www-form-urlencoded: ['application/x-www-form-urlencoded']
+ docs_formats:
+ jsonld: ['application/ld+json']
+ jsonopenapi: ['application/vnd.openapi+json']
+ html: ['text/html']
+ patch_formats:
+ json: [ 'application/merge-patch+json' ]
graphql:
+ introspection: '%kernel.debug%'
graphiql:
enabled: false
+ graphql_playground:
+ enabled: false
show_webby: false
- swagger:
- versions: [3]
- title: "%env(string:APP_TITLE)%"
- description: "%env(string:APP_DESCRIPTION)%"
- version: '%env(string:APP_VERSION)%'
mapping:
paths:
- '%kernel.project_dir%/src/Entity'
@@ -19,18 +36,13 @@ api_platform:
- '%kernel.project_dir%/vendor/roadiz/core-bundle/src/Entity'
- '%kernel.project_dir%/vendor/rezozero/tree-walker/src'
- '%kernel.project_dir%/config/api_resources'
-
- collection:
- pagination:
- page_parameter_name: page
- items_per_page_parameter_name: itemsPerPage
-
- http_cache:
- invalidation:
- enabled: true
- varnish_urls: [ '%env(VARNISH_URL)%' ]
-
+ swagger:
+ versions: [3]
defaults:
+ stateless: true
+ extra_properties:
+ standard_put: true
+ rfc_7807_compliant_errors: false
enable_max_depth: true
normalization_context:
skip_null_values: true
@@ -38,8 +50,29 @@ api_platform:
pagination_items_per_page: 15
pagination_maximum_items_per_page: 50
cache_headers:
+ # Automatically generate etags for API responses.
etag: true
public: true
+ # Default value for the response max age.
max_age: '%env(int:HTTP_CACHE_MAX_AGE)%'
+ # Default value for the response shared (proxy) max age.
shared_max_age: '%env(int:HTTP_CACHE_SHARED_MAX_AGE)%'
- vary: [ 'Accept', 'Authorization', 'Origin', 'Accept-Encoding', 'Content-Type' ]
+ stale_while_revalidate: '%env(int:HTTP_CACHE_STALE_WHILE_REVALIDATE)%'
+ # Default values of the "Vary" HTTP header.
+ vary: ['Accept', 'Authorization', 'Origin', 'Accept-Encoding', 'Content-Type']
+ collection:
+ pagination:
+ items_per_page_parameter_name: itemsPerPage
+
+when@prod:
+ api_platform:
+ graphql:
+ introspection: false
+ graphiql:
+ enabled: false
+ graphql_playground:
+ enabled: false
+ http_cache:
+ invalidation:
+ enabled: true
+ varnish_urls: [ '%env(VARNISH_URL)%' ]
diff --git a/config/packages/framework.yaml b/config/packages/framework.yaml
index ed735a18..d135adc5 100644
--- a/config/packages/framework.yaml
+++ b/config/packages/framework.yaml
@@ -20,6 +20,7 @@ framework:
serializer:
circular_reference_handler: 'RZ\Roadiz\CoreBundle\Serializer\CircularReferenceHandler'
max_depth_handler: 'RZ\Roadiz\CoreBundle\Serializer\CircularReferenceHandler'
+ handle_all_throwables: true
csrf_protection:
enabled: true
diff --git a/config/packages/security.yaml b/config/packages/security.yaml
index 8324dc43..b314b29a 100644
--- a/config/packages/security.yaml
+++ b/config/packages/security.yaml
@@ -75,6 +75,16 @@ security:
secret: '%kernel.secret%'
lifetime: 604800 # 1 week in seconds
path: /
+ # Enable login-link feature
+ # https://symfony.com/doc/current/security/login_link.html
+ login_link:
+ check_route: login_link_check
+ signature_properties: [ 'id', 'email' ]
+ # lifetime in seconds
+ lifetime: 300
+ # only allow the link to be used 3 times
+ max_uses: 3
+ success_handler: RZ\Roadiz\CoreBundle\Security\Authentication\BackofficeAuthenticationSuccessHandler
login_throttling:
max_attempts: 3
logout:
diff --git a/config/services.yaml b/config/services.yaml
index 1ef2b07b..a9831817 100644
--- a/config/services.yaml
+++ b/config/services.yaml
@@ -1,6 +1,6 @@
---
parameters:
- roadiz_core.cms_version: '2.3.31'
+ roadiz_core.cms_version: '2.4.0'
roadiz_core.cms_version_prefix: 'main'
env(APP_NAMESPACE): "roadiz"
env(APP_VERSION): "0.1.0"
@@ -61,8 +61,11 @@ services:
- '../src/Traits/'
- '../src/Kernel.php'
- '../src/Tests/'
- - '../src/DataCollector/'
- '../src/Event/'
+ - '../src/Model/'
+ - '../src/ListManager/'
+ - '../src/Serializer/Normalizer/'
+ - '../src/Importer/'
RZ\Roadiz\CoreBundle\EntityHandler\:
resource: '../src/EntityHandler/'
@@ -95,8 +98,6 @@ services:
tags: [ { name: 'roadiz_core.media_finder', platform: 'ted' } ]
RZ\Roadiz\CoreBundle\Document\MediaFinder\PodcastFinder:
tags: [ { name: 'roadiz_core.media_finder', platform: 'podcast' } ]
- RZ\Roadiz\CoreBundle\Document\MediaFinder\TwitchEmbedFinder:
- tags: [ { name: 'roadiz_core.media_finder', platform: 'twitch' } ]
# Removed DataTransformers
RZ\Roadiz\CoreBundle\Api\DataTransformer\:
@@ -178,16 +179,6 @@ services:
decorates: 'api_platform.serializer.normalizer.item'
decoration_priority: 21
- RZ\Roadiz\CoreBundle\DataCollector\RequestDataCollector:
- autoconfigure: false
- arguments: [ '%roadiz_core.cms_version%', '%roadiz_core.cms_version_prefix%']
- tags:
- - name: data_collector
- template: '@RoadizCore/DataCollector/request.html.twig'
- # must match the value returned by the getName() method
- id: 'roadiz.data_collector.request'
- priority: 400
-
# Document
RZ\Roadiz\CoreBundle\Serializer\Normalizer\DocumentNormalizer:
# By default, .inner is passed as argument
@@ -412,11 +403,6 @@ services:
RZ\Roadiz\CoreBundle\SearchEngine\ClientRegistry:
arguments: ['@service_container']
- RZ\Roadiz\CoreBundle\SearchEngine\SolariumLogger:
- tags:
- - { name: data_collector, template: '@RoadizCore/DataCollector/solarium.html.twig', id: 'solarium' }
- - { name: monolog.logger, channel: solr }
-
RZ\Roadiz\CoreBundle\SearchEngine\Indexer\IndexerFactory:
arguments: ['@service_container']
@@ -455,7 +441,12 @@ services:
arguments: ['%kernel.project_dir%']
public: true
- RZ\Roadiz\Random\PasswordGenerator: ~
+ RZ\Roadiz\Random\PasswordGeneratorInterface:
+ class: RZ\Roadiz\Random\PasswordGenerator
+ RZ\Roadiz\Random\SaltGeneratorInterface:
+ class: RZ\Roadiz\Random\SaltGenerator
+ RZ\Roadiz\Random\TokenGeneratorInterface:
+ class: RZ\Roadiz\Random\TokenGenerator
JMS\Serializer\Construction\ObjectConstructorInterface:
alias: RZ\Roadiz\CoreBundle\Serializer\ObjectConstructor\ObjectConstructor
@@ -480,9 +471,6 @@ services:
Solarium\Core\Client\Client:
factory: ['RZ\Roadiz\CoreBundle\SearchEngine\ClientRegistry', 'getClient']
- RZ\Roadiz\CoreBundle\Security\Authentication\JwtAuthenticationSuccessHandler:
- decorates: 'lexik_jwt_authentication.handler.authentication_success'
-
RZ\Roadiz\CoreBundle\Security\Authorization\Chroot\NodeChrootResolver:
alias: RZ\Roadiz\CoreBundle\Security\Authorization\Chroot\NodeChrootChainResolver
@@ -534,6 +522,7 @@ services:
#
RZ\Roadiz\CoreBundle\Document\MediaFinder\UnsplashPictureFinder:
arguments:
+ - '@http_client'
- '%roadiz_core.medias.unsplash_client_id%'
RZ\Roadiz\Documents\MediaFinders\RandomImageFinder:
alias: RZ\Roadiz\CoreBundle\Document\MediaFinder\UnsplashPictureFinder
@@ -557,6 +546,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:
@@ -655,6 +645,7 @@ services:
RZ\Roadiz\Documents\MediaFinders\EmbedFinderFactory:
arguments:
+ - '@http_client'
- '%roadiz_core.medias.supported_platforms%'
RZ\Roadiz\Documents\Renderer\ChainRenderer:
diff --git a/migrations/Version20201203004857.php b/migrations/Version20201203004857.php
index 48ccc417..57294c19 100644
--- a/migrations/Version20201203004857.php
+++ b/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/migrations/Version20201214232628.php b/migrations/Version20201214232628.php
index 3ec778c3..0f7a852c 100644
--- a/migrations/Version20201214232628.php
+++ b/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/migrations/Version20201225181256.php b/migrations/Version20201225181256.php
index 3e099267..91e16547 100644
--- a/migrations/Version20201225181256.php
+++ b/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/migrations/Version20210423072744.php b/migrations/Version20210423072744.php
index 2a92eff7..c463eaca 100644
--- a/migrations/Version20210423072744.php
+++ b/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/migrations/Version20210423161606.php b/migrations/Version20210423161606.php
index 56ae3af1..707e52e2 100644
--- a/migrations/Version20210423161606.php
+++ b/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/migrations/Version20210423164248.php b/migrations/Version20210423164248.php
index 74af5a4a..044e1cfc 100644
--- a/migrations/Version20210423164248.php
+++ b/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/migrations/Version20210506085247.php b/migrations/Version20210506085247.php
index d1801bc4..11f2f7c3 100644
--- a/migrations/Version20210506085247.php
+++ b/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/migrations/Version20210520092543.php b/migrations/Version20210520092543.php
index d20d9cc3..1b38b5ba 100644
--- a/migrations/Version20210520092543.php
+++ b/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/migrations/Version20210527131435.php b/migrations/Version20210527131435.php
index 44edb4ff..081ec0ae 100644
--- a/migrations/Version20210527131435.php
+++ b/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/migrations/Version20210701151713.php b/migrations/Version20210701151713.php
index 00a6a06e..c0e65fd7 100644
--- a/migrations/Version20210701151713.php
+++ b/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/migrations/Version20210715120118.php b/migrations/Version20210715120118.php
index 9e28c5b6..9a577148 100644
--- a/migrations/Version20210715120118.php
+++ b/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/migrations/Version20240713204610.php b/migrations/Version20240713204610.php
new file mode 100644
index 00000000..80c938de
--- /dev/null
+++ b/migrations/Version20240713204610.php
@@ -0,0 +1,31 @@
+addSql('CREATE INDEX ns_no_index ON nodes_sources (no_index)');
+ }
+
+ public function down(Schema $schema): void
+ {
+ // this down() migration is auto-generated, please modify it to your needs
+ $this->addSql('DROP INDEX ns_no_index ON nodes_sources');
+ }
+}
diff --git a/migrations/Version20241204010215.php b/migrations/Version20241204010215.php
new file mode 100644
index 00000000..4cf24130
--- /dev/null
+++ b/migrations/Version20241204010215.php
@@ -0,0 +1,41 @@
+addSql('ALTER TABLE custom_form_fields CHANGE type type SMALLINT DEFAULT 0 NOT NULL');
+ $this->addSql('ALTER TABLE documents CHANGE imageWidth imageWidth SMALLINT DEFAULT 0 NOT NULL, CHANGE imageHeight imageHeight SMALLINT DEFAULT 0 NOT NULL');
+ $this->addSql('ALTER TABLE node_type_fields CHANGE type type SMALLINT DEFAULT 0 NOT NULL, CHANGE min_length min_length SMALLINT DEFAULT NULL, CHANGE max_length max_length SMALLINT DEFAULT NULL, CHANGE serialization_max_depth serialization_max_depth SMALLINT DEFAULT NULL');
+ $this->addSql('ALTER TABLE nodes CHANGE status status SMALLINT DEFAULT 10 NOT NULL');
+ $this->addSql('ALTER TABLE redirections CHANGE type type SMALLINT NOT NULL');
+ $this->addSql('ALTER TABLE settings CHANGE type type SMALLINT NOT NULL');
+ }
+
+ public function down(Schema $schema): void
+ {
+ // this down() migration is auto-generated, please modify it to your needs
+ $this->addSql('ALTER TABLE custom_form_fields CHANGE type type INT NOT NULL');
+ $this->addSql('ALTER TABLE documents CHANGE imageWidth imageWidth INT DEFAULT 0 NOT NULL, CHANGE imageHeight imageHeight INT DEFAULT 0 NOT NULL');
+ $this->addSql('ALTER TABLE node_type_fields CHANGE serialization_max_depth serialization_max_depth INT DEFAULT NULL, CHANGE min_length min_length INT DEFAULT NULL, CHANGE max_length max_length INT DEFAULT NULL, CHANGE type type INT NOT NULL');
+ $this->addSql('ALTER TABLE nodes CHANGE status status INT NOT NULL');
+ $this->addSql('ALTER TABLE redirections CHANGE type type INT NOT NULL');
+ $this->addSql('ALTER TABLE settings CHANGE type type INT NOT NULL');
+ }
+}
diff --git a/phpcs.xml.dist b/phpcs.xml.dist
deleted file mode 100644
index 19bff0cc..00000000
--- a/phpcs.xml.dist
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- src/
-
diff --git a/src/Api/Breadcrumbs/Breadcrumbs.php b/src/Api/Breadcrumbs/Breadcrumbs.php
index 6d0fb068..c5bf0df2 100644
--- a/src/Api/Breadcrumbs/Breadcrumbs.php
+++ b/src/Api/Breadcrumbs/Breadcrumbs.php
@@ -7,15 +7,15 @@
use RZ\Roadiz\Core\AbstractEntities\PersistableInterface;
use Symfony\Component\Serializer\Annotation as Serializer;
-final class Breadcrumbs implements BreadcrumbsInterface
+final readonly 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 array $items,
) {
}
diff --git a/src/Api/Breadcrumbs/NodesSourcesBreadcrumbsFactory.php b/src/Api/Breadcrumbs/NodesSourcesBreadcrumbsFactory.php
index 93cb2ee1..8779fb19 100644
--- a/src/Api/Breadcrumbs/NodesSourcesBreadcrumbsFactory.php
+++ b/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/src/Api/Controller/GetWebResponseByPathController.php b/src/Api/Controller/GetWebResponseByPathController.php
index b6434889..3542e1df 100644
--- a/src/Api/Controller/GetWebResponseByPathController.php
+++ b/src/Api/Controller/GetWebResponseByPathController.php
@@ -4,10 +4,10 @@
namespace RZ\Roadiz\CoreBundle\Api\Controller;
-use ApiPlatform\Api\IriConverterInterface;
-use ApiPlatform\Exception\InvalidArgumentException;
-use ApiPlatform\Exception\ResourceClassNotFoundException;
+use ApiPlatform\Metadata\Exception\InvalidArgumentException;
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/src/Api/Controller/NodesSourcesSearchController.php b/src/Api/Controller/NodesSourcesSearchController.php
index ad76db3d..0fbfd1ed 100644
--- a/src/Api/Controller/NodesSourcesSearchController.php
+++ b/src/Api/Controller/NodesSourcesSearchController.php
@@ -19,21 +19,12 @@ class NodesSourcesSearchController extends AbstractController
{
use TranslationAwareControllerTrait;
- private ManagerRegistry $managerRegistry;
- private PreviewResolverInterface $previewResolver;
- private ?NodeSourceSearchHandlerInterface $nodeSourceSearchHandler;
- private int $highlightingFragmentSize;
-
public function __construct(
- ManagerRegistry $managerRegistry,
- PreviewResolverInterface $previewResolver,
- ?NodeSourceSearchHandlerInterface $nodeSourceSearchHandler,
- int $highlightingFragmentSize = 200
+ private readonly ManagerRegistry $managerRegistry,
+ private readonly PreviewResolverInterface $previewResolver,
+ private readonly ?NodeSourceSearchHandlerInterface $nodeSourceSearchHandler,
+ private readonly int $highlightingFragmentSize = 200,
) {
- $this->nodeSourceSearchHandler = $nodeSourceSearchHandler;
- $this->highlightingFragmentSize = $highlightingFragmentSize;
- $this->managerRegistry = $managerRegistry;
- $this->previewResolver = $previewResolver;
}
protected function getManagerRegistry(): ManagerRegistry
@@ -46,9 +37,6 @@ protected function getPreviewResolver(): PreviewResolverInterface
return $this->previewResolver;
}
- /**
- * @return SearchHandlerInterface
- */
protected function getSearchHandler(): SearchHandlerInterface
{
if (null === $this->nodeSourceSearchHandler) {
@@ -58,6 +46,7 @@ protected function getSearchHandler(): SearchHandlerInterface
if ($this->highlightingFragmentSize > 0) {
$this->nodeSourceSearchHandler->setHighlightingFragmentSize($this->highlightingFragmentSize);
}
+
return $this->nodeSourceSearchHandler;
}
@@ -65,7 +54,7 @@ protected function getCriteria(Request $request): array
{
return [
'publishedAt' => ['<=', new \DateTime()],
- 'translation' => $this->getTranslation($request)
+ 'translation' => $this->getTranslation($request),
];
}
@@ -77,6 +66,7 @@ public function __invoke(Request $request): SolrPaginator
$this->getCriteria($request),
true
);
+
return new SolrPaginator($entityListManager);
}
}
diff --git a/src/Api/Controller/TranslationAwareControllerTrait.php b/src/Api/Controller/TranslationAwareControllerTrait.php
index 47533414..465fb5d6 100644
--- a/src/Api/Controller/TranslationAwareControllerTrait.php
+++ b/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/src/Api/DataTransformer/BlocksAwareWebResponseOutputDataTransformerTrait.php b/src/Api/DataTransformer/BlocksAwareWebResponseOutputDataTransformerTrait.php
index 2e89b12e..db62eb8c 100644
--- a/src/Api/DataTransformer/BlocksAwareWebResponseOutputDataTransformerTrait.php
+++ b/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/src/Api/DataTransformer/RealmsAwareWebResponseOutputDataTransformerTrait.php b/src/Api/DataTransformer/RealmsAwareWebResponseOutputDataTransformerTrait.php
index 5645704e..b34a8cd5 100644
--- a/src/Api/DataTransformer/RealmsAwareWebResponseOutputDataTransformerTrait.php
+++ b/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/src/Api/DataTransformer/WebResponseDataTransformerInterface.php b/src/Api/DataTransformer/WebResponseDataTransformerInterface.php
index 424d02a3..72adf6f8 100644
--- a/src/Api/DataTransformer/WebResponseDataTransformerInterface.php
+++ b/src/Api/DataTransformer/WebResponseDataTransformerInterface.php
@@ -11,12 +11,18 @@ interface WebResponseDataTransformerInterface
{
/**
* @template T of PersistableInterface
- * @param T $object
- * @param string $to
- * @param array $context
+ *
+ * @param T $object
+ * @param WebResponseInterface|null $output pass an existing WebResponseInterface instance to avoid creating a new one
+ *
* @return WebResponseInterface|null
*/
- public function transform(PersistableInterface $object, string $to, array $context = []): ?WebResponseInterface;
+ public function transform(
+ PersistableInterface $object,
+ string $to,
+ array $context = [],
+ ?WebResponseInterface $output = null,
+ ): ?WebResponseInterface;
public function createWebResponse(): WebResponseInterface;
}
diff --git a/src/Api/DataTransformer/WebResponseOutputDataTransformer.php b/src/Api/DataTransformer/WebResponseOutputDataTransformer.php
index 7cd9a1e1..d6ace452 100644
--- a/src/Api/DataTransformer/WebResponseOutputDataTransformer.php
+++ b/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,
) {
}
@@ -86,9 +79,9 @@ public function createWebResponse(): WebResponseInterface
return new ($this->webResponseClass)();
}
- public function transform(PersistableInterface $object, string $to, array $context = []): ?WebResponseInterface
+ public function transform(PersistableInterface $object, string $to, array $context = [], ?WebResponseInterface $output = null): ?WebResponseInterface
{
- $output = $this->createWebResponse();
+ $output = $output ?? $this->createWebResponse();
$output->setItem($object);
if ($object instanceof NodesSources) {
if ($output instanceof RealmsAwareWebResponseInterface) {
@@ -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/src/Api/Dto/Archive.php b/src/Api/Dto/Archive.php
index d6204a70..9f410105 100644
--- a/src/Api/Dto/Archive.php
+++ b/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/src/Api/Extension/ArchiveExtension.php b/src/Api/Extension/ArchiveExtension.php
index 14c615c6..222fa0ca 100644
--- a/src/Api/Extension/ArchiveExtension.php
+++ b/src/Api/Extension/ArchiveExtension.php
@@ -19,7 +19,7 @@
* pagination_client_enabled: false
* archive_enabled: true
* archive_publication_field_name: publishedAt
- * ```
+ * ```.
*
* ```
* "hydra:member": [
@@ -41,11 +41,11 @@
* ],
* ```
*/
-final class ArchiveExtension implements QueryResultCollectionExtensionInterface
+final readonly class ArchiveExtension implements QueryResultCollectionExtensionInterface
{
public function __construct(
- private readonly RequestStack $requestStack,
- private readonly string $defaultPublicationFieldName = 'publishedAt'
+ private RequestStack $requestStack,
+ private 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/src/Api/Extension/AttributeValueQueryExtension.php b/src/Api/Extension/AttributeValueQueryExtension.php
index 889d8ef4..f3fe8b4f 100644
--- a/src/Api/Extension/AttributeValueQueryExtension.php
+++ b/src/Api/Extension/AttributeValueQueryExtension.php
@@ -12,12 +12,13 @@
use Doctrine\ORM\QueryBuilder;
use RZ\Roadiz\CoreBundle\Entity\AttributeValue;
use RZ\Roadiz\CoreBundle\Entity\Node;
+use RZ\Roadiz\CoreBundle\Enum\NodeStatus;
use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface;
-final class AttributeValueQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
+final readonly class AttributeValueQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
{
public function __construct(
- private readonly PreviewResolverInterface $previewResolver
+ private PreviewResolverInterface $previewResolver,
) {
}
@@ -27,7 +28,7 @@ public function applyToItem(
string $resourceClass,
array $identifiers,
?Operation $operation = null,
- array $context = []
+ array $context = [],
): void {
$this->apply($queryBuilder, $resourceClass);
}
@@ -37,17 +38,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 +61,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 +69,16 @@ private function apply(
if ($this->previewResolver->isPreview()) {
$queryBuilder
- ->andWhere($queryBuilder->expr()->lte($joinAlias . '.status', ':status'))
- ->setParameter(':status', Node::PUBLISHED);
+ ->andWhere($queryBuilder->expr()->lte($joinAlias.'.status', ':status'))
+ ->setParameter(':status', NodeStatus::PUBLISHED);
+
return;
}
$queryBuilder
- ->andWhere($queryBuilder->expr()->eq($joinAlias . '.status', ':status'))
- ->setParameter(':status', Node::PUBLISHED);
+ ->andWhere($queryBuilder->expr()->eq($joinAlias.'.status', ':status'))
+ ->setParameter(':status', NodeStatus::PUBLISHED);
+
return;
}
}
diff --git a/src/Api/Extension/AttributeValueRealmExtension.php b/src/Api/Extension/AttributeValueRealmExtension.php
index d14b3437..0128fd87 100644
--- a/src/Api/Extension/AttributeValueRealmExtension.php
+++ b/src/Api/Extension/AttributeValueRealmExtension.php
@@ -14,27 +14,27 @@
use RZ\Roadiz\CoreBundle\Realm\RealmResolverInterface;
use Symfony\Bundle\SecurityBundle\Security;
-final class AttributeValueRealmExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
+final readonly class AttributeValueRealmExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
public function __construct(
- private readonly Security $security,
- private readonly RealmResolverInterface $realmResolver
+ private Security $security,
+ private 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/src/Api/Extension/DocumentQueryExtension.php b/src/Api/Extension/DocumentQueryExtension.php
index 7d3894da..36daa36d 100644
--- a/src/Api/Extension/DocumentQueryExtension.php
+++ b/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/src/Api/Extension/NodeQueryExtension.php b/src/Api/Extension/NodeQueryExtension.php
index 9a4ee6c6..65c08c95 100644
--- a/src/Api/Extension/NodeQueryExtension.php
+++ b/src/Api/Extension/NodeQueryExtension.php
@@ -12,12 +12,13 @@
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use RZ\Roadiz\CoreBundle\Entity\Node;
+use RZ\Roadiz\CoreBundle\Enum\NodeStatus;
use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface;
-final class NodeQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
+final readonly class NodeQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
{
public function __construct(
- private readonly PreviewResolverInterface $previewResolver
+ private PreviewResolverInterface $previewResolver,
) {
}
@@ -26,8 +27,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,16 +36,17 @@ public function applyToItem(
private function apply(
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
- string $resourceClass
+ string $resourceClass,
): void {
- if ($resourceClass !== Node::class) {
+ if (Node::class !== $resourceClass) {
return;
}
if ($this->previewResolver->isPreview()) {
$queryBuilder
->andWhere($queryBuilder->expr()->lte('o.status', ':status'))
- ->setParameter(':status', Node::PUBLISHED);
+ ->setParameter(':status', NodeStatus::PUBLISHED);
+
return;
}
@@ -56,10 +58,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);
+ ->setParameter(':status', NodeStatus::PUBLISHED);
+
return;
}
@@ -67,8 +70,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/src/Api/Extension/NodesSourcesQueryExtension.php b/src/Api/Extension/NodesSourcesQueryExtension.php
index aca8ba43..dd6507a2 100644
--- a/src/Api/Extension/NodesSourcesQueryExtension.php
+++ b/src/Api/Extension/NodesSourcesQueryExtension.php
@@ -11,15 +11,15 @@
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
-use RZ\Roadiz\CoreBundle\Entity\Node;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
+use RZ\Roadiz\CoreBundle\Enum\NodeStatus;
use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface;
-final class NodesSourcesQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
+final readonly class NodesSourcesQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
{
public function __construct(
- private readonly PreviewResolverInterface $previewResolver,
- private readonly string $generatedEntityNamespacePattern = '#^App\\\GeneratedEntity\\\NS(?:[a-zA-Z]+)$#'
+ private PreviewResolverInterface $previewResolver,
+ private 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'))
- ->setParameter(':status', Node::PUBLISHED);
+ ->andWhere($queryBuilder->expr()->lte($alias.'.status', ':status'))
+ ->setParameter(':status', NodeStatus::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);
+ ->setParameter(':status', NodeStatus::PUBLISHED);
+
return;
}
}
diff --git a/src/Api/Extension/NodesTagsQueryExtension.php b/src/Api/Extension/NodesTagsQueryExtension.php
index 37afa629..c61c1f1b 100644
--- a/src/Api/Extension/NodesTagsQueryExtension.php
+++ b/src/Api/Extension/NodesTagsQueryExtension.php
@@ -10,14 +10,14 @@
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;
-use RZ\Roadiz\CoreBundle\Entity\Node;
use RZ\Roadiz\CoreBundle\Entity\Tag;
+use RZ\Roadiz\CoreBundle\Enum\NodeStatus;
use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface;
-final class NodesTagsQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
+final readonly class NodesTagsQueryExtension implements QueryItemExtensionInterface, QueryCollectionExtensionInterface
{
public function __construct(
- private readonly PreviewResolverInterface $previewResolver
+ private 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'))
- ->setParameter(':status', Node::PUBLISHED);
+ ->andWhere($queryBuilder->expr()->lte($existingNodeJoin->getAlias().'.status', ':status'))
+ ->setParameter(':status', NodeStatus::PUBLISHED);
+
return;
}
$queryBuilder
- ->andWhere($queryBuilder->expr()->eq($existingNodeJoin->getAlias() . '.status', ':status'))
- ->setParameter(':status', Node::PUBLISHED);
+ ->andWhere($queryBuilder->expr()->eq($existingNodeJoin->getAlias().'.status', ':status'))
+ ->setParameter(':status', NodeStatus::PUBLISHED);
+
return;
}
}
diff --git a/src/Api/Filter/ArchiveFilter.php b/src/Api/Filter/ArchiveFilter.php
index 7b58e2f5..a7e5b6dc 100644
--- a/src/Api/Filter/ArchiveFilter.php
+++ b/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/src/Api/Filter/CopyrightValidFilter.php b/src/Api/Filter/CopyrightValidFilter.php
index ea8f56f2..d20026a9 100644
--- a/src/Api/Filter/CopyrightValidFilter.php
+++ b/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/src/Api/Filter/GeneratedEntityFilter.php b/src/Api/Filter/GeneratedEntityFilter.php
index 255be66d..3b39c6a7 100644
--- a/src/Api/Filter/GeneratedEntityFilter.php
+++ b/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/src/Api/Filter/IntersectionFilter.php b/src/Api/Filter/IntersectionFilter.php
index 699e1edc..bd380435 100644
--- a/src/Api/Filter/IntersectionFilter.php
+++ b/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/src/Api/Filter/LocaleFilter.php b/src/Api/Filter/LocaleFilter.php
index aaefd4a5..54e7f74b 100644
--- a/src/Api/Filter/LocaleFilter.php
+++ b/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/src/Api/Filter/NotFilter.php b/src/Api/Filter/NotFilter.php
index b1677bd0..de2f0682 100644
--- a/src/Api/Filter/NotFilter.php
+++ b/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/src/Api/ListManager/SolrPaginator.php b/src/Api/ListManager/SolrPaginator.php
index b5e3f448..5056d140 100644
--- a/src/Api/ListManager/SolrPaginator.php
+++ b/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,9 +64,7 @@ public function getIterator(): \Traversable
{
$this->handleOnce();
$entities = $this->listManager->getEntities();
- if (\is_array($entities)) {
- return new \ArrayIterator($entities);
- }
- return $entities->getIterator();
+
+ return new \ArrayIterator($entities);
}
}
diff --git a/src/Api/ListManager/SolrSearchListManager.php b/src/Api/ListManager/SolrSearchListManager.php
index e0dca7e7..e0a93137 100644
--- a/src/Api/ListManager/SolrSearchListManager.php
+++ b/src/Api/ListManager/SolrSearchListManager.php
@@ -9,32 +9,33 @@
use RZ\Roadiz\CoreBundle\SearchEngine\SearchResultsInterface;
use Symfony\Component\DependencyInjection\Attribute\Exclude;
use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
#[Exclude]
final class SolrSearchListManager extends AbstractEntityListManager
{
- private ?SearchResultsInterface $searchResults;
+ private ?SearchResultsInterface $searchResults = null;
private ?string $query = null;
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)
+ public function handle(bool $disabled = false): void
{
- if ($this->request === null) {
+ if (null === $this->request) {
throw new \InvalidArgumentException('Cannot handle a NULL request.');
}
$this->handleRequestQuery($disabled);
if (null === $this->query) {
- throw new \InvalidArgumentException('Cannot handle a NULL query.');
+ throw new BadRequestHttpException('Search param is required.');
}
/*
* Query must be longer than 3 chars or Solr might crash
@@ -42,18 +43,18 @@ public function handle(bool $disabled = false)
*/
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 +66,6 @@ protected function handleSearchParam(string $search): void
$this->query = trim($search);
}
- /**
- * @inheritDoc
- */
public function getItemCount(): int
{
if (null !== $this->searchResults) {
@@ -76,9 +74,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/src/Api/Model/BlocksAwareWebResponseInterface.php b/src/Api/Model/BlocksAwareWebResponseInterface.php
index bdf356fe..0dc8a927 100644
--- a/src/Api/Model/BlocksAwareWebResponseInterface.php
+++ b/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/src/Api/Model/NodesSourcesHead.php b/src/Api/Model/NodesSourcesHead.php
index c0f52e2b..f509483c 100644
--- a/src/Api/Model/NodesSourcesHead.php
+++ b/src/Api/Model/NodesSourcesHead.php
@@ -17,108 +17,61 @@
class NodesSourcesHead implements NodesSourcesHeadInterface
{
- #[Serializer\Ignore]
- protected HandlerFactoryInterface $handlerFactory;
-
#[Serializer\Ignore]
protected ?array $seo = null;
- #[Serializer\Ignore]
- protected ?NodesSources $nodesSource;
-
- #[Serializer\Ignore]
- protected Settings $settingsBag;
-
- #[Serializer\Ignore]
- protected UrlGeneratorInterface $urlGenerator;
-
- #[Serializer\Ignore]
- protected NodeSourceApi $nodeSourceApi;
-
- #[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
+ #[Serializer\Ignore]
+ protected readonly ?NodesSources $nodesSource,
+ #[Serializer\Ignore]
+ protected readonly Settings $settingsBag,
+ #[Serializer\Ignore]
+ protected readonly UrlGeneratorInterface $urlGenerator,
+ #[Serializer\Ignore]
+ protected readonly NodeSourceApi $nodeSourceApi,
+ #[Serializer\Ignore]
+ protected readonly HandlerFactoryInterface $handlerFactory,
+ #[Serializer\Ignore]
+ protected readonly TranslationInterface $defaultTranslation,
) {
- $this->nodesSource = $nodesSource;
- $this->settingsBag = $settingsBag;
- $this->urlGenerator = $urlGenerator;
- $this->nodeSourceApi = $nodeSourceApi;
- $this->defaultTranslation = $defaultTranslation;
- $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 +81,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 +98,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 +108,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 +236,7 @@ public function getTranslation(): TranslationInterface
if (null !== $this->nodesSource) {
return $this->nodesSource->getTranslation();
}
+
return $this->defaultTranslation;
}
@@ -295,7 +245,7 @@ public function getHomePage(): ?NodesSources
{
return $this->nodeSourceApi->getOneBy([
'node.home' => true,
- 'translation' => $this->getTranslation()
+ 'translation' => $this->getTranslation(),
]);
}
}
diff --git a/src/Api/Model/NodesSourcesHeadFactory.php b/src/Api/Model/NodesSourcesHeadFactory.php
index 9cae9098..e0639693 100644
--- a/src/Api/Model/NodesSourcesHeadFactory.php
+++ b/src/Api/Model/NodesSourcesHeadFactory.php
@@ -11,13 +11,13 @@
use RZ\Roadiz\CoreBundle\EntityApi\NodeSourceApi;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
-final class NodesSourcesHeadFactory implements NodesSourcesHeadFactoryInterface
+final readonly class NodesSourcesHeadFactory implements NodesSourcesHeadFactoryInterface
{
public function __construct(
- private readonly Settings $settingsBag,
- private readonly UrlGeneratorInterface $urlGenerator,
- private readonly NodeSourceApi $nodeSourceApi,
- private readonly HandlerFactoryInterface $handlerFactory
+ private Settings $settingsBag,
+ private UrlGeneratorInterface $urlGenerator,
+ private NodeSourceApi $nodeSourceApi,
+ private HandlerFactoryInterface $handlerFactory,
) {
}
diff --git a/src/Api/Model/NodesSourcesHeadFactoryInterface.php b/src/Api/Model/NodesSourcesHeadFactoryInterface.php
index 51295929..b13f85f2 100644
--- a/src/Api/Model/NodesSourcesHeadFactoryInterface.php
+++ b/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/src/Api/Model/NodesSourcesHeadInterface.php b/src/Api/Model/NodesSourcesHeadInterface.php
index 36e0fd92..3413ee1f 100644
--- a/src/Api/Model/NodesSourcesHeadInterface.php
+++ b/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/src/Api/Model/RealmsAwareWebResponseInterface.php b/src/Api/Model/RealmsAwareWebResponseInterface.php
index 3962bfe0..adeded2b 100644
--- a/src/Api/Model/RealmsAwareWebResponseInterface.php
+++ b/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/src/Api/Model/WebResponseInterface.php b/src/Api/Model/WebResponseInterface.php
index 61ff1727..6b8f73ae 100644
--- a/src/Api/Model/WebResponseInterface.php
+++ b/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/src/Api/Model/WebResponseTrait.php b/src/Api/Model/WebResponseTrait.php
index 8acf455f..a7707a77 100644
--- a/src/Api/Model/WebResponseTrait.php
+++ b/src/Api/Model/WebResponseTrait.php
@@ -15,39 +15,51 @@
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'])]
+ #[ApiProperty(
+ identifier: false,
+ genId: false,
+ )]
public ?BreadcrumbsInterface $breadcrumbs = null;
- #[Serializer\Groups(["web_response"])]
+ #[Serializer\Groups(['web_response'])]
+ #[ApiProperty(
+ identifier: false,
+ genId: false,
+ )]
public ?NodesSourcesHeadInterface $head = null;
/**
* @var Collection|null
*/
- #[Serializer\Groups(["web_response"])]
+ #[Serializer\Groups(['web_response'])]
+ #[ApiProperty(
+ identifier: false,
+ genId: false,
+ )]
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 +70,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 +103,13 @@ public function getBlocks(): ?array
/**
* @param Collection|null $blocks
+ *
* @return $this
*/
public function setBlocks(?Collection $blocks): self
{
$this->blocks = $blocks;
+
return $this;
}
@@ -109,41 +123,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/src/Api/OpenApi/JwtDecorator.php b/src/Api/OpenApi/JwtDecorator.php
index cb41dee7..5b9b0e45 100644
--- a/src/Api/OpenApi/JwtDecorator.php
+++ b/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
+final readonly class JwtDecorator implements OpenApiFactoryInterface
{
public function __construct(
- private readonly OpenApiFactoryInterface $decorated
+ private OpenApiFactoryInterface $decorated,
) {
}
diff --git a/src/Api/OpenApi/PreviewDecorator.php b/src/Api/OpenApi/PreviewDecorator.php
index 7dcecaae..98103641 100644
--- a/src/Api/OpenApi/PreviewDecorator.php
+++ b/src/Api/OpenApi/PreviewDecorator.php
@@ -9,10 +9,10 @@
use ApiPlatform\OpenApi\Model\PathItem;
use ApiPlatform\OpenApi\OpenApi;
-final class PreviewDecorator implements OpenApiFactoryInterface
+final readonly class PreviewDecorator implements OpenApiFactoryInterface
{
public function __construct(
- private readonly OpenApiFactoryInterface $decorated
+ private 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/src/Api/OpenApi/WebResponseDecorator.php b/src/Api/OpenApi/WebResponseDecorator.php
index e76a1947..46b9ec9d 100644
--- a/src/Api/OpenApi/WebResponseDecorator.php
+++ b/src/Api/OpenApi/WebResponseDecorator.php
@@ -8,10 +8,10 @@
use ApiPlatform\OpenApi\Model;
use ApiPlatform\OpenApi\OpenApi;
-final class WebResponseDecorator implements OpenApiFactoryInterface
+final readonly class WebResponseDecorator implements OpenApiFactoryInterface
{
public function __construct(
- private readonly OpenApiFactoryInterface $decorated
+ private 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/src/Api/TreeWalker/AutoChildrenNodeSourceWalker.php b/src/Api/TreeWalker/AutoChildrenNodeSourceWalker.php
index 96ea462d..3d0c9a27 100644
--- a/src/Api/TreeWalker/AutoChildrenNodeSourceWalker.php
+++ b/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/src/Api/TreeWalker/Definition/DefinitionFactoryConfiguration.php b/src/Api/TreeWalker/Definition/DefinitionFactoryConfiguration.php
index a4326a3e..3b227a1c 100644
--- a/src/Api/TreeWalker/Definition/DefinitionFactoryConfiguration.php
+++ b/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/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php b/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php
index 9e6999ea..fd0c85fa 100644
--- a/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php
+++ b/src/Api/TreeWalker/Definition/MultiTypeChildrenDefinition.php
@@ -4,9 +4,9 @@
namespace RZ\Roadiz\CoreBundle\Api\TreeWalker\Definition;
-use Doctrine\ORM\Tools\Pagination\Paginator;
use RZ\Roadiz\CoreBundle\Api\TreeWalker\NodeSourceWalkerContext;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
+use RZ\Roadiz\CoreBundle\Entity\NodeType;
use RZ\TreeWalker\Definition\ContextualDefinitionTrait;
use RZ\TreeWalker\WalkerContextInterface;
@@ -15,42 +15,51 @@ 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|Paginator
+ * @return array
*/
- public function __invoke(NodesSources $source)
+ 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);
$bag = $this->context->getNodeTypesBag();
+ /** @var NodeType[] $nodeTypes */
+ $nodeTypes = array_map(function (string $singleType) use ($bag) {
+ return $bag->get($singleType);
+ }, $this->types);
$criteria = [
'node.parent' => $source->getNode(),
'translation' => $source->getTranslation(),
- 'node.nodeType' => array_map(function (string $singleType) use ($bag) {
- return $bag->get($singleType);
- }, $this->types)
+ 'node.nodeType' => $nodeTypes,
];
if ($this->onlyVisible) {
$criteria['node.visible'] = true;
}
- $children = $this->context->getNodeSourceApi()->getBy($criteria, [
- 'node.position' => 'ASC',
- ]);
+ if (1 === count($nodeTypes)) {
+ $entityName = $nodeTypes[0]->getSourceEntityFullQualifiedClassName();
+ } else {
+ $entityName = NodesSources::class;
+ }
+ // @phpstan-ignore-next-line
+ $children = $this->context
+ ->getManagerRegistry()
+ ->getRepository($entityName)
+ ->findBy($criteria, [
+ 'node.position' => 'ASC',
+ ]);
+
$this->context->getStopwatch()->stop(self::class);
return $children;
diff --git a/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php b/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php
index 64df42ec..91da32fc 100644
--- a/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php
+++ b/src/Api/TreeWalker/Definition/NonReachableNodeSourceBlockDefinition.php
@@ -4,9 +4,6 @@
namespace RZ\Roadiz\CoreBundle\Api\TreeWalker\Definition;
-use ArrayIterator;
-use Doctrine\ORM\Tools\Pagination\Paginator;
-use Exception;
use RZ\Roadiz\CoreBundle\Api\TreeWalker\NodeSourceWalkerContext;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
use RZ\TreeWalker\Definition\ContextualDefinitionTrait;
@@ -18,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);
@@ -40,19 +37,14 @@ public function __invoke(NodesSources $source): array
if ($this->onlyVisible) {
$criteria['node.visible'] = true;
}
- $children = $this->context->getNodeSourceApi()->getBy($criteria, [
- 'node.position' => 'ASC',
- ]);
+ // @phpstan-ignore-next-line
+ $children = $this->context->getManagerRegistry()
+ ->getRepository(NodesSources::class)
+ ->findBy($criteria, [
+ 'node.position' => 'ASC',
+ ]);
$this->context->getStopwatch()->stop(self::class);
- if ($children instanceof Paginator) {
- $iterator = $children->getIterator();
- if ($iterator instanceof ArrayIterator) {
- return $iterator->getArrayCopy();
- }
- // @phpstan-ignore-next-line
- return iterator_to_array($iterator);
- }
return $children;
}
}
diff --git a/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php b/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php
index 5eecf6b3..f50e947f 100644
--- a/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php
+++ b/src/Api/TreeWalker/Definition/ReachableNodeSourceDefinition.php
@@ -4,9 +4,6 @@
namespace RZ\Roadiz\CoreBundle\Api\TreeWalker\Definition;
-use ArrayIterator;
-use Doctrine\ORM\Tools\Pagination\Paginator;
-use Exception;
use RZ\Roadiz\CoreBundle\Api\TreeWalker\NodeSourceWalkerContext;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
use RZ\TreeWalker\Definition\ContextualDefinitionTrait;
@@ -18,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);
@@ -40,19 +37,14 @@ public function __invoke(NodesSources $source): array
if ($this->onlyVisible) {
$criteria['node.visible'] = true;
}
- $children = $this->context->getNodeSourceApi()->getBy($criteria, [
- 'node.position' => 'ASC',
- ]);
+ // @phpstan-ignore-next-line
+ $children = $this->context->getManagerRegistry()
+ ->getRepository(NodesSources::class)
+ ->findBy($criteria, [
+ 'node.position' => 'ASC',
+ ]);
$this->context->getStopwatch()->stop(self::class);
- if ($children instanceof Paginator) {
- $iterator = $children->getIterator();
- if ($iterator instanceof ArrayIterator) {
- return $iterator->getArrayCopy();
- }
- // @phpstan-ignore-next-line
- return iterator_to_array($iterator);
- }
return $children;
}
}
diff --git a/src/Api/TreeWalker/NodeSourceWalkerContext.php b/src/Api/TreeWalker/NodeSourceWalkerContext.php
index 164154ac..d5bd25ac 100644
--- a/src/Api/TreeWalker/NodeSourceWalkerContext.php
+++ b/src/Api/TreeWalker/NodeSourceWalkerContext.php
@@ -18,54 +18,44 @@
use Symfony\Component\Stopwatch\Stopwatch;
#[Exclude]
-class NodeSourceWalkerContext implements WalkerContextInterface
+readonly class NodeSourceWalkerContext implements WalkerContextInterface
{
public function __construct(
- private readonly Stopwatch $stopwatch,
- private readonly NodeTypes $nodeTypesBag,
- private readonly NodeSourceApi $nodeSourceApi,
- private readonly RequestStack $requestStack,
- private readonly ManagerRegistry $managerRegistry,
- private readonly CacheItemPoolInterface $cacheAdapter,
- private readonly NodeTypeResolver $nodeTypeResolver,
- private readonly PreviewResolverInterface $previewResolver
+ private Stopwatch $stopwatch,
+ private NodeTypes $nodeTypesBag,
+ private NodeSourceApi $nodeSourceApi,
+ private RequestStack $requestStack,
+ private ManagerRegistry $managerRegistry,
+ private CacheItemPoolInterface $cacheAdapter,
+ private NodeTypeResolver $nodeTypeResolver,
+ private 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
{
return $this->nodeSourceApi;
}
- /**
- * @return RequestStack
- */
public function getRequestStack(): RequestStack
{
return $this->requestStack;
}
/**
- * @return Request|null
* @deprecated Use getMainRequest
*/
public function getMasterRequest(): ?Request
@@ -73,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/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php b/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php
index 2c5099c6..35253742 100644
--- a/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php
+++ b/src/Api/TreeWalker/NodeSourceWalkerContextFactory.php
@@ -14,17 +14,17 @@
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Stopwatch\Stopwatch;
-final class NodeSourceWalkerContextFactory implements WalkerContextFactoryInterface
+final readonly class NodeSourceWalkerContextFactory implements WalkerContextFactoryInterface
{
public function __construct(
- private readonly Stopwatch $stopwatch,
- private readonly NodeTypes $nodeTypesBag,
- private readonly NodeSourceApi $nodeSourceApi,
- private readonly RequestStack $requestStack,
- private readonly ManagerRegistry $managerRegistry,
- private readonly CacheItemPoolInterface $cacheAdapter,
- private readonly NodeTypeResolver $nodeTypeResolver,
- private readonly PreviewResolverInterface $previewResolver
+ private Stopwatch $stopwatch,
+ private NodeTypes $nodeTypesBag,
+ private NodeSourceApi $nodeSourceApi,
+ private RequestStack $requestStack,
+ private ManagerRegistry $managerRegistry,
+ private CacheItemPoolInterface $cacheAdapter,
+ private NodeTypeResolver $nodeTypeResolver,
+ private PreviewResolverInterface $previewResolver,
) {
}
diff --git a/src/Api/TreeWalker/TreeWalkerGenerator.php b/src/Api/TreeWalker/TreeWalkerGenerator.php
index b456f2db..6d995b16 100644
--- a/src/Api/TreeWalker/TreeWalkerGenerator.php
+++ b/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/src/Bag/NodeTypes.php b/src/Bag/NodeTypes.php
index fbaf9dd5..410a5db3 100644
--- a/src/Bag/NodeTypes.php
+++ b/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/src/Bag/Roles.php b/src/Bag/Roles.php
index e98d7e14..b2b25044 100644
--- a/src/Bag/Roles.php
+++ b/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/src/Bag/Settings.php b/src/Bag/Settings.php
index 4760721b..3599c596 100644
--- a/src/Bag/Settings.php
+++ b/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/src/Cache/Clearer/ClearerInterface.php b/src/Cache/Clearer/ClearerInterface.php
index 3b76c801..d4dd9615 100644
--- a/src/Cache/Clearer/ClearerInterface.php
+++ b/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/src/Cache/Clearer/FileClearer.php b/src/Cache/Clearer/FileClearer.php
index 955e348f..c1a5e037 100644
--- a/src/Cache/Clearer/FileClearer.php
+++ b/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/src/Cache/Clearer/NodesSourcesUrlsCacheClearer.php b/src/Cache/Clearer/NodesSourcesUrlsCacheClearer.php
index a7018fe0..8cd5d7a2 100644
--- a/src/Cache/Clearer/NodesSourcesUrlsCacheClearer.php
+++ b/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/src/Cache/Clearer/OPCacheClearer.php b/src/Cache/Clearer/OPCacheClearer.php
index 9d165804..c9a8cadd 100644
--- a/src/Cache/Clearer/OPCacheClearer.php
+++ b/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/src/Cache/CloudflareProxyCache.php b/src/Cache/CloudflareProxyCache.php
index 93485e54..ef602313 100644
--- a/src/Cache/CloudflareProxyCache.php
+++ b/src/Cache/CloudflareProxyCache.php
@@ -4,70 +4,49 @@
namespace RZ\Roadiz\CoreBundle\Cache;
-final class CloudflareProxyCache
+final readonly class CloudflareProxyCache
{
public function __construct(
- private readonly string $name,
- private readonly string $zone,
- private readonly string $version,
- private readonly string $bearer,
- private readonly string $email,
- private readonly string $key,
- private readonly int $timeout
+ private string $name,
+ private string $zone,
+ private string $version,
+ private string $bearer,
+ private string $email,
+ private string $key,
+ private 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/src/Cache/ReverseProxyCache.php b/src/Cache/ReverseProxyCache.php
index 8aa36611..c7683f6d 100644
--- a/src/Cache/ReverseProxyCache.php
+++ b/src/Cache/ReverseProxyCache.php
@@ -4,35 +4,26 @@
namespace RZ\Roadiz\CoreBundle\Cache;
-final class ReverseProxyCache
+final readonly class ReverseProxyCache
{
public function __construct(
- private readonly string $name,
- private readonly string $host,
- private readonly string $domainName,
- private readonly int $timeout
+ private string $name,
+ private string $host,
+ private string $domainName,
+ private 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/src/Cache/ReverseProxyCacheLocator.php b/src/Cache/ReverseProxyCacheLocator.php
index b3f4b963..1fd879d3 100644
--- a/src/Cache/ReverseProxyCacheLocator.php
+++ b/src/Cache/ReverseProxyCacheLocator.php
@@ -4,15 +4,14 @@
namespace RZ\Roadiz\CoreBundle\Cache;
-final class ReverseProxyCacheLocator
+final readonly class ReverseProxyCacheLocator
{
/**
* @param ReverseProxyCache[] $frontends
- * @param CloudflareProxyCache|null $cloudflareProxyCache
*/
public function __construct(
- private readonly array $frontends,
- private readonly ?CloudflareProxyCache $cloudflareProxyCache = null
+ private array $frontends,
+ private ?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/src/Configuration/CollectionFieldConfiguration.php b/src/Configuration/CollectionFieldConfiguration.php
index faf08a15..1208b608 100644
--- a/src/Configuration/CollectionFieldConfiguration.php
+++ b/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/src/Configuration/JoinNodeTypeFieldConfiguration.php b/src/Configuration/JoinNodeTypeFieldConfiguration.php
index 952c6447..9a68111e 100644
--- a/src/Configuration/JoinNodeTypeFieldConfiguration.php
+++ b/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/src/Configuration/ProviderFieldConfiguration.php b/src/Configuration/ProviderFieldConfiguration.php
index c9a5d00f..8da8645d 100644
--- a/src/Configuration/ProviderFieldConfiguration.php
+++ b/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/src/Console/AppInstallCommand.php b/src/Console/AppInstallCommand.php
index e1023ba7..d47ebdd2 100644
--- a/src/Console/AppInstallCommand.php
+++ b/src/Console/AppInstallCommand.php
@@ -18,6 +18,7 @@
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
+use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Yaml\Yaml;
@@ -27,6 +28,7 @@ final class AppInstallCommand extends Command
private bool $dryRun = false;
public function __construct(
+ #[Autowire('%kernel.project_dir%')]
private readonly string $projectDir,
private readonly ManagerRegistry $managerRegistry,
private readonly NodeTypesImporter $nodeTypesImporter,
@@ -35,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);
}
@@ -62,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;
}
@@ -80,89 +84,92 @@ protected function importAppData(string $themeConfigPath): void
{
$data = $this->getAppConfig($themeConfigPath);
- if (isset($data["importFiles"])) {
- if (isset($data["importFiles"]['groups'])) {
- foreach ($data["importFiles"]['groups'] as $filename) {
- $this->importFile($filename, $this->groupsImporter);
- }
+ 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) {
+ $this->importFile($filename, $this->groupsImporter);
}
- if (isset($data["importFiles"]['roles'])) {
- foreach ($data["importFiles"]['roles'] as $filename) {
- $this->importFile($filename, $this->rolesImporter);
- }
+ }
+ 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) {
- $this->importFile($filename, $this->settingsImporter);
- }
+ }
+ 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) {
- $this->importFile($filename, $this->nodeTypesImporter);
- }
+ }
+ 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) {
- $this->importFile($filename, $this->tagsImporter);
- }
+ }
+ 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) {
- $this->importFile($filename, $this->attributeImporter);
- }
+ }
+ if (isset($data['importFiles']['attributes'])) {
+ foreach ($data['importFiles']['attributes'] as $filename) {
+ $this->importFile($filename, $this->attributeImporter);
}
- } else {
- $this->io->warning('Config file "' . $themeConfigPath . '" has no data to import.');
}
}
- /**
- * @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) {
- try {
- if (false === $fileContent = file_get_contents($file->getPathname())) {
- 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.'
- );
- return;
- } catch (EntityAlreadyExistsException $e) {
- $this->io->writeln(
- '* ' . $file->getPathname() . '' .
- ' has NOT been imported (' . $e->getMessage() . ').'
- );
+ if ($this->dryRun) {
+ $this->io->writeln(
+ '* '.$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');
}
+ $importer->import($fileContent);
+ $this->managerRegistry->getManager()->flush();
+ $this->io->writeln(
+ '* '.$file->getPathname().' file has been imported.'
+ );
+
+ return;
+ } catch (EntityAlreadyExistsException $e) {
+ $this->io->writeln(
+ '* '.$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/src/Console/AppMigrateCommand.php b/src/Console/AppMigrateCommand.php
index e8949486..6340f3ef 100644
--- a/src/Console/AppMigrateCommand.php
+++ b/src/Console/AppMigrateCommand.php
@@ -11,18 +11,26 @@
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Style\SymfonyStyle;
-use Symfony\Component\Process\Process;
+use Symfony\Component\DependencyInjection\Attribute\Autowire;
final class AppMigrateCommand extends Command
{
+ use RunningCommandsTrait;
+
public function __construct(
private readonly SchemaUpdater $schemaUpdater,
+ #[Autowire('%kernel.project_dir%')]
private readonly string $projectDir,
- ?string $name = null
+ ?string $name = null,
) {
parent::__construct($name);
}
+ public function getProjectDir(): string
+ {
+ return $this->projectDir;
+ }
+
protected function configure(): void
{
$this->setName('app:migrate')
@@ -43,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;
}
@@ -57,70 +66,37 @@ 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();
- $io->success('doctrine-migrations');
-
- $this->runCommand(
- 'doctrine:cache:clear-metadata',
+ 0 === $this->runCommand(
+ 'generate:api-resources',
'',
null,
- false,
- true
- ) === 0 ? $io->success('doctrine:cache:clear-metadata') : $io->error('doctrine:cache:clear-metadata');
+ $input->isInteractive(),
+ $output->isQuiet()
+ ) ? $io->success('generate:api-resources') : $io->error('generate:api-resources');
- $this->runCommand(
- 'cache:clear',
- '',
- null,
- false,
- true
- ) === 0 ? $io->success('cache:clear') : $io->error('cache:clear');
+ $this->schemaUpdater->updateNodeTypesSchema();
+ $this->schemaUpdater->updateSchema();
+ $io->success('doctrine-migrations');
- $this->runCommand(
- 'cache:pool:clear',
- 'cache.global_clearer',
- null,
- false,
- true
- ) === 0 ? $io->success('cache:pool:clear') : $io->error('cache:pool:clear');
+ $this->clearCaches($io);
}
- return 0;
- }
- protected function runCommand(
- string $command,
- string $args = '',
- ?string $environment = null,
- bool $interactive = true,
- bool $quiet = false
- ): int {
- $args .= $interactive ? '' : ' --no-interaction ';
- $args .= $quiet ? ' --quiet ' : ' -v ';
- $args .= is_string($environment) ? (' --env ' . $environment) : '';
-
- $process = Process::fromShellCommandline(
- 'php bin/console ' . $command . ' ' . $args
- );
- $process->setWorkingDirectory($this->projectDir);
- $process->setTty($interactive);
- $process->run();
- return $process->wait();
+ return 0;
}
}
diff --git a/src/Console/CustomFormAnswerPurgeCommand.php b/src/Console/CustomFormAnswerPurgeCommand.php
index 07270a01..a84d5cc3 100644
--- a/src/Console/CustomFormAnswerPurgeCommand.php
+++ b/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);
}
@@ -44,74 +44,85 @@ protected function execute(InputInterface $input, OutputInterface $output): int
->findAllWithRetentionTime();
foreach ($customForms as $customForm) {
- if (null !== $interval = $customForm->getRetentionTimeInterval()) {
- $purgeBefore = (new \DateTime())->sub($interval);
- $customFormAnswers = $this->managerRegistry
- ->getRepository(CustomFormAnswer::class)
- ->findByCustomFormSubmittedBefore($customForm, $purgeBefore);
- $count = count($customFormAnswers);
-
- $documents = $this->managerRegistry
- ->getRepository(Document::class)
- ->findByCustomFormSubmittedBefore($customForm, $purgeBefore);
- $documentsCount = count($documents);
+ $this->purgeCustomFormAnswers($customForm, $input, $output);
+ }
- if ($output->isVeryVerbose()) {
- $io->info(\sprintf(
- 'Checking if “%s” custom-form has answers before %s',
- $customForm->getName(),
- $purgeBefore->format('Y-m-d H:i')
- ));
- }
+ return 0;
+ }
+
+ protected function purgeCustomFormAnswers(CustomForm $customForm, InputInterface $input, OutputInterface $output): void
+ {
+ $io = new SymfonyStyle($input, $output);
+
+ if (null === $interval = $customForm->getRetentionTimeInterval()) {
+ return;
+ }
- if ($count > 0) {
+ $purgeBefore = (new \DateTime())->sub($interval);
+ $customFormAnswers = $this->managerRegistry
+ ->getRepository(CustomFormAnswer::class)
+ ->findByCustomFormSubmittedBefore($customForm, $purgeBefore);
+ $count = count($customFormAnswers);
+
+ $documents = $this->managerRegistry
+ ->getRepository(Document::class)
+ ->findByCustomFormSubmittedBefore($customForm, $purgeBefore);
+ $documentsCount = count($documents);
+
+ if ($output->isVeryVerbose()) {
+ $io->info(\sprintf(
+ 'Checking if “%s” custom-form has answers before %s',
+ $customForm->getName(),
+ $purgeBefore->format('Y-m-d H:i')
+ ));
+ }
+
+ if ($count <= 0) {
+ return;
+ }
+
+ $io->info(\sprintf(
+ 'Purge %d custom-form answer(s) with %d documents(s) from “%s” before %s',
+ $count,
+ $documentsCount,
+ $customForm->getName(),
+ $purgeBefore->format('Y-m-d H:i')
+ ));
+
+ if (
+ !$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,
+ $customForm->getName(),
+ $purgeBefore->format('Y-m-d H:i')
+ ), false))
+ ) {
+ $this->managerRegistry
+ ->getRepository(CustomFormAnswer::class)
+ ->deleteByCustomFormSubmittedBefore($customForm, $purgeBefore);
+
+ foreach ($documents as $document) {
+ $this->eventDispatcher->dispatch(
+ new DocumentDeletedEvent($document)
+ );
+ if ($output->isVeryVerbose()) {
$io->info(\sprintf(
- 'Purge %d custom-form answer(s) with %d documents(s) from “%s” before %s',
- $count,
- $documentsCount,
- $customForm->getName(),
- $purgeBefore->format('Y-m-d H:i')
+ '“%s” document has been deleted',
+ $document->getRelativePath()
));
-
- if (
- !$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,
- $customForm->getName(),
- $purgeBefore->format('Y-m-d H:i')
- ), false))
- ) {
- $this->managerRegistry
- ->getRepository(CustomFormAnswer::class)
- ->deleteByCustomFormSubmittedBefore($customForm, $purgeBefore);
-
- foreach ($documents as $document) {
- $this->eventDispatcher->dispatch(
- new DocumentDeletedEvent($document)
- );
- if ($output->isVeryVerbose()) {
- $io->info(\sprintf(
- '“%s” document has been deleted',
- $document->getRelativePath()
- ));
- }
- $this->managerRegistry->getManager()->remove($document);
- }
- $this->managerRegistry->getManager()->flush();
- $this->logger->info(\sprintf(
- '%d answer(s) and %d document(s) were deleted from “%s” custom-form before %s',
- $count,
- $documentsCount,
- $customForm->getName(),
- $purgeBefore->format('Y-m-d H:i')
- ));
- }
}
+ $this->managerRegistry->getManager()->remove($document);
}
+ $this->managerRegistry->getManager()->flush();
+ $this->logger->info(\sprintf(
+ '%d answer(s) and %d document(s) were deleted from “%s” custom-form before %s',
+ $count,
+ $documentsCount,
+ $customForm->getName(),
+ $purgeBefore->format('Y-m-d H:i')
+ ));
}
-
- return 0;
}
}
diff --git a/src/Console/FilesCommandTrait.php b/src/Console/FilesCommandTrait.php
index 15d73514..b745da54 100644
--- a/src/Console/FilesCommandTrait.php
+++ b/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/src/Console/FilesExportCommand.php b/src/Console/FilesExportCommand.php
index adf93e2d..49c4267e 100644
--- a/src/Console/FilesExportCommand.php
+++ b/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()
@@ -100,14 +85,15 @@ protected function zipFolder(ZipArchive $zip, string $folder, string $prefix = "
*/
foreach ($files as $file) {
// Skip directories (they would be added automatically)
- if (!$file->isDir()) {
- // Get real and relative path for current file
- $filePath = $file->getRealPath();
- $relativePath = \mb_substr($filePath, \mb_strlen($folder) + 1);
-
- // Add current file to archive
- $zip->addFile($filePath, $prefix . '/' . $relativePath);
+ if ($file->isDir()) {
+ continue;
}
+ // Get real and relative path for current file
+ $filePath = $file->getRealPath();
+ $relativePath = \mb_substr($filePath, \mb_strlen($folder) + 1);
+
+ // Add current file to archive
+ $zip->addFile($filePath, $prefix.'/'.$relativePath);
}
}
}
diff --git a/src/Console/FilesImportCommand.php b/src/Console/FilesImportCommand.php
index 4b910575..67783b6e 100644
--- a/src/Console/FilesImportCommand.php
+++ b/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,35 +56,35 @@ protected function execute(InputInterface $input, OutputInterface $output): int
mkdir($tempDir);
$zipArchivePath = $input->getArgument('input');
- $zip = new ZipArchive();
- if (true === $zip->open($zipArchivePath)) {
- if (
- $io->askQuestion(
- $confirmation
- )
- ) {
- $zip->extractTo($tempDir);
-
- $fs = new Filesystem();
- 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());
- $io->success('Private files have been imported.');
- }
- 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;
- } else {
+ $zip = new \ZipArchive();
+ if (true !== $zip->open($zipArchivePath)) {
$io->error('Zip archive does not exist or is invalid.');
+
return 1;
}
+
+ if (!$io->askQuestion($confirmation)) {
+ return 0;
+ }
+
+ $zip->extractTo($tempDir);
+
+ $fs = new Filesystem();
+ 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());
+ $io->success('Private files have been imported.');
+ }
+ 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/src/Console/GenerateApiResourceCommand.php b/src/Console/GenerateApiResourceCommand.php
index 87ae30e3..d1b68475 100644
--- a/src/Console/GenerateApiResourceCommand.php
+++ b/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) {
- foreach ($nodeTypes as $nt) {
- $resourcePath = $this->apiResourceGenerator->generate($nt);
- if (null !== $resourcePath) {
- $io->writeln("* API resource " . $resourcePath . " has been generated.");
- }
- }
- return 0;
- } else {
+ 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.');
+ }
+ }
+
+ return 0;
}
}
diff --git a/src/Console/GenerateNodeSourceEntitiesCommand.php b/src/Console/GenerateNodeSourceEntitiesCommand.php
index 04c3b8dc..22192299 100644
--- a/src/Console/GenerateNodeSourceEntitiesCommand.php
+++ b/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);
}
@@ -39,27 +39,29 @@ protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
- $nodetypes = $this->managerRegistry
+ $nodeTypes = $this->managerRegistry
->getRepository(NodeType::class)
->findAll();
- if (count($nodetypes) > 0) {
- /** @var NodeType $nt */
- foreach ($nodetypes as $nt) {
- /** @var NodeTypeHandler $handler */
- $handler = $this->handlerFactory->getHandler($nt);
- $handler->removeSourceEntityClass();
- $handler->generateSourceEntityClass();
- $io->writeln("* Source class " . $nt->getSourceEntityClassName() . " has been generated.");
-
- if ($output->isVeryVerbose()) {
- $io->writeln("\t" . $handler->getSourceClassPath() . "");
- }
- }
- return 0;
- } else {
+ if (0 === count($nodeTypes)) {
$io->error('No available node-types…');
+
return 1;
}
+
+ /** @var NodeType $nt */
+ foreach ($nodeTypes as $nt) {
+ /** @var NodeTypeHandler $handler */
+ $handler = $this->handlerFactory->getHandler($nt);
+ $handler->removeSourceEntityClass();
+ $handler->generateSourceEntityClass();
+ $io->writeln('* Source class '.$nt->getSourceEntityClassName().' has been generated.');
+
+ if ($output->isVeryVerbose()) {
+ $io->writeln("\t".$handler->getSourceClassPath().'');
+ }
+ }
+
+ return 0;
}
}
diff --git a/src/Console/GetCronLastExecDateCommand.php b/src/Console/GetCronLastExecDateCommand.php
index e090c16d..9cc65f30 100644
--- a/src/Console/GetCronLastExecDateCommand.php
+++ b/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/src/Console/InstallCommand.php b/src/Console/InstallCommand.php
index 913de1ca..a79e84ce 100644
--- a/src/Console/InstallCommand.php
+++ b/src/Console/InstallCommand.php
@@ -4,8 +4,6 @@
namespace RZ\Roadiz\CoreBundle\Console;
-use Doctrine\Common\Cache\CacheProvider;
-use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use RZ\Roadiz\CoreBundle\Entity\Translation;
use RZ\Roadiz\CoreBundle\Importer\GroupsImporter;
@@ -16,86 +14,106 @@
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Style\SymfonyStyle;
+use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Yaml\Yaml;
final class InstallCommand extends Command
{
+ use RunningCommandsTrait;
+
public function __construct(
private readonly ManagerRegistry $managerRegistry,
private readonly RolesImporter $rolesImporter,
private readonly GroupsImporter $groupsImporter,
private readonly SettingsImporter $settingsImporter,
- ?string $name = null
+ #[Autowire('%kernel.project_dir%')]
+ private readonly string $projectDir,
+ ?string $name = null,
) {
parent::__construct($name);
}
+ public function getProjectDir(): string
+ {
+ return $this->projectDir;
+ }
+
protected function configure(): void
{
$this
->setName('install')
- ->setDescription('Install Roadiz roles, settings, translations and default backend theme');
+ ->setDescription('Perform Doctrine migrations, install default Roadiz roles, settings and translation.');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
- $io->note('Before installing Roadiz, did you create database schema? ' . PHP_EOL .
- 'If not execute: bin/console doctrine:migrations:migrate');
$question = new ConfirmationQuestion(
'Are you sure to perform installation?',
false
);
if (
- $input->getOption('no-interaction') ||
- $io->askQuestion($question)
+ $input->getOption('no-interaction')
+ || $io->askQuestion($question)
) {
- $fixturesRoot = dirname(__DIR__) . '/../config';
- $fixtureFile = file_get_contents($fixturesRoot . "/fixtures.yaml");
+ 0 === $this->runCommand(
+ 'doctrine:migrations:migrate',
+ '',
+ null,
+ false,
+ true
+ ) ? $io->success('doctrine:migrations:migrate') : $io->error('doctrine:migrations:migrate');
+
+ $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);
@@ -106,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);
@@ -117,25 +135,17 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
$manager->flush();
- if ($manager instanceof EntityManagerInterface) {
- // Clear result cache
- $cacheDriver = $manager->getConfiguration()->getResultCacheImpl();
- if ($cacheDriver instanceof CacheProvider) {
- $cacheDriver->deleteAll();
- }
- }
+ $this->clearCaches($io);
}
+
return 0;
}
/**
* Tell if there is any translation.
- *
- * @return boolean
*/
public function hasDefaultTranslation(): bool
{
- $default = $this->managerRegistry->getRepository(Translation::class)->findOneBy([]);
- return $default !== null;
+ return null !== $this->managerRegistry->getRepository(Translation::class)->findDefault();
}
}
diff --git a/src/Console/LogsCleanupCommand.php b/src/Console/LogsCleanupCommand.php
index 56fd662a..66517c82 100644
--- a/src/Console/LogsCleanupCommand.php
+++ b/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/src/Console/MailerTestCommand.php b/src/Console/MailerTestCommand.php
index 5a5d4eec..0269ee96 100644
--- a/src/Console/MailerTestCommand.php
+++ b/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/src/Console/NodeApplyUniversalFieldsCommand.php b/src/Console/NodeApplyUniversalFieldsCommand.php
index 942e2541..645fb4d3 100644
--- a/src/Console/NodeApplyUniversalFieldsCommand.php
+++ b/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/src/Console/NodeClearTagCommand.php b/src/Console/NodeClearTagCommand.php
index e7e775f7..9a0db025 100644
--- a/src/Console/NodeClearTagCommand.php
+++ b/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/src/Console/NodeTypesAddFieldCommand.php b/src/Console/NodeTypesAddFieldCommand.php
index e8651e30..f5643271 100644
--- a/src/Console/NodeTypesAddFieldCommand.php
+++ b/src/Console/NodeTypesAddFieldCommand.php
@@ -38,23 +38,25 @@ protected function execute(InputInterface $input, OutputInterface $output): int
->getRepository(NodeType::class)
->findOneBy(['name' => $name]);
- if ($nodeType !== null) {
- $latestPosition = $this->managerRegistry
- ->getRepository(NodeTypeField::class)
- ->findLatestPositionInNodeType($nodeType);
- $this->addNodeTypeField($nodeType, $latestPosition + 1, $io);
- $this->managerRegistry->getManagerForClass(NodeTypeField::class)->flush();
-
- /** @var NodeTypeHandler $handler */
- $handler = $this->handlerFactory->getHandler($nodeType);
- $handler->regenerateEntityClass();
- $this->schemaUpdater->updateNodeTypesSchema();
-
- $io->success('Node type ' . $nodeType->getName() . ' has been updated.');
- return 0;
- } else {
- $io->error('Node-type "' . $name . '" does not exist.');
+ if (null === $nodeType) {
+ $io->error('Node-type "'.$name.'" does not exist.');
+
return 1;
}
+
+ $latestPosition = $this->managerRegistry
+ ->getRepository(NodeTypeField::class)
+ ->findLatestPositionInNodeType($nodeType);
+ $this->addNodeTypeField($nodeType, $latestPosition + 1, $io);
+ $this->managerRegistry->getManagerForClass(NodeTypeField::class)->flush();
+
+ /** @var NodeTypeHandler $handler */
+ $handler = $this->handlerFactory->getHandler($nodeType);
+ $handler->regenerateEntityClass();
+ $this->schemaUpdater->updateNodeTypesSchema();
+
+ $io->success('Node type '.$nodeType->getName().' has been updated.');
+
+ return 0;
}
}
diff --git a/src/Console/NodeTypesCommand.php b/src/Console/NodeTypesCommand.php
index 262bcaa6..b5275ab5 100644
--- a/src/Console/NodeTypesCommand.php
+++ b/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,51 +43,52 @@ protected function execute(InputInterface $input, OutputInterface $output): int
->getRepository(NodeType::class)
->findOneByName($name);
- if ($nodetype !== null) {
- /** @var array $fields */
- $fields = $this->managerRegistry->getRepository(NodeTypeField::class)
- ->findBy([
- 'nodeType' => $nodetype,
- ], ['position' => 'ASC']);
+ if (null === $nodetype) {
+ $io->note($name.' node type does not exist.');
- $tableContent = [];
- foreach ($fields as $field) {
- $tableContent[] = [
- $field->getId(),
- $field->getLabel(),
- $field->getName(),
- str_replace('.type', '', $field->getTypeName()),
- ($field->isVisible() ? 'X' : ''),
- ($field->isIndexed() ? 'X' : ''),
- ];
- }
- $io->table(['Id', 'Label', 'Name', 'Type', 'Visible', 'Index'], $tableContent);
- } else {
- $io->note($name . ' node type does not exist.');
return 0;
}
+ /** @var array $fields */
+ $fields = $this->managerRegistry->getRepository(NodeTypeField::class)
+ ->findBy([
+ 'nodeType' => $nodetype,
+ ], ['position' => 'ASC']);
+
+ $tableContent = [];
+ foreach ($fields as $field) {
+ $tableContent[] = [
+ $field->getId(),
+ $field->getLabel(),
+ $field->getName(),
+ str_replace('.type', '', $field->getTypeName()),
+ $field->isVisible() ? 'X' : '',
+ $field->isIndexed() ? 'X' : '',
+ ];
+ }
+ $io->table(['Id', 'Label', 'Name', 'Type', 'Visible', 'Index'], $tableContent);
} else {
/** @var array $nodetypes */
$nodetypes = $this->managerRegistry
->getRepository(NodeType::class)
->findBy([], ['name' => 'ASC']);
- if (count($nodetypes) > 0) {
- $tableContent = [];
+ if (0 === count($nodetypes)) {
+ $io->note('No available node-types…');
+ }
- foreach ($nodetypes as $nt) {
- $tableContent[] = [
- $nt->getId(),
- $nt->getName(),
- ($nt->isVisible() ? 'X' : ''),
- ];
- }
+ $tableContent = [];
- $io->table(['Id', 'Title', 'Visible'], $tableContent);
- } else {
- $io->note('No available node-types…');
+ foreach ($nodetypes as $nt) {
+ $tableContent[] = [
+ $nt->getId(),
+ $nt->getName(),
+ $nt->isVisible() ? 'X' : '',
+ ];
}
+
+ $io->table(['Id', 'Title', 'Visible'], $tableContent);
}
+
return 0;
}
}
diff --git a/src/Console/NodeTypesCreationCommand.php b/src/Console/NodeTypesCreationCommand.php
index 25788fec..af1577ef 100644
--- a/src/Console/NodeTypesCreationCommand.php
+++ b/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/src/Console/NodeTypesDefaultValuesCommand.php b/src/Console/NodeTypesDefaultValuesCommand.php
index 2c4c3ec7..5fdc67d1 100644
--- a/src/Console/NodeTypesDefaultValuesCommand.php
+++ b/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/src/Console/NodeTypesDeleteCommand.php b/src/Console/NodeTypesDeleteCommand.php
index 6e9d47c0..f312ecc0 100644
--- a/src/Console/NodeTypesDeleteCommand.php
+++ b/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,33 +55,35 @@ protected function execute(InputInterface $input, OutputInterface $output): int
->getRepository(NodeType::class)
->findOneByName($name);
- if ($nodeType !== null) {
- $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?',
- false
- );
- if (
- $io->askQuestion(
- $question
- )
- ) {
- /** @var NodeTypeHandler $handler */
- $handler = $this->handlerFactory->getHandler($nodeType);
- $handler->removeSourceEntityClass();
- $this->managerRegistry->getManagerForClass(NodeType::class)->remove($nodeType);
- $this->managerRegistry->getManagerForClass(NodeType::class)->flush();
- $this->schemaUpdater->updateNodeTypesSchema();
- $io->success('Node-type deleted.');
- }
- } else {
- $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.
+ '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?',
+ false
+ );
+ if (
+ $io->askQuestion(
+ $question
+ )
+ ) {
+ /** @var NodeTypeHandler $handler */
+ $handler = $this->handlerFactory->getHandler($nodeType);
+ $handler->removeSourceEntityClass();
+ $this->managerRegistry->getManagerForClass(NodeType::class)->remove($nodeType);
+ $this->managerRegistry->getManagerForClass(NodeType::class)->flush();
+ $this->schemaUpdater->updateNodeTypesSchema();
+ $io->success('Node-type deleted.');
+ }
+
return 0;
}
}
diff --git a/src/Console/NodesCleanNamesCommand.php b/src/Console/NodesCleanNamesCommand.php
index 394a55de..4f60243d 100644
--- a/src/Console/NodesCleanNamesCommand.php
+++ b/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,84 +65,83 @@ 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->note('Renaming ' . count($nodes) . ' nodes…');
- $renameCount = 0;
- $names = [];
-
- /** @var Node $node */
- foreach ($nodes as $node) {
- $nodeSource = $node->getNodeSources()->first() ?: null;
- if ($nodeSource !== null) {
- $prefixName = $nodeSource->getTitle() != "" ?
- $nodeSource->getTitle() :
- $node->getNodeName();
-
- $prefixNameSlug = $this->nodeNamePolicy->getCanonicalNodeName($nodeSource);
- /*
- * Proceed to rename only if best name is not the current
- * node-name AND if it is not ALREADY suffixed with a unique ID.
- */
+ if (!$io->askQuestion($question1)) {
+ $io->warning('Renaming cancelled…');
+
+ return 1;
+ }
+
+ $io->note('Renaming '.count($nodes).' nodes…');
+ $renameCount = 0;
+ $names = [];
+
+ /** @var Node $node */
+ foreach ($nodes as $node) {
+ $nodeSource = $node->getNodeSources()->first() ?: null;
+ if (null === $nodeSource) {
+ continue;
+ }
+
+ $prefixNameSlug = $this->nodeNamePolicy->getCanonicalNodeName($nodeSource);
+ /*
+ * Proceed to rename only if best name is not the current
+ * 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())
+ ) {
+ $alreadyUsed = $this->nodeNamePolicy->isNodeNameAlreadyUsed($prefixNameSlug);
+ if (!$alreadyUsed) {
+ $names[] = [
+ $node->getNodeName(),
+ $prefixNameSlug,
+ ];
+ $node->setNodeName($prefixNameSlug);
+ } else {
if (
- $prefixNameSlug != $node->getNodeName() &&
- $this->nodeNamePolicy->isNodeNameValid($prefixNameSlug) &&
- !$this->nodeNamePolicy->isNodeNameWithUniqId($prefixNameSlug, $nodeSource->getNode()->getNodeName())
+ $input->getOption('use-date')
+ && null !== $nodeSource->getPublishedAt()
) {
- $alreadyUsed = $this->nodeNamePolicy->isNodeNameAlreadyUsed($prefixNameSlug);
- if (!$alreadyUsed) {
- $names[] = [
- $node->getNodeName(),
- $prefixNameSlug
- ];
- $node->setNodeName($prefixNameSlug);
- } else {
- if (
- $input->getOption('use-date') &&
- null !== $nodeSource->getPublishedAt()
- ) {
- $suffixedNameSlug = $this->nodeNamePolicy->getDatestampedNodeName($nodeSource);
- } else {
- $suffixedNameSlug = $this->nodeNamePolicy->getSafeNodeName($nodeSource);
- }
- if (!$this->nodeNamePolicy->isNodeNameAlreadyUsed($suffixedNameSlug)) {
- $names[] = [
- $node->getNodeName(),
- $suffixedNameSlug
- ];
- $node->setNodeName($suffixedNameSlug);
- } else {
- $suffixedNameSlug = $this->nodeNamePolicy->getSafeNodeName($nodeSource);
- $names[] = [
- $node->getNodeName(),
- $suffixedNameSlug
- ];
- $node->setNodeName($suffixedNameSlug);
- }
- }
- if (!$input->getOption('dry-run')) {
- $entityManager->flush();
- }
- $renameCount++;
+ $suffixedNameSlug = $this->nodeNamePolicy->getDatestampedNodeName($nodeSource);
+ } else {
+ $suffixedNameSlug = $this->nodeNamePolicy->getSafeNodeName($nodeSource);
+ }
+ if (!$this->nodeNamePolicy->isNodeNameAlreadyUsed($suffixedNameSlug)) {
+ $names[] = [
+ $node->getNodeName(),
+ $suffixedNameSlug,
+ ];
+ $node->setNodeName($suffixedNameSlug);
+ } else {
+ $suffixedNameSlug = $this->nodeNamePolicy->getSafeNodeName($nodeSource);
+ $names[] = [
+ $node->getNodeName(),
+ $suffixedNameSlug,
+ ];
+ $node->setNodeName($suffixedNameSlug);
}
}
+ if (!$input->getOption('dry-run')) {
+ $entityManager->flush();
+ }
+ ++$renameCount;
}
+ }
- $io->table(['Old name', 'New name'], $names);
+ $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.');
- } else {
- $io->success($renameCount . ' nodes would have been affected. Nothing was saved to database.');
- }
+ 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.');
} else {
- $io->warning('Renaming cancelled…');
- return 1;
+ $io->success($renameCount.' nodes would have been affected. Nothing was saved to database.');
}
}
diff --git a/src/Console/NodesCommand.php b/src/Console/NodesCommand.php
index cd5e56a0..f3210b5e 100644
--- a/src/Console/NodesCommand.php
+++ b/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/src/Console/NodesDetailsCommand.php b/src/Console/NodesDetailsCommand.php
index 53515526..e2dc827a 100644
--- a/src/Console/NodesDetailsCommand.php
+++ b/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/src/Console/NodesEmptyTrashCommand.php b/src/Console/NodesEmptyTrashCommand.php
index 8e21028b..3084bc0b 100644
--- a/src/Console/NodesEmptyTrashCommand.php
+++ b/src/Console/NodesEmptyTrashCommand.php
@@ -9,6 +9,7 @@
use RZ\Roadiz\CoreBundle\Entity\Node;
use RZ\Roadiz\CoreBundle\EntityHandler\HandlerFactory;
use RZ\Roadiz\CoreBundle\EntityHandler\NodeHandler;
+use RZ\Roadiz\CoreBundle\Enum\NodeStatus;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -20,7 +21,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);
}
@@ -40,48 +41,55 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$em = $this->managerRegistry->getManagerForClass(Node::class);
$countQb = $this->createNodeQueryBuilder();
$countQuery = $countQb->select($countQb->expr()->count('n'))
- ->andWhere($countQb->expr()->eq('n.status', Node::DELETED))
+ ->andWhere($countQb->expr()->eq('n.status', ':status'))
+ ->setParameter('status', NodeStatus::DELETED)
->getQuery();
$emptiedCount = $countQuery->getSingleScalarResult();
- if ($emptiedCount > 0) {
- $confirmation = new ConfirmationQuestion(
- sprintf('Are you sure to empty nodes trashcan, %d nodes will be lost forever? [y/N]: ', $emptiedCount),
- false
- );
- if ($io->askQuestion($confirmation) || !$input->isInteractive()) {
- $i = 0;
- $batchSize = 100;
- $io->progressStart((int) $emptiedCount);
-
- $qb = $this->createNodeQueryBuilder();
- $q = $qb->select('n')
- ->andWhere($countQb->expr()->eq('n.status', Node::DELETED))
- ->getQuery();
-
- foreach ($q->toIterable() as $row) {
- /** @var NodeHandler $nodeHandler */
- $nodeHandler = $this->handlerFactory->getHandler($row);
- $nodeHandler->removeWithChildrenAndAssociations();
- $io->progressAdvance();
- ++$i;
- // Call flush time to times
- if (($i % $batchSize) === 0) {
- $em->flush();
- $em->clear();
- }
- }
-
- /*
- * Final flush
- */
+ if (0 == $emptiedCount) {
+ $io->success('Nodes trashcan is already empty.');
+
+ return 0;
+ }
+
+ $confirmation = new ConfirmationQuestion(
+ sprintf('Are you sure to empty nodes trashcan, %d nodes will be lost forever? [y/N]: ', $emptiedCount),
+ false
+ );
+
+ if ($input->isInteractive() && !$io->askQuestion($confirmation)) {
+ return 0;
+ }
+
+ $i = 0;
+ $batchSize = 100;
+ $io->progressStart((int) $emptiedCount);
+
+ $qb = $this->createNodeQueryBuilder();
+ $q = $qb->select('n')
+ ->andWhere($countQb->expr()->eq('n.status', ':status'))
+ ->setParameter('status', NodeStatus::DELETED)
+ ->getQuery();
+
+ foreach ($q->toIterable() as $row) {
+ /** @var NodeHandler $nodeHandler */
+ $nodeHandler = $this->handlerFactory->getHandler($row);
+ $nodeHandler->removeWithChildrenAndAssociations();
+ $io->progressAdvance();
+ ++$i;
+ // Call flush time to times
+ if (($i % $batchSize) === 0) {
$em->flush();
- $io->progressFinish();
- $io->success('Nodes trashcan has been emptied.');
+ $em->clear();
}
- } else {
- $io->success('Nodes trashcan is already empty.');
}
+ /*
+ * Final flush
+ */
+ $em->flush();
+ $io->progressFinish();
+ $io->success('Nodes trashcan has been emptied.');
+
return 0;
}
diff --git a/src/Console/NodesOrphansCommand.php b/src/Console/NodesOrphansCommand.php
index e3a68598..bdfb3f41 100644
--- a/src/Console/NodesOrphansCommand.php
+++ b/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,37 +55,40 @@ protected function execute(InputInterface $input, OutputInterface $output): int
} catch (NoResultException $e) {
}
- if (count($orphans) > 0) {
- $io->note(sprintf('You have %s orphan node(s)!', count($orphans)));
- $tableContent = [];
+ if (0 === count($orphans)) {
+ $io->success('That’s OK, you don’t have any orphan node.');
- /** @var Node $node */
- foreach ($orphans as $node) {
- $tableContent[] = [
- $node->getId(),
- $node->getNodeName(),
- null !== $node->getNodeType() ? $node->getNodeType()->getName() : '',
- (!$node->isVisible() ? 'X' : ''),
- ($node->isPublished() ? 'X' : ''),
- ];
- }
+ return 0;
+ }
+
+ $io->note(sprintf('You have %s orphan node(s)!', count($orphans)));
+ $tableContent = [];
- $io->table(['Id', 'Name', 'Type', 'Hidden', 'Published'], $tableContent);
+ /** @var Node $node */
+ foreach ($orphans as $node) {
+ $tableContent[] = [
+ $node->getId(),
+ $node->getNodeName(),
+ null !== $node->getNodeType() ? $node->getNodeType()->getName() : '',
+ !$node->isVisible() ? 'X' : '',
+ $node->isPublished() ? 'X' : '',
+ ];
+ }
- if ($input->getOption('delete')) {
- /** @var Node $orphan */
- foreach ($orphans as $orphan) {
- $entityManager->remove($orphan);
- }
- $entityManager->flush();
+ $io->table(['Id', 'Name', 'Type', 'Hidden', 'Published'], $tableContent);
- $io->success('Orphan nodes have been removed from your database.');
- } else {
- $io->note('Use --delete option to actually remove these nodes.');
+ if ($input->getOption('delete')) {
+ /** @var Node $orphan */
+ foreach ($orphans as $orphan) {
+ $entityManager->remove($orphan);
}
+ $entityManager->flush();
+
+ $io->success('Orphan nodes have been removed from your database.');
} else {
- $io->success('That’s OK, you don’t have any orphan node.');
+ $io->note('Use --delete option to actually remove these nodes.');
}
+
return 0;
}
}
diff --git a/src/Console/RegisterCronLastExecDateCommand.php b/src/Console/RegisterCronLastExecDateCommand.php
index 20bed441..8ebf77f1 100644
--- a/src/Console/RegisterCronLastExecDateCommand.php
+++ b/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
+ {
+ 0 === $this->runCommand(
+ 'doctrine:cache:clear-metadata',
+ '',
+ null,
+ false,
+ true
+ ) ? $io->success('doctrine:cache:clear-metadata') : $io->error('doctrine:cache:clear-metadata');
+
+ 0 === $this->runCommand(
+ 'cache:clear',
+ '',
+ null,
+ false,
+ true
+ ) ? $io->success('cache:clear') : $io->error('cache:clear');
+
+ 0 === $this->runCommand(
+ 'cache:pool:clear',
+ 'cache.global_clearer',
+ null,
+ false,
+ true
+ ) ? $io->success('cache:pool:clear') : $io->error('cache:pool:clear');
+ }
+}
diff --git a/src/Console/SolrCommand.php b/src/Console/SolrCommand.php
index 32396f2b..0372582e 100644
--- a/src/Console/SolrCommand.php
+++ b/src/Console/SolrCommand.php
@@ -5,6 +5,7 @@
namespace RZ\Roadiz\CoreBundle\Console;
use RZ\Roadiz\CoreBundle\SearchEngine\ClientRegistry;
+use Solarium\Core\Client\Client;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -16,7 +17,7 @@ class SolrCommand extends Command
public function __construct(
protected readonly ClientRegistry $clientRegistry,
- ?string $name = null
+ ?string $name = null,
) {
parent::__construct($name);
}
@@ -27,31 +28,47 @@ protected function configure(): void
->setDescription('Check Solr search engine server');
}
- protected function execute(InputInterface $input, OutputInterface $output): int
+ protected function validateSolrState(SymfonyStyle $io): ?Client
{
$client = $this->clientRegistry->getClient();
- $this->io = new SymfonyStyle($input, $output);
- if (null !== $client) {
- if (true === $this->clientRegistry->isClientReady($client)) {
- $this->io->writeln('Solr search engine server is running…');
- } else {
- $this->io->error('Solr search engine server does not respond…');
- $this->io->note('See your config.yml file to correct your Solr connexion settings.');
- return 1;
- }
- } else {
+ 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;
+ }
+
+ return $client;
+ }
+
+ protected function execute(InputInterface $input, OutputInterface $output): int
+ {
+ $this->io = new SymfonyStyle($input, $output);
+ if (null === $this->validateSolrState($this->io)) {
+ return 1;
}
+
+ $this->io->success('Solr search engine server is running.');
+
return 0;
}
protected function displayBasicConfig(): void
{
- if (null !== $this->io) {
- $this->io->error('No Solr search engine server has been configured…');
- $this->io->note(<<io) {
+ return;
+ }
+
+ $this->io->error('No Solr search engine server has been configured…');
+ $this->io->note(<<clientRegistry->getClient();
$this->io = new SymfonyStyle($input, $output);
- if (null !== $solr) {
- if (true === $this->clientRegistry->isClientReady($solr)) {
- $documentIndexer = $this->indexerFactory->getIndexerFor(Document::class);
- if ($documentIndexer instanceof CliAwareIndexer) {
- $documentIndexer->setIo($this->io);
- }
- $documentIndexer->optimizeSolr();
- $this->io->success('Solr core has been optimized.');
- } else {
- $this->io->error('Solr search engine server does not respond…');
- $this->io->note('See your config.yml file to correct your Solr connexion settings.');
- return 1;
- }
- } else {
- $this->displayBasicConfig();
+ if (null === $this->validateSolrState($this->io)) {
+ return 1;
}
+
+ $documentIndexer = $this->indexerFactory->getIndexerFor(Document::class);
+ if ($documentIndexer instanceof CliAwareIndexer) {
+ $documentIndexer->setIo($this->io);
+ }
+ $documentIndexer->optimizeSolr();
+ $this->io->success('Solr core has been optimized.');
+
return 0;
}
}
diff --git a/src/Console/SolrReindexCommand.php b/src/Console/SolrReindexCommand.php
index 041a22fb..cbfef2a6 100644
--- a/src/Console/SolrReindexCommand.php
+++ b/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);
}
@@ -40,38 +40,32 @@ protected function configure(): void
protected function execute(InputInterface $input, OutputInterface $output): int
{
- $solr = $this->clientRegistry->getClient();
$this->io = new SymfonyStyle($input, $output);
- if (null !== $solr) {
- if (true === $this->clientRegistry->isClientReady($solr)) {
- if (
- $this->io->confirm(
- 'Are you sure to reindex your Node and Document database?',
- !$input->isInteractive()
- )
- ) {
- $stopwatch = new Stopwatch();
- $stopwatch->start('global');
-
- if ($input->getOption('documents')) {
- $this->executeForDocuments($stopwatch);
- } elseif ($input->getOption('nodes')) {
- $batchCount = (int) ($input->getOption('batch-count') ?? 1);
- $batchNumber = (int) ($input->getOption('batch-number') ?? 0);
- $this->executeForNodes($stopwatch, $batchCount, $batchNumber);
- } else {
- $this->executeForAll($stopwatch);
- }
- }
+ if (null === $this->validateSolrState($this->io)) {
+ return 1;
+ }
+
+ if (
+ $this->io->confirm(
+ 'Are you sure to reindex your Node and Document database?',
+ !$input->isInteractive()
+ )
+ ) {
+ $stopwatch = new Stopwatch();
+ $stopwatch->start('global');
+
+ if ($input->getOption('documents')) {
+ $this->executeForDocuments($stopwatch);
+ } elseif ($input->getOption('nodes')) {
+ $batchCount = (int) ($input->getOption('batch-count') ?? 1);
+ $batchNumber = (int) ($input->getOption('batch-number') ?? 0);
+ $this->executeForNodes($stopwatch, $batchCount, $batchNumber);
} else {
- $this->io->error('Solr search engine server does not respond…');
- $this->io->note('See your config.yml file to correct your Solr connexion settings.');
- return 1;
+ $this->executeForAll($stopwatch);
}
- } else {
- $this->displayBasicConfig();
}
+
return 0;
}
@@ -116,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/src/Console/SolrResetCommand.php b/src/Console/SolrResetCommand.php
index ac48d1f3..2789e2bc 100644
--- a/src/Console/SolrResetCommand.php
+++ b/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);
}
@@ -31,31 +31,24 @@ protected function configure(): void
protected function execute(InputInterface $input, OutputInterface $output): int
{
- $solr = $this->clientRegistry->getClient();
$this->io = new SymfonyStyle($input, $output);
- if (null !== $solr) {
- if (true === $this->clientRegistry->isClientReady($solr)) {
- $confirmation = new ConfirmationQuestion(
- 'Are you sure to reset Solr index?',
- false
- );
- if ($this->io->askQuestion($confirmation)) {
- $indexer = $this->indexerFactory->getIndexerFor(NodesSources::class);
- if ($indexer instanceof CliAwareIndexer) {
- $indexer->setIo($this->io);
- }
- $indexer->emptySolr();
- $this->io->success('Solr index resetted.');
- }
- } else {
- $this->io->error('Solr search engine server does not respond…');
- $this->io->note('See your config.yml file to correct your Solr connexion settings.');
- return 1;
+ if (null === $this->validateSolrState($this->io)) {
+ return 1;
+ }
+ $confirmation = new ConfirmationQuestion(
+ 'Are you sure to reset Solr index?',
+ false
+ );
+ if ($this->io->askQuestion($confirmation)) {
+ $indexer = $this->indexerFactory->getIndexerFor(NodesSources::class);
+ if ($indexer instanceof CliAwareIndexer) {
+ $indexer->setIo($this->io);
}
- } else {
- $this->displayBasicConfig();
+ $indexer->emptySolr();
+ $this->io->success('Solr index resetted.');
}
+
return 0;
}
}
diff --git a/src/Console/TranslationsCommand.php b/src/Console/TranslationsCommand.php
index e3781525..61fd990e 100644
--- a/src/Console/TranslationsCommand.php
+++ b/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,22 +33,25 @@ protected function execute(InputInterface $input, OutputInterface $output): int
->getRepository(Translation::class)
->findAll();
- if (count($translations) > 0) {
- $tableContent = [];
- /** @var Translation $trans */
- foreach ($translations as $trans) {
- $tableContent[] = [
- $trans->getId(),
- $trans->getName(),
- $trans->getLocale(),
- (!$trans->isAvailable() ? 'X' : ''),
- ($trans->isDefaultTranslation() ? 'X' : ''),
- ];
- }
- $io->table(['Id', 'Name', 'Locale', 'Disabled', 'Default'], $tableContent);
- } else {
+ if (0 === count($translations)) {
$io->error('No available translations.');
+
+ return 1;
+ }
+
+ $tableContent = [];
+ /** @var Translation $trans */
+ foreach ($translations as $trans) {
+ $tableContent[] = [
+ $trans->getId(),
+ $trans->getName(),
+ $trans->getLocale(),
+ !$trans->isAvailable() ? 'X' : '',
+ $trans->isDefaultTranslation() ? 'X' : '',
+ ];
}
+ $io->table(['Id', 'Name', 'Locale', 'Disabled', 'Default'], $tableContent);
+
return 0;
}
}
diff --git a/src/Console/TranslationsCreationCommand.php b/src/Console/TranslationsCreationCommand.php
index 9d0f8b90..52f5b679 100644
--- a/src/Console/TranslationsCreationCommand.php
+++ b/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
{
@@ -38,42 +38,47 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$name = $input->getArgument('name');
$locale = $input->getArgument('locale');
- if ($name) {
- $translationByName = $this->managerRegistry
- ->getRepository(Translation::class)
- ->findOneByName($name);
- $translationByLocale = $this->managerRegistry
- ->getRepository(Translation::class)
- ->findOneByLocale($locale);
+ if (!$name) {
+ return 1;
+ }
- $confirmation = new ConfirmationQuestion(
- 'Are you sure to create ' . $name . ' (' . $locale . ') translation?',
- false
- );
+ $translationByName = $this->managerRegistry
+ ->getRepository(Translation::class)
+ ->findOneByName($name);
+ $translationByLocale = $this->managerRegistry
+ ->getRepository(Translation::class)
+ ->findOneByLocale($locale);
+
+ $confirmation = new ConfirmationQuestion(
+ 'Are you sure to create '.$name.' ('.$locale.') translation?',
+ false
+ );
- if (null !== $translationByName) {
- $io->error('Translation ' . $name . ' already exists.');
- return 1;
- } elseif (null !== $translationByLocale) {
- $io->error('Translation locale ' . $locale . ' is already used.');
- return 1;
- } else {
- if (
- $io->askQuestion(
- $confirmation
- )
- ) {
- $newTrans = new Translation();
- $newTrans->setName($name)
- ->setLocale($locale);
+ if (null !== $translationByName) {
+ $io->error('Translation '.$name.' already exists.');
- $this->managerRegistry->getManagerForClass(Translation::class)->persist($newTrans);
- $this->managerRegistry->getManagerForClass(Translation::class)->flush();
+ return 1;
+ } elseif (null !== $translationByLocale) {
+ $io->error('Translation locale '.$locale.' is already used.');
- $io->success('New ' . $newTrans->getName() . ' translation for ' . $newTrans->getLocale() . ' locale.');
- }
- }
+ return 1;
}
+
+ if (
+ $io->askQuestion(
+ $confirmation
+ )
+ ) {
+ $newTrans = new Translation();
+ $newTrans->setName($name)
+ ->setLocale($locale);
+
+ $this->managerRegistry->getManagerForClass(Translation::class)->persist($newTrans);
+ $this->managerRegistry->getManagerForClass(Translation::class)->flush();
+
+ $io->success('New '.$newTrans->getName().' translation for '.$newTrans->getLocale().' locale.');
+ }
+
return 0;
}
}
diff --git a/src/Console/TranslationsDeleteCommand.php b/src/Console/TranslationsDeleteCommand.php
index 60f54562..a12097c3 100644
--- a/src/Console/TranslationsDeleteCommand.php
+++ b/src/Console/TranslationsDeleteCommand.php
@@ -41,30 +41,35 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if ($translationCount < 2) {
$io->error('You cannot delete the only one available translation!');
+
return 1;
- } elseif ($translation !== null) {
- $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?',
- false
- );
- if (
- $io->askQuestion(
- $confirmation
- )
- ) {
- $this->managerRegistry->getManagerForClass(Translation::class)->remove($translation);
- $this->managerRegistry->getManagerForClass(Translation::class)->flush();
- $io->success('Translation deleted.');
- }
- } else {
- $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.
+ '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?',
+ false
+ );
+ if (
+ $io->askQuestion(
+ $confirmation
+ )
+ ) {
+ $this->managerRegistry->getManagerForClass(Translation::class)->remove($translation);
+ $this->managerRegistry->getManagerForClass(Translation::class)->flush();
+ $io->success('Translation deleted.');
+ }
+
return 0;
}
}
diff --git a/src/Console/TranslationsDisableCommand.php b/src/Console/TranslationsDisableCommand.php
index 164b7422..124039e4 100644
--- a/src/Console/TranslationsDisableCommand.php
+++ b/src/Console/TranslationsDisableCommand.php
@@ -36,24 +36,26 @@ protected function execute(InputInterface $input, OutputInterface $output): int
->getRepository(Translation::class)
->findOneByLocale($locale);
- if ($translation !== null) {
- $confirmation = new ConfirmationQuestion(
- 'Are you sure to disable ' . $translation->getName() . ' (' . $translation->getLocale() . ') translation?',
- false
- );
- if (
- $io->askQuestion(
- $confirmation
- )
- ) {
- $translation->setAvailable(false);
- $this->managerRegistry->getManagerForClass(Translation::class)->flush();
- $io->success('Translation disabled.');
- }
- } else {
- $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?',
+ false
+ );
+ if (
+ $io->askQuestion(
+ $confirmation
+ )
+ ) {
+ $translation->setAvailable(false);
+ $this->managerRegistry->getManagerForClass(Translation::class)->flush();
+ $io->success('Translation disabled.');
+ }
+
return 0;
}
}
diff --git a/src/Console/TranslationsEnableCommand.php b/src/Console/TranslationsEnableCommand.php
index f6656694..c196b97a 100644
--- a/src/Console/TranslationsEnableCommand.php
+++ b/src/Console/TranslationsEnableCommand.php
@@ -36,24 +36,26 @@ protected function execute(InputInterface $input, OutputInterface $output): int
->getRepository(Translation::class)
->findOneByLocale($locale);
- if ($translation !== null) {
- $confirmation = new ConfirmationQuestion(
- 'Are you sure to enable ' . $translation->getName() . ' (' . $translation->getLocale() . ') translation?',
- false
- );
- if (
- $io->askQuestion(
- $confirmation
- )
- ) {
- $translation->setAvailable(true);
- $this->managerRegistry->getManagerForClass(Translation::class)->flush();
- $io->success('Translation enabled.');
- }
- } else {
- $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?',
+ false
+ );
+ if (
+ $io->askQuestion(
+ $confirmation
+ )
+ ) {
+ $translation->setAvailable(true);
+ $this->managerRegistry->getManagerForClass(Translation::class)->flush();
+ $io->success('Translation enabled.');
+ }
+
return 0;
}
}
diff --git a/src/Console/UsersCommand.php b/src/Console/UsersCommand.php
index 2309ff8d..36de8d56 100644
--- a/src/Console/UsersCommand.php
+++ b/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/src/Console/UsersCreationCommand.php b/src/Console/UsersCreationCommand.php
index 2373093e..9d3723e5 100644
--- a/src/Console/UsersCreationCommand.php
+++ b/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/src/Console/UsersDeleteCommand.php b/src/Console/UsersDeleteCommand.php
index 2e8c3062..0f2007fa 100644
--- a/src/Console/UsersDeleteCommand.php
+++ b/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/src/Console/UsersDisableCommand.php b/src/Console/UsersDisableCommand.php
index 97b0062a..587e8ecf 100644
--- a/src/Console/UsersDisableCommand.php
+++ b/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/src/Console/UsersEnableCommand.php b/src/Console/UsersEnableCommand.php
index b9092656..11488c5e 100644
--- a/src/Console/UsersEnableCommand.php
+++ b/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/src/Console/UsersExpireCommand.php b/src/Console/UsersExpireCommand.php
index f8aafd30..c9d865e5 100644
--- a/src/Console/UsersExpireCommand.php
+++ b/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/src/Console/UsersInactiveCommand.php b/src/Console/UsersInactiveCommand.php
new file mode 100644
index 00000000..37e0f086
--- /dev/null
+++ b/src/Console/UsersInactiveCommand.php
@@ -0,0 +1,142 @@
+setName('users:inactive')
+ ->setDescription('List users that did not logged-in for 30 days.')
+ ->addOption(
+ 'days',
+ 'd',
+ InputOption::VALUE_REQUIRED,
+ 'Number of days since last login.',
+ 30
+ )
+ ->addOption(
+ 'role',
+ 'r',
+ InputOption::VALUE_REQUIRED,
+ 'List users with a specific role.',
+ null
+ )
+ ->addOption(
+ 'missing-role',
+ 'm',
+ InputOption::VALUE_REQUIRED,
+ 'List users without a specific role. Can be combined with --role.',
+ null
+ )
+ ->addOption(
+ 'purge',
+ null,
+ InputOption::VALUE_NONE,
+ 'Purge and delete inactive users with a specific role, destructive action.'
+ )
+ ;
+ }
+
+ protected function execute(InputInterface $input, OutputInterface $output): int
+ {
+ $io = new SymfonyStyle($input, $output);
+
+ $daysCount = $input->getOption('days');
+ if (!\is_numeric($daysCount) || $daysCount < 1) {
+ $io->error('Days option must be a positive number.');
+
+ return 1;
+ }
+
+ $sinceDate = new \DateTimeImmutable("-$daysCount days");
+
+ $inactiveUsers = $this->managerRegistry
+ ->getRepository(User::class)
+ ->findAllInactiveSinceDays(
+ (int) $daysCount
+ )
+ ;
+
+ $filteringRole = $input->getOption('role');
+ if (\is_string($filteringRole) && !empty(trim($filteringRole))) {
+ $inactiveUsers = array_filter($inactiveUsers, function (User $user) use ($filteringRole) {
+ return \in_array($filteringRole, $user->getRoles(), true);
+ });
+ }
+
+ $missingRole = $input->getOption('missing-role');
+ if (\is_string($missingRole) && !empty(trim($missingRole))) {
+ $inactiveUsers = array_filter($inactiveUsers, function (User $user) use ($missingRole) {
+ return !\in_array($missingRole, $user->getRoles(), true);
+ });
+ }
+
+ $io->success(sprintf(
+ '%d inactive users since %s.',
+ count($inactiveUsers),
+ $sinceDate->format('Y-m-d')
+ ));
+
+ if ($output->isVerbose() && count($inactiveUsers) > 0) {
+ $io->table(
+ ['ID', 'Username', 'Last login', 'Created at'],
+ array_map(function (User $user) {
+ return [
+ $user->getId(),
+ $user->getUsername(),
+ $user->getLastLogin()?->format('Y-m-d H:i:s') ?? 'Never',
+ $user->getCreatedAt()?->format('Y-m-d H:i:s') ?? 'Never',
+ ];
+ }, $inactiveUsers)
+ );
+ }
+
+ $purge = $input->getOption('purge');
+ if (!$purge || 0 === count($inactiveUsers)) {
+ return 0;
+ }
+
+ if (!\is_string($filteringRole) || empty(trim($filteringRole))) {
+ $io->error(sprintf(
+ '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;
+ }
+
+ foreach ($inactiveUsers as $user) {
+ $this->managerRegistry->getManager()->remove($user);
+ }
+ $this->managerRegistry->getManager()->flush();
+ $io->success(sprintf(
+ '%d inactive users have been deleted.',
+ count($inactiveUsers)
+ ));
+
+ return 0;
+ }
+}
diff --git a/src/Console/UsersLockCommand.php b/src/Console/UsersLockCommand.php
index 03e9b9dc..7df7055d 100644
--- a/src/Console/UsersLockCommand.php
+++ b/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/src/Console/UsersPasswordCommand.php b/src/Console/UsersPasswordCommand.php
index 9d265e1f..76dd9d3e 100644
--- a/src/Console/UsersPasswordCommand.php
+++ b/src/Console/UsersPasswordCommand.php
@@ -6,7 +6,7 @@
use Doctrine\Persistence\ManagerRegistry;
use RZ\Roadiz\CoreBundle\Entity\User;
-use RZ\Roadiz\Random\PasswordGenerator;
+use RZ\Roadiz\Random\PasswordGeneratorInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -16,9 +16,9 @@
final class UsersPasswordCommand extends UsersCommand
{
public function __construct(
- private readonly PasswordGenerator $passwordGenerator,
+ private readonly PasswordGeneratorInterface $passwordGenerator,
ManagerRegistry $managerRegistry,
- ?string $name = null
+ ?string $name = null,
) {
parent::__construct($managerRegistry, $name);
}
@@ -31,6 +31,11 @@ protected function configure(): void
'username',
InputArgument::REQUIRED,
'Username'
+ )->addOption(
+ 'length',
+ 'l',
+ InputArgument::OPTIONAL,
+ default: 16,
);
}
@@ -41,7 +46,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 (
@@ -49,12 +54,16 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$confirmation
)
) {
- $user->setPlainPassword($this->passwordGenerator->generatePassword(12));
+ $user->setPlainPassword($this->passwordGenerator->generatePassword(
+ (int) $input->getOption('length')
+ ));
$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/src/Console/UsersRolesCommand.php b/src/Console/UsersRolesCommand.php
index 047a2d5b..304998db 100644
--- a/src/Console/UsersRolesCommand.php
+++ b/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/src/Console/UsersUnexpireCommand.php b/src/Console/UsersUnexpireCommand.php
index 0430a728..a3dd5055 100644
--- a/src/Console/UsersUnexpireCommand.php
+++ b/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/src/Console/UsersUnlockCommand.php b/src/Console/UsersUnlockCommand.php
index 0fd4be6a..bd4684cb 100644
--- a/src/Console/UsersUnlockCommand.php
+++ b/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/src/Console/VersionsPurgeCommand.php b/src/Console/VersionsPurgeCommand.php
index 8891e472..d7531d84 100644
--- a/src/Console/VersionsPurgeCommand.php
+++ b/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;
}
@@ -79,7 +80,6 @@ private function getRepository(): UserLogEntryRepository
private function purgeByDate(InputInterface $input, OutputInterface $output): void
{
$io = new SymfonyStyle($input, $output);
- $em = $this->managerRegistry->getManagerForClass(UserLogEntry::class);
$dateTime = new \DateTime($input->getOption('before'));
if ($dateTime >= new \DateTime()) {
@@ -105,7 +105,6 @@ private function purgeByCount(InputInterface $input, OutputInterface $output): v
{
$io = new SymfonyStyle($input, $output);
$count = (int) $input->getOption('count');
- $em = $this->managerRegistry->getManagerForClass(UserLogEntry::class);
$question = new ConfirmationQuestion(sprintf(
'Do you want to purge all entities versions and to keep only the latest %s?',
diff --git a/src/Controller/CustomFormController.php b/src/Controller/CustomFormController.php
index 179d96cf..f878a43d 100644
--- a/src/Controller/CustomFormController.php
+++ b/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;
@@ -22,7 +21,6 @@
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
@@ -47,7 +45,7 @@ public function __construct(
) {
}
- protected function validateCustomForm(?CustomForm $customForm): void
+ private function validateCustomForm(?CustomForm $customForm): void
{
if (null === $customForm) {
throw new NotFoundHttpException('Custom form not found');
@@ -57,11 +55,6 @@ protected 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 */
@@ -80,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
{
@@ -115,6 +105,7 @@ public function postAction(Request $request, int $id): Response
if ($mixed instanceof Response) {
$mixed->prepare($request);
+
return $mixed;
}
@@ -122,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,
@@ -137,14 +129,11 @@ 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
{
- /** @var CustomForm $customForm */
+ /** @var CustomForm|null $customForm */
$customForm = $this->registry->getRepository(CustomForm::class)->find($customFormId);
$this->validateCustomForm($customForm);
@@ -154,7 +143,7 @@ public function addAction(Request $request, int $customFormId): Response
new RedirectResponse(
$this->generateUrl(
'customFormSentAction',
- ["customFormId" => $customFormId]
+ ['customFormId' => $customFormId]
)
)
);
@@ -166,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 = [];
@@ -179,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);
}
@@ -191,30 +176,24 @@ 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 boolean $forceExpanded
- * @param string|null $emailSender
- * @param bool $prefix
* @return array|Response
+ *
* @throws FilesystemException
*/
- public function prepareAndHandleCustomFormAssignation(
+ private function prepareAndHandleCustomFormAssignation(
Request $request,
CustomForm $customFormsEntity,
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'),
- 'mainColor' => $this->settingsBag->get('main_color'),
- ]
+ ],
];
$helper = $this->customFormHelperFactory->createHelper($customFormsEntity);
$form = $helper->getForm(
@@ -258,13 +237,6 @@ public function prepareAndHandleCustomFormAssignation(
['%name%' => $customFormsEntity->getDisplayName()]
);
- if (!$request->attributes->getBoolean('_stateless') && $request->hasPreviousSession()) {
- $session = $request->getSession();
- if ($session instanceof Session) {
- $session->getFlashBag()->add('confirm', $msg);
- }
- }
-
$this->logger->info($msg);
return $response;
@@ -275,6 +247,7 @@ public function prepareAndHandleCustomFormAssignation(
$assignation['form'] = $form->createView();
$assignation['formObject'] = $form;
+
return $assignation;
}
}
diff --git a/src/Controller/DefaultNodeSourceController.php b/src/Controller/DefaultNodeSourceController.php
index 541668b2..007ae0ad 100644
--- a/src/Controller/DefaultNodeSourceController.php
+++ b/src/Controller/DefaultNodeSourceController.php
@@ -8,12 +8,12 @@
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
-class DefaultNodeSourceController extends AbstractController
+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/src/Controller/HealthCheckController.php b/src/Controller/HealthCheckController.php
index 952f17f1..1129a866 100644
--- a/src/Controller/HealthCheckController.php
+++ b/src/Controller/HealthCheckController.php
@@ -9,21 +9,21 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
-final class HealthCheckController
+final readonly class HealthCheckController
{
public function __construct(
- private readonly ?string $healthCheckToken,
- private readonly ?string $appVersion,
- private readonly ?string $cmsVersion,
- private readonly ?string $cmsVersionPrefix
+ private ?string $healthCheckToken,
+ private ?string $appVersion,
+ private ?string $cmsVersion,
+ private ?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/src/Controller/RedirectionController.php b/src/Controller/RedirectionController.php
index 6ede96a6..7d2d2cc3 100644
--- a/src/Controller/RedirectionController.php
+++ b/src/Controller/RedirectionController.php
@@ -12,9 +12,9 @@
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
-final class RedirectionController
+final readonly class RedirectionController
{
- public function __construct(private readonly UrlGeneratorInterface $urlGenerator)
+ public function __construct(private UrlGeneratorInterface $urlGenerator)
{
}
@@ -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
+ bool|array $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/src/CustomForm/CustomFormAnswerSerializer.php b/src/CustomForm/CustomFormAnswerSerializer.php
index cdf08b8e..6456ab6d 100644
--- a/src/CustomForm/CustomFormAnswerSerializer.php
+++ b/src/CustomForm/CustomFormAnswerSerializer.php
@@ -9,17 +9,20 @@
use RZ\Roadiz\CoreBundle\Entity\Document;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
-class CustomFormAnswerSerializer
+final readonly class CustomFormAnswerSerializer
{
- public function __construct(protected readonly UrlGeneratorInterface $urlGenerator)
+ public function __construct(private UrlGeneratorInterface $urlGenerator)
{
}
+ /**
+ * @throws \Exception
+ */
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) {
@@ -27,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/src/CustomForm/CustomFormHelper.php b/src/CustomForm/CustomFormHelper.php
index 1a2dcb27..9c84c496 100644
--- a/src/CustomForm/CustomFormHelper.php
+++ b/src/CustomForm/CustomFormHelper.php
@@ -6,7 +6,6 @@
use Doctrine\Persistence\ObjectManager;
use League\Flysystem\FilesystemException;
-use RZ\Roadiz\CoreBundle\Bag\Settings;
use RZ\Roadiz\CoreBundle\Entity\CustomForm;
use RZ\Roadiz\CoreBundle\Entity\CustomFormAnswer;
use RZ\Roadiz\CoreBundle\Entity\CustomFormField;
@@ -26,30 +25,23 @@
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
#[Exclude]
-class CustomFormHelper
+final class CustomFormHelper
{
public const ARRAY_SEPARATOR = ', ';
public function __construct(
- protected readonly ObjectManager $em,
- protected readonly CustomForm $customForm,
- protected readonly AbstractDocumentFactory $documentFactory,
- protected readonly FormFactoryInterface $formFactory,
- protected readonly Settings $settingsBag,
- protected readonly EventDispatcherInterface $eventDispatcher
+ private readonly ObjectManager $em,
+ private readonly CustomForm $customForm,
+ private readonly AbstractDocumentFactory $documentFactory,
+ private readonly FormFactoryInterface $formFactory,
+ 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) {
@@ -57,6 +49,7 @@ public function getForm(
} else {
$name = '';
}
+
return $this->formFactory->createNamed($name, CustomFormsType::class, $defaults, [
'customForm' => $this->customForm,
'forceExpanded' => $forceExpanded,
@@ -67,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.');
@@ -105,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())) {
@@ -159,22 +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;
}
@@ -182,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)
);
}
@@ -196,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/src/CustomForm/CustomFormHelperFactory.php b/src/CustomForm/CustomFormHelperFactory.php
index a04deb5e..6a947f7f 100644
--- a/src/CustomForm/CustomFormHelperFactory.php
+++ b/src/CustomForm/CustomFormHelperFactory.php
@@ -5,20 +5,18 @@
namespace RZ\Roadiz\CoreBundle\CustomForm;
use Doctrine\Persistence\ObjectManager;
-use RZ\Roadiz\CoreBundle\Bag\Settings;
use RZ\Roadiz\CoreBundle\Document\PrivateDocumentFactory;
use RZ\Roadiz\CoreBundle\Entity\CustomForm;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
-final class CustomFormHelperFactory
+final readonly class CustomFormHelperFactory
{
public function __construct(
- private readonly PrivateDocumentFactory $privateDocumentFactory,
- private readonly ObjectManager $em,
- private readonly FormFactoryInterface $formFactory,
- private readonly Settings $settingsBag,
- private readonly EventDispatcherInterface $eventDispatcher
+ private PrivateDocumentFactory $privateDocumentFactory,
+ private ObjectManager $em,
+ private FormFactoryInterface $formFactory,
+ private EventDispatcherInterface $eventDispatcher,
) {
}
@@ -29,7 +27,6 @@ public function createHelper(CustomForm $customForm): CustomFormHelper
$customForm,
$this->privateDocumentFactory,
$this->formFactory,
- $this->settingsBag,
$this->eventDispatcher
);
}
diff --git a/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php b/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php
index ce56e283..9caec19f 100644
--- a/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php
+++ b/src/CustomForm/Message/CustomFormAnswerNotifyMessage.php
@@ -6,13 +6,13 @@
use RZ\Roadiz\CoreBundle\Message\AsyncMessage;
-final class CustomFormAnswerNotifyMessage implements AsyncMessage
+final readonly class CustomFormAnswerNotifyMessage implements AsyncMessage
{
public function __construct(
- private readonly int $customFormAnswerId,
- private readonly string $title,
- private readonly string $senderAddress,
- private readonly string $locale
+ private int $customFormAnswerId,
+ private string $title,
+ private string $senderAddress,
+ private string $locale,
) {
}
diff --git a/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php b/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php
index 5e8d9a1c..7a72f1df 100644
--- a/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php
+++ b/src/CustomForm/Message/Handler/CustomFormAnswerNotifyMessageHandler.php
@@ -14,21 +14,22 @@
use RZ\Roadiz\CoreBundle\Mailer\EmailManagerFactory;
use RZ\Roadiz\Documents\Models\DocumentInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
+use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
-use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Mime\Address;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
-final class CustomFormAnswerNotifyMessageHandler implements MessageHandlerInterface
+#[AsMessageHandler]
+final readonly class CustomFormAnswerNotifyMessageHandler
{
public function __construct(
- private readonly ManagerRegistry $managerRegistry,
- private readonly EmailManagerFactory $emailManagerFactory,
- private readonly Settings $settingsBag,
- private readonly FilesystemOperator $documentsStorage,
- private readonly LoggerInterface $messengerLogger,
+ private ManagerRegistry $managerRegistry,
+ private EmailManagerFactory $emailManagerFactory,
+ private Settings $settingsBag,
+ private FilesystemOperator $documentsStorage,
+ private LoggerInterface $messengerLogger,
) {
}
@@ -43,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,
@@ -71,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);
@@ -79,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
@@ -88,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';
@@ -120,7 +120,7 @@ private function sendAnswer(
}
} catch (FilesystemException $exception) {
$this->messengerLogger->error($exception->getMessage(), [
- 'entity' => $answer
+ 'entity' => $answer,
]);
}
diff --git a/src/DataCollector/RequestDataCollector.php b/src/DataCollector/RequestDataCollector.php
index 38ed74f9..28a170f5 100644
--- a/src/DataCollector/RequestDataCollector.php
+++ b/src/DataCollector/RequestDataCollector.php
@@ -5,47 +5,41 @@
namespace RZ\Roadiz\CoreBundle\DataCollector;
use Symfony\Bundle\FrameworkBundle\DataCollector\AbstractDataCollector;
+use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
+use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
+#[AutoconfigureTag('data_collector', [
+ 'template' => '@RoadizCore/DataCollector/request.html.twig',
+ // must match the value returned by the getName() method
+ 'id' => 'roadiz.data_collector.request',
+ 'priority' => 400,
+])]
final class RequestDataCollector extends AbstractDataCollector
{
public function __construct(
+ #[Autowire('%roadiz_core.cms_version%')]
private readonly string $cmsVersion,
- private readonly string $cmsVersionPrefix
+ #[Autowire('%roadiz_core.cms_version_prefix%')]
+ 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(' - ', array_filter([$this->cmsVersionPrefix, $this->cmsVersion])),
+ 'version' => implode(' - ', [$this->cmsVersionPrefix, $this->cmsVersion]),
];
}
public function getVersion(): string
{
- return $this->data['version'];
+ return $this->data['version'] ?? '';
}
- public static function getTemplate(): ?string
- {
- return '@RoadizCore/DataCollector/request.html.twig';
- }
-
- /**
- * {@inheritdoc}
- */
public function getName(): string
{
return 'roadiz.data_collector.request';
}
-
- public function reset(): void
- {
- $this->data = [];
- }
}
diff --git a/src/SearchEngine/SolariumLogger.php b/src/DataCollector/SolariumLogger.php
similarity index 88%
rename from src/SearchEngine/SolariumLogger.php
rename to src/DataCollector/SolariumLogger.php
index fb0f7e19..555396e7 100644
--- a/src/SearchEngine/SolariumLogger.php
+++ b/src/DataCollector/SolariumLogger.php
@@ -2,7 +2,7 @@
declare(strict_types=1);
-namespace RZ\Roadiz\CoreBundle\SearchEngine;
+namespace RZ\Roadiz\CoreBundle\DataCollector;
use Psr\Log\LoggerInterface;
use Solarium\Core\Client\Endpoint as SolariumEndpoint;
@@ -13,6 +13,7 @@
use Solarium\Core\Event\PreExecuteRequest as SolariumPreExecuteRequestEvent;
use Solarium\Core\Plugin\AbstractPlugin as SolariumPlugin;
use Symfony\Bundle\FrameworkBundle\DataCollector\TemplateAwareDataCollectorInterface;
+use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
@@ -22,6 +23,14 @@
/**
* @see https://github.com/nelmio/NelmioSolariumBundle
*/
+#[AutoconfigureTag('data_collector', [
+ 'template' => '@RoadizCore/DataCollector/solarium.html.twig',
+ // must match the value returned by the getName() method
+ 'id' => 'solarium',
+])]
+#[AutoconfigureTag('monolog.logger', [
+ 'channel' => 'solr',
+])]
final class SolariumLogger extends SolariumPlugin implements DataCollectorInterface, \Serializable, EventSubscriberInterface, TemplateAwareDataCollectorInterface
{
private array $data = [];
@@ -32,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();
}
@@ -49,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();
@@ -69,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
@@ -105,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/src/DependencyInjection/Compiler/CommonMarkCompilerPass.php b/src/DependencyInjection/Compiler/CommonMarkCompilerPass.php
index fc540e8c..7c24a3d2 100644
--- a/src/DependencyInjection/Compiler/CommonMarkCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php b/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php
index 4a4a5a29..7609a4ee 100644
--- a/src/DependencyInjection/Compiler/DoctrineMigrationCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/DocumentRendererCompilerPass.php b/src/DependencyInjection/Compiler/DocumentRendererCompilerPass.php
index 80542056..ecf0ac81 100644
--- a/src/DependencyInjection/Compiler/DocumentRendererCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/FlysystemStorageCompilerPass.php b/src/DependencyInjection/Compiler/FlysystemStorageCompilerPass.php
index b4f53aae..7e833e8f 100644
--- a/src/DependencyInjection/Compiler/FlysystemStorageCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/ImporterCompilerPass.php b/src/DependencyInjection/Compiler/ImporterCompilerPass.php
index b2de17cc..08fed012 100644
--- a/src/DependencyInjection/Compiler/ImporterCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/MediaFinderCompilerPass.php b/src/DependencyInjection/Compiler/MediaFinderCompilerPass.php
index ee69f857..38344fb6 100644
--- a/src/DependencyInjection/Compiler/MediaFinderCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/NodeWorkflowCompilerPass.php b/src/DependencyInjection/Compiler/NodeWorkflowCompilerPass.php
index e2216544..1053e6ca 100644
--- a/src/DependencyInjection/Compiler/NodeWorkflowCompilerPass.php
+++ b/src/DependencyInjection/Compiler/NodeWorkflowCompilerPass.php
@@ -4,7 +4,7 @@
namespace RZ\Roadiz\CoreBundle\DependencyInjection\Compiler;
-use RZ\Roadiz\CoreBundle\Entity\Node;
+use RZ\Roadiz\Core\AbstractEntities\NodeInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
@@ -23,7 +23,7 @@ public function process(ContainerBuilder $container): void
$workflowId = 'state_machine.node';
$registryDefinition = $container->getDefinition('workflow.registry');
- $strategyDefinition = new Definition(InstanceOfSupportStrategy::class, [Node::class]);
+ $strategyDefinition = new Definition(InstanceOfSupportStrategy::class, [NodeInterface::class]);
$strategyDefinition->setPublic(false);
$registryDefinition->addMethodCall('addWorkflow', [new Reference($workflowId), $strategyDefinition]);
}
diff --git a/src/DependencyInjection/Compiler/NodesSourcesEntitiesPathCompilerPass.php b/src/DependencyInjection/Compiler/NodesSourcesEntitiesPathCompilerPass.php
index 037afe46..849facef 100644
--- a/src/DependencyInjection/Compiler/NodesSourcesEntitiesPathCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/PathResolverCompilerPass.php b/src/DependencyInjection/Compiler/PathResolverCompilerPass.php
index aff479f2..d94474cd 100644
--- a/src/DependencyInjection/Compiler/PathResolverCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/RateLimitersCompilerPass.php b/src/DependencyInjection/Compiler/RateLimitersCompilerPass.php
index d619971c..bdd67acb 100644
--- a/src/DependencyInjection/Compiler/RateLimitersCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/TreeWalkerDefinitionFactoryCompilerPass.php b/src/DependencyInjection/Compiler/TreeWalkerDefinitionFactoryCompilerPass.php
index b8c0d188..1a142ee7 100644
--- a/src/DependencyInjection/Compiler/TreeWalkerDefinitionFactoryCompilerPass.php
+++ b/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/src/DependencyInjection/Compiler/TwigLoaderCompilerPass.php b/src/DependencyInjection/Compiler/TwigLoaderCompilerPass.php
index a59480e1..ab0b250f 100644
--- a/src/DependencyInjection/Compiler/TwigLoaderCompilerPass.php
+++ b/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/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php
index 7f5e8948..1cbf4f65 100644
--- a/src/DependencyInjection/Configuration.php
+++ b/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/src/DependencyInjection/RoadizCoreExtension.php b/src/DependencyInjection/RoadizCoreExtension.php
index dce12f58..de82ceec 100644
--- a/src/DependencyInjection/RoadizCoreExtension.php
+++ b/src/DependencyInjection/RoadizCoreExtension.php
@@ -9,6 +9,7 @@
use RZ\Roadiz\CoreBundle\Cache\CloudflareProxyCache;
use RZ\Roadiz\CoreBundle\Cache\ReverseProxyCache;
use RZ\Roadiz\CoreBundle\Cache\ReverseProxyCacheLocator;
+use RZ\Roadiz\CoreBundle\DataCollector\SolariumLogger;
use RZ\Roadiz\CoreBundle\Entity\CustomForm;
use RZ\Roadiz\CoreBundle\Entity\Document;
use RZ\Roadiz\CoreBundle\Entity\Node;
@@ -18,10 +19,9 @@
use RZ\Roadiz\CoreBundle\Entity\NodeType;
use RZ\Roadiz\CoreBundle\Entity\Translation;
use RZ\Roadiz\CoreBundle\Repository\NodesSourcesRepository;
-use RZ\Roadiz\CoreBundle\SearchEngine\SolariumLogger;
-use RZ\Roadiz\CoreBundle\Webhook\Message\GenericJsonPostMessage;
-use RZ\Roadiz\CoreBundle\Webhook\Message\GitlabPipelineTriggerMessage;
-use RZ\Roadiz\CoreBundle\Webhook\Message\NetlifyBuildHookMessage;
+use RZ\Roadiz\CoreBundle\Webhook\Message\GenericJsonPostMessageInterface;
+use RZ\Roadiz\CoreBundle\Webhook\Message\GitlabPipelineTriggerMessageInterface;
+use RZ\Roadiz\CoreBundle\Webhook\Message\NetlifyBuildHookMessageInterface;
use RZ\Roadiz\Markdown\CommonMark;
use RZ\Roadiz\Markdown\MarkdownInterface;
use Solarium\Core\Client\Adapter\Curl;
@@ -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
@@ -116,9 +113,9 @@ public function load(array $configs, ContainerBuilder $container): void
$container->setParameter('roadiz_core.medias.supported_platforms', []);
$container->setParameter('roadiz_core.webhook.message_types', [
- 'webhook.type.generic_json_post' => GenericJsonPostMessage::class,
- 'webhook.type.gitlab_pipeline' => GitlabPipelineTriggerMessage::class,
- 'webhook.type.netlify_build_hook' => NetlifyBuildHookMessage::class,
+ 'webhook.type.generic_json_post' => GenericJsonPostMessageInterface::class,
+ 'webhook.type.gitlab_pipeline' => GitlabPipelineTriggerMessageInterface::class,
+ 'webhook.type.netlify_build_hook' => NetlifyBuildHookMessageInterface::class,
]);
$this->registerEntityGenerator($config, $container);
@@ -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/src/Doctrine/Event/FilterNodesSourcesQueryBuilderCriteriaEvent.php b/src/Doctrine/Event/FilterNodesSourcesQueryBuilderCriteriaEvent.php
index ee8da9b0..5337a9d1 100644
--- a/src/Doctrine/Event/FilterNodesSourcesQueryBuilderCriteriaEvent.php
+++ b/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/src/Doctrine/Event/FilterQueryBuilderCriteriaEvent.php b/src/Doctrine/Event/FilterQueryBuilderCriteriaEvent.php
index 974ff248..3e056d90 100644
--- a/src/Doctrine/Event/FilterQueryBuilderCriteriaEvent.php
+++ b/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/src/Doctrine/Event/FilterQueryBuilderEvent.php b/src/Doctrine/Event/FilterQueryBuilderEvent.php
index 202811ca..a3aa4c20 100644
--- a/src/Doctrine/Event/FilterQueryBuilderEvent.php
+++ b/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/src/Doctrine/Event/FilterQueryCriteriaEvent.php b/src/Doctrine/Event/FilterQueryCriteriaEvent.php
index baa4f5c5..23b761e4 100644
--- a/src/Doctrine/Event/FilterQueryCriteriaEvent.php
+++ b/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/src/Doctrine/Event/QueryEvent.php b/src/Doctrine/Event/QueryEvent.php
index dc85f161..ce966683 100644
--- a/src/Doctrine/Event/QueryEvent.php
+++ b/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/src/Doctrine/Event/QueryNodesSourcesEvent.php b/src/Doctrine/Event/QueryNodesSourcesEvent.php
index 07999c22..8ec8187f 100644
--- a/src/Doctrine/Event/QueryNodesSourcesEvent.php
+++ b/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/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php b/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php
index 4e7ada54..96c1fdd2 100644
--- a/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php
+++ b/src/Doctrine/EventSubscriber/AttributeValueLifeCycleSubscriber.php
@@ -4,37 +4,23 @@
namespace RZ\Roadiz\CoreBundle\Doctrine\EventSubscriber;
-use ArrayIterator;
-use Doctrine\Common\EventSubscriber;
-use Doctrine\Persistence\Event\LifecycleEventArgs;
+use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
-use Doctrine\ORM\Events;
-use RZ\Roadiz\CoreBundle\Model\AttributeValueInterface;
+use Doctrine\Persistence\Event\LifecycleEventArgs;
use RZ\Roadiz\CoreBundle\Entity\AttributeValue;
+use RZ\Roadiz\CoreBundle\Model\AttributeValueInterface;
-final class AttributeValueLifeCycleSubscriber implements EventSubscriber
+#[AsDoctrineListener('prePersist')]
+#[AsDoctrineListener('onFlush')]
+final class AttributeValueLifeCycleSubscriber
{
- /**
- * {@inheritdoc}
- */
- public function getSubscribedEvents(): array
- {
- return [
- Events::prePersist,
- Events::onFlush,
- ];
- }
-
- /**
- * @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());
}
@@ -42,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
*/
@@ -50,7 +36,7 @@ public function prePersist(LifecycleEventArgs $event): void
$lastPosition = 1;
foreach ($nodeAttributes as $nodeAttribute) {
$nodeAttribute->setPosition($lastPosition);
- $lastPosition++;
+ ++$lastPosition;
}
$entity->setPosition($lastPosition);
@@ -59,8 +45,6 @@ public function prePersist(LifecycleEventArgs $event): void
}
/**
- * @param OnFlushEventArgs $eventArgs
- *
* @throws \Exception
*/
public function onFlush(OnFlushEventArgs $eventArgs): void
@@ -72,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;
@@ -90,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/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php b/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php
index 37b42b22..15c56304 100644
--- a/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php
+++ b/src/Doctrine/EventSubscriber/CustomFormFieldLifeCycleSubscriber.php
@@ -4,31 +4,18 @@
namespace RZ\Roadiz\CoreBundle\Doctrine\EventSubscriber;
-use Doctrine\Common\EventSubscriber;
+use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\Persistence\Event\LifecycleEventArgs;
-use Doctrine\ORM\Events;
use RZ\Roadiz\CoreBundle\Entity\CustomFormField;
use RZ\Roadiz\CoreBundle\EntityHandler\CustomFormFieldHandler;
-final class CustomFormFieldLifeCycleSubscriber implements EventSubscriber
+#[AsDoctrineListener('prePersist')]
+final class CustomFormFieldLifeCycleSubscriber
{
public function __construct(private readonly CustomFormFieldHandler $customFormFieldHandler)
{
}
- /**
- * {@inheritdoc}
- */
- public function getSubscribedEvents(): array
- {
- return [
- Events::prePersist,
- ];
- }
-
- /**
- * @param LifecycleEventArgs $event
- */
public function prePersist(LifecycleEventArgs $event): void
{
$field = $event->getObject();
@@ -36,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/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php b/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php
index 0f1b7c4b..d5256b85 100644
--- a/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php
+++ b/src/Doctrine/EventSubscriber/NodesSourcesInheritanceSubscriber.php
@@ -4,9 +4,9 @@
namespace RZ\Roadiz\CoreBundle\Doctrine\EventSubscriber;
-use Doctrine\Common\EventSubscriber;
-use Doctrine\Persistence\Event\LifecycleEventArgs;
+use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
+use Doctrine\ORM\Event\PostLoadEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Psr\Log\LoggerInterface;
@@ -15,38 +15,29 @@
use RZ\Roadiz\CoreBundle\DependencyInjection\Configuration;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
use RZ\Roadiz\CoreBundle\Entity\NodeType;
+use Symfony\Component\Stopwatch\Stopwatch;
-final class NodesSourcesInheritanceSubscriber implements EventSubscriber
+#[AsDoctrineListener(event: Events::postLoad)]
+#[AsDoctrineListener(event: Events::loadClassMetadata)]
+final class NodesSourcesInheritanceSubscriber
{
public function __construct(
private readonly NodeTypes $nodeTypes,
private readonly string $inheritanceType,
- private readonly LoggerInterface $logger
+ private readonly LoggerInterface $logger,
+ private readonly Stopwatch $stopwatch,
) {
}
- /**
- * @inheritDoc
- */
- public function getSubscribedEvents(): array
- {
- return [
- Events::loadClassMetadata,
- Events::postLoad
- ];
- }
-
- public function postLoad(LifecycleEventArgs $event): void
+ public function postLoad(PostLoadEventArgs $event): void
{
$object = $event->getObject();
- if ($object instanceof NodesSources) {
- $object->injectObjectManager($event->getObjectManager());
+ if (!$object instanceof NodesSources) {
+ return;
}
+ $object->injectObjectManager($event->getObjectManager());
}
- /**
- * @param LoadClassMetadataEventArgs $eventArgs
- */
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
{
// the $metadata is all the mapping info for this class
@@ -55,7 +46,8 @@ 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 */
$nodeTypes = $this->nodeTypes->all();
@@ -82,6 +74,7 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
['columns' => ['discr']],
['columns' => ['title']],
['columns' => ['published_at']],
+ 'ns_no_index' => ['columns' => ['no_index']],
'ns_node_translation_published' => ['columns' => ['node_id', 'translation_id', 'published_at']],
'ns_node_discr_translation' => ['columns' => ['node_id', 'discr', 'translation_id']],
'ns_node_discr_translation_published' => ['columns' => ['node_id', 'discr', 'translation_id', 'published_at']],
@@ -92,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
@@ -109,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) {
@@ -124,6 +117,8 @@ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
* Need Install
*/
}
+
+ $this->stopwatch->stop('NodesSources loadClassMetadata');
}
}
}
diff --git a/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php b/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php
index 0e3b98f8..80d085fa 100644
--- a/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php
+++ b/src/Doctrine/EventSubscriber/UserLifeCycleSubscriber.php
@@ -4,10 +4,10 @@
namespace RZ\Roadiz\CoreBundle\Doctrine\EventSubscriber;
-use Doctrine\Common\EventSubscriber;
-use Doctrine\Persistence\Event\LifecycleEventArgs;
+use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
+use Doctrine\Persistence\Event\LifecycleEventArgs;
use Psr\Log\LoggerInterface;
use RZ\Roadiz\CoreBundle\Entity\User;
use RZ\Roadiz\CoreBundle\Event\User\UserCreatedEvent;
@@ -22,51 +22,38 @@
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
-final class UserLifeCycleSubscriber implements EventSubscriber
+#[AsDoctrineListener(event: Events::preUpdate)]
+#[AsDoctrineListener(event: Events::prePersist)]
+#[AsDoctrineListener(event: Events::postPersist)]
+#[AsDoctrineListener(event: Events::postUpdate)]
+#[AsDoctrineListener(event: Events::postRemove)]
+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,
) {
}
- /**
- * {@inheritdoc}
- */
- public function getSubscribedEvents(): array
- {
- return [
- Events::preUpdate,
- Events::prePersist,
- Events::postPersist,
- Events::postUpdate,
- Events::postRemove,
- ];
- }
-
- /**
- * @param PreUpdateEventArgs $event
- * @return void
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
public function preUpdate(PreUpdateEventArgs $event): void
{
- $user = $event->getEntity();
+ $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);
@@ -75,8 +62,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('');
@@ -92,9 +78,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);
@@ -103,10 +89,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) {
@@ -116,9 +98,6 @@ protected function setPassword(User $user, ?string $plainPassword): void
}
}
- /**
- * @param LifecycleEventArgs $event
- */
public function postUpdate(LifecycleEventArgs $event): void
{
$user = $event->getObject();
@@ -128,9 +107,6 @@ public function postUpdate(LifecycleEventArgs $event): void
}
}
- /**
- * @param LifecycleEventArgs $event
- */
public function postRemove(LifecycleEventArgs $event): void
{
$user = $event->getObject();
@@ -141,8 +117,6 @@ public function postRemove(LifecycleEventArgs $event): void
}
/**
- * @param LifecycleEventArgs $event
- *
* @throws \Exception
*/
public function postPersist(LifecycleEventArgs $event): void
@@ -155,7 +129,6 @@ public function postPersist(LifecycleEventArgs $event): void
}
/**
- * @param LifecycleEventArgs $event
* @throws \Throwable
*/
public function prePersist(LifecycleEventArgs $event): void
@@ -163,9 +136,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/src/Doctrine/ORM/Filter/ANodesFilter.php b/src/Doctrine/ORM/Filter/ANodesFilter.php
index ebfcb49e..5e654e85 100644
--- a/src/Doctrine/ORM/Filter/ANodesFilter.php
+++ b/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/src/Doctrine/ORM/Filter/BNodesFilter.php b/src/Doctrine/ORM/Filter/BNodesFilter.php
index 8cb6f894..4b15cb47 100644
--- a/src/Doctrine/ORM/Filter/BNodesFilter.php
+++ b/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/src/Doctrine/ORM/Filter/NodeTranslationFilter.php b/src/Doctrine/ORM/Filter/NodeTranslationFilter.php
index 5f86e660..d7d22312 100644
--- a/src/Doctrine/ORM/Filter/NodeTranslationFilter.php
+++ b/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/src/Doctrine/ORM/Filter/NodeTypeFilter.php b/src/Doctrine/ORM/Filter/NodeTypeFilter.php
index 561797e7..3da315da 100644
--- a/src/Doctrine/ORM/Filter/NodeTypeFilter.php
+++ b/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/src/Doctrine/ORM/Filter/NodesSourcesNodeFilter.php b/src/Doctrine/ORM/Filter/NodesSourcesNodeFilter.php
index 3a4f3310..18ffc69f 100644
--- a/src/Doctrine/ORM/Filter/NodesSourcesNodeFilter.php
+++ b/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/src/Doctrine/ORM/Filter/NodesSourcesNodeTypeFilter.php b/src/Doctrine/ORM/Filter/NodesSourcesNodeTypeFilter.php
index 62d943e5..974709ff 100644
--- a/src/Doctrine/ORM/Filter/NodesSourcesNodeTypeFilter.php
+++ b/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/src/Doctrine/ORM/Filter/NodesSourcesReachableFilter.php b/src/Doctrine/ORM/Filter/NodesSourcesReachableFilter.php
index 6f524f5c..9a038091 100644
--- a/src/Doctrine/ORM/Filter/NodesSourcesReachableFilter.php
+++ b/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/src/Doctrine/ORM/SimpleQueryBuilder.php b/src/Doctrine/ORM/SimpleQueryBuilder.php
index 90c7713b..38d54ce4 100644
--- a/src/Doctrine/ORM/SimpleQueryBuilder.php
+++ b/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/src/Doctrine/SchemaUpdater.php b/src/Doctrine/SchemaUpdater.php
index bd1ccdeb..e00257f1 100644
--- a/src/Doctrine/SchemaUpdater.php
+++ b/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/src/Document/DocumentFactory.php b/src/Document/DocumentFactory.php
index 91f6f612..7ff20cb1 100644
--- a/src/Document/DocumentFactory.php
+++ b/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/src/Document/DocumentFinder.php b/src/Document/DocumentFinder.php
index 7de00596..cb542b1d 100644
--- a/src/Document/DocumentFinder.php
+++ b/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/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php b/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php
index cf6a6844..217e0eb4 100644
--- a/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php
+++ b/src/Document/EventSubscriber/DocumentMessageDispatchSubscriber.php
@@ -20,21 +20,18 @@
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
-final class DocumentMessageDispatchSubscriber implements EventSubscriberInterface
+final readonly class DocumentMessageDispatchSubscriber implements EventSubscriberInterface
{
- public function __construct(private readonly MessageBusInterface $bus)
+ public function __construct(private 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/src/Document/MediaFinder/DailymotionEmbedFinder.php b/src/Document/MediaFinder/DailymotionEmbedFinder.php
index 71385a08..c322ded7 100644
--- a/src/Document/MediaFinder/DailymotionEmbedFinder.php
+++ b/src/Document/MediaFinder/DailymotionEmbedFinder.php
@@ -6,9 +6,6 @@
use RZ\Roadiz\Documents\MediaFinders\AbstractDailymotionEmbedFinder;
-/**
- * Dailymotion tools class.
- */
class DailymotionEmbedFinder extends AbstractDailymotionEmbedFinder
{
use EmbedFinderTrait;
diff --git a/src/Document/MediaFinder/EmbedFinderTrait.php b/src/Document/MediaFinder/EmbedFinderTrait.php
index 66dfee7b..07d2e011 100644
--- a/src/Document/MediaFinder/EmbedFinderTrait.php
+++ b/src/Document/MediaFinder/EmbedFinderTrait.php
@@ -5,19 +5,16 @@
namespace RZ\Roadiz\CoreBundle\Document\MediaFinder;
use Doctrine\Persistence\ObjectManager;
-use GuzzleHttp\Exception\ClientException;
use RZ\Roadiz\CoreBundle\Entity\Document;
use RZ\Roadiz\CoreBundle\Entity\DocumentTranslation;
use RZ\Roadiz\CoreBundle\Entity\Translation;
use RZ\Roadiz\Documents\Exceptions\APINeedsAuthentificationException;
use RZ\Roadiz\Documents\Models\DocumentInterface;
+use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
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();
@@ -56,9 +50,9 @@ 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 credentials are not provided.
+ } catch (ClientExceptionInterface $exception) {
+ // do not prevent from creating document if platform has errors, such as
// too much API usage.
}
diff --git a/src/Document/MediaFinder/PodcastFinder.php b/src/Document/MediaFinder/PodcastFinder.php
index bc10601d..384373bb 100644
--- a/src/Document/MediaFinder/PodcastFinder.php
+++ b/src/Document/MediaFinder/PodcastFinder.php
@@ -5,11 +5,11 @@
namespace RZ\Roadiz\CoreBundle\Document\MediaFinder;
use Doctrine\Persistence\ObjectManager;
-use GuzzleHttp\Exception\ClientException;
use RZ\Roadiz\CoreBundle\Entity\DocumentTranslation;
use RZ\Roadiz\CoreBundle\Entity\Translation;
use RZ\Roadiz\Documents\MediaFinders\AbstractPodcastFinder;
use RZ\Roadiz\Documents\Models\DocumentInterface;
+use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
class PodcastFinder extends AbstractPodcastFinder
{
@@ -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();
@@ -33,8 +33,8 @@ protected function injectMetaFromPodcastItem(
$documentTr->setCopyright($this->getPodcastItemCopyright($item));
$objectManager->persist($documentTr);
}
- } catch (ClientException $exception) {
- // do no prevent from creating document if platform has errors, such as
+ } catch (ClientExceptionInterface $exception) {
+ // do not prevent from creating document if platform has errors, such as
// too much API usage.
}
}
diff --git a/src/Document/MediaFinder/SoundcloudEmbedFinder.php b/src/Document/MediaFinder/SoundcloudEmbedFinder.php
index 30daf162..ef7b3330 100644
--- a/src/Document/MediaFinder/SoundcloudEmbedFinder.php
+++ b/src/Document/MediaFinder/SoundcloudEmbedFinder.php
@@ -6,9 +6,6 @@
use RZ\Roadiz\Documents\MediaFinders\AbstractSoundcloudEmbedFinder;
-/**
- * Soundcloud tools class.
- */
class SoundcloudEmbedFinder extends AbstractSoundcloudEmbedFinder
{
use EmbedFinderTrait;
diff --git a/src/Document/MediaFinder/TwitchEmbedFinder.php b/src/Document/MediaFinder/TwitchEmbedFinder.php
deleted file mode 100644
index de8ef24c..00000000
--- a/src/Document/MediaFinder/TwitchEmbedFinder.php
+++ /dev/null
@@ -1,12 +0,0 @@
-documentId = $documentId;
}
- /**
- * @return int
- */
public function getDocumentId(): int
{
return $this->documentId;
diff --git a/src/Document/MessageHandler/AbstractDocumentMessageHandler.php b/src/Document/MessageHandler/AbstractDocumentMessageHandler.php
index e9747f8b..311b6358 100644
--- a/src/Document/MessageHandler/AbstractDocumentMessageHandler.php
+++ b/src/Document/MessageHandler/AbstractDocumentMessageHandler.php
@@ -10,15 +10,16 @@
use Psr\Log\LoggerInterface;
use RZ\Roadiz\CoreBundle\Document\Message\AbstractDocumentMessage;
use RZ\Roadiz\Documents\Models\DocumentInterface;
+use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\RecoverableMessageHandlingException;
-use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
-abstract class AbstractDocumentMessageHandler implements MessageHandlerInterface
+#[AsMessageHandler]
+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/src/Document/MessageHandler/AbstractLockingDocumentMessageHandler.php b/src/Document/MessageHandler/AbstractLockingDocumentMessageHandler.php
index e15c6139..1a78fba5 100644
--- a/src/Document/MessageHandler/AbstractLockingDocumentMessageHandler.php
+++ b/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/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php b/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php
index 056f2f8b..0b841c53 100644
--- a/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php
+++ b/src/Document/MessageHandler/DocumentAudioVideoMessageHandler.php
@@ -25,6 +25,7 @@
*
* Detect Audio and Video files metadata using https://github.com/JamesHeinrich/getID3 lib
* And extract video thumbnail using local ffmpeg.
+ *
* @see https://github.com/JamesHeinrich/getID3
*/
final class DocumentAudioVideoMessageHandler extends AbstractLockingDocumentMessageHandler
@@ -35,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
@@ -135,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/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php b/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php
index 6c251078..e2e9c8b7 100644
--- a/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php
+++ b/src/Document/MessageHandler/DocumentAverageColorMessageHandler.php
@@ -17,27 +17,20 @@
final class DocumentAverageColorMessageHandler extends AbstractLockingDocumentMessageHandler
{
public function __construct(
+ private readonly ImageManager $imageManager,
ManagerRegistry $managerRegistry,
LoggerInterface $messengerLogger,
FilesystemOperator $documentsStorage,
- private readonly ImageManager $imageManager
) {
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/src/Document/MessageHandler/DocumentExifMessageHandler.php b/src/Document/MessageHandler/DocumentExifMessageHandler.php
index 5983a7b3..94b38602 100644
--- a/src/Document/MessageHandler/DocumentExifMessageHandler.php
+++ b/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/src/Document/MessageHandler/DocumentFilesizeMessageHandler.php b/src/Document/MessageHandler/DocumentFilesizeMessageHandler.php
index 14600d04..5a5a96a5 100644
--- a/src/Document/MessageHandler/DocumentFilesizeMessageHandler.php
+++ b/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/src/Document/MessageHandler/DocumentPdfMessageHandler.php b/src/Document/MessageHandler/DocumentPdfMessageHandler.php
index 2a6453ff..54ade391 100644
--- a/src/Document/MessageHandler/DocumentPdfMessageHandler.php
+++ b/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/src/Document/MessageHandler/DocumentRawMessageHandler.php b/src/Document/MessageHandler/DocumentRawMessageHandler.php
index dc2c1588..fcb658db 100644
--- a/src/Document/MessageHandler/DocumentRawMessageHandler.php
+++ b/src/Document/MessageHandler/DocumentRawMessageHandler.php
@@ -16,16 +16,12 @@ final class DocumentRawMessageHandler extends AbstractLockingDocumentMessageHand
public function __construct(
private readonly DownscaleImageManager $downscaleImageManager,
ManagerRegistry $managerRegistry,
- LoggerInterface $logger,
- FilesystemOperator $documentsStorage
+ LoggerInterface $messengerLogger,
+ FilesystemOperator $documentsStorage,
) {
- parent::__construct($managerRegistry, $logger, $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/src/Document/MessageHandler/DocumentSizeMessageHandler.php b/src/Document/MessageHandler/DocumentSizeMessageHandler.php
index b337463f..ab917f95 100644
--- a/src/Document/MessageHandler/DocumentSizeMessageHandler.php
+++ b/src/Document/MessageHandler/DocumentSizeMessageHandler.php
@@ -16,18 +16,14 @@
final class DocumentSizeMessageHandler extends AbstractLockingDocumentMessageHandler
{
public function __construct(
+ private readonly ImageManager $imageManager,
ManagerRegistry $managerRegistry,
LoggerInterface $messengerLogger,
FilesystemOperator $documentsStorage,
- private readonly ImageManager $imageManager
) {
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/src/Document/MessageHandler/DocumentSvgMessageHandler.php b/src/Document/MessageHandler/DocumentSvgMessageHandler.php
index b833a3d3..240f389c 100644
--- a/src/Document/MessageHandler/DocumentSvgMessageHandler.php
+++ b/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/src/Document/PrivateDocumentFactory.php b/src/Document/PrivateDocumentFactory.php
index 68713ac9..e29f9454 100644
--- a/src/Document/PrivateDocumentFactory.php
+++ b/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/src/Entity/AbstractDateTimedPositioned.php b/src/Entity/AbstractDateTimedPositioned.php
index 9f33830a..5151807a 100644
--- a/src/Entity/AbstractDateTimedPositioned.php
+++ b/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/src/Entity/Attribute.php b/src/Entity/Attribute.php
index 04657460..7edc8776 100644
--- a/src/Entity/Attribute.php
+++ b/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/src/Entity/AttributeDocuments.php b/src/Entity/AttributeDocuments.php
index 596a3947..fad0ebce 100644
--- a/src/Entity/AttributeDocuments.php
+++ b/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/src/Entity/AttributeGroup.php b/src/Entity/AttributeGroup.php
index a0601959..cd56cac5 100644
--- a/src/Entity/AttributeGroup.php
+++ b/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/src/Entity/AttributeGroupTranslation.php b/src/Entity/AttributeGroupTranslation.php
index 502e2ea7..299e70d7 100644
--- a/src/Entity/AttributeGroupTranslation.php
+++ b/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/src/Entity/AttributeTranslation.php b/src/Entity/AttributeTranslation.php
index ef55c991..780ed7fd 100644
--- a/src/Entity/AttributeTranslation.php
+++ b/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/src/Entity/AttributeValue.php b/src/Entity/AttributeValue.php
index f5df8d02..1bc3488d 100644
--- a/src/Entity/AttributeValue.php
+++ b/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/src/Entity/AttributeValueTranslation.php b/src/Entity/AttributeValueTranslation.php
index 83ed9f1d..180144d7 100644
--- a/src/Entity/AttributeValueTranslation.php
+++ b/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/src/Entity/CustomForm.php b/src/Entity/CustomForm.php
index b4f9be4e..6fd474c0 100644
--- a/src/Entity/CustomForm.php
+++ b/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/src/Entity/CustomFormAnswer.php b/src/Entity/CustomFormAnswer.php
index 3199d4d1..0ba86fcb 100644
--- a/src/Entity/CustomFormAnswer.php
+++ b/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/src/Entity/CustomFormField.php b/src/Entity/CustomFormField.php
index b58a6f29..f2048c53 100644
--- a/src/Entity/CustomFormField.php
+++ b/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/src/Entity/CustomFormFieldAttribute.php b/src/Entity/CustomFormFieldAttribute.php
index b8452226..188a0d91 100644
--- a/src/Entity/CustomFormFieldAttribute.php
+++ b/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/src/Entity/Document.php b/src/Entity/Document.php
index e81e5633..aefebf93 100644
--- a/src/Entity/Document.php
+++ b/src/Entity/Document.php
@@ -11,6 +11,7 @@
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
+use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use RZ\Roadiz\Core\AbstractEntities\AbstractDateTimed;
@@ -34,39 +35,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 +124,7 @@ class Document extends AbstractDateTimed implements AdvancedDocumentInterface, H
'right',
'bottom-left',
'bottom',
- 'bottom-right'
+ 'bottom-right',
])]
protected ?string $imageCropAlignment = null;
@@ -140,8 +141,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 +150,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 +172,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 +231,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,27 +257,18 @@ 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])]
+ #[ORM\Column(name: 'imageWidth', type: Types::SMALLINT, nullable: false, options: ['default' => 0])]
#[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])]
#[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])]
#[Serializer\Type('int')]
@@ -291,10 +277,7 @@ 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])]
+ #[ORM\Column(name: 'imageHeight', type: Types::SMALLINT, nullable: false, options: ['default' => 0])]
#[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])]
#[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])]
#[Serializer\Type('int')]
@@ -303,10 +286,7 @@ 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])]
+ #[ORM\Column(name: 'duration', type: Types::INTEGER, nullable: false, options: ['default' => 0])]
#[SymfonySerializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])]
#[Serializer\Groups(['document', 'document_display', 'nodes_sources', 'tag', 'attribute'])]
#[Serializer\Type('int')]
@@ -315,9 +295,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 +306,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 +323,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 +347,6 @@ public function __construct()
$this->thumbnails = new ArrayCollection();
}
- /**
- * @return string|null
- */
public function getMimeType(): ?string
{
return $this->mimeType;
@@ -384,12 +355,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 +367,7 @@ public function getFolder(): string
public function setFolder(string $folder): static
{
$this->folder = $folder;
+
return $this;
}
@@ -422,11 +392,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 +465,6 @@ public function removeFolder(FolderInterface $folder): static
}
/**
- * @param TranslationInterface $translation
* @return Collection
*/
#[SymfonySerializer\Ignore]
@@ -515,7 +485,6 @@ public function getDocumentTranslationsByDefaultTranslation(): ?DocumentTranslat
}
/**
- * @param DocumentTranslation $documentTranslation
* @return $this
*/
public function addDocumentTranslation(DocumentTranslation $documentTranslation): static
@@ -535,9 +504,6 @@ public function getDocumentTranslations(): Collection
return $this->documentTranslations;
}
- /**
- * @return bool
- */
#[SymfonySerializer\Ignore]
public function hasTranslations(): bool
{
@@ -546,8 +512,6 @@ public function hasTranslations(): bool
/**
* Is document a raw one.
- *
- * @return bool
*/
public function isRaw(): bool
{
@@ -557,13 +521,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 +534,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 +556,6 @@ public function setImageWidth(int $imageWidth): static
return $this;
}
- /**
- * @return int
- */
public function getImageHeight(): int
{
return $this->imageHeight;
@@ -613,9 +568,6 @@ public function setImageHeight(int $imageHeight): static
return $this;
}
- /**
- * @return int
- */
public function getMediaDuration(): int
{
return $this->mediaDuration;
@@ -624,12 +576,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 +588,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 +600,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 +619,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 +633,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 +656,6 @@ public function setOriginal(?HasThumbnailInterface $original): static
return $this;
}
- /**
- * @return bool
- */
#[SymfonySerializer\Groups(['document'])]
#[Serializer\Groups(['document'])]
#[Serializer\VirtualProperty]
@@ -723,9 +664,6 @@ public function hasThumbnails(): bool
return $this->getThumbnails()->count() > 0;
}
- /**
- * @return Collection
- */
public function getThumbnails(): Collection
{
// Filter private thumbnails
@@ -755,9 +693,6 @@ public function setThumbnails(Collection $thumbnails): static
return $this;
}
- /**
- * @return DocumentInterface|null
- */
#[SymfonySerializer\Groups(['document_thumbnails'])]
#[SymfonySerializer\SerializedName('thumbnail')]
#[SymfonySerializer\MaxDepth(1)]
@@ -767,20 +702,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 +719,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 +731,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 +743,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 +755,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 +769,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 +787,6 @@ public function setFilename(string $filename): static
return $this;
}
-
public function getEmbedPlatform(): ?string
{
return $this->embedPlatform;
@@ -876,6 +795,7 @@ public function getEmbedPlatform(): ?string
public function setEmbedPlatform(?string $embedPlatform): static
{
$this->embedPlatform = $embedPlatform;
+
return $this;
}
@@ -887,6 +807,7 @@ public function getEmbedId(): ?string
public function setEmbedId(?string $embedId): static
{
$this->embedId = $embedId;
+
return $this;
}
@@ -898,6 +819,7 @@ public function getImageCropAlignment(): ?string
public function setImageCropAlignment(?string $imageCropAlignment): Document
{
$this->imageCropAlignment = $imageCropAlignment;
+
return $this;
}
}
diff --git a/src/Entity/DocumentTranslation.php b/src/Entity/DocumentTranslation.php
index e7ac1609..db4872b3 100644
--- a/src/Entity/DocumentTranslation.php
+++ b/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/src/Entity/FieldAwareEntityTrait.php b/src/Entity/FieldAwareEntityTrait.php
index be0611eb..db01735e 100644
--- a/src/Entity/FieldAwareEntityTrait.php
+++ b/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/src/Entity/Folder.php b/src/Entity/Folder.php
index c583b4e9..f2ff8c59 100644
--- a/src/Entity/Folder.php
+++ b/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')]
@@ -87,11 +84,6 @@ class Folder extends AbstractDateTimedPositioned implements FolderInterface, Lea
/** @phpstan-ignore-next-line */
protected Collection $documents;
- /**
- * @var string
- * @Serializer\Groups({"folder", "folder_color"})
- * @Serializer\Type("string")
- */
#[ORM\Column(
name: 'color',
type: 'string',
@@ -102,9 +94,11 @@ class Folder extends AbstractDateTimedPositioned implements FolderInterface, Lea
)]
#[Assert\Length(max: 7)]
#[SymfonySerializer\Groups(['folder', 'folder_color'])]
+ #[Serializer\Groups(['folder', 'folder_color'])]
+ #[Serializer\Type('string')]
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 +145,6 @@ public function __construct()
}
/**
- * @param DocumentInterface $document
* @return $this
*/
public function addDocument(DocumentInterface $document): static
@@ -172,7 +165,6 @@ public function getDocuments(): Collection
}
/**
- * @param DocumentInterface $document
* @return $this
*/
public function removeDocument(DocumentInterface $document): static
@@ -184,34 +176,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]
@@ -231,12 +216,9 @@ public function getTranslatedFoldersByDefaultTranslation(): ?FolderTranslation
});
}
- /**
- * @return string|null
- * @Serializer\VirtualProperty
- * @Serializer\Groups({"folder", "document_folders"})
- */
#[SymfonySerializer\Groups(['folder', 'document_folders'])]
+ #[Serializer\Groups(['folder', 'document_folders'])]
+ #[Serializer\VirtualProperty]
public function getName(): ?string
{
return $this->getTranslatedFolders()->first() ?
@@ -254,91 +236,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/src/Entity/FolderTranslation.php b/src/Entity/FolderTranslation.php
index 76a78b84..c9bca9c5 100644
--- a/src/Entity/FolderTranslation.php
+++ b/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/src/Entity/Group.php b/src/Entity/Group.php
index 5bb7efd0..741f8a06 100644
--- a/src/Entity/Group.php
+++ b/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
{
@@ -52,12 +52,9 @@ class Group extends AbstractEntity
#[Serializer\Type("ArrayCollection")]
private Collection $roleEntities;
- /**
- * @var array|null
- * @Serializer\Groups({"group", "user"})
- * @Serializer\Type("array")
- */
#[SymfonySerializer\Groups(['group', 'user'])]
+ #[Serializer\Groups(['group', 'user'])]
+ #[Serializer\Type('array')]
private ?array $roles = null;
public function __construct()
@@ -66,17 +63,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 +78,6 @@ public function setName(string $name)
return $this;
}
- /**
- * @return Collection
- */
public function getUsers(): Collection
{
return $this->users;
@@ -101,7 +90,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 +101,6 @@ public function getRoles(): array
/**
* Get roles entities.
- *
- * @return Collection
*/
public function getRolesEntities(): ?Collection
{
@@ -122,10 +109,6 @@ public function getRolesEntities(): ?Collection
/**
* Get roles entities.
- *
- * @param Collection $roles
- *
- * @return Group
*/
public function setRolesEntities(Collection $roles): self
{
@@ -134,12 +117,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 +132,6 @@ public function addRole(Role $role): Group
}
/**
- * @param Role $role
- *
* @return $this
*/
public function addRoleEntity(Role $role): Group
@@ -162,8 +144,8 @@ public function addRoleEntity(Role $role): Group
}
/**
- * @param Role $role
* @return $this
+ *
* @deprecated Use removeRoleEntity
*/
public function removeRole(Role $role): Group
@@ -172,8 +154,6 @@ public function removeRole(Role $role): Group
}
/**
- * @param Role $role
- *
* @return $this
*/
public function removeRoleEntity(Role $role): Group
diff --git a/src/Entity/Node.php b/src/Entity/Node.php
index 18b73384..c9e9e683 100644
--- a/src/Entity/Node.php
+++ b/src/Entity/Node.php
@@ -11,6 +11,7 @@
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
+use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Loggable\Loggable;
use Gedmo\Mapping\Annotation as Gedmo;
@@ -19,8 +20,10 @@
use RZ\Roadiz\Contracts\NodeType\NodeTypeInterface;
use RZ\Roadiz\Core\AbstractEntities\LeafInterface;
use RZ\Roadiz\Core\AbstractEntities\LeafTrait;
+use RZ\Roadiz\Core\AbstractEntities\NodeInterface;
use RZ\Roadiz\Core\AbstractEntities\TranslationInterface;
use RZ\Roadiz\CoreBundle\Api\Filter as RoadizFilter;
+use RZ\Roadiz\CoreBundle\Enum\NodeStatus;
use RZ\Roadiz\CoreBundle\Model\AttributableInterface;
use RZ\Roadiz\CoreBundle\Model\AttributableTrait;
use RZ\Roadiz\CoreBundle\Repository\NodeRepository;
@@ -36,26 +39,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
@@ -66,15 +69,20 @@
),
ApiFilter(PropertyFilter::class)
]
-class Node extends AbstractDateTimedPositioned implements LeafInterface, AttributableInterface, Loggable
+class Node extends AbstractDateTimedPositioned implements LeafInterface, AttributableInterface, Loggable, NodeInterface
{
use LeafTrait;
use AttributableTrait;
+ /** @deprecated Use NodeStatus enum */
public const DRAFT = 10;
+ /** @deprecated Use NodeStatus enum */
public const PENDING = 20;
+ /** @deprecated Use NodeStatus enum */
public const PUBLISHED = 30;
+ /** @deprecated Use NodeStatus enum */
public const ARCHIVED = 40;
+ /** @deprecated Use NodeStatus enum */
public const DELETED = 50;
#[SymfonySerializer\Ignore]
@@ -90,7 +98,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)]
@@ -120,14 +128,23 @@ 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')]
+ #[ORM\Column(
+ name: 'status',
+ type: Types::SMALLINT,
+ enumType: NodeStatus::class,
+ options: ['default' => NodeStatus::DRAFT]
+ )]
#[Serializer\Exclude]
#[SymfonySerializer\Ignore]
- private int $status = Node::DRAFT;
+ private NodeStatus $status = NodeStatus::DRAFT;
- #[ORM\Column(type: 'integer', nullable: false, options: ['default' => 0])]
+ #[ORM\Column(
+ type: Types::INTEGER,
+ nullable: false,
+ options: ['default' => 0]
+ )]
#[Assert\GreaterThanOrEqual(value: 0)]
#[Assert\NotNull]
#[SymfonySerializer\Ignore]
@@ -177,7 +194,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';
@@ -194,13 +211,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]
@@ -237,16 +254,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;
@@ -333,24 +350,13 @@ public function __construct()
}
/**
- * @param int $status
- * @return string
+ * @deprecated Use NodeStatus enum getLabel method
*/
- public static function getStatusLabel($status): string
+ public static function getStatusLabel(int|string $status): string
{
- $nodeStatuses = [
- static::DRAFT => 'draft',
- static::PENDING => 'pending',
- static::PUBLISHED => 'published',
- static::ARCHIVED => 'archived',
- static::DELETED => 'deleted',
- ];
-
- if (isset($nodeStatuses[$status])) {
- return $nodeStatuses[$status];
- }
+ $status = NodeStatus::tryFrom((int) $status);
- throw new \InvalidArgumentException('Status does not exist.');
+ return $status->getLabel();
}
/**
@@ -359,8 +365,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
{
@@ -368,217 +372,189 @@ 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
+ public function getStatus(): NodeStatus
{
return $this->status;
}
/**
- * @param int|string $status Workflow only use marking places
+ * @param int|string|NodeStatus $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
+ public function setStatus(int|string|NodeStatus $status): Node
+ {
+ if ($status instanceof NodeStatus) {
+ $this->status = $status;
+ } else {
+ $this->status = NodeStatus::tryFrom((int) $status) ?? NodeStatus::DRAFT;
+ }
+
+ return $this;
+ }
+
+ public function setStatusAsString(string $name): Node
{
- $this->status = (int) $status;
+ $this->status = NodeStatus::fromName($name);
+
return $this;
}
- /**
- * @return int
- */
+ public function getStatusAsString(): string
+ {
+ return $this->status->name;
+ }
+
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 $this->status->isPublished();
}
- /**
- * @return bool
- */
public function isPending(): bool
{
- return ($this->status === Node::PENDING);
+ return $this->status->isPending();
}
- /**
- * @return bool
- */
public function isDraft(): bool
{
- return ($this->status === Node::DRAFT);
+ return $this->status->isDraft();
}
- /**
- * @return bool
- */
public function isDeleted(): bool
{
- return ($this->status === Node::DELETED);
+ return $this->status->isDeleted();
+ }
+
+ public function isArchived(): bool
+ {
+ return $this->status->isArchived();
}
- /**
- * @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 $this;
}
- /**
- * @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;
}
@@ -592,6 +568,7 @@ public function getNodesTags(): Collection
/**
* @param Collection $nodesTags
+ *
* @return $this
*/
public function setNodesTags(Collection $nodesTags): static
@@ -631,12 +608,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
@@ -682,18 +658,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
@@ -701,12 +678,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
@@ -727,8 +703,6 @@ public function getStackTypes(): Collection
}
/**
- * @param NodeType $stackType
- *
* @return $this
*/
public function addStackType(NodeType $stackType): static
@@ -743,7 +717,6 @@ public function addStackType(NodeType $stackType): static
/**
* Get node-sources using a given translation.
*
- * @param TranslationInterface $translation
* @return Collection
*/
#[SymfonySerializer\Ignore]
@@ -755,8 +728,6 @@ public function getNodeSourcesByTranslation(TranslationInterface $translation):
}
/**
- * @param NodesSources $ns
- *
* @return $this
*/
public function removeNodeSources(NodesSources $ns): static
@@ -777,8 +748,6 @@ public function getNodeSources(): Collection
}
/**
- * @param NodesSources $ns
- *
* @return $this
*/
public function addNodeSources(NodesSources $ns): static
@@ -801,6 +770,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);
}
@@ -816,6 +786,7 @@ public function getBNodes(): Collection
/**
* @param Collection $bNodes
+ *
* @return $this
*/
public function setBNodes(Collection $bNodes): static
@@ -826,20 +797,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
@@ -848,6 +819,7 @@ public function addBNode(NodesToNodes $bNode): static
$this->getBNodes()->add($bNode);
$bNode->setNodeA($this);
}
+
return $this;
}
@@ -860,6 +832,7 @@ public function clearBNodesForField(NodeTypeFieldInterface $field): Node
foreach ($toRemoveCollection as $toRemove) {
$this->getBNodes()->removeElement($toRemove);
}
+
return $this;
}
@@ -873,31 +846,18 @@ 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 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;
}
@@ -909,49 +869,23 @@ 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 " .
- (
- $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() : '') .
- PHP_EOL;
- }
- return $text;
+ return $this;
}
/**
@@ -964,6 +898,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) {
@@ -973,7 +908,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());
@@ -1000,14 +935,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());
}
@@ -1027,9 +962,6 @@ public function setParent(?LeafInterface $parent = null): static
return $this;
}
- /**
- * @return string
- */
public function __toString(): string
{
return (string) $this->getId();
diff --git a/src/Entity/NodeType.php b/src/Entity/NodeType.php
index 53ab01ff..e41f85ad 100644
--- a/src/Entity/NodeType.php
+++ b/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/src/Entity/NodeTypeField.php b/src/Entity/NodeTypeField.php
index 07dd18bf..ec3b331f 100644
--- a/src/Entity/NodeTypeField.php
+++ b/src/Entity/NodeTypeField.php
@@ -4,6 +4,7 @@
namespace RZ\Roadiz\CoreBundle\Entity;
+use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use RZ\Roadiz\Contracts\NodeType\NodeTypeFieldInterface;
@@ -22,30 +23,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 +56,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 +67,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: Types::SMALLINT, 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: Types::SMALLINT, 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: Types::SMALLINT, 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 +162,7 @@ public function getNodeType(): NodeTypeInterface
public function setNodeType(NodeTypeInterface $nodeType): NodeTypeField
{
$this->nodeType = $nodeType;
+
return $this;
}
@@ -172,12 +174,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 +186,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 +231,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 +242,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 +282,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 +303,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/src/Entity/NodesCustomForms.php b/src/Entity/NodesCustomForms.php
index 8f7d4a39..fc4a2ec8 100644
--- a/src/Entity/NodesCustomForms.php
+++ b/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/src/Entity/NodesSources.php b/src/Entity/NodesSources.php
index 8ebc470e..c18cc534 100644
--- a/src/Entity/NodesSources.php
+++ b/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"]),
- 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,36 +444,27 @@ 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')]
#[SymfonySerializer\Groups(['nodes_sources', 'nodes_sources_base'])]
+ #[Serializer\SerializedName('slug')]
+ #[Serializer\VirtualProperty]
+ #[Serializer\Groups(['nodes_sources', 'nodes_sources_base'])]
public function getIdentifier(): string
{
$urlAlias = $this->getUrlAliases()->first();
- if (false !== $urlAlias && $urlAlias->getAlias() !== '') {
+ if (false !== $urlAlias && '' !== $urlAlias->getAlias()) {
return $urlAlias->getAlias();
}
@@ -517,12 +480,10 @@ public function getUrlAliases(): Collection
}
/**
- * Get parent node’ source based on the same translation.
- *
- * @return NodesSources|null
- * @Serializer\Exclude
+ * Get parent node source based on the same translation.
*/
#[SymfonySerializer\Ignore]
+ #[Serializer\Exclude]
public function getParent(): ?NodesSources
{
/** @var Node|null $parent */
@@ -530,65 +491,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'])]
#[SymfonySerializer\SerializedName('@type')]
+ #[Serializer\Groups(['nodes_sources', 'nodes_sources_default'])]
+ #[Serializer\SerializedName('@type')]
+ #[Serializer\VirtualProperty]
public function getNodeTypeName(): string
{
return 'NodesSources';
@@ -596,8 +545,6 @@ public function getNodeTypeName(): string
/**
* Overridden in NS classes.
- *
- * @return bool
*/
public function isPublishable(): bool
{
@@ -606,8 +553,6 @@ public function isPublishable(): bool
/**
* Overridden in NS classes.
- *
- * @return bool
*/
public function isReachable(): bool
{
@@ -616,8 +561,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 +569,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/src/Entity/NodesSourcesDocuments.php b/src/Entity/NodesSourcesDocuments.php
index 6842bba9..f0472cc2 100644
--- a/src/Entity/NodesSourcesDocuments.php
+++ b/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/src/Entity/NodesTags.php b/src/Entity/NodesTags.php
index e2e82b67..746dff6d 100644
--- a/src/Entity/NodesTags.php
+++ b/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/src/Entity/NodesToNodes.php b/src/Entity/NodesToNodes.php
index b80836c9..6b24f4ca 100644
--- a/src/Entity/NodesToNodes.php
+++ b/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/src/Entity/Realm.php b/src/Entity/Realm.php
index 9cf68e49..2f063c1e 100644
--- a/src/Entity/Realm.php
+++ b/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
@@ -61,12 +61,9 @@ class Realm extends AbstractEntity implements RealmInterface
#[Assert\Regex('#^[\w\s]+$#u')]
private string $name = '';
- /**
- * @var string|null
- * @Serializer\Exclude()
- */
#[ORM\Column(name: 'plain_password', type: 'string', length: 255, unique: false, nullable: true)]
#[SymfonySerializer\Ignore]
+ #[Serializer\Exclude]
#[Assert\Length(max: 255)]
private ?string $plainPassword = null;
@@ -105,73 +102,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 +162,13 @@ public function getRealmNodes(): Collection
/**
* @param Collection $realmNodes
+ *
* @return Realm
*/
public function setRealmNodes(Collection $realmNodes)
{
$this->realmNodes = $realmNodes;
+
return $this;
}
@@ -203,58 +182,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 +233,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/src/Entity/RealmNode.php b/src/Entity/RealmNode.php
index 8007a309..e0623569 100644
--- a/src/Entity/RealmNode.php
+++ b/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/src/Entity/Redirection.php b/src/Entity/Redirection.php
index 469222ef..aeedd398 100644
--- a/src/Entity/Redirection.php
+++ b/src/Entity/Redirection.php
@@ -4,6 +4,7 @@
namespace RZ\Roadiz\CoreBundle\Entity;
+use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use RZ\Roadiz\Core\AbstractEntities\AbstractDateTimed;
use RZ\Roadiz\CoreBundle\Repository\RedirectionRepository;
@@ -16,19 +17,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 +39,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')]
+ #[ORM\Column(type: Types::SMALLINT)]
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 +97,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 +110,6 @@ public function __construct()
$this->initAbstractDateTimed();
}
- /**
- * @return int
- */
public function getUseCount(): int
{
return $this->useCount;
@@ -152,7 +117,8 @@ public function getUseCount(): int
public function incrementUseCount(): self
{
- $this->useCount++;
+ ++$this->useCount;
+
return $this;
}
}
diff --git a/src/Entity/Role.php b/src/Entity/Role.php
index d1a03ca8..230df685 100644
--- a/src/Entity/Role.php
+++ b/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
@@ -186,33 +163,25 @@ public function removeGroup(Group $group): Role
* Get a classified version of current role name.
*
* It replaces underscores by dashes and lowercase.
- *
- * @return string
- * @Serializer\Groups({"role"})
*/
#[SymfonySerializer\Groups(['role'])]
+ #[Serializer\Groups(['role'])]
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 +189,6 @@ public function required(): bool
return false;
}
- /**
- * @return string
- */
public function __toString(): string
{
return $this->getRole();
diff --git a/src/Entity/Setting.php b/src/Entity/Setting.php
index 2670a463..21065bfc 100644
--- a/src/Entity/Setting.php
+++ b/src/Entity/Setting.php
@@ -4,13 +4,14 @@
namespace RZ\Roadiz\CoreBundle\Entity;
+use Doctrine\DBAL\Types\Types;
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 +20,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,14 +86,14 @@ 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;
/**
* Value types.
* Use NodeTypeField types constants.
*/
- #[ORM\Column(type: 'integer')]
+ #[ORM\Column(type: Types::SMALLINT)]
#[SymfonySerializer\Groups(['setting'])]
#[Serializer\Groups(['setting'])]
private int $type = AbstractField::STRING_T;
@@ -105,17 +106,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 +125,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 +137,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 +165,6 @@ public function getValue(): string|bool|\DateTime|int|null
}
/**
- * @param mixed $value
- *
* @return $this
*/
public function setValue(mixed $value): self
@@ -198,17 +180,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 +195,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 +210,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 +225,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/src/Entity/SettingGroup.php b/src/Entity/SettingGroup.php
index a8d73195..364661b4 100644
--- a/src/Entity/SettingGroup.php
+++ b/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/src/Entity/Tag.php b/src/Entity/Tag.php
index e8503dea..9a3bd3a2 100644
--- a/src/Entity/Tag.php
+++ b/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,22 +388,15 @@ 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]
+ #[Serializer\Groups(['tag', 'tag_base', 'node', 'nodes_sources'])]
+ #[Serializer\VirtualProperty]
+ #[Serializer\Type('string|null')]
public function getName(): ?string
{
return $this->getTranslatedTags()->first() ?
@@ -455,6 +414,7 @@ public function getTranslatedTags(): Collection
/**
* @param Collection $translatedTags
+ *
* @return $this
*/
public function setTranslatedTags(Collection $translatedTags): static
@@ -464,17 +424,14 @@ 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]
+ #[Serializer\VirtualProperty]
+ #[Serializer\Groups(['tag', 'node', 'nodes_sources'])]
+ #[Serializer\Type('string|null')]
public function getDescription(): ?string
{
return $this->getTranslatedTags()->first() ?
@@ -482,14 +439,10 @@ public function getDescription(): ?string
'';
}
- /**
- * @return array
- *
- * @Serializer\Groups({"tag", "node", "nodes_sources"})
- * @Serializer\VirtualProperty
- * @Serializer\Type("array")
- */
#[SymfonySerializer\Ignore]
+ #[Serializer\VirtualProperty]
+ #[Serializer\Groups(['tag', 'node', 'nodes_sources'])]
+ #[Serializer\Type('array')]
public function getDocuments(): array
{
return $this->getTranslatedTags()->first() ?
@@ -511,7 +464,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/src/Entity/TagTranslation.php b/src/Entity/TagTranslation.php
index 36017fe1..bb1d5125 100644
--- a/src/Entity/TagTranslation.php
+++ b/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,7 +58,6 @@ class TagTranslation extends AbstractEntity
/**
* @var Collection
- * @Serializer\Exclude
*/
#[ORM\OneToMany(
mappedBy: 'tagTranslation',
@@ -68,20 +67,18 @@ class TagTranslation extends AbstractEntity
)]
#[ORM\OrderBy(['position' => 'ASC'])]
#[SymfonySerializer\Ignore]
+ #[Serializer\Exclude]
protected Collection $tagTranslationDocuments;
/**
* 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 +113,7 @@ public function getTag(): Tag
public function setTag(Tag $tag): TagTranslation
{
$this->tag = $tag;
+
return $this;
}
@@ -152,14 +150,10 @@ public function __clone()
}
}
- /**
- * @return array
- *
- * @Serializer\Groups({"tag"})
- * @Serializer\VirtualProperty
- * @Serializer\Type("array")
- */
#[SymfonySerializer\Groups(['tag'])]
+ #[Serializer\Groups(['tag'])]
+ #[Serializer\VirtualProperty]
+ #[Serializer\Type('array')]
public function getDocuments(): array
{
return array_map(function (TagTranslationDocuments $tagTranslationDocument) {
@@ -167,21 +161,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/src/Entity/TagTranslationDocuments.php b/src/Entity/TagTranslationDocuments.php
index d06683da..cb350fb9 100644
--- a/src/Entity/TagTranslationDocuments.php
+++ b/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/src/Entity/Theme.php b/src/Entity/Theme.php
index 57d5afd6..69234999 100644
--- a/src/Entity/Theme.php
+++ b/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/src/Entity/Translation.php b/src/Entity/Translation.php
index 549360e8..d83812dc 100644
--- a/src/Entity/Translation.php
+++ b/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,13 +548,11 @@ 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)]
#[SymfonySerializer\Ignore]
+ #[Serializer\Exclude]
#[Assert\NotBlank]
#[Assert\NotNull]
#[Assert\Length(max: 10)]
@@ -564,13 +562,9 @@ 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)]
#[SymfonySerializer\Ignore]
+ #[Serializer\Exclude]
#[Assert\Length(max: 10)]
#[ApiProperty(
description: 'Override standard locale with an other one (for example, `uk` instead of `en`)',
@@ -578,13 +572,10 @@ 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)]
#[SymfonySerializer\Groups(['translation', 'translation_base'])]
+ #[Serializer\Groups(['translation', 'translation_base'])]
+ #[Serializer\Type('string')]
#[Assert\NotNull]
#[Assert\NotBlank]
#[Assert\Length(max: 250)]
@@ -594,26 +585,20 @@ 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])]
#[SymfonySerializer\Groups(['translation', 'translation_base'])]
+ #[Serializer\Groups(['translation', 'translation_base'])]
+ #[Serializer\Type('bool')]
#[ApiProperty(
description: 'Is translation default one?',
example: 'true',
)]
private bool $defaultTranslation = false;
- /**
- * @var bool
- * @Serializer\Groups({"translation", "translation_base"})
- * @Serializer\Type("bool")
- */
#[ORM\Column(type: 'boolean', nullable: false, options: ['default' => true])]
#[SymfonySerializer\Groups(['translation', 'translation_base'])]
+ #[Serializer\Groups(['translation', 'translation_base'])]
+ #[Serializer\Type('bool')]
#[ApiProperty(
description: 'Is translation available publicly?',
example: 'true',
@@ -657,8 +642,6 @@ public function __construct()
/**
* Return available locales in an array.
- *
- * @return array
*/
#[SymfonySerializer\Ignore]
public static function getAvailableLocales(): array
@@ -666,120 +649,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 +739,6 @@ public function getDocumentTranslations(): Collection
/**
* Gets the value of overrideLocale.
- *
- * @return string
*/
public function getOverrideLocale(): ?string
{
@@ -799,8 +749,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,11 +759,11 @@ public function setOverrideLocale(?string $overrideLocale): Translation
/**
* Get preferred locale between overrideLocale or locale.
- *
- * @return string
*/
#[SymfonySerializer\SerializedName('locale')]
#[SymfonySerializer\Groups(['translation_base'])]
+ #[Serializer\SerializedName('locale')]
+ #[Serializer\Groups(['translation_base'])]
#[ApiProperty(
description: 'Translation ISO 639-1 locale. See https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes',
example: 'fr',
@@ -825,26 +773,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/src/Entity/UrlAlias.php b/src/Entity/UrlAlias.php
index 9f713fef..9718184a 100644
--- a/src/Entity/UrlAlias.php
+++ b/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/src/Entity/User.php b/src/Entity/User.php
index a5d39a62..f0fc18fd 100644
--- a/src/Entity/User.php
+++ b/src/Entity/User.php
@@ -7,7 +7,6 @@
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
-use JMS\Serializer\Annotation as Serializer;
use Rollerworks\Component\PasswordStrength\Validator\Constraints\PasswordStrength;
use RZ\Roadiz\Core\AbstractEntities\AbstractHuman;
use RZ\Roadiz\CoreBundle\Form\Constraint\ValidFacebookName;
@@ -17,26 +16,26 @@
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
-use Symfony\Component\Serializer\Annotation as SymfonySerializer;
+use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
#[
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
{
@@ -48,12 +47,8 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface
*/
public const CONFIRMATION_TTL = 900;
- /**
- * @Serializer\Groups({"user_personal", "human"})
- * @var string|null
- */
#[ORM\Column(type: 'string', length: 200, unique: true, nullable: false)]
- #[SymfonySerializer\Groups(['user_personal', 'human'])]
+ #[Serializer\Groups(['user_personal', 'human'])]
#[Assert\NotNull]
#[Assert\NotBlank]
#[Assert\Length(max: 200)]
@@ -61,60 +56,35 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface
/** @phpstan-ignore-next-line */
protected ?string $email = null;
- /**
- * @var bool
- * @Serializer\Exclude()
- */
- #[SymfonySerializer\Ignore]
+ #[Serializer\Ignore]
protected bool $sendCreationConfirmationEmail = false;
#[ORM\Column(name: 'facebook_name', type: 'string', length: 128, unique: false, nullable: true)]
- #[SymfonySerializer\Groups(['user_social'])]
#[Serializer\Groups(['user_social'])]
#[Assert\Length(max: 128)]
#[ValidFacebookName]
protected ?string $facebookName = null;
- /**
- * @var string|null
- * @Serializer\Groups({"user"})
- */
#[ORM\Column(name: 'picture_url', type: 'text', nullable: true)]
- #[SymfonySerializer\Groups(['user'])]
+ #[Serializer\Groups(['user'])]
#[Assert\Length(max: 250)]
protected ?string $pictureUrl = null;
- /**
- * @var boolean
- * @Serializer\Groups({"user_security"})
- */
#[ORM\Column(type: 'boolean', nullable: false, options: ['default' => true])]
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
protected bool $enabled = true;
- /**
- * @Serializer\Groups({"user_security"})
- * @var string|null
- */
#[ORM\Column(name: 'confirmation_token', type: 'string', length: 128, unique: true, nullable: true)]
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
#[Assert\Length(max: 128)]
protected ?string $confirmationToken = null;
- /**
- * @Serializer\Groups({"user_security"})
- * @var \DateTime|null
- */
#[ORM\Column(name: 'password_requested_at', type: 'datetime', nullable: true)]
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
protected ?\DateTime $passwordRequestedAt = null;
- /**
- * @Serializer\Groups({"user_personal", "log_user"})
- * @var string
- */
#[ORM\Column(type: 'string', length: 200, unique: true)]
- #[SymfonySerializer\Groups(['user_personal', 'log_user'])]
+ #[Serializer\Groups(['user_personal', 'log_user'])]
#[Assert\NotNull]
#[Assert\NotBlank]
#[Assert\Length(max: 200)]
@@ -124,29 +94,21 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface
* Encrypted password.
*/
#[ORM\Column(type: 'string', length: 128, nullable: false)]
- #[SymfonySerializer\Ignore]
- #[Serializer\Exclude]
+ #[Serializer\Ignore]
#[Assert\Length(max: 128)]
private string $password = '';
/**
* Plain password. Used for model validation.
- * **Must not be persisted.**
- *
- * @var string|null
- * @Serializer\Groups({"user:write"})
- * @PasswordStrength(minLength=8, minStrength=3)
+ * **Must not be persisted.**.
*/
- #[SymfonySerializer\Groups(['user:write'])]
+ #[PasswordStrength(minStrength: 3, minLength: 8)]
+ #[Serializer\Groups(['user:write'])]
#[Assert\NotBlank(groups: ['no_empty_password'])]
private ?string $plainPassword = null;
- /**
- * @var \DateTime|null
- * @Serializer\Groups({"user_security"})
- */
#[ORM\Column(name: 'last_login', type: 'datetime', nullable: true)]
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
private ?\DateTime $lastLogin = null;
/**
@@ -156,70 +118,47 @@ class User extends AbstractHuman implements UserInterface, AdvancedUserInterface
#[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
#[ORM\InverseJoinColumn(name: 'role_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
#[ORM\ManyToMany(targetEntity: Role::class)]
- #[SymfonySerializer\Ignore]
- #[Serializer\Exclude]
+ #[Serializer\Ignore]
private Collection $roleEntities;
/**
* Names of current User roles
- * to be compatible with symfony security scheme
+ * to be compatible with symfony security scheme.
*
* @var array|null
*/
- #[SymfonySerializer\Ignore]
- #[Serializer\Exclude]
+ #[Serializer\Ignore]
private ?array $roles = null;
/**
* @var Collection
- * @Serializer\Groups({"user_group"})
*/
#[ORM\JoinTable(name: 'users_groups')]
#[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id')]
#[ORM\InverseJoinColumn(name: 'group_id', referencedColumnName: 'id')]
#[ORM\ManyToMany(targetEntity: Group::class, inversedBy: 'users')]
- #[SymfonySerializer\Groups(['user_group'])]
+ #[Serializer\Groups(['user_group'])]
private Collection $groups;
- /**
- * @var boolean
- * @Serializer\Groups({"user_security"})
- */
#[ORM\Column(type: 'boolean', nullable: false, options: ['default' => false])]
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
private bool $locked = false;
- /**
- * @Serializer\Groups({"user_security"})
- * @var \DateTime|null
- */
#[ORM\Column(name: 'credentials_expires_at', type: 'datetime', nullable: true)]
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
private ?\DateTime $credentialsExpiresAt = null;
- /**
- * @Serializer\Groups({"user_security"})
- * @var \DateTime|null
- */
#[ORM\Column(name: 'expires_at', type: 'datetime', nullable: true)]
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
private ?\DateTime $expiresAt = null;
- /**
- * @Serializer\Groups({"user_chroot"})
- * @var Node|null
- */
#[ORM\ManyToOne(targetEntity: Node::class)]
#[ORM\JoinColumn(name: 'chroot_id', referencedColumnName: 'id', onDelete: 'SET NULL')]
- #[SymfonySerializer\Groups(['user_chroot'])]
+ #[Serializer\Groups(['user_chroot'])]
private ?Node $chroot = null;
- /**
- * @var null|string
- * @Serializer\Groups({"user"})
- */
#[ORM\Column(name: 'locale', type: 'string', length: 7, nullable: true)]
- #[SymfonySerializer\Groups(['user'])]
+ #[Serializer\Groups(['user'])]
#[Assert\Length(max: 7)]
private ?string $locale = null;
@@ -234,21 +173,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
{
@@ -258,29 +193,21 @@ 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]
+ #[Serializer\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();
}
}
- /**
- * @return string
- * @Serializer\Groups({"user_identifier", "user_personal"})
- * @Serializer\VirtualProperty()
- */
- #[SymfonySerializer\SerializedName('identifier')]
- #[SymfonySerializer\Groups(['user_identifier', 'user_personal'])]
+ #[Serializer\SerializedName('identifier')]
+ #[Serializer\Groups(['user_identifier', 'user_personal'])]
public function getUserIdentifier(): string
{
return $this->username;
@@ -295,20 +222,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 +240,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 +278,12 @@ public function getPassword(): string
}
/**
- * @param string $password
* @return $this
*/
public function setPassword(string $password): User
{
$this->password = $password;
+
return $this;
}
@@ -377,19 +295,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 +316,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 +334,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 +346,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 +365,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 +387,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 +399,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 +426,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 +433,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 +448,6 @@ public function eraseCredentials(): User
/**
* Insert user into group.
*
- * @param Group $group
- *
* @return $this
*/
public function addGroup(Group $group): User
@@ -566,18 +459,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,10 +482,8 @@ public function removeGroup(Group $group): User
* Get current user groups name.
*
* @return array Array of strings
- * @Serializer\Groups({"user"})
- * @Serializer\VirtualProperty()
*/
- #[SymfonySerializer\Groups(['user'])]
+ #[Serializer\Groups(['user'])]
public function getGroupNames(): array
{
$names = [];
@@ -616,16 +502,14 @@ 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'])]
+ #[Serializer\Groups(['user_security'])]
public function isAccountNonExpired(): bool
{
- return $this->expiresAt === null || $this->expiresAt->getTimestamp() > time();
+ return null === $this->expiresAt || $this->expiresAt->getTimestamp() > time();
}
/**
@@ -637,10 +521,8 @@ 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'])]
+ #[Serializer\Groups(['user_security'])]
public function isAccountNonLocked(): bool
{
return !$this->locked;
@@ -649,43 +531,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 +561,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 +568,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;
@@ -716,17 +578,16 @@ 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
+ #[Serializer\Ignore]
+ 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 +614,6 @@ public function isEnabled(): bool
return $this->enabled;
}
- /**
- * @param boolean $enabled
- *
- * @return User
- */
public function setEnabled(bool $enabled): User
{
$this->enabled = $enabled;
@@ -773,31 +629,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]
+ #[Serializer\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;
}
@@ -806,8 +656,8 @@ public function setExpiresAt(?\DateTime $expiresAt): User
*
* @return array
*/
- #[SymfonySerializer\SerializedName('roles')]
- #[SymfonySerializer\Groups(['user_role'])]
+ #[Serializer\SerializedName('roles')]
+ #[Serializer\Groups(['user_role'])]
public function getRoles(): array
{
if (null === $this->roles) {
@@ -836,21 +686,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;
}
@@ -891,30 +735,17 @@ public function __unserialize(array $data): void
] = $data;
}
- /**
- * @Serializer\Groups({"user_security"})
- */
- #[SymfonySerializer\Groups(['user_security'])]
+ #[Serializer\Groups(['user_security'])]
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,12 +753,8 @@ public function hasRole(string $role): bool
/**
* Every field tested in this methods must be serialized in token.
- *
- * @param UserInterface $user
- *
- * @return bool
*/
- #[SymfonySerializer\Ignore]
+ #[Serializer\Ignore]
public function isEqualTo(UserInterface $user): bool
{
if (!$user instanceof User) {
diff --git a/src/Entity/UserLogEntry.php b/src/Entity/UserLogEntry.php
index 9714f502..84dc6b61 100644
--- a/src/Entity/UserLogEntry.php
+++ b/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/src/Entity/Webhook.php b/src/Entity/Webhook.php
index 840cff92..bb02f6ed 100644
--- a/src/Entity/Webhook.php
+++ b/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/src/EntityApi/AbstractApi.php b/src/EntityApi/AbstractApi.php
index 23d662b9..1e4037db 100644
--- a/src/EntityApi/AbstractApi.php
+++ b/src/EntityApi/AbstractApi.php
@@ -4,49 +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/src/EntityApi/NodeApi.php b/src/EntityApi/NodeApi.php
index 2024bf32..108e7673 100644
--- a/src/EntityApi/NodeApi.php
+++ b/src/EntityApi/NodeApi.php
@@ -8,12 +8,12 @@
use RZ\Roadiz\CoreBundle\Entity\Node;
use RZ\Roadiz\CoreBundle\Repository\NodeRepository;
+/**
+ * @deprecated Use NodeRepository directly
+ */
class NodeApi extends AbstractApi
{
- /**
- * @return NodeRepository
- */
- public function getRepository()
+ public function getRepository(): NodeRepository
{
// phpstan cannot resolve repository type.
/** @var NodeRepository $repository */
@@ -21,22 +21,19 @@ public function getRepository()
->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;
}
@@ -50,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;
@@ -65,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/src/EntityApi/NodeSourceApi.php b/src/EntityApi/NodeSourceApi.php
index d3821a8b..ba4eb6f6 100644
--- a/src/EntityApi/NodeSourceApi.php
+++ b/src/EntityApi/NodeSourceApi.php
@@ -10,27 +10,29 @@
use RZ\Roadiz\CoreBundle\Entity\NodeType;
use RZ\Roadiz\CoreBundle\Repository\NodesSourcesRepository;
+/**
+ * @deprecated Use NodesSourcesRepository directly
+ */
class NodeSourceApi extends AbstractApi
{
/**
- * @var class-string
+ * @var class-string
*/
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']);
@@ -41,9 +43,6 @@ protected function getNodeSourceClassName(array $criteria = null): string
return $this->nodeSourceClassName;
}
- /**
- * @return NodesSourcesRepository
- */
public function getRepository(): NodesSourcesRepository
{
// @phpstan-ignore-next-line
@@ -51,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()
@@ -75,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
@@ -90,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,
@@ -108,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/src/EntityApi/NodeTypeApi.php b/src/EntityApi/NodeTypeApi.php
index c3aecd2a..43ebde2b 100644
--- a/src/EntityApi/NodeTypeApi.php
+++ b/src/EntityApi/NodeTypeApi.php
@@ -4,36 +4,31 @@
namespace RZ\Roadiz\CoreBundle\EntityApi;
+use Doctrine\ORM\Tools\Pagination\Paginator;
use RZ\Roadiz\CoreBundle\Entity\NodeType;
use RZ\Roadiz\CoreBundle\Repository\NodeTypeRepository;
+/**
+ * @deprecated Use NodeTypeRepository directly
+ */
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/src/EntityApi/TagApi.php b/src/EntityApi/TagApi.php
index 3b363371..c894b897 100644
--- a/src/EntityApi/TagApi.php
+++ b/src/EntityApi/TagApi.php
@@ -8,12 +8,12 @@
use RZ\Roadiz\CoreBundle\Entity\Tag;
use RZ\Roadiz\CoreBundle\Repository\TagRepository;
+/**
+ * @deprecated Use TagRepository directly
+ */
class TagApi extends AbstractApi
{
- /**
- * @return TagRepository
- */
- public function getRepository()
+ public function getRepository(): TagRepository
{
return $this->managerRegistry->getRepository(Tag::class);
}
@@ -23,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',
@@ -51,10 +46,8 @@ public function getBy(
null
);
}
- /**
- * {@inheritdoc}
- */
- public function countBy(array $criteria)
+
+ public function countBy(array $criteria): int
{
return $this->getRepository()
->countBy(
@@ -62,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/src/EntityHandler/CustomFormFieldHandler.php b/src/EntityHandler/CustomFormFieldHandler.php
index dfa24595..38fc7b1b 100644
--- a/src/EntityHandler/CustomFormFieldHandler.php
+++ b/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/src/EntityHandler/CustomFormHandler.php b/src/EntityHandler/CustomFormHandler.php
index 721e121a..a04f0fd4 100644
--- a/src/EntityHandler/CustomFormHandler.php
+++ b/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/src/EntityHandler/DocumentHandler.php b/src/EntityHandler/DocumentHandler.php
index 44e9d885..75381fe9 100644
--- a/src/EntityHandler/DocumentHandler.php
+++ b/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/src/EntityHandler/FolderHandler.php b/src/EntityHandler/FolderHandler.php
index 5cb16fdb..5233f87d 100644
--- a/src/EntityHandler/FolderHandler.php
+++ b/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/src/EntityHandler/GroupHandler.php b/src/EntityHandler/GroupHandler.php
index 9fb78ea9..751157bd 100644
--- a/src/EntityHandler/GroupHandler.php
+++ b/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/src/EntityHandler/HandlerFactory.php b/src/EntityHandler/HandlerFactory.php
index 860b941e..df97de0d 100644
--- a/src/EntityHandler/HandlerFactory.php
+++ b/src/EntityHandler/HandlerFactory.php
@@ -20,45 +20,43 @@
use RZ\Roadiz\CoreBundle\Entity\Tag;
use RZ\Roadiz\CoreBundle\Entity\Translation;
-final class HandlerFactory implements HandlerFactoryInterface
+final readonly class HandlerFactory implements HandlerFactoryInterface
{
- public function __construct(private readonly ContainerInterface $container)
+ public function __construct(private 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/src/EntityHandler/NodeHandler.php b/src/EntityHandler/NodeHandler.php
index fced6244..7a3deb1b 100644
--- a/src/EntityHandler/NodeHandler.php
+++ b/src/EntityHandler/NodeHandler.php
@@ -15,7 +15,6 @@
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
use RZ\Roadiz\CoreBundle\Entity\NodesToNodes;
use RZ\Roadiz\CoreBundle\Entity\NodeTypeField;
-use RZ\Roadiz\CoreBundle\Entity\Translation;
use RZ\Roadiz\CoreBundle\Node\NodeDuplicator;
use RZ\Roadiz\CoreBundle\Node\NodeNamePolicyInterface;
use RZ\Roadiz\CoreBundle\Repository\NodeRepository;
@@ -35,7 +34,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 +49,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 +72,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 +95,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 +129,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 +144,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 +161,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
@@ -196,59 +188,6 @@ public function addNodeForField(Node $node, NodeTypeFieldInterface $field, bool
return $this;
}
- /**
- * Get nodes linked to current node for a given field name.
- *
- * @param string $fieldName Name of the node-type field
- * @return Node[]
- */
- public function getNodesFromFieldName(string $fieldName): array
- {
- $field = $this->getNode()->getNodeType()->getFieldByName($fieldName);
- if (null !== $field) {
- return $this->getRepository()
- ->findByNodeAndField(
- $this->getNode(),
- $field
- );
- }
- return [];
- }
-
- /**
- * Get nodes reversed-linked to current node for a given field name.
- *
- * @param string $fieldName Name of the node-type field
- * @return Node[]
- */
- public function getReverseNodesFromFieldName(string $fieldName): array
- {
- $field = $this->getNode()->getNodeType()->getFieldByName($fieldName);
- if (null !== $field) {
- return $this->getRepository()
- ->findByReverseNodeAndField(
- $this->getNode(),
- $field
- );
- }
- return [];
- }
-
- /**
- * Get node source by translation.
- *
- * @param Translation $translation
- *
- * @return null|NodesSources
- * @deprecated Use Node::getNodeSourcesByTranslation() instead.
- */
- public function getNodeSourceByTranslation($translation): ?NodesSources
- {
- return $this->objectManager
- ->getRepository(NodesSources::class)
- ->findOneBy(["node" => $this->getNode(), "translation" => $translation]);
- }
-
/**
* Remove only current node children.
*
@@ -265,6 +204,7 @@ private function removeChildren(): self
return $this;
}
+
/**
* Remove only current node associations.
*
@@ -279,6 +219,7 @@ public function removeAssociations(): self
return $this;
}
+
/**
* Remove current node with its children recursively and
* its associations.
@@ -296,9 +237,6 @@ public function removeWithChildrenAndAssociations(): self
return $this;
}
- /**
- * @return WorkflowInterface
- */
private function getWorkflow(): WorkflowInterface
{
return $this->registry->get($this->getNode());
@@ -372,6 +310,7 @@ public function publishWithChildren(): self
$handler->setNode($node);
$handler->publishWithChildren();
}
+
return $this;
}
@@ -401,10 +340,6 @@ public function archiveWithChildren(): self
/**
* Return if part of Node offspring.
- *
- * @param Node $relative
- *
- * @return bool
*/
public function isRelatedToNode(Node $relative): bool
{
@@ -418,13 +353,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
@@ -433,13 +368,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();
}
@@ -452,16 +387,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);
@@ -473,7 +408,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
@@ -483,7 +417,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);
@@ -493,7 +427,7 @@ public function cleanChildrenPositions(bool $setPositions = true): float
if ($setPositions) {
$child->setPosition($i);
}
- $i++;
+ ++$i;
}
return $i;
@@ -504,7 +438,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
@@ -519,49 +452,16 @@ public function cleanRootNodesPositions(bool $setPositions = true): float
if ($setPositions) {
$child->setPosition($i);
}
- $i++;
+ ++$i;
}
return $i;
}
- /**
- * Return all node offspring id.
- *
- * @return array
- * @deprecated Use NodeOffspringResolverInterface::getAllOffspringIds($chroot).
- */
- public function getAllOffspringId(): array
- {
- return $this->getRepository()->findAllOffspringIdByNode($this->getNode());
- }
-
- /**
- * Set current node as the Home node.
- *
- * @return $this
- */
- public function makeHome(): self
- {
- $defaults = $this->getRepository()
- ->setDisplayingNotPublishedNodes(true)
- ->findBy(['home' => true]);
-
- /** @var Node $default */
- foreach ($defaults as $default) {
- $default->setHome(false);
- }
- $this->getNode()->setHome(true);
- $this->objectManager->flush();
-
- return $this;
- }
-
/**
* Duplicate current node with all its children.
*
- * @return Node
- * @deprecated Use NodeDuplicator::duplicate() instead.
+ * @deprecated use NodeDuplicator::duplicate() instead
*/
public function duplicate(): Node
{
@@ -570,22 +470,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;
@@ -619,16 +517,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 = [];
@@ -656,9 +551,6 @@ public function getNext(
);
}
- /**
- * @return NodeRepository
- */
protected function getRepository(): NodeRepository
{
return $this->objectManager->getRepository(Node::class);
diff --git a/src/EntityHandler/NodeTypeFieldHandler.php b/src/EntityHandler/NodeTypeFieldHandler.php
index 2a17f9d5..d660c2ec 100644
--- a/src/EntityHandler/NodeTypeFieldHandler.php
+++ b/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/src/EntityHandler/NodeTypeHandler.php b/src/EntityHandler/NodeTypeHandler.php
index e391a276..5e423b64 100644
--- a/src/EntityHandler/NodeTypeHandler.php
+++ b/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/src/EntityHandler/NodesSourcesHandler.php b/src/EntityHandler/NodesSourcesHandler.php
index 55b2eb90..23467a2f 100644
--- a/src/EntityHandler/NodesSourcesHandler.php
+++ b/src/EntityHandler/NodesSourcesHandler.php
@@ -10,7 +10,6 @@
use RZ\Roadiz\Core\Handlers\AbstractHandler;
use RZ\Roadiz\CoreBundle\Bag\Settings;
use RZ\Roadiz\CoreBundle\Entity\Document;
-use RZ\Roadiz\CoreBundle\Entity\Node;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
use RZ\Roadiz\CoreBundle\Entity\NodesSourcesDocuments;
use RZ\Roadiz\CoreBundle\Entity\NodeTypeField;
@@ -40,24 +39,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 +62,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 +79,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 +115,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 +134,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 +151,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 +160,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 +204,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