diff --git a/.ddev/config.yaml b/.ddev/config.yaml
new file mode 100644
index 000000000..3d0e1970e
--- /dev/null
+++ b/.ddev/config.yaml
@@ -0,0 +1,16 @@
+name: charcoal
+type: php
+docroot: ""
+php_version: "8.5"
+webserver_type: apache-fpm
+xdebug_enabled: true
+additional_hostnames: []
+additional_fqdns: []
+database:
+ type: mariadb
+ version: "10.11"
+use_dns_when_possible: true
+composer_version: "2"
+web_environment:
+ - XDEBUG_MODE=coverage,debug,develop
+corepack_enable: false
diff --git a/.ddev/php/php-xdebug.ini b/.ddev/php/php-xdebug.ini
new file mode 100644
index 000000000..c9a635b8c
--- /dev/null
+++ b/.ddev/php/php-xdebug.ini
@@ -0,0 +1,2 @@
+[PHP]
+xdebug.mode=coverage,debug,develop
diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml
index f2cd9f660..9a3f2a034 100644
--- a/.github/workflows/php.yml
+++ b/.github/workflows/php.yml
@@ -2,7 +2,7 @@ name: PHP Testing
on:
push:
- branches: [ main ]
+# branches: [ main ]
pull_request:
branches: [ main ]
@@ -28,7 +28,7 @@ jobs:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
- php-version: 8.0
+ php-version: 8.5
coverage: none
- name: Install Composer dependencies
@@ -36,7 +36,7 @@ jobs:
- name: Output list of packages as JSON
id: output_data
- run: echo "matrix=$(vendor/bin/monorepo-builder packages-json)" >> $GITHUB_OUTPUT
+ run: echo "matrix=$(./monorepo packages -t json)" >> $GITHUB_OUTPUT
outputs:
matrix: ${{ steps.output_data.outputs.matrix }}
@@ -48,7 +48,13 @@ jobs:
strategy:
matrix:
- php-versions: ['7.4', '8.0']
+ php-versions:
+ - '8.3'
+ - '8.4'
+ - '8.5'
+ include:
+ - php-versions: '8.3'
+ dependencies: 'highest'
package: ${{fromJson(needs.provide_packages_json.outputs.matrix)}}
steps:
@@ -67,6 +73,8 @@ jobs:
- name: Install Composer dependencies
uses: ramsey/composer-install@v2
+ with:
+ dependency-versions: ${{ matrix.dependencies }}
- name: Install ImageMagick
if: ${{ matrix.package == 'image' }}
@@ -82,4 +90,6 @@ jobs:
run: tests/script/phpcs --ci ${{ matrix.package }}
- name: Run PHPunit for all packages
+ env:
+ TEST_MODE: PACKAGE
run: tests/script/phpunit --ci ${{ matrix.package }}
diff --git a/.gitignore b/.gitignore
index 119d860c5..e53552d75 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
.phpunit.result.cache
+phpunit.xml.dist.bak
+.phpunit.cache
charcoal_test
node_modules/
packages/**/composer.lock
@@ -7,3 +9,6 @@ phpstan.neon
phpunit.xml
psalm.xml
vendor/
+tests/logs
+build/report/
+packages/**/build/report
diff --git a/composer.json b/composer.json
index 5fa2a7da2..3f49bedc3 100644
--- a/composer.json
+++ b/composer.json
@@ -32,17 +32,18 @@
}
],
"require": {
- "php": "^7.4 || ^8.0",
+ "php": "^8.3",
"ext-fileinfo": "*",
"ext-json": "*",
"ext-mbstring": "*",
"ext-pdo": "*",
+ "ext-pdo_mysql": "*",
"ext-simplexml": "*",
"ext-spl": "*",
+ "assetic/framework": "^3.1",
"barryvdh/elfinder-flysystem-driver": "^0.3",
"erusev/parsedown": "^1.7",
"guzzlehttp/guzzle": "^6.0 || ^7.0",
- "kriswallsmith/assetic": "^1.4",
"laminas/laminas-permissions-acl": "^2.8",
"league/climate": "^3.2",
"league/flysystem": "^1.0",
@@ -50,15 +51,16 @@
"monolog/monolog": "^1.17",
"phpmailer/phpmailer": "~6.0",
"pimple/pimple": "^3.0",
- "psr/cache": "^1.0",
+ "psr/cache": "^2.0",
"psr/container": "^1.0",
"psr/http-message": "^1.0",
"psr/log": "^1.0",
"seld/jsonlint": "^1.9",
- "slim/slim": "^3.7",
- "studio-42/elfinder": "2.1.64",
- "symfony/translation": "^3.4",
- "tedivm/stash": "~0.16",
+ "slim/slim": "^3.13",
+ "studio-42/elfinder": "^2.1.64",
+ "symfony/polyfill-php85": "^1.37",
+ "symfony/translation": "^7.2",
+ "tedivm/stash": "^1.1",
"vlucas/phpdotenv": "^5.4"
},
"require-dev": {
@@ -68,14 +70,16 @@
"league/flysystem-memory": "^1.0",
"league/flysystem-sftp": "^1.0",
"mockery/mockery": "^1.0",
- "mustache/mustache": "^2.11",
+ "mustache/mustache": "^3.2",
"php-coveralls/php-coveralls": "^2.2",
- "phpstan/phpstan": "^1.6",
- "phpunit/phpunit": "^9.5",
- "squizlabs/php_codesniffer": "^3.5",
- "symfony/yaml": "^3.0",
- "symplify/monorepo-builder": "^10.2",
- "twig/twig": "^3.4"
+ "phpstan/phpstan": "^2.0",
+ "phpunit/phpunit": "^12.5",
+ "rector/rector": "^2.4",
+ "squizlabs/php_codesniffer": "^4.0",
+ "symfony/yaml": "^7.2",
+ "symplify/monorepo-builder": "^12.7",
+ "twig/twig": "^3.4",
+ "yoast/phpunit-polyfills": "^4.0"
},
"autoload": {
"psr-4": {
@@ -123,6 +127,9 @@
"packages/ui/tests/Charcoal",
"packages/user/tests/Charcoal/",
"packages/view/tests/Charcoal"
+ ],
+ "Charcoal\\Rector\\Property\\": [
+ "src/Rector/Property/"
]
}
},
diff --git a/composer.lock b/composer.lock
index fdd9567eb..d8d440581 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,8 +4,97 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "29faccd918f465a35b04d246acab37e4",
+ "content-hash": "606558ecf298822aace0fbfc62f5c9bf",
"packages": [
+ {
+ "name": "assetic/framework",
+ "version": "v3.1.5",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/assetic-php/assetic.git",
+ "reference": "0dc41d117ac679dc21f46b7022d393ef02b3f781"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/assetic-php/assetic/zipball/0dc41d117ac679dc21f46b7022d393ef02b3f781",
+ "reference": "0dc41d117ac679dc21f46b7022d393ef02b3f781",
+ "shasum": ""
+ },
+ "require": {
+ "ext-curl": "*",
+ "ext-json": "*",
+ "ext-simplexml": "*",
+ "php": "^7.3 || ^8.0",
+ "symfony/deprecation-contracts": "^2.2.0 || ^3.0",
+ "symfony/process": "^3.4 || ^4.0 || ^5.0 || ^6.0 || ^7.0"
+ },
+ "replace": {
+ "kriswallsmith/assetic": "1.4.0"
+ },
+ "require-dev": {
+ "meenie/javascript-packer": "^1.1",
+ "phpspec/prophecy-phpunit": "^2.0",
+ "phpunit/phpunit": "^9.5.8",
+ "psr/log": "^1.0",
+ "ptachoire/cssembed": "^1.0",
+ "scssphp/scssphp": "^1.0",
+ "symfony/phpunit-bridge": "^3.4 || ^4.0 || ^5.0 || ^6.0 || ^7.0",
+ "twig/twig": "^2.11",
+ "wikimedia/less.php": "^3.0 || ^5.0",
+ "wikimedia/minify": "^2.2"
+ },
+ "suggest": {
+ "meenie/javascript-packer": "The Assetic\\Filter\\PackerFilter requires meenie/javascript-packer",
+ "ptachoire/cssembed": "The Assetic\\Filter\\PhpCssEmbedFilter requires ptachoire/cssembed",
+ "scssphp/scssphp": "The Assetic\\Filter\\ScssphpFilter requires scssphp/scssphp",
+ "twig/twig": "Assetic provides an integration with the Twig templating engine",
+ "wikimedia/less.php": "The Assetic\\Filter\\LessphpFilter requires wikimedia/less.php",
+ "wikimedia/minify": "The Assetic\\Filter\\JavaScriptMinifierFilter && Assetic\\Filter\\CSSMinFilter requires wikimedia/minify"
+ },
+ "type": "library",
+ "autoload": {
+ "files": [
+ "src/functions.php",
+ "src/aliasing.php"
+ ],
+ "psr-0": {
+ "Assetic": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Kris Wallsmith",
+ "email": "kris.wallsmith@gmail.com",
+ "homepage": "http://kriswallsmith.net/"
+ },
+ {
+ "name": "Jack Wilkinson",
+ "email": "me@jackwilky.com",
+ "homepage": "https://jackwilky.com/"
+ },
+ {
+ "name": "Luke Towers",
+ "email": "octobercms@luketowers.ca",
+ "homepage": "https://luketowers.ca"
+ }
+ ],
+ "description": "Asset Management for PHP",
+ "homepage": "https://github.com/assetic-php/assetic",
+ "keywords": [
+ "assets",
+ "compression",
+ "minification"
+ ],
+ "support": {
+ "issues": "https://github.com/assetic-php/assetic/issues",
+ "source": "https://github.com/assetic-php/assetic/tree/v3.1.5"
+ },
+ "time": "2026-04-23T03:30:22+00:00"
+ },
{
"name": "barryvdh/elfinder-flysystem-driver",
"version": "v0.3.0",
@@ -68,24 +157,24 @@
},
{
"name": "erusev/parsedown",
- "version": "1.7.4",
+ "version": "1.8.0",
"source": {
"type": "git",
"url": "https://github.com/erusev/parsedown.git",
- "reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3"
+ "reference": "96baaad00f71ba04d76e45b4620f54d3beabd6f7"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/erusev/parsedown/zipball/cb17b6477dfff935958ba01325f2e8a2bfa6dab3",
- "reference": "cb17b6477dfff935958ba01325f2e8a2bfa6dab3",
+ "url": "https://api.github.com/repos/erusev/parsedown/zipball/96baaad00f71ba04d76e45b4620f54d3beabd6f7",
+ "reference": "96baaad00f71ba04d76e45b4620f54d3beabd6f7",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
- "php": ">=5.3.0"
+ "php": ">=7.1"
},
"require-dev": {
- "phpunit/phpunit": "^4.8.35"
+ "phpunit/phpunit": "^7.5|^8.5|^9.6"
},
"type": "library",
"autoload": {
@@ -112,30 +201,36 @@
],
"support": {
"issues": "https://github.com/erusev/parsedown/issues",
- "source": "https://github.com/erusev/parsedown/tree/1.7.x"
+ "source": "https://github.com/erusev/parsedown/tree/1.8.0"
},
- "time": "2019-12-30T22:54:17+00:00"
+ "funding": [
+ {
+ "url": "https://github.com/erusev",
+ "type": "github"
+ }
+ ],
+ "time": "2026-02-16T11:41:01+00:00"
},
{
"name": "graham-campbell/result-type",
- "version": "v1.1.2",
+ "version": "v1.1.4",
"source": {
"type": "git",
"url": "https://github.com/GrahamCampbell/Result-Type.git",
- "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862"
+ "reference": "e01f4a821471308ba86aa202fed6698b6b695e3b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862",
- "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862",
+ "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/e01f4a821471308ba86aa202fed6698b6b695e3b",
+ "reference": "e01f4a821471308ba86aa202fed6698b6b695e3b",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
- "phpoption/phpoption": "^1.9.2"
+ "phpoption/phpoption": "^1.9.5"
},
"require-dev": {
- "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
+ "phpunit/phpunit": "^8.5.41 || ^9.6.22 || ^10.5.45 || ^11.5.7"
},
"type": "library",
"autoload": {
@@ -164,7 +259,7 @@
],
"support": {
"issues": "https://github.com/GrahamCampbell/Result-Type/issues",
- "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2"
+ "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.4"
},
"funding": [
{
@@ -176,26 +271,26 @@
"type": "tidelift"
}
],
- "time": "2023-11-12T22:16:48+00:00"
+ "time": "2025-12-27T19:43:20+00:00"
},
{
"name": "guzzlehttp/guzzle",
- "version": "7.8.1",
+ "version": "7.10.5",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
- "reference": "41042bc7ab002487b876a0683fc8dce04ddce104"
+ "reference": "7c8d84b39e680315f687e8662a9d6fb0865c5148"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/guzzle/guzzle/zipball/41042bc7ab002487b876a0683fc8dce04ddce104",
- "reference": "41042bc7ab002487b876a0683fc8dce04ddce104",
+ "url": "https://api.github.com/repos/guzzle/guzzle/zipball/7c8d84b39e680315f687e8662a9d6fb0865c5148",
+ "reference": "7c8d84b39e680315f687e8662a9d6fb0865c5148",
"shasum": ""
},
"require": {
"ext-json": "*",
- "guzzlehttp/promises": "^1.5.3 || ^2.0.1",
- "guzzlehttp/psr7": "^1.9.1 || ^2.5.1",
+ "guzzlehttp/promises": "^2.3",
+ "guzzlehttp/psr7": "^2.8",
"php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2 || ^3.0"
@@ -206,9 +301,10 @@
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"ext-curl": "*",
- "php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999",
+ "guzzle/client-integration-tests": "3.0.2",
+ "guzzlehttp/test-server": "^0.4",
"php-http/message-factory": "^1.1",
- "phpunit/phpunit": "^8.5.36 || ^9.6.15",
+ "phpunit/phpunit": "^8.5.52 || ^9.6.34",
"psr/log": "^1.1 || ^2.0 || ^3.0"
},
"suggest": {
@@ -286,7 +382,7 @@
],
"support": {
"issues": "https://github.com/guzzle/guzzle/issues",
- "source": "https://github.com/guzzle/guzzle/tree/7.8.1"
+ "source": "https://github.com/guzzle/guzzle/tree/7.10.5"
},
"funding": [
{
@@ -302,20 +398,20 @@
"type": "tidelift"
}
],
- "time": "2023-12-03T20:35:24+00:00"
+ "time": "2026-05-27T11:53:46+00:00"
},
{
"name": "guzzlehttp/promises",
- "version": "2.0.2",
+ "version": "2.4.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
- "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223"
+ "reference": "09e8a212562fb1fb6a512c4156ed71525969d6c2"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/guzzle/promises/zipball/bbff78d96034045e58e13dedd6ad91b5d1253223",
- "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223",
+ "url": "https://api.github.com/repos/guzzle/promises/zipball/09e8a212562fb1fb6a512c4156ed71525969d6c2",
+ "reference": "09e8a212562fb1fb6a512c4156ed71525969d6c2",
"shasum": ""
},
"require": {
@@ -323,7 +419,7 @@
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
- "phpunit/phpunit": "^8.5.36 || ^9.6.15"
+ "phpunit/phpunit": "^8.5.52 || ^9.6.34"
},
"type": "library",
"extra": {
@@ -369,7 +465,7 @@
],
"support": {
"issues": "https://github.com/guzzle/promises/issues",
- "source": "https://github.com/guzzle/promises/tree/2.0.2"
+ "source": "https://github.com/guzzle/promises/tree/2.4.1"
},
"funding": [
{
@@ -385,20 +481,20 @@
"type": "tidelift"
}
],
- "time": "2023-12-03T20:19:20+00:00"
+ "time": "2026-05-20T22:57:30+00:00"
},
{
"name": "guzzlehttp/psr7",
- "version": "2.6.2",
+ "version": "2.10.4",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
- "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221"
+ "reference": "d2a1a094e396da8957e797489fddaf860c340cfc"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/guzzle/psr7/zipball/45b30f99ac27b5ca93cb4831afe16285f57b8221",
- "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221",
+ "url": "https://api.github.com/repos/guzzle/psr7/zipball/d2a1a094e396da8957e797489fddaf860c340cfc",
+ "reference": "d2a1a094e396da8957e797489fddaf860c340cfc",
"shasum": ""
},
"require": {
@@ -413,8 +509,9 @@
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
- "http-interop/http-factory-tests": "^0.9",
- "phpunit/phpunit": "^8.5.36 || ^9.6.15"
+ "http-interop/http-factory-tests": "1.1.0",
+ "jshttp/mime-db": "1.54.0.1",
+ "phpunit/phpunit": "^8.5.52 || ^9.6.34"
},
"suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
@@ -485,7 +582,7 @@
],
"support": {
"issues": "https://github.com/guzzle/psr7/issues",
- "source": "https://github.com/guzzle/psr7/tree/2.6.2"
+ "source": "https://github.com/guzzle/psr7/tree/2.10.4"
},
"funding": [
{
@@ -501,7 +598,7 @@
"type": "tidelift"
}
],
- "time": "2023-12-03T20:05:35+00:00"
+ "time": "2026-05-29T12:59:07+00:00"
},
{
"name": "intervention/image",
@@ -533,16 +630,16 @@
},
"type": "library",
"extra": {
- "branch-alias": {
- "dev-master": "2.4-dev"
- },
"laravel": {
- "providers": [
- "Intervention\\Image\\ImageServiceProvider"
- ],
"aliases": {
"Image": "Intervention\\Image\\Facades\\Image"
- }
+ },
+ "providers": [
+ "Intervention\\Image\\ImageServiceProvider"
+ ]
+ },
+ "branch-alias": {
+ "dev-master": "2.4-dev"
}
},
"autoload": {
@@ -587,114 +684,34 @@
],
"time": "2022-05-21T17:30:32+00:00"
},
- {
- "name": "kriswallsmith/assetic",
- "version": "v1.4.0",
- "source": {
- "type": "git",
- "url": "https://github.com/kriswallsmith/assetic.git",
- "reference": "e911c437dbdf006a8f62c2f59b15b2d69a5e0aa1"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/kriswallsmith/assetic/zipball/e911c437dbdf006a8f62c2f59b15b2d69a5e0aa1",
- "reference": "e911c437dbdf006a8f62c2f59b15b2d69a5e0aa1",
- "shasum": ""
- },
- "require": {
- "php": ">=5.3.1",
- "symfony/process": "~2.1|~3.0"
- },
- "conflict": {
- "twig/twig": "<1.27"
- },
- "require-dev": {
- "leafo/lessphp": "^0.3.7",
- "leafo/scssphp": "~0.1",
- "meenie/javascript-packer": "^1.1",
- "mrclay/minify": "<2.3",
- "natxet/cssmin": "3.0.4",
- "patchwork/jsqueeze": "~1.0|~2.0",
- "phpunit/phpunit": "~4.8 || ^5.6",
- "psr/log": "~1.0",
- "ptachoire/cssembed": "~1.0",
- "symfony/phpunit-bridge": "~2.7|~3.0",
- "twig/twig": "~1.23|~2.0",
- "yfix/packager": "dev-master"
- },
- "suggest": {
- "leafo/lessphp": "Assetic provides the integration with the lessphp LESS compiler",
- "leafo/scssphp": "Assetic provides the integration with the scssphp SCSS compiler",
- "leafo/scssphp-compass": "Assetic provides the integration with the SCSS compass plugin",
- "patchwork/jsqueeze": "Assetic provides the integration with the JSqueeze JavaScript compressor",
- "ptachoire/cssembed": "Assetic provides the integration with phpcssembed to embed data uris",
- "twig/twig": "Assetic provides the integration with the Twig templating engine"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.4-dev"
- }
- },
- "autoload": {
- "files": [
- "src/functions.php"
- ],
- "psr-0": {
- "Assetic": "src/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Kris Wallsmith",
- "email": "kris.wallsmith@gmail.com",
- "homepage": "http://kriswallsmith.net/"
- }
- ],
- "description": "Asset Management for PHP",
- "homepage": "https://github.com/kriswallsmith/assetic",
- "keywords": [
- "assets",
- "compression",
- "minification"
- ],
- "support": {
- "issues": "https://github.com/kriswallsmith/assetic/issues",
- "source": "https://github.com/kriswallsmith/assetic/tree/master"
- },
- "time": "2016-11-11T18:43:20+00:00"
- },
{
"name": "laminas/laminas-permissions-acl",
- "version": "2.10.0",
+ "version": "2.18.0",
"source": {
"type": "git",
"url": "https://github.com/laminas/laminas-permissions-acl.git",
- "reference": "e927ae0a3001655fea97eb240eeea9d10638e82f"
+ "reference": "5940f6e7b9e2e3eba671f13dd26e610d2fe9acc3"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laminas/laminas-permissions-acl/zipball/e927ae0a3001655fea97eb240eeea9d10638e82f",
- "reference": "e927ae0a3001655fea97eb240eeea9d10638e82f",
+ "url": "https://api.github.com/repos/laminas/laminas-permissions-acl/zipball/5940f6e7b9e2e3eba671f13dd26e610d2fe9acc3",
+ "reference": "5940f6e7b9e2e3eba671f13dd26e610d2fe9acc3",
"shasum": ""
},
"require": {
- "php": "^7.4 || ~8.0.0 || ~8.1.0"
+ "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0"
},
"conflict": {
"laminas/laminas-servicemanager": "<3.0",
"zendframework/zend-permissions-acl": "*"
},
"require-dev": {
- "laminas/laminas-coding-standard": "~2.3.0",
- "laminas/laminas-servicemanager": "^3.15.1",
- "phpunit/phpunit": "^9.5.0",
- "psalm/plugin-phpunit": "^0.17.0",
- "vimeo/psalm": "^4.24.0"
+ "laminas/laminas-coding-standard": "^3.0.1",
+ "laminas/laminas-servicemanager": "^3.21",
+ "phpbench/phpbench": "^1.2.10",
+ "phpunit/phpunit": "^10.5.58",
+ "psalm/plugin-phpunit": "^0.19.0",
+ "vimeo/psalm": "^6.13.1"
},
"suggest": {
"laminas/laminas-servicemanager": "To support Laminas\\Permissions\\Acl\\Assertion\\AssertionManager plugin manager usage"
@@ -729,20 +746,20 @@
"type": "community_bridge"
}
],
- "time": "2022-07-21T09:23:39+00:00"
+ "time": "2025-11-03T09:15:20+00:00"
},
{
"name": "league/climate",
- "version": "3.8.2",
+ "version": "3.10.1",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/climate.git",
- "reference": "a785a3ac8f584eed4abd45e4e16fe64c46659a28"
+ "reference": "f2d78fbc504740bcd0209e40a4586c886567ddc9"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/thephpleague/climate/zipball/a785a3ac8f584eed4abd45e4e16fe64c46659a28",
- "reference": "a785a3ac8f584eed4abd45e4e16fe64c46659a28",
+ "url": "https://api.github.com/repos/thephpleague/climate/zipball/f2d78fbc504740bcd0209e40a4586c886567ddc9",
+ "reference": "f2d78fbc504740bcd0209e40a4586c886567ddc9",
"shasum": ""
},
"require": {
@@ -751,9 +768,10 @@
"seld/cli-prompt": "^1.0"
},
"require-dev": {
- "mikey179/vfsstream": "^1.6.10",
- "mockery/mockery": "^1.4.2",
- "phpunit/phpunit": "^9.5.10"
+ "mikey179/vfsstream": "^1.6.12",
+ "mockery/mockery": "^1.6.12",
+ "phpunit/phpunit": "^9.6.21",
+ "squizlabs/php_codesniffer": "^3.10"
},
"suggest": {
"ext-mbstring": "If ext-mbstring is not available you MUST install symfony/polyfill-mbstring"
@@ -792,9 +810,9 @@
],
"support": {
"issues": "https://github.com/thephpleague/climate/issues",
- "source": "https://github.com/thephpleague/climate/tree/3.8.2"
+ "source": "https://github.com/thephpleague/climate/tree/3.10.1"
},
- "time": "2022-06-18T14:42:08+00:00"
+ "time": "2026-03-19T19:32:55+00:00"
},
{
"name": "league/flysystem",
@@ -892,26 +910,26 @@
},
{
"name": "league/flysystem-cached-adapter",
- "version": "1.1.0",
+ "version": "1.0.2",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/flysystem-cached-adapter.git",
- "reference": "d1925efb2207ac4be3ad0c40b8277175f99ffaff"
+ "reference": "7bb5cd9d996904cf43d7da8ba45a724ff8c7ef14"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/thephpleague/flysystem-cached-adapter/zipball/d1925efb2207ac4be3ad0c40b8277175f99ffaff",
- "reference": "d1925efb2207ac4be3ad0c40b8277175f99ffaff",
+ "url": "https://api.github.com/repos/thephpleague/flysystem-cached-adapter/zipball/7bb5cd9d996904cf43d7da8ba45a724ff8c7ef14",
+ "reference": "7bb5cd9d996904cf43d7da8ba45a724ff8c7ef14",
"shasum": ""
},
"require": {
- "league/flysystem": "~1.0",
- "psr/cache": "^1.0.0"
+ "league/flysystem": "~1.0"
},
"require-dev": {
+ "henrikbjorn/phpspec-code-coverage": "~1.0@dev",
"mockery/mockery": "~0.9",
- "phpspec/phpspec": "^3.4",
- "phpunit/phpunit": "^5.7",
+ "phpspec/phpspec": "~2.1",
+ "phpunit/phpunit": "~4.1",
"predis/predis": "~1.0",
"tedivm/stash": "~0.12"
},
@@ -939,20 +957,20 @@
"issues": "https://github.com/thephpleague/flysystem-cached-adapter/issues",
"source": "https://github.com/thephpleague/flysystem-cached-adapter/tree/master"
},
- "time": "2020-07-25T15:56:04+00:00"
+ "time": "2015-07-09T21:00:39+00:00"
},
{
"name": "league/mime-type-detection",
- "version": "1.14.0",
+ "version": "1.16.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/mime-type-detection.git",
- "reference": "b6a5854368533df0295c5761a0253656a2e52d9e"
+ "reference": "2d6702ff215bf922936ccc1ad31007edc76451b9"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/thephpleague/mime-type-detection/zipball/b6a5854368533df0295c5761a0253656a2e52d9e",
- "reference": "b6a5854368533df0295c5761a0253656a2e52d9e",
+ "url": "https://api.github.com/repos/thephpleague/mime-type-detection/zipball/2d6702ff215bf922936ccc1ad31007edc76451b9",
+ "reference": "2d6702ff215bf922936ccc1ad31007edc76451b9",
"shasum": ""
},
"require": {
@@ -983,7 +1001,7 @@
"description": "Mime-type detection for Flysystem",
"support": {
"issues": "https://github.com/thephpleague/mime-type-detection/issues",
- "source": "https://github.com/thephpleague/mime-type-detection/tree/1.14.0"
+ "source": "https://github.com/thephpleague/mime-type-detection/tree/1.16.0"
},
"funding": [
{
@@ -995,25 +1013,25 @@
"type": "tidelift"
}
],
- "time": "2023-10-17T14:13:20+00:00"
+ "time": "2024-09-21T08:32:55+00:00"
},
{
"name": "mcaskill/php-html-build-attributes",
- "version": "v1.3.0",
+ "version": "v1.4.0",
"source": {
"type": "git",
"url": "https://github.com/mcaskill/php-html-build-attributes.git",
- "reference": "2f0390b856610b7da2c235263a5a7d90bade64e4"
+ "reference": "ae8753fcfccec6f5aa08392b95a4fc949ce870cb"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/mcaskill/php-html-build-attributes/zipball/2f0390b856610b7da2c235263a5a7d90bade64e4",
- "reference": "2f0390b856610b7da2c235263a5a7d90bade64e4",
+ "url": "https://api.github.com/repos/mcaskill/php-html-build-attributes/zipball/ae8753fcfccec6f5aa08392b95a4fc949ce870cb",
+ "reference": "ae8753fcfccec6f5aa08392b95a4fc949ce870cb",
"shasum": ""
},
"require": {
"ext-json": "*",
- "php": ">=5.4.0"
+ "php": ">=7.1.0"
},
"require-dev": {
"pestphp/pest": "^1.22",
@@ -1044,9 +1062,9 @@
],
"support": {
"issues": "https://github.com/mcaskill/php-html-build-attributes/issues",
- "source": "https://github.com/mcaskill/php-html-build-attributes/tree/v1.3.0"
+ "source": "https://github.com/mcaskill/php-html-build-attributes/tree/v1.4.0"
},
- "time": "2023-08-09T03:09:43+00:00"
+ "time": "2025-07-18T17:25:44+00:00"
},
{
"name": "monolog/monolog",
@@ -1186,16 +1204,16 @@
},
{
"name": "phpmailer/phpmailer",
- "version": "v6.9.1",
+ "version": "v6.12.0",
"source": {
"type": "git",
"url": "https://github.com/PHPMailer/PHPMailer.git",
- "reference": "039de174cd9c17a8389754d3b877a2ed22743e18"
+ "reference": "d1ac35d784bf9f5e61b424901d5a014967f15b12"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/039de174cd9c17a8389754d3b877a2ed22743e18",
- "reference": "039de174cd9c17a8389754d3b877a2ed22743e18",
+ "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/d1ac35d784bf9f5e61b424901d5a014967f15b12",
+ "reference": "d1ac35d784bf9f5e61b424901d5a014967f15b12",
"shasum": ""
},
"require": {
@@ -1255,7 +1273,7 @@
"description": "PHPMailer is a full-featured email creation and transfer class for PHP",
"support": {
"issues": "https://github.com/PHPMailer/PHPMailer/issues",
- "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.9.1"
+ "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.12.0"
},
"funding": [
{
@@ -1263,20 +1281,20 @@
"type": "github"
}
],
- "time": "2023-11-25T22:23:28+00:00"
+ "time": "2025-10-15T16:49:08+00:00"
},
{
"name": "phpoption/phpoption",
- "version": "1.9.2",
+ "version": "1.9.5",
"source": {
"type": "git",
"url": "https://github.com/schmittjoh/php-option.git",
- "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820"
+ "reference": "75365b91986c2405cf5e1e012c5595cd487a98be"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820",
- "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820",
+ "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/75365b91986c2405cf5e1e012c5595cd487a98be",
+ "reference": "75365b91986c2405cf5e1e012c5595cd487a98be",
"shasum": ""
},
"require": {
@@ -1284,13 +1302,13 @@
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
- "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
+ "phpunit/phpunit": "^8.5.44 || ^9.6.25 || ^10.5.53 || ^11.5.34"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
- "forward-command": true
+ "forward-command": false
},
"branch-alias": {
"dev-master": "1.9-dev"
@@ -1326,7 +1344,7 @@
],
"support": {
"issues": "https://github.com/schmittjoh/php-option/issues",
- "source": "https://github.com/schmittjoh/php-option/tree/1.9.2"
+ "source": "https://github.com/schmittjoh/php-option/tree/1.9.5"
},
"funding": [
{
@@ -1338,20 +1356,20 @@
"type": "tidelift"
}
],
- "time": "2023-11-12T21:59:55+00:00"
+ "time": "2025-12-27T19:41:33+00:00"
},
{
"name": "pimple/pimple",
- "version": "v3.5.0",
+ "version": "v3.6.2",
"source": {
"type": "git",
"url": "https://github.com/silexphp/Pimple.git",
- "reference": "a94b3a4db7fb774b3d78dad2315ddc07629e1bed"
+ "reference": "8cfe7f74ac22a433d303914eba9ea4c2a834edce"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/silexphp/Pimple/zipball/a94b3a4db7fb774b3d78dad2315ddc07629e1bed",
- "reference": "a94b3a4db7fb774b3d78dad2315ddc07629e1bed",
+ "url": "https://api.github.com/repos/silexphp/Pimple/zipball/8cfe7f74ac22a433d303914eba9ea4c2a834edce",
+ "reference": "8cfe7f74ac22a433d303914eba9ea4c2a834edce",
"shasum": ""
},
"require": {
@@ -1359,12 +1377,12 @@
"psr/container": "^1.1 || ^2.0"
},
"require-dev": {
- "symfony/phpunit-bridge": "^5.4@dev"
+ "phpunit/phpunit": "*"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "3.4.x-dev"
+ "dev-master": "3.x-dev"
}
},
"autoload": {
@@ -1389,26 +1407,26 @@
"dependency injection"
],
"support": {
- "source": "https://github.com/silexphp/Pimple/tree/v3.5.0"
+ "source": "https://github.com/silexphp/Pimple/tree/v3.6.2"
},
- "time": "2021-10-28T11:13:42+00:00"
+ "time": "2026-02-26T08:23:44+00:00"
},
{
"name": "psr/cache",
- "version": "1.0.1",
+ "version": "2.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/cache.git",
- "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8"
+ "reference": "213f9dbc5b9bfbc4f8db86d2838dc968752ce13b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8",
- "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8",
+ "url": "https://api.github.com/repos/php-fig/cache/zipball/213f9dbc5b9bfbc4f8db86d2838dc968752ce13b",
+ "reference": "213f9dbc5b9bfbc4f8db86d2838dc968752ce13b",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": ">=8.0.0"
},
"type": "library",
"extra": {
@@ -1428,7 +1446,7 @@
"authors": [
{
"name": "PHP-FIG",
- "homepage": "http://www.php-fig.org/"
+ "homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for caching libraries",
@@ -1438,9 +1456,9 @@
"psr-6"
],
"support": {
- "source": "https://github.com/php-fig/cache/tree/master"
+ "source": "https://github.com/php-fig/cache/tree/2.0.0"
},
- "time": "2016-08-06T20:24:11+00:00"
+ "time": "2021-02-03T23:23:37+00:00"
},
{
"name": "psr/container",
@@ -1544,20 +1562,20 @@
},
{
"name": "psr/http-factory",
- "version": "1.0.2",
+ "version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
- "reference": "e616d01114759c4c489f93b099585439f795fe35"
+ "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35",
- "reference": "e616d01114759c4c489f93b099585439f795fe35",
+ "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
+ "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"shasum": ""
},
"require": {
- "php": ">=7.0.0",
+ "php": ">=7.1",
"psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
@@ -1581,7 +1599,7 @@
"homepage": "https://www.php-fig.org/"
}
],
- "description": "Common interfaces for PSR-7 HTTP message factories",
+ "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
@@ -1593,9 +1611,9 @@
"response"
],
"support": {
- "source": "https://github.com/php-fig/http-factory/tree/1.0.2"
+ "source": "https://github.com/php-fig/http-factory"
},
- "time": "2023-04-10T20:10:41+00:00"
+ "time": "2024-04-15T12:06:14+00:00"
},
{
"name": "psr/http-message",
@@ -1801,23 +1819,23 @@
},
{
"name": "seld/jsonlint",
- "version": "1.10.1",
+ "version": "1.11.0",
"source": {
"type": "git",
"url": "https://github.com/Seldaek/jsonlint.git",
- "reference": "76d449a358ece77d6f1d6331c68453e657172202"
+ "reference": "1748aaf847fc731cfad7725aec413ee46f0cc3a2"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/Seldaek/jsonlint/zipball/76d449a358ece77d6f1d6331c68453e657172202",
- "reference": "76d449a358ece77d6f1d6331c68453e657172202",
+ "url": "https://api.github.com/repos/Seldaek/jsonlint/zipball/1748aaf847fc731cfad7725aec413ee46f0cc3a2",
+ "reference": "1748aaf847fc731cfad7725aec413ee46f0cc3a2",
"shasum": ""
},
"require": {
"php": "^5.3 || ^7.0 || ^8.0"
},
"require-dev": {
- "phpstan/phpstan": "^1.5",
+ "phpstan/phpstan": "^1.11",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0 || ^8.5.13"
},
"bin": [
@@ -1849,7 +1867,7 @@
],
"support": {
"issues": "https://github.com/Seldaek/jsonlint/issues",
- "source": "https://github.com/Seldaek/jsonlint/tree/1.10.1"
+ "source": "https://github.com/Seldaek/jsonlint/tree/1.11.0"
},
"funding": [
{
@@ -1861,20 +1879,20 @@
"type": "tidelift"
}
],
- "time": "2023-12-18T13:03:25+00:00"
+ "time": "2024-07-11T14:55:45+00:00"
},
{
"name": "slim/slim",
- "version": "3.12.5",
+ "version": "3.13.0",
"source": {
"type": "git",
"url": "https://github.com/slimphp/Slim.git",
- "reference": "565632b2d9b64ecedf89546edbbf4f3648089f0c"
+ "reference": "f899a6e0be000b9e56d164a4241aa60ab8f33c7f"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/slimphp/Slim/zipball/565632b2d9b64ecedf89546edbbf4f3648089f0c",
- "reference": "565632b2d9b64ecedf89546edbbf4f3648089f0c",
+ "url": "https://api.github.com/repos/slimphp/Slim/zipball/f899a6e0be000b9e56d164a4241aa60ab8f33c7f",
+ "reference": "f899a6e0be000b9e56d164a4241aa60ab8f33c7f",
"shasum": ""
},
"require": {
@@ -1882,7 +1900,7 @@
"ext-libxml": "*",
"ext-simplexml": "*",
"nikic/fast-route": "^1.0",
- "php": ">=5.5.0",
+ "php": "^8.1",
"pimple/pimple": "^3.0",
"psr/container": "^1.0",
"psr/http-message": "^1.0"
@@ -1891,7 +1909,8 @@
"psr/http-message-implementation": "1.0"
},
"require-dev": {
- "phpunit/phpunit": "^4.0",
+ "phpstan/phpstan": "^2.1",
+ "phpunit/phpunit": "^10.5",
"squizlabs/php_codesniffer": "^3.6.0"
},
"type": "library",
@@ -1936,7 +1955,7 @@
],
"support": {
"issues": "https://github.com/slimphp/Slim/issues",
- "source": "https://github.com/slimphp/Slim/tree/3.12.5"
+ "source": "https://github.com/slimphp/Slim/tree/3.13.0"
},
"funding": [
{
@@ -1948,20 +1967,20 @@
"type": "tidelift"
}
],
- "time": "2023-07-23T04:32:51+00:00"
+ "time": "2026-04-28T08:53:26+00:00"
},
{
"name": "studio-42/elfinder",
- "version": "2.1.64",
+ "version": "2.1.69",
"source": {
"type": "git",
"url": "https://github.com/Studio-42/elFinder.git",
- "reference": "deaa6797df1c6f288238b47284c9b593174bfc0f"
+ "reference": "8f2c3ffafcdd52cf4515f1eec172f4eee44552ad"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/Studio-42/elFinder/zipball/deaa6797df1c6f288238b47284c9b593174bfc0f",
- "reference": "deaa6797df1c6f288238b47284c9b593174bfc0f",
+ "url": "https://api.github.com/repos/Studio-42/elFinder/zipball/8f2c3ffafcdd52cf4515f1eec172f4eee44552ad",
+ "reference": "8f2c3ffafcdd52cf4515f1eec172f4eee44552ad",
"shasum": ""
},
"require": {
@@ -2008,7 +2027,7 @@
"homepage": "http://elfinder.org",
"support": {
"issues": "https://github.com/Studio-42/elFinder/issues",
- "source": "https://github.com/Studio-42/elFinder/tree/2.1.64"
+ "source": "https://github.com/Studio-42/elFinder/tree/2.1.69"
},
"funding": [
{
@@ -2016,33 +2035,33 @@
"type": "github"
}
],
- "time": "2023-12-20T07:43:10+00:00"
+ "time": "2026-05-07T12:53:30+00:00"
},
{
"name": "symfony/deprecation-contracts",
- "version": "v2.5.2",
+ "version": "v3.7.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
- "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66"
+ "reference": "50f59d1f3ca46d41ac911f97a78626b6756af35b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/e8b495ea28c1d97b5e0c121748d6f9b53d075c66",
- "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66",
+ "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/50f59d1f3ca46d41ac911f97a78626b6756af35b",
+ "reference": "50f59d1f3ca46d41ac911f97a78626b6756af35b",
"shasum": ""
},
"require": {
- "php": ">=7.1"
+ "php": ">=8.1"
},
"type": "library",
"extra": {
- "branch-alias": {
- "dev-main": "2.5-dev"
- },
"thanks": {
- "name": "symfony/contracts",
- "url": "https://github.com/symfony/contracts"
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.7-dev"
}
},
"autoload": {
@@ -2067,7 +2086,7 @@
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
- "source": "https://github.com/symfony/deprecation-contracts/tree/v2.5.2"
+ "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.0"
},
"funding": [
{
@@ -2078,29 +2097,33 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2022-01-02T09:53:40+00:00"
+ "time": "2026-04-13T15:52:40+00:00"
},
{
"name": "symfony/polyfill-ctype",
- "version": "v1.28.0",
+ "version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
- "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb"
+ "reference": "141046a8f9477948ff284fa65be2095baafb94f2"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb",
- "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb",
+ "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/141046a8f9477948ff284fa65be2095baafb94f2",
+ "reference": "141046a8f9477948ff284fa65be2095baafb94f2",
"shasum": ""
},
"require": {
- "php": ">=7.1"
+ "php": ">=7.2"
},
"provide": {
"ext-ctype": "*"
@@ -2110,12 +2133,9 @@
},
"type": "library",
"extra": {
- "branch-alias": {
- "dev-main": "1.28-dev"
- },
"thanks": {
- "name": "symfony/polyfill",
- "url": "https://github.com/symfony/polyfill"
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
}
},
"autoload": {
@@ -2149,7 +2169,7 @@
"portable"
],
"support": {
- "source": "https://github.com/symfony/polyfill-ctype/tree/v1.28.0"
+ "source": "https://github.com/symfony/polyfill-ctype/tree/v1.37.0"
},
"funding": [
{
@@ -2160,29 +2180,34 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-01-26T09:26:14+00:00"
+ "time": "2026-04-10T16:19:22+00:00"
},
{
"name": "symfony/polyfill-mbstring",
- "version": "v1.28.0",
+ "version": "v1.38.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
- "reference": "42292d99c55abe617799667f454222c54c60e229"
+ "reference": "14c5439eec4ccff081ac14eca2dc57feb2a66d92"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/42292d99c55abe617799667f454222c54c60e229",
- "reference": "42292d99c55abe617799667f454222c54c60e229",
+ "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/14c5439eec4ccff081ac14eca2dc57feb2a66d92",
+ "reference": "14c5439eec4ccff081ac14eca2dc57feb2a66d92",
"shasum": ""
},
"require": {
- "php": ">=7.1"
+ "ext-iconv": "*",
+ "php": ">=7.2"
},
"provide": {
"ext-mbstring": "*"
@@ -2192,12 +2217,9 @@
},
"type": "library",
"extra": {
- "branch-alias": {
- "dev-main": "1.28-dev"
- },
"thanks": {
- "name": "symfony/polyfill",
- "url": "https://github.com/symfony/polyfill"
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
}
},
"autoload": {
@@ -2232,7 +2254,7 @@
"shim"
],
"support": {
- "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.28.0"
+ "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.38.1"
},
"funding": [
{
@@ -2243,38 +2265,39 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-07-28T09:04:16+00:00"
+ "time": "2026-05-26T12:51:13+00:00"
},
{
"name": "symfony/polyfill-php80",
- "version": "v1.28.0",
+ "version": "v1.37.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php80.git",
- "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5"
+ "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5",
- "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5",
+ "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
+ "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
"shasum": ""
},
"require": {
- "php": ">=7.1"
+ "php": ">=7.2"
},
"type": "library",
"extra": {
- "branch-alias": {
- "dev-main": "1.28-dev"
- },
"thanks": {
- "name": "symfony/polyfill",
- "url": "https://github.com/symfony/polyfill"
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
}
},
"autoload": {
@@ -2315,7 +2338,7 @@
"shim"
],
"support": {
- "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0"
+ "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0"
},
"funding": [
{
@@ -2326,37 +2349,50 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-01-26T09:26:14+00:00"
+ "time": "2026-04-10T16:19:22+00:00"
},
{
- "name": "symfony/process",
- "version": "v3.4.47",
+ "name": "symfony/polyfill-php85",
+ "version": "v1.38.1",
"source": {
"type": "git",
- "url": "https://github.com/symfony/process.git",
- "reference": "b8648cf1d5af12a44a51d07ef9bf980921f15fca"
+ "url": "https://github.com/symfony/polyfill-php85.git",
+ "reference": "ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/process/zipball/b8648cf1d5af12a44a51d07ef9bf980921f15fca",
- "reference": "b8648cf1d5af12a44a51d07ef9bf980921f15fca",
+ "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1",
+ "reference": "ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1",
"shasum": ""
},
"require": {
- "php": "^5.5.9|>=7.0.8"
+ "php": ">=7.2"
},
"type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
"autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
"psr-4": {
- "Symfony\\Component\\Process\\": ""
+ "Symfony\\Polyfill\\Php85\\": ""
},
- "exclude-from-classmap": [
- "/Tests/"
+ "classmap": [
+ "Resources/stubs"
]
},
"notification-url": "https://packagist.org/downloads/",
@@ -2365,18 +2401,24 @@
],
"authors": [
{
- "name": "Fabien Potencier",
- "email": "fabien@symfony.com"
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Symfony Process Component",
+ "description": "Symfony polyfill backporting some PHP 8.5+ features to lower PHP versions",
"homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
"support": {
- "source": "https://github.com/symfony/process/tree/v3.4.47"
+ "source": "https://github.com/symfony/polyfill-php85/tree/v1.38.1"
},
"funding": [
{
@@ -2387,55 +2429,38 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2020-10-24T10:57:07+00:00"
+ "time": "2026-05-26T02:25:22+00:00"
},
{
- "name": "symfony/translation",
- "version": "v3.4.47",
+ "name": "symfony/process",
+ "version": "v7.4.13",
"source": {
"type": "git",
- "url": "https://github.com/symfony/translation.git",
- "reference": "be83ee6c065cb32becdb306ba61160d598b1ce88"
+ "url": "https://github.com/symfony/process.git",
+ "reference": "f5804be144caceb570f6747519999636b664f24c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/translation/zipball/be83ee6c065cb32becdb306ba61160d598b1ce88",
- "reference": "be83ee6c065cb32becdb306ba61160d598b1ce88",
+ "url": "https://api.github.com/repos/symfony/process/zipball/f5804be144caceb570f6747519999636b664f24c",
+ "reference": "f5804be144caceb570f6747519999636b664f24c",
"shasum": ""
},
"require": {
- "php": "^5.5.9|>=7.0.8",
- "symfony/polyfill-mbstring": "~1.0"
- },
- "conflict": {
- "symfony/config": "<2.8",
- "symfony/dependency-injection": "<3.4",
- "symfony/yaml": "<3.4"
- },
- "require-dev": {
- "psr/log": "~1.0",
- "symfony/config": "~2.8|~3.0|~4.0",
- "symfony/dependency-injection": "~3.4|~4.0",
- "symfony/finder": "~2.8|~3.0|~4.0",
- "symfony/http-kernel": "~3.4|~4.0",
- "symfony/intl": "^2.8.18|^3.2.5|~4.0",
- "symfony/var-dumper": "~3.4|~4.0",
- "symfony/yaml": "~3.4|~4.0"
- },
- "suggest": {
- "psr/log-implementation": "To use logging capability in translator",
- "symfony/config": "",
- "symfony/yaml": ""
+ "php": ">=8.2"
},
"type": "library",
"autoload": {
"psr-4": {
- "Symfony\\Component\\Translation\\": ""
+ "Symfony\\Component\\Process\\": ""
},
"exclude-from-classmap": [
"/Tests/"
@@ -2455,10 +2480,10 @@
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Symfony Translation Component",
+ "description": "Executes commands in sub-processes",
"homepage": "https://symfony.com",
"support": {
- "source": "https://github.com/symfony/translation/tree/v3.4.47"
+ "source": "https://github.com/symfony/process/tree/v7.4.13"
},
"funding": [
{
@@ -2469,111 +2494,296 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2020-10-24T10:57:07+00:00"
+ "time": "2026-05-23T16:05:06+00:00"
},
{
- "name": "tedivm/stash",
- "version": "v0.17.6",
+ "name": "symfony/translation",
+ "version": "v7.4.10",
"source": {
"type": "git",
- "url": "https://github.com/tedious/Stash.git",
- "reference": "a2c9df16c77b13e1f90462f30597a772166eea8f"
+ "url": "https://github.com/symfony/translation.git",
+ "reference": "ada7578c30dd5feaa8259cff3e885069ea81ddde"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/tedious/Stash/zipball/a2c9df16c77b13e1f90462f30597a772166eea8f",
- "reference": "a2c9df16c77b13e1f90462f30597a772166eea8f",
+ "url": "https://api.github.com/repos/symfony/translation/zipball/ada7578c30dd5feaa8259cff3e885069ea81ddde",
+ "reference": "ada7578c30dd5feaa8259cff3e885069ea81ddde",
"shasum": ""
},
"require": {
- "php": ">7.0",
- "psr/cache": "~1.0"
+ "php": ">=8.2",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-mbstring": "~1.0",
+ "symfony/translation-contracts": "^2.5.3|^3.3"
+ },
+ "conflict": {
+ "nikic/php-parser": "<5.0",
+ "symfony/config": "<6.4",
+ "symfony/console": "<6.4",
+ "symfony/dependency-injection": "<6.4",
+ "symfony/http-client-contracts": "<2.5",
+ "symfony/http-kernel": "<6.4",
+ "symfony/service-contracts": "<2.5",
+ "symfony/twig-bundle": "<6.4",
+ "symfony/yaml": "<6.4"
},
"provide": {
- "psr/cache-implementation": "1.0.0"
+ "symfony/translation-implementation": "2.3|3.0"
},
"require-dev": {
- "dms/phpunit-arraysubset-asserts": "^0.4.0",
- "friendsofphp/php-cs-fixer": "^2.8",
- "php": "^7.2|^8.0",
- "php-coveralls/php-coveralls": "^2.0",
- "phpunit/phpunit": "^9.0"
+ "nikic/php-parser": "^5.0",
+ "psr/log": "^1|^2|^3",
+ "symfony/config": "^6.4|^7.0|^8.0",
+ "symfony/console": "^6.4|^7.0|^8.0",
+ "symfony/dependency-injection": "^6.4|^7.0|^8.0",
+ "symfony/finder": "^6.4|^7.0|^8.0",
+ "symfony/http-client-contracts": "^2.5|^3.0",
+ "symfony/http-kernel": "^6.4|^7.0|^8.0",
+ "symfony/intl": "^6.4|^7.0|^8.0",
+ "symfony/polyfill-intl-icu": "^1.21",
+ "symfony/routing": "^6.4|^7.0|^8.0",
+ "symfony/service-contracts": "^2.5|^3",
+ "symfony/yaml": "^6.4|^7.0|^8.0"
},
"type": "library",
"autoload": {
+ "files": [
+ "Resources/functions.php"
+ ],
"psr-4": {
- "Stash\\": "src/Stash/"
- }
+ "Symfony\\Component\\Translation\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
- "BSD-3-Clause"
+ "MIT"
],
"authors": [
{
- "name": "Robert Hafner",
- "email": "tedivm@tedivm.com"
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
},
{
- "name": "Josh Hall-Bachner",
- "email": "charlequin@gmail.com"
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
}
],
- "description": "The place to keep your cache.",
- "homepage": "http://github.com/tedious/Stash",
- "keywords": [
- "apc",
- "cache",
- "caching",
- "memcached",
- "psr-6",
- "psr6",
- "redis",
- "sessions"
- ],
+ "description": "Provides tools to internationalize your application",
+ "homepage": "https://symfony.com",
"support": {
- "issues": "https://github.com/tedious/Stash/issues",
- "source": "https://github.com/tedious/Stash/tree/v0.17.6"
+ "source": "https://github.com/symfony/translation/tree/v7.4.10"
},
"funding": [
{
- "url": "https://github.com/tedivm",
- "type": "github"
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-06T11:19:24+00:00"
+ },
+ {
+ "name": "symfony/translation-contracts",
+ "version": "v3.7.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/translation-contracts.git",
+ "reference": "0ab302977a952b42fd51475c4ebac81f8da0a95d"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/0ab302977a952b42fd51475c4ebac81f8da0a95d",
+ "reference": "0ab302977a952b42fd51475c4ebac81f8da0a95d",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.7-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Contracts\\Translation\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Test/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Generic abstractions related to translation",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "abstractions",
+ "contracts",
+ "decoupling",
+ "interfaces",
+ "interoperability",
+ "standards"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/translation-contracts/tree/v3.7.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-01-05T13:30:16+00:00"
+ },
+ {
+ "name": "tedivm/stash",
+ "version": "v1.2.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/tedious/Stash.git",
+ "reference": "39c426ed180f25a40c973608370191dacd5e0b56"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/tedious/Stash/zipball/39c426ed180f25a40c973608370191dacd5e0b56",
+ "reference": "39c426ed180f25a40c973608370191dacd5e0b56",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^8.0",
+ "psr/cache": "^2|^3"
+ },
+ "provide": {
+ "psr/cache-implementation": "2.0|3.0"
+ },
+ "require-dev": {
+ "dms/phpunit-arraysubset-asserts": "^0.5.0",
+ "friendsofphp/php-cs-fixer": "^2.8",
+ "php-coveralls/php-coveralls": "^2.0",
+ "phpunit/phpunit": "^9.0|^10"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Stash\\": "src/Stash/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-3-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Robert Hafner",
+ "email": "tedivm@tedivm.com"
+ },
+ {
+ "name": "Josh Hall-Bachner",
+ "email": "charlequin@gmail.com"
+ }
+ ],
+ "description": "The place to keep your cache.",
+ "homepage": "http://github.com/tedious/Stash",
+ "keywords": [
+ "apc",
+ "cache",
+ "caching",
+ "memcached",
+ "psr-6",
+ "psr6",
+ "redis",
+ "sessions"
+ ],
+ "support": {
+ "issues": "https://github.com/tedious/Stash/issues",
+ "source": "https://github.com/tedious/Stash/tree/v1.2.2"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/tedivm",
+ "type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/tedivm/stash",
"type": "tidelift"
}
],
- "time": "2022-07-26T14:15:03+00:00"
+ "time": "2025-12-27T14:08:18+00:00"
},
{
"name": "vlucas/phpdotenv",
- "version": "v5.6.0",
+ "version": "v5.6.3",
"source": {
"type": "git",
"url": "https://github.com/vlucas/phpdotenv.git",
- "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4"
+ "reference": "955e7815d677a3eaa7075231212f2110983adecc"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4",
- "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4",
+ "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/955e7815d677a3eaa7075231212f2110983adecc",
+ "reference": "955e7815d677a3eaa7075231212f2110983adecc",
"shasum": ""
},
"require": {
"ext-pcre": "*",
- "graham-campbell/result-type": "^1.1.2",
+ "graham-campbell/result-type": "^1.1.4",
"php": "^7.2.5 || ^8.0",
- "phpoption/phpoption": "^1.9.2",
- "symfony/polyfill-ctype": "^1.24",
- "symfony/polyfill-mbstring": "^1.24",
- "symfony/polyfill-php80": "^1.24"
+ "phpoption/phpoption": "^1.9.5",
+ "symfony/polyfill-ctype": "^1.26",
+ "symfony/polyfill-mbstring": "^1.26",
+ "symfony/polyfill-php80": "^1.26"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
@@ -2587,7 +2797,7 @@
"extra": {
"bamarni-bin": {
"bin-links": true,
- "forward-command": true
+ "forward-command": false
},
"branch-alias": {
"dev-master": "5.6-dev"
@@ -2622,7 +2832,7 @@
],
"support": {
"issues": "https://github.com/vlucas/phpdotenv/issues",
- "source": "https://github.com/vlucas/phpdotenv/tree/v5.6.0"
+ "source": "https://github.com/vlucas/phpdotenv/tree/v5.6.3"
},
"funding": [
{
@@ -2634,22 +2844,22 @@
"type": "tidelift"
}
],
- "time": "2023-11-12T22:43:29+00:00"
+ "time": "2025-12-27T19:49:13+00:00"
}
],
"packages-dev": [
{
"name": "aws/aws-crt-php",
- "version": "v1.2.4",
+ "version": "v1.2.7",
"source": {
"type": "git",
"url": "https://github.com/awslabs/aws-crt-php.git",
- "reference": "eb0c6e4e142224a10b08f49ebf87f32611d162b2"
+ "reference": "d71d9906c7bb63a28295447ba12e74723bd3730e"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/awslabs/aws-crt-php/zipball/eb0c6e4e142224a10b08f49ebf87f32611d162b2",
- "reference": "eb0c6e4e142224a10b08f49ebf87f32611d162b2",
+ "url": "https://api.github.com/repos/awslabs/aws-crt-php/zipball/d71d9906c7bb63a28295447ba12e74723bd3730e",
+ "reference": "d71d9906c7bb63a28295447ba12e74723bd3730e",
"shasum": ""
},
"require": {
@@ -2688,22 +2898,22 @@
],
"support": {
"issues": "https://github.com/awslabs/aws-crt-php/issues",
- "source": "https://github.com/awslabs/aws-crt-php/tree/v1.2.4"
+ "source": "https://github.com/awslabs/aws-crt-php/tree/v1.2.7"
},
- "time": "2023-11-08T00:42:13+00:00"
+ "time": "2024-10-18T22:15:13+00:00"
},
{
"name": "aws/aws-sdk-php",
- "version": "3.294.2",
+ "version": "3.383.1",
"source": {
"type": "git",
"url": "https://github.com/aws/aws-sdk-php.git",
- "reference": "e6a63e39fed0fd9fb553af42e99aaf8d7c104c88"
+ "reference": "56b7ff3ff9e086eb3945bf31e75c97cde5ab531a"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/e6a63e39fed0fd9fb553af42e99aaf8d7c104c88",
- "reference": "e6a63e39fed0fd9fb553af42e99aaf8d7c104c88",
+ "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/56b7ff3ff9e086eb3945bf31e75c97cde5ab531a",
+ "reference": "56b7ff3ff9e086eb3945bf31e75c97cde5ab531a",
"shasum": ""
},
"require": {
@@ -2711,37 +2921,36 @@
"ext-json": "*",
"ext-pcre": "*",
"ext-simplexml": "*",
- "guzzlehttp/guzzle": "^6.5.8 || ^7.4.5",
- "guzzlehttp/promises": "^1.4.0 || ^2.0",
- "guzzlehttp/psr7": "^1.9.1 || ^2.4.5",
- "mtdowling/jmespath.php": "^2.6",
- "php": ">=7.2.5",
- "psr/http-message": "^1.0 || ^2.0"
+ "guzzlehttp/guzzle": "^7.4.5",
+ "guzzlehttp/promises": "^2.0",
+ "guzzlehttp/psr7": "^2.4.5",
+ "mtdowling/jmespath.php": "^2.8.0",
+ "php": ">=8.1",
+ "psr/http-message": "^1.0 || ^2.0",
+ "symfony/filesystem": "^v5.4.45 || ^v6.4.3 || ^v7.1.0 || ^v8.0.0"
},
"require-dev": {
"andrewsville/php-token-reflection": "^1.4",
"aws/aws-php-sns-message-validator": "~1.0",
"behat/behat": "~3.0",
- "composer/composer": "^1.10.22",
- "dms/phpunit-arraysubset-asserts": "^0.4.0",
+ "composer/composer": "^2.7.8",
+ "dms/phpunit-arraysubset-asserts": "^v0.5.0",
"doctrine/cache": "~1.4",
"ext-dom": "*",
"ext-openssl": "*",
- "ext-pcntl": "*",
"ext-sockets": "*",
- "nette/neon": "^2.3",
- "paragonie/random_compat": ">= 2",
- "phpunit/phpunit": "^5.6.3 || ^8.5 || ^9.5",
- "psr/cache": "^1.0",
- "psr/simple-cache": "^1.0",
- "sebastian/comparator": "^1.2.3 || ^4.0",
- "yoast/phpunit-polyfills": "^1.0"
+ "phpunit/phpunit": "^10.0",
+ "psr/cache": "^2.0 || ^3.0",
+ "psr/simple-cache": "^2.0 || ^3.0",
+ "sebastian/comparator": "^1.2.3 || ^4.0 || ^5.0",
+ "yoast/phpunit-polyfills": "^2.0"
},
"suggest": {
"aws/aws-php-sns-message-validator": "To validate incoming SNS notifications",
"doctrine/cache": "To use the DoctrineCacheAdapter",
"ext-curl": "To send requests using cURL",
"ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages",
+ "ext-pcntl": "To use client-side monitoring",
"ext-sockets": "To use client-side monitoring"
},
"type": "library",
@@ -2756,7 +2965,10 @@
],
"psr-4": {
"Aws\\": "src/"
- }
+ },
+ "exclude-from-classmap": [
+ "src/data/"
+ ]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@@ -2765,11 +2977,11 @@
"authors": [
{
"name": "Amazon Web Services",
- "homepage": "http://aws.amazon.com"
+ "homepage": "https://aws.amazon.com"
}
],
"description": "AWS SDK for PHP - Use Amazon Web Services in your PHP project",
- "homepage": "http://aws.amazon.com/sdkforphp",
+ "homepage": "https://aws.amazon.com/sdk-for-php",
"keywords": [
"amazon",
"aws",
@@ -2781,11 +2993,11 @@
"sdk"
],
"support": {
- "forum": "https://forums.aws.amazon.com/forum.jspa?forumID=80",
+ "forum": "https://github.com/aws/aws-sdk-php/discussions",
"issues": "https://github.com/aws/aws-sdk-php/issues",
- "source": "https://github.com/aws/aws-sdk-php/tree/3.294.2"
+ "source": "https://github.com/aws/aws-sdk-php/tree/3.383.1"
},
- "time": "2023-12-18T19:11:16+00:00"
+ "time": "2026-05-29T18:13:12+00:00"
},
{
"name": "cache/adapter-common",
@@ -3047,92 +3259,22 @@
},
"time": "2022-01-15T15:47:19+00:00"
},
- {
- "name": "doctrine/instantiator",
- "version": "1.5.0",
- "source": {
- "type": "git",
- "url": "https://github.com/doctrine/instantiator.git",
- "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/doctrine/instantiator/zipball/0a0fa9780f5d4e507415a065172d26a98d02047b",
- "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b",
- "shasum": ""
- },
- "require": {
- "php": "^7.1 || ^8.0"
- },
- "require-dev": {
- "doctrine/coding-standard": "^9 || ^11",
- "ext-pdo": "*",
- "ext-phar": "*",
- "phpbench/phpbench": "^0.16 || ^1",
- "phpstan/phpstan": "^1.4",
- "phpstan/phpstan-phpunit": "^1",
- "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
- "vimeo/psalm": "^4.30 || ^5.4"
- },
- "type": "library",
- "autoload": {
- "psr-4": {
- "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Marco Pivetta",
- "email": "ocramius@gmail.com",
- "homepage": "https://ocramius.github.io/"
- }
- ],
- "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
- "homepage": "https://www.doctrine-project.org/projects/instantiator.html",
- "keywords": [
- "constructor",
- "instantiate"
- ],
- "support": {
- "issues": "https://github.com/doctrine/instantiator/issues",
- "source": "https://github.com/doctrine/instantiator/tree/1.5.0"
- },
- "funding": [
- {
- "url": "https://www.doctrine-project.org/sponsorship.html",
- "type": "custom"
- },
- {
- "url": "https://www.patreon.com/phpdoctrine",
- "type": "patreon"
- },
- {
- "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finstantiator",
- "type": "tidelift"
- }
- ],
- "time": "2022-12-30T00:15:36+00:00"
- },
{
"name": "hamcrest/hamcrest-php",
- "version": "v2.0.1",
+ "version": "v2.1.1",
"source": {
"type": "git",
"url": "https://github.com/hamcrest/hamcrest-php.git",
- "reference": "8c3d0a3f6af734494ad8f6fbbee0ba92422859f3"
+ "reference": "f8b1c0173b22fa6ec77a81fe63e5b01eba7e6487"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/hamcrest/hamcrest-php/zipball/8c3d0a3f6af734494ad8f6fbbee0ba92422859f3",
- "reference": "8c3d0a3f6af734494ad8f6fbbee0ba92422859f3",
+ "url": "https://api.github.com/repos/hamcrest/hamcrest-php/zipball/f8b1c0173b22fa6ec77a81fe63e5b01eba7e6487",
+ "reference": "f8b1c0173b22fa6ec77a81fe63e5b01eba7e6487",
"shasum": ""
},
"require": {
- "php": "^5.3|^7.0|^8.0"
+ "php": "^7.4|^8.0"
},
"replace": {
"cordoval/hamcrest-php": "*",
@@ -3140,8 +3282,8 @@
"kodova/hamcrest-php": "*"
},
"require-dev": {
- "phpunit/php-file-iterator": "^1.4 || ^2.0",
- "phpunit/phpunit": "^4.8.36 || ^5.7 || ^6.5 || ^7.0"
+ "phpunit/php-file-iterator": "^1.4 || ^2.0 || ^3.0",
+ "phpunit/phpunit": "^4.8.36 || ^5.7 || ^6.5 || ^7.0 || ^8.0 || ^9.0"
},
"type": "library",
"extra": {
@@ -3164,41 +3306,48 @@
],
"support": {
"issues": "https://github.com/hamcrest/hamcrest-php/issues",
- "source": "https://github.com/hamcrest/hamcrest-php/tree/v2.0.1"
+ "source": "https://github.com/hamcrest/hamcrest-php/tree/v2.1.1"
},
- "time": "2020-07-09T08:09:16+00:00"
+ "time": "2025-04-30T06:54:44+00:00"
},
{
"name": "league/csv",
- "version": "9.8.0",
+ "version": "9.28.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/csv.git",
- "reference": "9d2e0265c5d90f5dd601bc65ff717e05cec19b47"
+ "reference": "6582ace29ae09ba5b07049d40ea13eb19c8b5073"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/thephpleague/csv/zipball/9d2e0265c5d90f5dd601bc65ff717e05cec19b47",
- "reference": "9d2e0265c5d90f5dd601bc65ff717e05cec19b47",
+ "url": "https://api.github.com/repos/thephpleague/csv/zipball/6582ace29ae09ba5b07049d40ea13eb19c8b5073",
+ "reference": "6582ace29ae09ba5b07049d40ea13eb19c8b5073",
"shasum": ""
},
"require": {
- "ext-json": "*",
- "ext-mbstring": "*",
- "php": "^7.4 || ^8.0"
+ "ext-filter": "*",
+ "php": "^8.1.2"
},
"require-dev": {
- "ext-curl": "*",
"ext-dom": "*",
- "friendsofphp/php-cs-fixer": "^v3.4.0",
- "phpstan/phpstan": "^1.3.0",
- "phpstan/phpstan-phpunit": "^1.0.0",
- "phpstan/phpstan-strict-rules": "^1.1.0",
- "phpunit/phpunit": "^9.5.11"
+ "ext-xdebug": "*",
+ "friendsofphp/php-cs-fixer": "^3.92.3",
+ "phpbench/phpbench": "^1.4.3",
+ "phpstan/phpstan": "^1.12.32",
+ "phpstan/phpstan-deprecation-rules": "^1.2.1",
+ "phpstan/phpstan-phpunit": "^1.4.2",
+ "phpstan/phpstan-strict-rules": "^1.6.2",
+ "phpunit/phpunit": "^10.5.16 || ^11.5.22 || ^12.5.4",
+ "symfony/var-dumper": "^6.4.8 || ^7.4.0 || ^8.0"
},
"suggest": {
- "ext-dom": "Required to use the XMLConverter and or the HTMLConverter classes",
- "ext-iconv": "Needed to ease transcoding CSV using iconv stream filters"
+ "ext-dom": "Required to use the XMLConverter and the HTMLConverter classes",
+ "ext-iconv": "Needed to ease transcoding CSV using iconv stream filters",
+ "ext-mbstring": "Needed to ease transcoding CSV using mb stream filters",
+ "ext-mysqli": "Requiered to use the package with the MySQLi extension",
+ "ext-pdo": "Required to use the package with the PDO extension",
+ "ext-pgsql": "Requiered to use the package with the PgSQL extension",
+ "ext-sqlite3": "Required to use the package with the SQLite3 extension"
},
"type": "library",
"extra": {
@@ -3250,7 +3399,7 @@
"type": "github"
}
],
- "time": "2022-01-04T00:13:07+00:00"
+ "time": "2025-12-27T15:18:42+00:00"
},
{
"name": "league/flysystem-aws-s3-v3",
@@ -3435,16 +3584,16 @@
},
{
"name": "mockery/mockery",
- "version": "1.6.7",
+ "version": "1.6.12",
"source": {
"type": "git",
"url": "https://github.com/mockery/mockery.git",
- "reference": "0cc058854b3195ba21dc6b1f7b1f60f4ef3a9c06"
+ "reference": "1f4efdd7d3beafe9807b08156dfcb176d18f1699"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/mockery/mockery/zipball/0cc058854b3195ba21dc6b1f7b1f60f4ef3a9c06",
- "reference": "0cc058854b3195ba21dc6b1f7b1f60f4ef3a9c06",
+ "url": "https://api.github.com/repos/mockery/mockery/zipball/1f4efdd7d3beafe9807b08156dfcb176d18f1699",
+ "reference": "1f4efdd7d3beafe9807b08156dfcb176d18f1699",
"shasum": ""
},
"require": {
@@ -3456,8 +3605,8 @@
"phpunit/phpunit": "<8.0"
},
"require-dev": {
- "phpunit/phpunit": "^8.5 || ^9.6.10",
- "symplify/easy-coding-standard": "^12.0.8"
+ "phpunit/phpunit": "^8.5 || ^9.6.17",
+ "symplify/easy-coding-standard": "^12.1.14"
},
"type": "library",
"autoload": {
@@ -3514,20 +3663,20 @@
"security": "https://github.com/mockery/mockery/security/advisories",
"source": "https://github.com/mockery/mockery"
},
- "time": "2023-12-10T02:24:34+00:00"
+ "time": "2024-05-16T03:13:13+00:00"
},
{
"name": "mtdowling/jmespath.php",
- "version": "2.7.0",
+ "version": "2.8.0",
"source": {
"type": "git",
"url": "https://github.com/jmespath/jmespath.php.git",
- "reference": "bbb69a935c2cbb0c03d7f481a238027430f6440b"
+ "reference": "a2a865e05d5f420b50cc2f85bb78d565db12a6bc"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/jmespath/jmespath.php/zipball/bbb69a935c2cbb0c03d7f481a238027430f6440b",
- "reference": "bbb69a935c2cbb0c03d7f481a238027430f6440b",
+ "url": "https://api.github.com/repos/jmespath/jmespath.php/zipball/a2a865e05d5f420b50cc2f85bb78d565db12a6bc",
+ "reference": "a2a865e05d5f420b50cc2f85bb78d565db12a6bc",
"shasum": ""
},
"require": {
@@ -3544,7 +3693,7 @@
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "2.7-dev"
+ "dev-master": "2.8-dev"
}
},
"autoload": {
@@ -3578,36 +3727,39 @@
],
"support": {
"issues": "https://github.com/jmespath/jmespath.php/issues",
- "source": "https://github.com/jmespath/jmespath.php/tree/2.7.0"
+ "source": "https://github.com/jmespath/jmespath.php/tree/2.8.0"
},
- "time": "2023-08-25T10:54:48+00:00"
+ "time": "2024-09-04T18:46:31+00:00"
},
{
"name": "mustache/mustache",
- "version": "v2.14.2",
+ "version": "v3.2.0",
"source": {
"type": "git",
"url": "https://github.com/bobthecow/mustache.php.git",
- "reference": "e62b7c3849d22ec55f3ec425507bf7968193a6cb"
+ "reference": "bd4fb2e45ac2df0570c0f4da6898054a950d1ed0"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/bobthecow/mustache.php/zipball/e62b7c3849d22ec55f3ec425507bf7968193a6cb",
- "reference": "e62b7c3849d22ec55f3ec425507bf7968193a6cb",
+ "url": "https://api.github.com/repos/bobthecow/mustache.php/zipball/bd4fb2e45ac2df0570c0f4da6898054a950d1ed0",
+ "reference": "bd4fb2e45ac2df0570c0f4da6898054a950d1ed0",
"shasum": ""
},
"require": {
- "php": ">=5.2.4"
+ "php": ">=5.6"
},
"require-dev": {
- "friendsofphp/php-cs-fixer": "~1.11",
- "phpunit/phpunit": "~3.7|~4.0|~5.0"
+ "friendsofphp/php-cs-fixer": "~2.19.3",
+ "yoast/phpunit-polyfills": "^2.0"
},
"type": "library",
"autoload": {
- "psr-0": {
- "Mustache": "src/"
- }
+ "psr-4": {
+ "Mustache\\": "src/"
+ },
+ "classmap": [
+ "src/compat.php"
+ ]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@@ -3628,22 +3780,22 @@
],
"support": {
"issues": "https://github.com/bobthecow/mustache.php/issues",
- "source": "https://github.com/bobthecow/mustache.php/tree/v2.14.2"
+ "source": "https://github.com/bobthecow/mustache.php/tree/v3.2.0"
},
- "time": "2022-08-23T13:07:01+00:00"
+ "time": "2026-05-10T04:13:08+00:00"
},
{
"name": "myclabs/deep-copy",
- "version": "1.11.1",
+ "version": "1.13.4",
"source": {
"type": "git",
"url": "https://github.com/myclabs/DeepCopy.git",
- "reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c"
+ "reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/7284c22080590fb39f2ffa3e9057f10a4ddd0e0c",
- "reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c",
+ "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/07d290f0c47959fd5eed98c95ee5602db07e0b6a",
+ "reference": "07d290f0c47959fd5eed98c95ee5602db07e0b6a",
"shasum": ""
},
"require": {
@@ -3651,11 +3803,12 @@
},
"conflict": {
"doctrine/collections": "<1.6.8",
- "doctrine/common": "<2.13.3 || >=3,<3.2.2"
+ "doctrine/common": "<2.13.3 || >=3 <3.2.2"
},
"require-dev": {
"doctrine/collections": "^1.6.8",
"doctrine/common": "^2.13.3 || ^3.2.2",
+ "phpspec/prophecy": "^1.10",
"phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"
},
"type": "library",
@@ -3681,7 +3834,7 @@
],
"support": {
"issues": "https://github.com/myclabs/DeepCopy/issues",
- "source": "https://github.com/myclabs/DeepCopy/tree/1.11.1"
+ "source": "https://github.com/myclabs/DeepCopy/tree/1.13.4"
},
"funding": [
{
@@ -3689,29 +3842,122 @@
"type": "tidelift"
}
],
- "time": "2023-03-08T13:26:56+00:00"
+ "time": "2025-08-01T08:46:24+00:00"
+ },
+ {
+ "name": "nette/utils",
+ "version": "v4.1.4",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/nette/utils.git",
+ "reference": "7da6c396d7ebe142bc857c20479d5e70a5e1aac7"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/nette/utils/zipball/7da6c396d7ebe142bc857c20479d5e70a5e1aac7",
+ "reference": "7da6c396d7ebe142bc857c20479d5e70a5e1aac7",
+ "shasum": ""
+ },
+ "require": {
+ "php": "8.2 - 8.5"
+ },
+ "conflict": {
+ "nette/finder": "<3",
+ "nette/schema": "<1.2.2"
+ },
+ "require-dev": {
+ "jetbrains/phpstorm-attributes": "^1.2",
+ "nette/phpstan-rules": "^1.0",
+ "nette/tester": "^2.5",
+ "phpstan/extension-installer": "^1.4@stable",
+ "phpstan/phpstan": "^2.1@stable",
+ "tracy/tracy": "^2.9"
+ },
+ "suggest": {
+ "ext-gd": "to use Image",
+ "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()",
+ "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()",
+ "ext-json": "to use Nette\\Utils\\Json",
+ "ext-mbstring": "to use Strings::lower() etc...",
+ "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "4.1-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Nette\\": "src"
+ },
+ "classmap": [
+ "src/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-3-Clause",
+ "GPL-2.0-only",
+ "GPL-3.0-only"
+ ],
+ "authors": [
+ {
+ "name": "David Grudl",
+ "homepage": "https://davidgrudl.com"
+ },
+ {
+ "name": "Nette Community",
+ "homepage": "https://nette.org/contributors"
+ }
+ ],
+ "description": "🛠Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.",
+ "homepage": "https://nette.org",
+ "keywords": [
+ "array",
+ "core",
+ "datetime",
+ "images",
+ "json",
+ "nette",
+ "paginator",
+ "password",
+ "slugify",
+ "string",
+ "unicode",
+ "utf-8",
+ "utility",
+ "validation"
+ ],
+ "support": {
+ "issues": "https://github.com/nette/utils/issues",
+ "source": "https://github.com/nette/utils/tree/v4.1.4"
+ },
+ "time": "2026-05-11T20:49:54+00:00"
},
{
"name": "nikic/php-parser",
- "version": "v4.18.0",
+ "version": "v5.7.0",
"source": {
"type": "git",
"url": "https://github.com/nikic/PHP-Parser.git",
- "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999"
+ "reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/1bcbb2179f97633e98bbbc87044ee2611c7d7999",
- "reference": "1bcbb2179f97633e98bbbc87044ee2611c7d7999",
+ "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/dca41cd15c2ac9d055ad70dbfd011130757d1f82",
+ "reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82",
"shasum": ""
},
"require": {
+ "ext-ctype": "*",
+ "ext-json": "*",
"ext-tokenizer": "*",
- "php": ">=7.0"
+ "php": ">=7.4"
},
"require-dev": {
"ircmaxell/php-yacc": "^0.0.7",
- "phpunit/phpunit": "^6.5 || ^7.0 || ^8.0 || ^9.0"
+ "phpunit/phpunit": "^9.0"
},
"bin": [
"bin/php-parse"
@@ -3719,7 +3965,7 @@
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "4.9-dev"
+ "dev-master": "5.x-dev"
}
},
"autoload": {
@@ -3743,26 +3989,27 @@
],
"support": {
"issues": "https://github.com/nikic/PHP-Parser/issues",
- "source": "https://github.com/nikic/PHP-Parser/tree/v4.18.0"
+ "source": "https://github.com/nikic/PHP-Parser/tree/v5.7.0"
},
- "time": "2023-12-10T21:03:43+00:00"
+ "time": "2025-12-06T11:56:16+00:00"
},
{
"name": "phar-io/manifest",
- "version": "2.0.3",
+ "version": "2.0.4",
"source": {
"type": "git",
"url": "https://github.com/phar-io/manifest.git",
- "reference": "97803eca37d319dfa7826cc2437fc020857acb53"
+ "reference": "54750ef60c58e43759730615a392c31c80e23176"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/phar-io/manifest/zipball/97803eca37d319dfa7826cc2437fc020857acb53",
- "reference": "97803eca37d319dfa7826cc2437fc020857acb53",
+ "url": "https://api.github.com/repos/phar-io/manifest/zipball/54750ef60c58e43759730615a392c31c80e23176",
+ "reference": "54750ef60c58e43759730615a392c31c80e23176",
"shasum": ""
},
"require": {
"ext-dom": "*",
+ "ext-libxml": "*",
"ext-phar": "*",
"ext-xmlwriter": "*",
"phar-io/version": "^3.0.1",
@@ -3803,14 +4050,20 @@
"description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)",
"support": {
"issues": "https://github.com/phar-io/manifest/issues",
- "source": "https://github.com/phar-io/manifest/tree/2.0.3"
+ "source": "https://github.com/phar-io/manifest/tree/2.0.4"
},
- "time": "2021-07-20T11:28:43+00:00"
- },
- {
- "name": "phar-io/version",
- "version": "3.2.1",
- "source": {
+ "funding": [
+ {
+ "url": "https://github.com/theseer",
+ "type": "github"
+ }
+ ],
+ "time": "2024-03-03T12:33:53+00:00"
+ },
+ {
+ "name": "phar-io/version",
+ "version": "3.2.1",
+ "source": {
"type": "git",
"url": "https://github.com/phar-io/version.git",
"reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74"
@@ -3860,32 +4113,32 @@
},
{
"name": "php-coveralls/php-coveralls",
- "version": "v2.7.0",
+ "version": "v2.9.1",
"source": {
"type": "git",
"url": "https://github.com/php-coveralls/php-coveralls.git",
- "reference": "b36fa4394e519dafaddc04ae03976bc65a25ba15"
+ "reference": "916bdb118597f61ce6715fb738ab8f234b89a2cb"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-coveralls/php-coveralls/zipball/b36fa4394e519dafaddc04ae03976bc65a25ba15",
- "reference": "b36fa4394e519dafaddc04ae03976bc65a25ba15",
+ "url": "https://api.github.com/repos/php-coveralls/php-coveralls/zipball/916bdb118597f61ce6715fb738ab8f234b89a2cb",
+ "reference": "916bdb118597f61ce6715fb738ab8f234b89a2cb",
"shasum": ""
},
"require": {
"ext-json": "*",
"ext-simplexml": "*",
"guzzlehttp/guzzle": "^6.0 || ^7.0",
- "php": "^7.0 || ^8.0",
- "psr/log": "^1.0 || ^2.0",
- "symfony/config": "^2.1 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0",
- "symfony/console": "^2.1 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0",
- "symfony/stopwatch": "^2.0 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0",
- "symfony/yaml": "^2.0.5 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0"
+ "php": "^7.4 || ^8.0",
+ "psr/log": "^1.0 || ^2.0 || ^3.0",
+ "symfony/config": "^5.4 || ^6.4 || ^7.0 || ^8.0",
+ "symfony/console": "^5.4 || ^6.4 || ^7.0 || ^8.0",
+ "symfony/stopwatch": "^5.4 || ^6.4 || ^7.0 || ^8.0",
+ "symfony/yaml": "^5.4 || ^6.4 || ^7.0 || ^8.0"
},
"require-dev": {
- "phpunit/phpunit": "^4.8.35 || ^5.4.3 || ^6.0 || ^7.0 || >=8.0 <8.5.29 || >=9.0 <9.5.23",
- "sanmai/phpunit-legacy-adapter": "^6.1 || ^8.0"
+ "phpspec/prophecy-phpunit": "^2.4",
+ "phpunit/phpunit": "^9.6.29 || ^10.5.58 || ^11.5.43"
},
"suggest": {
"symfony/http-kernel": "Allows Symfony integration"
@@ -3937,22 +4190,22 @@
],
"support": {
"issues": "https://github.com/php-coveralls/php-coveralls/issues",
- "source": "https://github.com/php-coveralls/php-coveralls/tree/v2.7.0"
+ "source": "https://github.com/php-coveralls/php-coveralls/tree/v2.9.1"
},
- "time": "2023-11-22T10:21:01+00:00"
+ "time": "2025-12-18T13:08:37+00:00"
},
{
"name": "phpseclib/phpseclib",
- "version": "2.0.45",
+ "version": "2.0.54",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
- "reference": "28d8f438a0064c9de80857e3270d071495544640"
+ "reference": "a96a835067c39ee7a709329fe70869817da18081"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/28d8f438a0064c9de80857e3270d071495544640",
- "reference": "28d8f438a0064c9de80857e3270d071495544640",
+ "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/a96a835067c39ee7a709329fe70869817da18081",
+ "reference": "a96a835067c39ee7a709329fe70869817da18081",
"shasum": ""
},
"require": {
@@ -3960,7 +4213,7 @@
},
"require-dev": {
"phing/phing": "~2.7",
- "phpunit/phpunit": "^4.8.35|^5.7|^6.0|^9.4",
+ "phpunit/phpunit": "^4.8.35|^5.7|^6.0|^8.5|^9.4",
"squizlabs/php_codesniffer": "~2.0"
},
"suggest": {
@@ -4033,7 +4286,7 @@
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
- "source": "https://github.com/phpseclib/phpseclib/tree/2.0.45"
+ "source": "https://github.com/phpseclib/phpseclib/tree/2.0.54"
},
"funding": [
{
@@ -4049,24 +4302,19 @@
"type": "tidelift"
}
],
- "time": "2023-09-15T20:55:47+00:00"
+ "time": "2026-04-27T06:59:24+00:00"
},
{
"name": "phpstan/phpstan",
- "version": "1.10.50",
- "source": {
- "type": "git",
- "url": "https://github.com/phpstan/phpstan.git",
- "reference": "06a98513ac72c03e8366b5a0cb00750b487032e4"
- },
+ "version": "2.2.1",
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/phpstan/phpstan/zipball/06a98513ac72c03e8366b5a0cb00750b487032e4",
- "reference": "06a98513ac72c03e8366b5a0cb00750b487032e4",
+ "url": "https://api.github.com/repos/phpstan/phpstan/zipball/dea9c8f2d25cc849391042b71e429c1a4bf82660",
+ "reference": "dea9c8f2d25cc849391042b71e429c1a4bf82660",
"shasum": ""
},
"require": {
- "php": "^7.2|^8.0"
+ "php": "^7.4|^8.0"
},
"conflict": {
"phpstan/phpstan-shim": "*"
@@ -4085,6 +4333,17 @@
"license": [
"MIT"
],
+ "authors": [
+ {
+ "name": "Ondřej Mirtes"
+ },
+ {
+ "name": "Markus Staab"
+ },
+ {
+ "name": "Vincent Langlet"
+ }
+ ],
"description": "PHPStan - PHP Static Analysis Tool",
"keywords": [
"dev",
@@ -4105,45 +4364,39 @@
{
"url": "https://github.com/phpstan",
"type": "github"
- },
- {
- "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan",
- "type": "tidelift"
}
],
- "time": "2023-12-13T10:59:42+00:00"
+ "time": "2026-05-28T14:44:12+00:00"
},
{
"name": "phpunit/php-code-coverage",
- "version": "9.2.29",
+ "version": "12.5.6",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
- "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76"
+ "reference": "876099a072646c7745f673d7aeab5382c4439691"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6a3a87ac2bbe33b25042753df8195ba4aa534c76",
- "reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/876099a072646c7745f673d7aeab5382c4439691",
+ "reference": "876099a072646c7745f673d7aeab5382c4439691",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-libxml": "*",
"ext-xmlwriter": "*",
- "nikic/php-parser": "^4.15",
- "php": ">=7.3",
- "phpunit/php-file-iterator": "^3.0.3",
- "phpunit/php-text-template": "^2.0.2",
- "sebastian/code-unit-reverse-lookup": "^2.0.2",
- "sebastian/complexity": "^2.0",
- "sebastian/environment": "^5.1.2",
- "sebastian/lines-of-code": "^1.0.3",
- "sebastian/version": "^3.0.1",
- "theseer/tokenizer": "^1.2.0"
+ "nikic/php-parser": "^5.7.0",
+ "php": ">=8.3",
+ "phpunit/php-text-template": "^5.0",
+ "sebastian/complexity": "^5.0",
+ "sebastian/environment": "^8.0.3",
+ "sebastian/lines-of-code": "^4.0",
+ "sebastian/version": "^6.0",
+ "theseer/tokenizer": "^2.0.1"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.5.1"
},
"suggest": {
"ext-pcov": "PHP extension that provides line coverage",
@@ -4152,7 +4405,7 @@
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "9.2-dev"
+ "dev-main": "12.5.x-dev"
}
},
"autoload": {
@@ -4181,40 +4434,52 @@
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",
- "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.29"
+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/12.5.6"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/phpunit/php-code-coverage",
+ "type": "tidelift"
}
],
- "time": "2023-09-19T04:57:46+00:00"
+ "time": "2026-04-15T08:23:17+00:00"
},
{
"name": "phpunit/php-file-iterator",
- "version": "3.0.6",
+ "version": "6.0.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-file-iterator.git",
- "reference": "cf1c2e7c203ac650e352f4cc675a7021e7d1b3cf"
+ "reference": "3d1cd096ef6bea4bf2762ba586e35dbd317cbfd5"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/cf1c2e7c203ac650e352f4cc675a7021e7d1b3cf",
- "reference": "cf1c2e7c203ac650e352f4cc675a7021e7d1b3cf",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/3d1cd096ef6bea4bf2762ba586e35dbd317cbfd5",
+ "reference": "3d1cd096ef6bea4bf2762ba586e35dbd317cbfd5",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "3.0-dev"
+ "dev-main": "6.0-dev"
}
},
"autoload": {
@@ -4241,36 +4506,49 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-file-iterator/issues",
- "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/3.0.6"
+ "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy",
+ "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/6.0.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/phpunit/php-file-iterator",
+ "type": "tidelift"
}
],
- "time": "2021-12-02T12:48:52+00:00"
+ "time": "2026-02-02T14:04:18+00:00"
},
{
"name": "phpunit/php-invoker",
- "version": "3.1.1",
+ "version": "6.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-invoker.git",
- "reference": "5a10147d0aaf65b58940a0b72f71c9ac0423cc67"
+ "reference": "12b54e689b07a25a9b41e57736dfab6ec9ae5406"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/5a10147d0aaf65b58940a0b72f71c9ac0423cc67",
- "reference": "5a10147d0aaf65b58940a0b72f71c9ac0423cc67",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/12b54e689b07a25a9b41e57736dfab6ec9ae5406",
+ "reference": "12b54e689b07a25a9b41e57736dfab6ec9ae5406",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
"ext-pcntl": "*",
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"suggest": {
"ext-pcntl": "*"
@@ -4278,7 +4556,7 @@
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "3.1-dev"
+ "dev-main": "6.0-dev"
}
},
"autoload": {
@@ -4304,7 +4582,8 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-invoker/issues",
- "source": "https://github.com/sebastianbergmann/php-invoker/tree/3.1.1"
+ "security": "https://github.com/sebastianbergmann/php-invoker/security/policy",
+ "source": "https://github.com/sebastianbergmann/php-invoker/tree/6.0.0"
},
"funding": [
{
@@ -4312,32 +4591,32 @@
"type": "github"
}
],
- "time": "2020-09-28T05:58:55+00:00"
+ "time": "2025-02-07T04:58:58+00:00"
},
{
"name": "phpunit/php-text-template",
- "version": "2.0.4",
+ "version": "5.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-text-template.git",
- "reference": "5da5f67fc95621df9ff4c4e5a84d6a8a2acf7c28"
+ "reference": "e1367a453f0eda562eedb4f659e13aa900d66c53"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/5da5f67fc95621df9ff4c4e5a84d6a8a2acf7c28",
- "reference": "5da5f67fc95621df9ff4c4e5a84d6a8a2acf7c28",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/e1367a453f0eda562eedb4f659e13aa900d66c53",
+ "reference": "e1367a453f0eda562eedb4f659e13aa900d66c53",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "2.0-dev"
+ "dev-main": "5.0-dev"
}
},
"autoload": {
@@ -4363,7 +4642,8 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-text-template/issues",
- "source": "https://github.com/sebastianbergmann/php-text-template/tree/2.0.4"
+ "security": "https://github.com/sebastianbergmann/php-text-template/security/policy",
+ "source": "https://github.com/sebastianbergmann/php-text-template/tree/5.0.0"
},
"funding": [
{
@@ -4371,32 +4651,32 @@
"type": "github"
}
],
- "time": "2020-10-26T05:33:50+00:00"
+ "time": "2025-02-07T04:59:16+00:00"
},
{
"name": "phpunit/php-timer",
- "version": "5.0.3",
+ "version": "8.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-timer.git",
- "reference": "5a63ce20ed1b5bf577850e2c4e87f4aa902afbd2"
+ "reference": "f258ce36aa457f3aa3339f9ed4c81fc66dc8c2cc"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/5a63ce20ed1b5bf577850e2c4e87f4aa902afbd2",
- "reference": "5a63ce20ed1b5bf577850e2c4e87f4aa902afbd2",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/f258ce36aa457f3aa3339f9ed4c81fc66dc8c2cc",
+ "reference": "f258ce36aa457f3aa3339f9ed4c81fc66dc8c2cc",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "5.0-dev"
+ "dev-main": "8.0-dev"
}
},
"autoload": {
@@ -4422,7 +4702,8 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-timer/issues",
- "source": "https://github.com/sebastianbergmann/php-timer/tree/5.0.3"
+ "security": "https://github.com/sebastianbergmann/php-timer/security/policy",
+ "source": "https://github.com/sebastianbergmann/php-timer/tree/8.0.0"
},
"funding": [
{
@@ -4430,54 +4711,49 @@
"type": "github"
}
],
- "time": "2020-10-26T13:16:10+00:00"
+ "time": "2025-02-07T04:59:38+00:00"
},
{
"name": "phpunit/phpunit",
- "version": "9.6.15",
+ "version": "12.5.28",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
- "reference": "05017b80304e0eb3f31d90194a563fd53a6021f1"
+ "reference": "5895d05f5bf421ed230fbd76e1277e4b8955def4"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/05017b80304e0eb3f31d90194a563fd53a6021f1",
- "reference": "05017b80304e0eb3f31d90194a563fd53a6021f1",
+ "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/5895d05f5bf421ed230fbd76e1277e4b8955def4",
+ "reference": "5895d05f5bf421ed230fbd76e1277e4b8955def4",
"shasum": ""
},
"require": {
- "doctrine/instantiator": "^1.3.1 || ^2",
"ext-dom": "*",
"ext-json": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
"ext-xml": "*",
"ext-xmlwriter": "*",
- "myclabs/deep-copy": "^1.10.1",
- "phar-io/manifest": "^2.0.3",
- "phar-io/version": "^3.0.2",
- "php": ">=7.3",
- "phpunit/php-code-coverage": "^9.2.28",
- "phpunit/php-file-iterator": "^3.0.5",
- "phpunit/php-invoker": "^3.1.1",
- "phpunit/php-text-template": "^2.0.3",
- "phpunit/php-timer": "^5.0.2",
- "sebastian/cli-parser": "^1.0.1",
- "sebastian/code-unit": "^1.0.6",
- "sebastian/comparator": "^4.0.8",
- "sebastian/diff": "^4.0.3",
- "sebastian/environment": "^5.1.3",
- "sebastian/exporter": "^4.0.5",
- "sebastian/global-state": "^5.0.1",
- "sebastian/object-enumerator": "^4.0.3",
- "sebastian/resource-operations": "^3.0.3",
- "sebastian/type": "^3.2",
- "sebastian/version": "^3.0.2"
- },
- "suggest": {
- "ext-soap": "To be able to generate mocks based on WSDL files",
- "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage"
+ "myclabs/deep-copy": "^1.13.4",
+ "phar-io/manifest": "^2.0.4",
+ "phar-io/version": "^3.2.1",
+ "php": ">=8.3",
+ "phpunit/php-code-coverage": "^12.5.6",
+ "phpunit/php-file-iterator": "^6.0.1",
+ "phpunit/php-invoker": "^6.0.0",
+ "phpunit/php-text-template": "^5.0.0",
+ "phpunit/php-timer": "^8.0.0",
+ "sebastian/cli-parser": "^4.2.1",
+ "sebastian/comparator": "^7.1.8",
+ "sebastian/diff": "^7.0.0",
+ "sebastian/environment": "^8.1.2",
+ "sebastian/exporter": "^7.0.3",
+ "sebastian/global-state": "^8.0.2",
+ "sebastian/object-enumerator": "^7.0.0",
+ "sebastian/recursion-context": "^7.0.1",
+ "sebastian/type": "^6.0.4",
+ "sebastian/version": "^6.0.0",
+ "staabm/side-effects-detector": "^1.0.5"
},
"bin": [
"phpunit"
@@ -4485,7 +4761,7 @@
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "9.6-dev"
+ "dev-main": "12.5-dev"
}
},
"autoload": {
@@ -4517,40 +4793,32 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
- "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.15"
+ "source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.28"
},
"funding": [
{
- "url": "https://phpunit.de/sponsors.html",
- "type": "custom"
- },
- {
- "url": "https://github.com/sebastianbergmann",
- "type": "github"
- },
- {
- "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit",
- "type": "tidelift"
+ "url": "https://phpunit.de/sponsoring.html",
+ "type": "other"
}
],
- "time": "2023-12-01T16:55:19+00:00"
+ "time": "2026-05-27T14:01:10+00:00"
},
{
- "name": "psr/simple-cache",
- "version": "1.0.1",
+ "name": "psr/event-dispatcher",
+ "version": "1.0.0",
"source": {
"type": "git",
- "url": "https://github.com/php-fig/simple-cache.git",
- "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b"
+ "url": "https://github.com/php-fig/event-dispatcher.git",
+ "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
- "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
+ "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0",
+ "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0",
"shasum": ""
},
"require": {
- "php": ">=5.3.0"
+ "php": ">=7.2.0"
},
"type": "library",
"extra": {
@@ -4560,7 +4828,7 @@
},
"autoload": {
"psr-4": {
- "Psr\\SimpleCache\\": "src/"
+ "Psr\\EventDispatcher\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
@@ -4573,155 +4841,153 @@
"homepage": "http://www.php-fig.org/"
}
],
- "description": "Common interfaces for simple caching",
+ "description": "Standard interfaces for event handling.",
"keywords": [
- "cache",
- "caching",
+ "events",
"psr",
- "psr-16",
- "simple-cache"
+ "psr-14"
],
"support": {
- "source": "https://github.com/php-fig/simple-cache/tree/master"
+ "issues": "https://github.com/php-fig/event-dispatcher/issues",
+ "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0"
},
- "time": "2017-10-23T01:57:42+00:00"
+ "time": "2019-01-08T18:20:26+00:00"
},
{
- "name": "sebastian/cli-parser",
+ "name": "psr/simple-cache",
"version": "1.0.1",
"source": {
"type": "git",
- "url": "https://github.com/sebastianbergmann/cli-parser.git",
- "reference": "442e7c7e687e42adc03470c7b668bc4b2402c0b2"
+ "url": "https://github.com/php-fig/simple-cache.git",
+ "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/442e7c7e687e42adc03470c7b668bc4b2402c0b2",
- "reference": "442e7c7e687e42adc03470c7b668bc4b2402c0b2",
+ "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
+ "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
"shasum": ""
},
"require": {
- "php": ">=7.3"
- },
- "require-dev": {
- "phpunit/phpunit": "^9.3"
+ "php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0-dev"
+ "dev-master": "1.0.x-dev"
}
},
"autoload": {
- "classmap": [
- "src/"
- ]
+ "psr-4": {
+ "Psr\\SimpleCache\\": "src/"
+ }
},
"notification-url": "https://packagist.org/downloads/",
"license": [
- "BSD-3-Clause"
+ "MIT"
],
"authors": [
{
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de",
- "role": "lead"
+ "name": "PHP-FIG",
+ "homepage": "http://www.php-fig.org/"
}
],
- "description": "Library for parsing CLI options",
- "homepage": "https://github.com/sebastianbergmann/cli-parser",
+ "description": "Common interfaces for simple caching",
+ "keywords": [
+ "cache",
+ "caching",
+ "psr",
+ "psr-16",
+ "simple-cache"
+ ],
"support": {
- "issues": "https://github.com/sebastianbergmann/cli-parser/issues",
- "source": "https://github.com/sebastianbergmann/cli-parser/tree/1.0.1"
+ "source": "https://github.com/php-fig/simple-cache/tree/master"
},
- "funding": [
- {
- "url": "https://github.com/sebastianbergmann",
- "type": "github"
- }
- ],
- "time": "2020-09-28T06:08:49+00:00"
+ "time": "2017-10-23T01:57:42+00:00"
},
{
- "name": "sebastian/code-unit",
- "version": "1.0.8",
+ "name": "rector/rector",
+ "version": "2.4.5",
"source": {
"type": "git",
- "url": "https://github.com/sebastianbergmann/code-unit.git",
- "reference": "1fc9f64c0927627ef78ba436c9b17d967e68e120"
+ "url": "https://github.com/rectorphp/rector.git",
+ "reference": "cbd86024be5014d3c14d9f0b3f7aae8ecbffd62c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/1fc9f64c0927627ef78ba436c9b17d967e68e120",
- "reference": "1fc9f64c0927627ef78ba436c9b17d967e68e120",
+ "url": "https://api.github.com/repos/rectorphp/rector/zipball/cbd86024be5014d3c14d9f0b3f7aae8ecbffd62c",
+ "reference": "cbd86024be5014d3c14d9f0b3f7aae8ecbffd62c",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": "^7.4|^8.0",
+ "phpstan/phpstan": "^2.1.56"
},
- "require-dev": {
- "phpunit/phpunit": "^9.3"
+ "conflict": {
+ "rector/rector-doctrine": "*",
+ "rector/rector-downgrade-php": "*",
+ "rector/rector-phpunit": "*",
+ "rector/rector-symfony": "*"
},
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.0-dev"
- }
+ "suggest": {
+ "ext-dom": "To manipulate phpunit.xml via the custom-rule command"
},
+ "bin": [
+ "bin/rector"
+ ],
+ "type": "library",
"autoload": {
- "classmap": [
- "src/"
+ "files": [
+ "bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
- "BSD-3-Clause"
+ "MIT"
],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de",
- "role": "lead"
- }
+ "description": "Instant Upgrade and Automated Refactoring of any PHP code",
+ "homepage": "https://getrector.com/",
+ "keywords": [
+ "automation",
+ "dev",
+ "migration",
+ "refactoring"
],
- "description": "Collection of value objects that represent the PHP code units",
- "homepage": "https://github.com/sebastianbergmann/code-unit",
"support": {
- "issues": "https://github.com/sebastianbergmann/code-unit/issues",
- "source": "https://github.com/sebastianbergmann/code-unit/tree/1.0.8"
+ "issues": "https://github.com/rectorphp/rector/issues",
+ "source": "https://github.com/rectorphp/rector/tree/2.4.5"
},
"funding": [
{
- "url": "https://github.com/sebastianbergmann",
+ "url": "https://github.com/tomasvotruba",
"type": "github"
}
],
- "time": "2020-10-26T13:08:54+00:00"
+ "time": "2026-05-26T21:03:22+00:00"
},
{
- "name": "sebastian/code-unit-reverse-lookup",
- "version": "2.0.3",
+ "name": "sebastian/cli-parser",
+ "version": "4.2.1",
"source": {
"type": "git",
- "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git",
- "reference": "ac91f01ccec49fb77bdc6fd1e548bc70f7faa3e5"
+ "url": "https://github.com/sebastianbergmann/cli-parser.git",
+ "reference": "7d05781b13f7dec9043a629a21d086ed74582a15"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/ac91f01ccec49fb77bdc6fd1e548bc70f7faa3e5",
- "reference": "ac91f01ccec49fb77bdc6fd1e548bc70f7faa3e5",
+ "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/7d05781b13f7dec9043a629a21d086ed74582a15",
+ "reference": "7d05781b13f7dec9043a629a21d086ed74582a15",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.5.25"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "2.0-dev"
+ "dev-main": "4.2-dev"
}
},
"autoload": {
@@ -4736,49 +5002,68 @@
"authors": [
{
"name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
+ "email": "sebastian@phpunit.de",
+ "role": "lead"
}
],
- "description": "Looks up which function or method a line of code belongs to",
- "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
+ "description": "Library for parsing CLI options",
+ "homepage": "https://github.com/sebastianbergmann/cli-parser",
"support": {
- "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues",
- "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/2.0.3"
+ "issues": "https://github.com/sebastianbergmann/cli-parser/issues",
+ "security": "https://github.com/sebastianbergmann/cli-parser/security/policy",
+ "source": "https://github.com/sebastianbergmann/cli-parser/tree/4.2.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/cli-parser",
+ "type": "tidelift"
}
],
- "time": "2020-09-28T05:30:19+00:00"
+ "time": "2026-05-17T05:29:34+00:00"
},
{
"name": "sebastian/comparator",
- "version": "4.0.8",
+ "version": "7.1.8",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/comparator.git",
- "reference": "fa0f136dd2334583309d32b62544682ee972b51a"
+ "reference": "7c65c1e79836812819705b473a90c12399542485"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/fa0f136dd2334583309d32b62544682ee972b51a",
- "reference": "fa0f136dd2334583309d32b62544682ee972b51a",
+ "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/7c65c1e79836812819705b473a90c12399542485",
+ "reference": "7c65c1e79836812819705b473a90c12399542485",
"shasum": ""
},
"require": {
- "php": ">=7.3",
- "sebastian/diff": "^4.0",
- "sebastian/exporter": "^4.0"
+ "ext-dom": "*",
+ "ext-mbstring": "*",
+ "php": ">=8.3",
+ "sebastian/diff": "^7.0",
+ "sebastian/exporter": "^7.0.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.5.25"
+ },
+ "suggest": {
+ "ext-bcmath": "For comparing BcMath\\Number objects"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "4.0-dev"
+ "dev-main": "7.1-dev"
}
},
"autoload": {
@@ -4817,41 +5102,54 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/comparator/issues",
- "source": "https://github.com/sebastianbergmann/comparator/tree/4.0.8"
+ "security": "https://github.com/sebastianbergmann/comparator/security/policy",
+ "source": "https://github.com/sebastianbergmann/comparator/tree/7.1.8"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/comparator",
+ "type": "tidelift"
}
],
- "time": "2022-09-14T12:41:17+00:00"
+ "time": "2026-05-21T04:45:25+00:00"
},
{
"name": "sebastian/complexity",
- "version": "2.0.2",
+ "version": "5.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/complexity.git",
- "reference": "739b35e53379900cc9ac327b2147867b8b6efd88"
+ "reference": "bad4316aba5303d0221f43f8cee37eb58d384bbb"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/739b35e53379900cc9ac327b2147867b8b6efd88",
- "reference": "739b35e53379900cc9ac327b2147867b8b6efd88",
+ "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/bad4316aba5303d0221f43f8cee37eb58d384bbb",
+ "reference": "bad4316aba5303d0221f43f8cee37eb58d384bbb",
"shasum": ""
},
"require": {
- "nikic/php-parser": "^4.7",
- "php": ">=7.3"
+ "nikic/php-parser": "^5.0",
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "2.0-dev"
+ "dev-main": "5.0-dev"
}
},
"autoload": {
@@ -4874,7 +5172,8 @@
"homepage": "https://github.com/sebastianbergmann/complexity",
"support": {
"issues": "https://github.com/sebastianbergmann/complexity/issues",
- "source": "https://github.com/sebastianbergmann/complexity/tree/2.0.2"
+ "security": "https://github.com/sebastianbergmann/complexity/security/policy",
+ "source": "https://github.com/sebastianbergmann/complexity/tree/5.0.0"
},
"funding": [
{
@@ -4882,33 +5181,33 @@
"type": "github"
}
],
- "time": "2020-10-26T15:52:27+00:00"
+ "time": "2025-02-07T04:55:25+00:00"
},
{
"name": "sebastian/diff",
- "version": "4.0.5",
+ "version": "7.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/diff.git",
- "reference": "74be17022044ebaaecfdf0c5cd504fc9cd5a7131"
+ "reference": "7ab1ea946c012266ca32390913653d844ecd085f"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/74be17022044ebaaecfdf0c5cd504fc9cd5a7131",
- "reference": "74be17022044ebaaecfdf0c5cd504fc9cd5a7131",
+ "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/7ab1ea946c012266ca32390913653d844ecd085f",
+ "reference": "7ab1ea946c012266ca32390913653d844ecd085f",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3",
- "symfony/process": "^4.2 || ^5"
+ "phpunit/phpunit": "^12.0",
+ "symfony/process": "^7.2"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "4.0-dev"
+ "dev-main": "7.0-dev"
}
},
"autoload": {
@@ -4940,7 +5239,8 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/diff/issues",
- "source": "https://github.com/sebastianbergmann/diff/tree/4.0.5"
+ "security": "https://github.com/sebastianbergmann/diff/security/policy",
+ "source": "https://github.com/sebastianbergmann/diff/tree/7.0.0"
},
"funding": [
{
@@ -4948,27 +5248,27 @@
"type": "github"
}
],
- "time": "2023-05-07T05:35:17+00:00"
+ "time": "2025-02-07T04:55:46+00:00"
},
{
"name": "sebastian/environment",
- "version": "5.1.5",
+ "version": "8.1.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/environment.git",
- "reference": "830c43a844f1f8d5b7a1f6d6076b784454d8b7ed"
+ "reference": "9d32c685773823b1983e256ae4ecd48a10d6e439"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/830c43a844f1f8d5b7a1f6d6076b784454d8b7ed",
- "reference": "830c43a844f1f8d5b7a1f6d6076b784454d8b7ed",
+ "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/9d32c685773823b1983e256ae4ecd48a10d6e439",
+ "reference": "9d32c685773823b1983e256ae4ecd48a10d6e439",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.5.26"
},
"suggest": {
"ext-posix": "*"
@@ -4976,7 +5276,7 @@
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "5.1-dev"
+ "dev-main": "8.1-dev"
}
},
"autoload": {
@@ -4995,7 +5295,7 @@
}
],
"description": "Provides functionality to handle HHVM/PHP environments",
- "homepage": "http://www.github.com/sebastianbergmann/environment",
+ "homepage": "https://github.com/sebastianbergmann/environment",
"keywords": [
"Xdebug",
"environment",
@@ -5003,42 +5303,55 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/environment/issues",
- "source": "https://github.com/sebastianbergmann/environment/tree/5.1.5"
+ "security": "https://github.com/sebastianbergmann/environment/security/policy",
+ "source": "https://github.com/sebastianbergmann/environment/tree/8.1.2"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/environment",
+ "type": "tidelift"
}
],
- "time": "2023-02-03T06:03:51+00:00"
+ "time": "2026-05-25T13:40:20+00:00"
},
{
"name": "sebastian/exporter",
- "version": "4.0.5",
+ "version": "7.0.3",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/exporter.git",
- "reference": "ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d"
+ "reference": "c5e21b5de653ce0a769fb36f5cdfcb5e7a32cf23"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d",
- "reference": "ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d",
+ "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/c5e21b5de653ce0a769fb36f5cdfcb5e7a32cf23",
+ "reference": "c5e21b5de653ce0a769fb36f5cdfcb5e7a32cf23",
"shasum": ""
},
"require": {
- "php": ">=7.3",
- "sebastian/recursion-context": "^4.0"
+ "ext-mbstring": "*",
+ "php": ">=8.3",
+ "sebastian/recursion-context": "^7.0.1"
},
"require-dev": {
- "ext-mbstring": "*",
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.5.25"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "4.0-dev"
+ "dev-main": "7.0-dev"
}
},
"autoload": {
@@ -5080,46 +5393,56 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/exporter/issues",
- "source": "https://github.com/sebastianbergmann/exporter/tree/4.0.5"
+ "security": "https://github.com/sebastianbergmann/exporter/security/policy",
+ "source": "https://github.com/sebastianbergmann/exporter/tree/7.0.3"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/exporter",
+ "type": "tidelift"
}
],
- "time": "2022-09-14T06:03:37+00:00"
+ "time": "2026-05-20T04:37:17+00:00"
},
{
"name": "sebastian/global-state",
- "version": "5.0.6",
+ "version": "8.0.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/global-state.git",
- "reference": "bde739e7565280bda77be70044ac1047bc007e34"
+ "reference": "ef1377171613d09edd25b7816f05be8313f9115d"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bde739e7565280bda77be70044ac1047bc007e34",
- "reference": "bde739e7565280bda77be70044ac1047bc007e34",
+ "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/ef1377171613d09edd25b7816f05be8313f9115d",
+ "reference": "ef1377171613d09edd25b7816f05be8313f9115d",
"shasum": ""
},
"require": {
- "php": ">=7.3",
- "sebastian/object-reflector": "^2.0",
- "sebastian/recursion-context": "^4.0"
+ "php": ">=8.3",
+ "sebastian/object-reflector": "^5.0",
+ "sebastian/recursion-context": "^7.0"
},
"require-dev": {
"ext-dom": "*",
- "phpunit/phpunit": "^9.3"
- },
- "suggest": {
- "ext-uopz": "*"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "5.0-dev"
+ "dev-main": "8.0-dev"
}
},
"autoload": {
@@ -5138,47 +5461,60 @@
}
],
"description": "Snapshotting of global state",
- "homepage": "http://www.github.com/sebastianbergmann/global-state",
+ "homepage": "https://www.github.com/sebastianbergmann/global-state",
"keywords": [
"global state"
],
"support": {
"issues": "https://github.com/sebastianbergmann/global-state/issues",
- "source": "https://github.com/sebastianbergmann/global-state/tree/5.0.6"
+ "security": "https://github.com/sebastianbergmann/global-state/security/policy",
+ "source": "https://github.com/sebastianbergmann/global-state/tree/8.0.2"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/global-state",
+ "type": "tidelift"
}
],
- "time": "2023-08-02T09:26:13+00:00"
+ "time": "2025-08-29T11:29:25+00:00"
},
{
"name": "sebastian/lines-of-code",
- "version": "1.0.3",
+ "version": "4.0.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/lines-of-code.git",
- "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc"
+ "reference": "d543b8ef219dcd8da262cbb958639a96bedba10e"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/c1c2e997aa3146983ed888ad08b15470a2e22ecc",
- "reference": "c1c2e997aa3146983ed888ad08b15470a2e22ecc",
+ "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d543b8ef219dcd8da262cbb958639a96bedba10e",
+ "reference": "d543b8ef219dcd8da262cbb958639a96bedba10e",
"shasum": ""
},
"require": {
- "nikic/php-parser": "^4.6",
- "php": ">=7.3"
+ "nikic/php-parser": "^5.7.0",
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.5.25"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0-dev"
+ "dev-main": "4.0-dev"
}
},
"autoload": {
@@ -5201,42 +5537,55 @@
"homepage": "https://github.com/sebastianbergmann/lines-of-code",
"support": {
"issues": "https://github.com/sebastianbergmann/lines-of-code/issues",
- "source": "https://github.com/sebastianbergmann/lines-of-code/tree/1.0.3"
+ "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy",
+ "source": "https://github.com/sebastianbergmann/lines-of-code/tree/4.0.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/lines-of-code",
+ "type": "tidelift"
}
],
- "time": "2020-11-28T06:42:11+00:00"
+ "time": "2026-05-19T16:22:07+00:00"
},
{
"name": "sebastian/object-enumerator",
- "version": "4.0.4",
+ "version": "7.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/object-enumerator.git",
- "reference": "5c9eeac41b290a3712d88851518825ad78f45c71"
+ "reference": "1effe8e9b8e068e9ae228e542d5d11b5d16db894"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/5c9eeac41b290a3712d88851518825ad78f45c71",
- "reference": "5c9eeac41b290a3712d88851518825ad78f45c71",
+ "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/1effe8e9b8e068e9ae228e542d5d11b5d16db894",
+ "reference": "1effe8e9b8e068e9ae228e542d5d11b5d16db894",
"shasum": ""
},
"require": {
- "php": ">=7.3",
- "sebastian/object-reflector": "^2.0",
- "sebastian/recursion-context": "^4.0"
+ "php": ">=8.3",
+ "sebastian/object-reflector": "^5.0",
+ "sebastian/recursion-context": "^7.0"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "4.0-dev"
+ "dev-main": "7.0-dev"
}
},
"autoload": {
@@ -5258,7 +5607,8 @@
"homepage": "https://github.com/sebastianbergmann/object-enumerator/",
"support": {
"issues": "https://github.com/sebastianbergmann/object-enumerator/issues",
- "source": "https://github.com/sebastianbergmann/object-enumerator/tree/4.0.4"
+ "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy",
+ "source": "https://github.com/sebastianbergmann/object-enumerator/tree/7.0.0"
},
"funding": [
{
@@ -5266,32 +5616,32 @@
"type": "github"
}
],
- "time": "2020-10-26T13:12:34+00:00"
+ "time": "2025-02-07T04:57:48+00:00"
},
{
"name": "sebastian/object-reflector",
- "version": "2.0.4",
+ "version": "5.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/object-reflector.git",
- "reference": "b4f479ebdbf63ac605d183ece17d8d7fe49c15c7"
+ "reference": "4bfa827c969c98be1e527abd576533293c634f6a"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/b4f479ebdbf63ac605d183ece17d8d7fe49c15c7",
- "reference": "b4f479ebdbf63ac605d183ece17d8d7fe49c15c7",
+ "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/4bfa827c969c98be1e527abd576533293c634f6a",
+ "reference": "4bfa827c969c98be1e527abd576533293c634f6a",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "2.0-dev"
+ "dev-main": "5.0-dev"
}
},
"autoload": {
@@ -5313,7 +5663,8 @@
"homepage": "https://github.com/sebastianbergmann/object-reflector/",
"support": {
"issues": "https://github.com/sebastianbergmann/object-reflector/issues",
- "source": "https://github.com/sebastianbergmann/object-reflector/tree/2.0.4"
+ "security": "https://github.com/sebastianbergmann/object-reflector/security/policy",
+ "source": "https://github.com/sebastianbergmann/object-reflector/tree/5.0.0"
},
"funding": [
{
@@ -5321,32 +5672,32 @@
"type": "github"
}
],
- "time": "2020-10-26T13:14:26+00:00"
+ "time": "2025-02-07T04:58:17+00:00"
},
{
"name": "sebastian/recursion-context",
- "version": "4.0.5",
+ "version": "7.0.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/recursion-context.git",
- "reference": "e75bd0f07204fec2a0af9b0f3cfe97d05f92efc1"
+ "reference": "0b01998a7d5b1f122911a66bebcb8d46f0c82d8c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/e75bd0f07204fec2a0af9b0f3cfe97d05f92efc1",
- "reference": "e75bd0f07204fec2a0af9b0f3cfe97d05f92efc1",
+ "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/0b01998a7d5b1f122911a66bebcb8d46f0c82d8c",
+ "reference": "0b01998a7d5b1f122911a66bebcb8d46f0c82d8c",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.3"
+ "phpunit/phpunit": "^12.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "4.0-dev"
+ "dev-main": "7.0-dev"
}
},
"autoload": {
@@ -5376,40 +5727,53 @@
"homepage": "https://github.com/sebastianbergmann/recursion-context",
"support": {
"issues": "https://github.com/sebastianbergmann/recursion-context/issues",
- "source": "https://github.com/sebastianbergmann/recursion-context/tree/4.0.5"
+ "security": "https://github.com/sebastianbergmann/recursion-context/security/policy",
+ "source": "https://github.com/sebastianbergmann/recursion-context/tree/7.0.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/recursion-context",
+ "type": "tidelift"
}
],
- "time": "2023-02-03T06:07:39+00:00"
+ "time": "2025-08-13T04:44:59+00:00"
},
{
- "name": "sebastian/resource-operations",
- "version": "3.0.3",
+ "name": "sebastian/type",
+ "version": "6.0.4",
"source": {
"type": "git",
- "url": "https://github.com/sebastianbergmann/resource-operations.git",
- "reference": "0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8"
+ "url": "https://github.com/sebastianbergmann/type.git",
+ "reference": "82ff822c2edc46724be9f7411d3163021f602773"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8",
- "reference": "0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8",
+ "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/82ff822c2edc46724be9f7411d3163021f602773",
+ "reference": "82ff822c2edc46724be9f7411d3163021f602773",
"shasum": ""
},
"require": {
- "php": ">=7.3"
+ "php": ">=8.3"
},
"require-dev": {
- "phpunit/phpunit": "^9.0"
+ "phpunit/phpunit": "^12.5.25"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "3.0-dev"
+ "dev-main": "6.0-dev"
}
},
"autoload": {
@@ -5424,48 +5788,58 @@
"authors": [
{
"name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
+ "email": "sebastian@phpunit.de",
+ "role": "lead"
}
],
- "description": "Provides a list of PHP built-in functions that operate on resources",
- "homepage": "https://www.github.com/sebastianbergmann/resource-operations",
+ "description": "Collection of value objects that represent the types of the PHP type system",
+ "homepage": "https://github.com/sebastianbergmann/type",
"support": {
- "issues": "https://github.com/sebastianbergmann/resource-operations/issues",
- "source": "https://github.com/sebastianbergmann/resource-operations/tree/3.0.3"
+ "issues": "https://github.com/sebastianbergmann/type/issues",
+ "security": "https://github.com/sebastianbergmann/type/security/policy",
+ "source": "https://github.com/sebastianbergmann/type/tree/6.0.4"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
+ },
+ {
+ "url": "https://liberapay.com/sebastianbergmann",
+ "type": "liberapay"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/sebastianbergmann",
+ "type": "thanks_dev"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/sebastian/type",
+ "type": "tidelift"
}
],
- "abandoned": true,
- "time": "2020-09-28T06:45:17+00:00"
+ "time": "2026-05-20T06:45:45+00:00"
},
{
- "name": "sebastian/type",
- "version": "3.2.1",
+ "name": "sebastian/version",
+ "version": "6.0.0",
"source": {
"type": "git",
- "url": "https://github.com/sebastianbergmann/type.git",
- "reference": "75e2c2a32f5e0b3aef905b9ed0b179b953b3d7c7"
+ "url": "https://github.com/sebastianbergmann/version.git",
+ "reference": "3e6ccf7657d4f0a59200564b08cead899313b53c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/75e2c2a32f5e0b3aef905b9ed0b179b953b3d7c7",
- "reference": "75e2c2a32f5e0b3aef905b9ed0b179b953b3d7c7",
+ "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/3e6ccf7657d4f0a59200564b08cead899313b53c",
+ "reference": "3e6ccf7657d4f0a59200564b08cead899313b53c",
"shasum": ""
},
"require": {
- "php": ">=7.3"
- },
- "require-dev": {
- "phpunit/phpunit": "^9.5"
+ "php": ">=8.3"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "3.2-dev"
+ "dev-main": "6.0-dev"
}
},
"autoload": {
@@ -5484,11 +5858,12 @@
"role": "lead"
}
],
- "description": "Collection of value objects that represent the types of the PHP type system",
- "homepage": "https://github.com/sebastianbergmann/type",
+ "description": "Library that helps with managing the version number of Git-hosted PHP projects",
+ "homepage": "https://github.com/sebastianbergmann/version",
"support": {
- "issues": "https://github.com/sebastianbergmann/type/issues",
- "source": "https://github.com/sebastianbergmann/type/tree/3.2.1"
+ "issues": "https://github.com/sebastianbergmann/version/issues",
+ "security": "https://github.com/sebastianbergmann/version/security/policy",
+ "source": "https://github.com/sebastianbergmann/version/tree/6.0.0"
},
"funding": [
{
@@ -5496,94 +5871,36 @@
"type": "github"
}
],
- "time": "2023-02-03T06:13:03+00:00"
- },
- {
- "name": "sebastian/version",
- "version": "3.0.2",
- "source": {
- "type": "git",
- "url": "https://github.com/sebastianbergmann/version.git",
- "reference": "c6c1022351a901512170118436c764e473f6de8c"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c6c1022351a901512170118436c764e473f6de8c",
- "reference": "c6c1022351a901512170118436c764e473f6de8c",
- "shasum": ""
- },
- "require": {
- "php": ">=7.3"
- },
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "3.0-dev"
- }
- },
- "autoload": {
- "classmap": [
- "src/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "BSD-3-Clause"
- ],
- "authors": [
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de",
- "role": "lead"
- }
- ],
- "description": "Library that helps with managing the version number of Git-hosted PHP projects",
- "homepage": "https://github.com/sebastianbergmann/version",
- "support": {
- "issues": "https://github.com/sebastianbergmann/version/issues",
- "source": "https://github.com/sebastianbergmann/version/tree/3.0.2"
- },
- "funding": [
- {
- "url": "https://github.com/sebastianbergmann",
- "type": "github"
- }
- ],
- "time": "2020-09-28T06:39:44+00:00"
+ "time": "2025-02-07T05:00:38+00:00"
},
{
"name": "squizlabs/php_codesniffer",
- "version": "3.8.0",
+ "version": "4.0.1",
"source": {
"type": "git",
"url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git",
- "reference": "5805f7a4e4958dbb5e944ef1e6edae0a303765e7"
+ "reference": "0525c73950de35ded110cffafb9892946d7771b5"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/5805f7a4e4958dbb5e944ef1e6edae0a303765e7",
- "reference": "5805f7a4e4958dbb5e944ef1e6edae0a303765e7",
+ "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/0525c73950de35ded110cffafb9892946d7771b5",
+ "reference": "0525c73950de35ded110cffafb9892946d7771b5",
"shasum": ""
},
"require": {
"ext-simplexml": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*",
- "php": ">=5.4.0"
+ "php": ">=7.2.0"
},
"require-dev": {
- "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0"
+ "phpunit/phpunit": "^8.4.0 || ^9.3.4 || ^10.5.32 || 11.3.3 - 11.5.28 || ^11.5.31"
},
"bin": [
- "bin/phpcs",
- "bin/phpcbf"
+ "bin/phpcbf",
+ "bin/phpcs"
],
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "3.x-dev"
- }
- },
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
@@ -5602,7 +5919,7 @@
"homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer/graphs/contributors"
}
],
- "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.",
+ "description": "PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.",
"homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer",
"keywords": [
"phpcs",
@@ -5627,44 +5944,95 @@
{
"url": "https://opencollective.com/php_codesniffer",
"type": "open_collective"
+ },
+ {
+ "url": "https://thanks.dev/u/gh/phpcsstandards",
+ "type": "thanks_dev"
+ }
+ ],
+ "time": "2025-11-10T16:43:36+00:00"
+ },
+ {
+ "name": "staabm/side-effects-detector",
+ "version": "1.0.5",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/staabm/side-effects-detector.git",
+ "reference": "d8334211a140ce329c13726d4a715adbddd0a163"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/staabm/side-effects-detector/zipball/d8334211a140ce329c13726d4a715adbddd0a163",
+ "reference": "d8334211a140ce329c13726d4a715adbddd0a163",
+ "shasum": ""
+ },
+ "require": {
+ "ext-tokenizer": "*",
+ "php": "^7.4 || ^8.0"
+ },
+ "require-dev": {
+ "phpstan/extension-installer": "^1.4.3",
+ "phpstan/phpstan": "^1.12.6",
+ "phpunit/phpunit": "^9.6.21",
+ "symfony/var-dumper": "^5.4.43",
+ "tomasvotruba/type-coverage": "1.0.0",
+ "tomasvotruba/unused-public": "1.0.0"
+ },
+ "type": "library",
+ "autoload": {
+ "classmap": [
+ "lib/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "A static analysis tool to detect side effects in PHP code",
+ "keywords": [
+ "static analysis"
+ ],
+ "support": {
+ "issues": "https://github.com/staabm/side-effects-detector/issues",
+ "source": "https://github.com/staabm/side-effects-detector/tree/1.0.5"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/staabm",
+ "type": "github"
}
],
- "time": "2023-12-08T12:32:31+00:00"
+ "time": "2024-10-20T05:08:20+00:00"
},
{
"name": "symfony/config",
- "version": "v5.4.31",
+ "version": "v8.1.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/config.git",
- "reference": "dd5ea39de228813aba0c23c3a4153da2a4cf3cd9"
+ "reference": "429783a0c649696f2058ea5ab5315f082dba6de9"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/config/zipball/dd5ea39de228813aba0c23c3a4153da2a4cf3cd9",
- "reference": "dd5ea39de228813aba0c23c3a4153da2a4cf3cd9",
+ "url": "https://api.github.com/repos/symfony/config/zipball/429783a0c649696f2058ea5ab5315f082dba6de9",
+ "reference": "429783a0c649696f2058ea5ab5315f082dba6de9",
"shasum": ""
},
"require": {
- "php": ">=7.2.5",
- "symfony/deprecation-contracts": "^2.1|^3",
- "symfony/filesystem": "^4.4|^5.0|^6.0",
- "symfony/polyfill-ctype": "~1.8",
- "symfony/polyfill-php80": "^1.16",
- "symfony/polyfill-php81": "^1.22"
+ "php": ">=8.4.1",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/filesystem": "^7.4|^8.0",
+ "symfony/polyfill-ctype": "^1.8"
},
"conflict": {
- "symfony/finder": "<4.4"
+ "symfony/service-contracts": "<2.5"
},
"require-dev": {
- "symfony/event-dispatcher": "^4.4|^5.0|^6.0",
- "symfony/finder": "^4.4|^5.0|^6.0",
- "symfony/messenger": "^4.4|^5.0|^6.0",
- "symfony/service-contracts": "^1.1|^2|^3",
- "symfony/yaml": "^4.4|^5.0|^6.0"
- },
- "suggest": {
- "symfony/yaml": "To use the yaml reference dumper"
+ "symfony/event-dispatcher": "^7.4|^8.0",
+ "symfony/finder": "^7.4|^8.0",
+ "symfony/messenger": "^7.4|^8.0",
+ "symfony/service-contracts": "^2.5|^3",
+ "symfony/yaml": "^7.4|^8.0"
},
"type": "library",
"autoload": {
@@ -5692,7 +6060,7 @@
"description": "Helps you find, load, combine, autofill and validate configuration values of any kind",
"homepage": "https://symfony.com",
"support": {
- "source": "https://github.com/symfony/config/tree/v5.4.31"
+ "source": "https://github.com/symfony/config/tree/v8.1.0"
},
"funding": [
{
@@ -5703,58 +6071,62 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-11-09T08:22:43+00:00"
+ "time": "2026-05-29T05:06:50+00:00"
},
{
"name": "symfony/console",
- "version": "v4.4.49",
+ "version": "v8.1.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
- "reference": "33fa45ffc81fdcc1ca368d4946da859c8cdb58d9"
+ "reference": "f5a856c6ecb56b3c21ed94a5b7bf940d857d110a"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/console/zipball/33fa45ffc81fdcc1ca368d4946da859c8cdb58d9",
- "reference": "33fa45ffc81fdcc1ca368d4946da859c8cdb58d9",
+ "url": "https://api.github.com/repos/symfony/console/zipball/f5a856c6ecb56b3c21ed94a5b7bf940d857d110a",
+ "reference": "f5a856c6ecb56b3c21ed94a5b7bf940d857d110a",
"shasum": ""
},
"require": {
- "php": ">=7.1.3",
- "symfony/polyfill-mbstring": "~1.0",
- "symfony/polyfill-php73": "^1.8",
- "symfony/polyfill-php80": "^1.16",
- "symfony/service-contracts": "^1.1|^2"
+ "php": ">=8.4.1",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-mbstring": "^1.0",
+ "symfony/polyfill-php85": "^1.32",
+ "symfony/service-contracts": "^2.5|^3",
+ "symfony/string": "^7.4.6|^8.0.6"
},
"conflict": {
- "psr/log": ">=3",
- "symfony/dependency-injection": "<3.4",
- "symfony/event-dispatcher": "<4.3|>=5",
- "symfony/lock": "<4.4",
- "symfony/process": "<3.3"
+ "symfony/dependency-injection": "<8.1",
+ "symfony/event-dispatcher": "<8.1"
},
"provide": {
- "psr/log-implementation": "1.0|2.0"
+ "psr/log-implementation": "1.0|2.0|3.0"
},
"require-dev": {
- "psr/log": "^1|^2",
- "symfony/config": "^3.4|^4.0|^5.0",
- "symfony/dependency-injection": "^3.4|^4.0|^5.0",
- "symfony/event-dispatcher": "^4.3",
- "symfony/lock": "^4.4|^5.0",
- "symfony/process": "^3.4|^4.0|^5.0",
- "symfony/var-dumper": "^4.3|^5.0"
- },
- "suggest": {
- "psr/log": "For using the console logger",
- "symfony/event-dispatcher": "",
- "symfony/lock": "",
- "symfony/process": ""
+ "psr/log": "^1|^2|^3",
+ "symfony/config": "^7.4|^8.0",
+ "symfony/dependency-injection": "^8.1",
+ "symfony/event-dispatcher": "^8.1",
+ "symfony/filesystem": "^7.4|^8.0",
+ "symfony/http-foundation": "^7.4|^8.0",
+ "symfony/http-kernel": "^7.4|^8.0",
+ "symfony/lock": "^7.4|^8.0",
+ "symfony/messenger": "^7.4|^8.0",
+ "symfony/mime": "^7.4|^8.0",
+ "symfony/process": "^7.4|^8.0",
+ "symfony/stopwatch": "^7.4|^8.0",
+ "symfony/uid": "^7.4|^8.0",
+ "symfony/validator": "^7.4|^8.0",
+ "symfony/var-dumper": "^7.4|^8.0"
},
"type": "library",
"autoload": {
@@ -5781,8 +6153,14 @@
],
"description": "Eases the creation of beautiful and testable command line interfaces",
"homepage": "https://symfony.com",
+ "keywords": [
+ "cli",
+ "command-line",
+ "console",
+ "terminal"
+ ],
"support": {
- "source": "https://github.com/symfony/console/tree/v4.4.49"
+ "source": "https://github.com/symfony/console/tree/v8.1.0"
},
"funding": [
{
@@ -5793,37 +6171,54 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2022-11-05T17:10:16+00:00"
+ "time": "2026-05-29T05:06:50+00:00"
},
{
- "name": "symfony/filesystem",
- "version": "v5.4.25",
+ "name": "symfony/dependency-injection",
+ "version": "v8.1.0",
"source": {
"type": "git",
- "url": "https://github.com/symfony/filesystem.git",
- "reference": "0ce3a62c9579a53358d3a7eb6b3dfb79789a6364"
+ "url": "https://github.com/symfony/dependency-injection.git",
+ "reference": "b6ba1f45127106885de4b77558c5ecca8feb1e1b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/filesystem/zipball/0ce3a62c9579a53358d3a7eb6b3dfb79789a6364",
- "reference": "0ce3a62c9579a53358d3a7eb6b3dfb79789a6364",
+ "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/b6ba1f45127106885de4b77558c5ecca8feb1e1b",
+ "reference": "b6ba1f45127106885de4b77558c5ecca8feb1e1b",
"shasum": ""
},
"require": {
- "php": ">=7.2.5",
- "symfony/polyfill-ctype": "~1.8",
- "symfony/polyfill-mbstring": "~1.8",
- "symfony/polyfill-php80": "^1.16"
+ "php": ">=8.4.1",
+ "psr/container": "^1.1|^2.0",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/service-contracts": "^3.6",
+ "symfony/var-exporter": "^8.1"
+ },
+ "conflict": {
+ "ext-psr": "<1.1|>=2"
+ },
+ "provide": {
+ "psr/container-implementation": "1.1|2.0",
+ "symfony/service-implementation": "1.1|2.0|3.0"
+ },
+ "require-dev": {
+ "symfony/config": "^7.4|^8.0",
+ "symfony/expression-language": "^7.4|^8.0",
+ "symfony/yaml": "^7.4|^8.0"
},
"type": "library",
"autoload": {
"psr-4": {
- "Symfony\\Component\\Filesystem\\": ""
+ "Symfony\\Component\\DependencyInjection\\": ""
},
"exclude-from-classmap": [
"/Tests/"
@@ -5843,10 +6238,10 @@
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Provides basic utilities for the filesystem",
+ "description": "Allows you to standardize and centralize the way objects are constructed in your application",
"homepage": "https://symfony.com",
"support": {
- "source": "https://github.com/symfony/filesystem/tree/v5.4.25"
+ "source": "https://github.com/symfony/dependency-injection/tree/v8.1.0"
},
"funding": [
{
@@ -5857,49 +6252,57 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-05-31T13:04:02+00:00"
+ "time": "2026-05-29T05:06:50+00:00"
},
{
- "name": "symfony/polyfill-php73",
- "version": "v1.28.0",
+ "name": "symfony/error-handler",
+ "version": "v8.1.0",
"source": {
"type": "git",
- "url": "https://github.com/symfony/polyfill-php73.git",
- "reference": "fe2f306d1d9d346a7fee353d0d5012e401e984b5"
+ "url": "https://github.com/symfony/error-handler.git",
+ "reference": "d8aeb1abd3fef84795567850d3a567bdb5945ee5"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/fe2f306d1d9d346a7fee353d0d5012e401e984b5",
- "reference": "fe2f306d1d9d346a7fee353d0d5012e401e984b5",
+ "url": "https://api.github.com/repos/symfony/error-handler/zipball/d8aeb1abd3fef84795567850d3a567bdb5945ee5",
+ "reference": "d8aeb1abd3fef84795567850d3a567bdb5945ee5",
"shasum": ""
},
"require": {
- "php": ">=7.1"
+ "php": ">=8.4.1",
+ "psr/log": "^1|^2|^3",
+ "symfony/polyfill-php85": "^1.32",
+ "symfony/var-dumper": "^7.4|^8.0"
},
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-main": "1.28-dev"
- },
- "thanks": {
- "name": "symfony/polyfill",
- "url": "https://github.com/symfony/polyfill"
- }
+ "conflict": {
+ "symfony/deprecation-contracts": "<2.5"
+ },
+ "require-dev": {
+ "symfony/console": "^7.4|^8.0",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/http-kernel": "^7.4|^8.0",
+ "symfony/serializer": "^7.4|^8.0",
+ "symfony/webpack-encore-bundle": "^1.0|^2.0"
},
+ "bin": [
+ "Resources/bin/patch-type-declarations"
+ ],
+ "type": "library",
"autoload": {
- "files": [
- "bootstrap.php"
- ],
"psr-4": {
- "Symfony\\Polyfill\\Php73\\": ""
+ "Symfony\\Component\\ErrorHandler\\": ""
},
- "classmap": [
- "Resources/stubs"
+ "exclude-from-classmap": [
+ "/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
@@ -5908,24 +6311,18 @@
],
"authors": [
{
- "name": "Nicolas Grekas",
- "email": "p@tchwork.com"
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions",
+ "description": "Provides tools to manage errors and ease debugging PHP code",
"homepage": "https://symfony.com",
- "keywords": [
- "compatibility",
- "polyfill",
- "portable",
- "shim"
- ],
"support": {
- "source": "https://github.com/symfony/polyfill-php73/tree/v1.28.0"
+ "source": "https://github.com/symfony/error-handler/tree/v8.1.0"
},
"funding": [
{
@@ -5936,49 +6333,62 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-01-26T09:26:14+00:00"
+ "time": "2026-05-29T05:06:50+00:00"
},
{
- "name": "symfony/polyfill-php81",
- "version": "v1.28.0",
+ "name": "symfony/event-dispatcher",
+ "version": "v8.1.0",
"source": {
"type": "git",
- "url": "https://github.com/symfony/polyfill-php81.git",
- "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b"
+ "url": "https://github.com/symfony/event-dispatcher.git",
+ "reference": "f249ae3f680958b6f1f9dd76e5747cf0695b4102"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/7581cd600fa9fd681b797d00b02f068e2f13263b",
- "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b",
+ "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/f249ae3f680958b6f1f9dd76e5747cf0695b4102",
+ "reference": "f249ae3f680958b6f1f9dd76e5747cf0695b4102",
"shasum": ""
},
"require": {
- "php": ">=7.1"
+ "php": ">=8.4.1",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/event-dispatcher-contracts": "^2.5|^3"
},
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-main": "1.28-dev"
- },
- "thanks": {
- "name": "symfony/polyfill",
- "url": "https://github.com/symfony/polyfill"
- }
+ "conflict": {
+ "symfony/security-http": "<7.4",
+ "symfony/service-contracts": "<2.5"
+ },
+ "provide": {
+ "psr/event-dispatcher-implementation": "1.0",
+ "symfony/event-dispatcher-implementation": "2.0|3.0"
+ },
+ "require-dev": {
+ "psr/log": "^1|^2|^3",
+ "symfony/config": "^7.4|^8.0",
+ "symfony/dependency-injection": "^7.4|^8.0",
+ "symfony/error-handler": "^7.4|^8.0",
+ "symfony/expression-language": "^7.4|^8.0",
+ "symfony/framework-bundle": "^7.4|^8.0",
+ "symfony/http-foundation": "^7.4|^8.0",
+ "symfony/service-contracts": "^2.5|^3",
+ "symfony/stopwatch": "^7.4|^8.0"
},
+ "type": "library",
"autoload": {
- "files": [
- "bootstrap.php"
- ],
"psr-4": {
- "Symfony\\Polyfill\\Php81\\": ""
+ "Symfony\\Component\\EventDispatcher\\": ""
},
- "classmap": [
- "Resources/stubs"
+ "exclude-from-classmap": [
+ "/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
@@ -5987,24 +6397,18 @@
],
"authors": [
{
- "name": "Nicolas Grekas",
- "email": "p@tchwork.com"
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions",
+ "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them",
"homepage": "https://symfony.com",
- "keywords": [
- "compatibility",
- "polyfill",
- "portable",
- "shim"
- ],
"support": {
- "source": "https://github.com/symfony/polyfill-php81/tree/v1.28.0"
+ "source": "https://github.com/symfony/event-dispatcher/tree/v8.1.0"
},
"funding": [
{
@@ -6015,51 +6419,48 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-01-26T09:26:14+00:00"
+ "time": "2026-05-29T05:06:50+00:00"
},
{
- "name": "symfony/service-contracts",
- "version": "v2.5.2",
+ "name": "symfony/event-dispatcher-contracts",
+ "version": "v3.7.0",
"source": {
"type": "git",
- "url": "https://github.com/symfony/service-contracts.git",
- "reference": "4b426aac47d6427cc1a1d0f7e2ac724627f5966c"
+ "url": "https://github.com/symfony/event-dispatcher-contracts.git",
+ "reference": "ccba7060602b7fed0b03c85bf025257f76d9ef32"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/service-contracts/zipball/4b426aac47d6427cc1a1d0f7e2ac724627f5966c",
- "reference": "4b426aac47d6427cc1a1d0f7e2ac724627f5966c",
+ "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/ccba7060602b7fed0b03c85bf025257f76d9ef32",
+ "reference": "ccba7060602b7fed0b03c85bf025257f76d9ef32",
"shasum": ""
},
"require": {
- "php": ">=7.2.5",
- "psr/container": "^1.1",
- "symfony/deprecation-contracts": "^2.1|^3"
- },
- "conflict": {
- "ext-psr": "<1.1|>=2"
- },
- "suggest": {
- "symfony/service-implementation": ""
+ "php": ">=8.1",
+ "psr/event-dispatcher": "^1"
},
"type": "library",
"extra": {
- "branch-alias": {
- "dev-main": "2.5-dev"
- },
"thanks": {
- "name": "symfony/contracts",
- "url": "https://github.com/symfony/contracts"
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.7-dev"
}
},
"autoload": {
"psr-4": {
- "Symfony\\Contracts\\Service\\": ""
+ "Symfony\\Contracts\\EventDispatcher\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
@@ -6076,7 +6477,7 @@
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Generic abstractions related to writing services",
+ "description": "Generic abstractions related to dispatching event",
"homepage": "https://symfony.com",
"keywords": [
"abstractions",
@@ -6087,7 +6488,7 @@
"standards"
],
"support": {
- "source": "https://github.com/symfony/service-contracts/tree/v2.5.2"
+ "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.7.0"
},
"funding": [
{
@@ -6098,35 +6499,44 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2022-05-30T19:17:29+00:00"
+ "time": "2026-01-05T13:30:16+00:00"
},
{
- "name": "symfony/stopwatch",
- "version": "v5.4.21",
+ "name": "symfony/filesystem",
+ "version": "v8.1.0",
"source": {
"type": "git",
- "url": "https://github.com/symfony/stopwatch.git",
- "reference": "f83692cd869a6f2391691d40a01e8acb89e76fee"
+ "url": "https://github.com/symfony/filesystem.git",
+ "reference": "99aec13b82b4967ec5088222c4a3ecca955949c2"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/stopwatch/zipball/f83692cd869a6f2391691d40a01e8acb89e76fee",
- "reference": "f83692cd869a6f2391691d40a01e8acb89e76fee",
+ "url": "https://api.github.com/repos/symfony/filesystem/zipball/99aec13b82b4967ec5088222c4a3ecca955949c2",
+ "reference": "99aec13b82b4967ec5088222c4a3ecca955949c2",
"shasum": ""
},
"require": {
- "php": ">=7.2.5",
- "symfony/service-contracts": "^1|^2|^3"
+ "php": ">=8.4.1",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-ctype": "~1.8",
+ "symfony/polyfill-mbstring": "~1.8"
+ },
+ "require-dev": {
+ "symfony/process": "^7.4|^8.0"
},
"type": "library",
"autoload": {
"psr-4": {
- "Symfony\\Component\\Stopwatch\\": ""
+ "Symfony\\Component\\Filesystem\\": ""
},
"exclude-from-classmap": [
"/Tests/"
@@ -6146,10 +6556,10 @@
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Provides a way to profile code",
+ "description": "Provides basic utilities for the filesystem",
"homepage": "https://symfony.com",
"support": {
- "source": "https://github.com/symfony/stopwatch/tree/v5.4.21"
+ "source": "https://github.com/symfony/filesystem/tree/v8.1.0"
},
"funding": [
{
@@ -6160,44 +6570,41 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2023-02-14T08:03:56+00:00"
+ "time": "2026-05-29T05:06:50+00:00"
},
{
- "name": "symfony/yaml",
- "version": "v3.4.47",
+ "name": "symfony/finder",
+ "version": "v8.1.0",
"source": {
"type": "git",
- "url": "https://github.com/symfony/yaml.git",
- "reference": "88289caa3c166321883f67fe5130188ebbb47094"
+ "url": "https://github.com/symfony/finder.git",
+ "reference": "58d2e767a66052c1487356f953445634a8194c64"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symfony/yaml/zipball/88289caa3c166321883f67fe5130188ebbb47094",
- "reference": "88289caa3c166321883f67fe5130188ebbb47094",
+ "url": "https://api.github.com/repos/symfony/finder/zipball/58d2e767a66052c1487356f953445634a8194c64",
+ "reference": "58d2e767a66052c1487356f953445634a8194c64",
"shasum": ""
},
"require": {
- "php": "^5.5.9|>=7.0.8",
- "symfony/polyfill-ctype": "~1.8"
- },
- "conflict": {
- "symfony/console": "<3.4"
+ "php": ">=8.4.1"
},
"require-dev": {
- "symfony/console": "~3.4|~4.0"
- },
- "suggest": {
- "symfony/console": "For validating YAML files using the lint command"
+ "symfony/filesystem": "^7.4|^8.0"
},
"type": "library",
"autoload": {
"psr-4": {
- "Symfony\\Component\\Yaml\\": ""
+ "Symfony\\Component\\Finder\\": ""
},
"exclude-from-classmap": [
"/Tests/"
@@ -6217,10 +6624,10 @@
"homepage": "https://symfony.com/contributors"
}
],
- "description": "Symfony Yaml Component",
+ "description": "Finds files and directories via an intuitive fluent interface",
"homepage": "https://symfony.com",
"support": {
- "source": "https://github.com/symfony/yaml/tree/v3.4.47"
+ "source": "https://github.com/symfony/finder/tree/v8.1.0"
},
"funding": [
{
@@ -6231,78 +6638,1050 @@
"url": "https://github.com/fabpot",
"type": "github"
},
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
- "time": "2020-10-24T10:57:07+00:00"
+ "time": "2026-05-29T05:06:50+00:00"
},
{
- "name": "symplify/monorepo-builder",
- "version": "10.3.3",
+ "name": "symfony/http-foundation",
+ "version": "v8.1.0",
"source": {
"type": "git",
- "url": "https://github.com/symplify/monorepo-builder.git",
- "reference": "5f97613a2015b74aa86a7330b47a88c283877fd4"
+ "url": "https://github.com/symfony/http-foundation.git",
+ "reference": "af11474600f06718086c2cda4fa6fa8d0a672e7e"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/symplify/monorepo-builder/zipball/5f97613a2015b74aa86a7330b47a88c283877fd4",
- "reference": "5f97613a2015b74aa86a7330b47a88c283877fd4",
+ "url": "https://api.github.com/repos/symfony/http-foundation/zipball/af11474600f06718086c2cda4fa6fa8d0a672e7e",
+ "reference": "af11474600f06718086c2cda4fa6fa8d0a672e7e",
"shasum": ""
},
"require": {
- "php": ">=7.2"
+ "php": ">=8.4.1",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-mbstring": "^1.1"
+ },
+ "conflict": {
+ "doctrine/dbal": "<4.3"
+ },
+ "require-dev": {
+ "doctrine/dbal": "^4.3",
+ "predis/predis": "^1.1|^2.0",
+ "symfony/cache": "^7.4|^8.0",
+ "symfony/clock": "^7.4|^8.0",
+ "symfony/dependency-injection": "^7.4|^8.0",
+ "symfony/expression-language": "^7.4|^8.0",
+ "symfony/http-kernel": "^7.4|^8.0",
+ "symfony/mime": "^7.4|^8.0",
+ "symfony/rate-limiter": "^7.4|^8.0"
},
- "bin": [
- "bin/monorepo-builder"
- ],
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-main": "10.3-dev"
- }
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\HttpFoundation\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
- "description": "Prefixed version of Not only Composer tools to build a Monorepo.",
- "support": {
- "source": "https://github.com/symplify/monorepo-builder/tree/10.3.3"
- },
- "funding": [
+ "authors": [
{
- "url": "https://www.paypal.me/rectorphp",
- "type": "custom"
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Defines an object-oriented layer for the HTTP specification",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/http-foundation/tree/v8.1.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-29T05:06:50+00:00"
+ },
+ {
+ "name": "symfony/http-kernel",
+ "version": "v8.1.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/http-kernel.git",
+ "reference": "cefeb37c82eed3e0c42fa25ba64cd3a908d90f39"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/http-kernel/zipball/cefeb37c82eed3e0c42fa25ba64cd3a908d90f39",
+ "reference": "cefeb37c82eed3e0c42fa25ba64cd3a908d90f39",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.4.1",
+ "psr/log": "^1|^2|^3",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/error-handler": "^7.4|^8.0",
+ "symfony/event-dispatcher": "^7.4|^8.0",
+ "symfony/http-foundation": "^7.4|^8.0",
+ "symfony/polyfill-ctype": "^1.8"
+ },
+ "conflict": {
+ "symfony/dependency-injection": "<8.1",
+ "symfony/flex": "<2.10",
+ "symfony/http-client-contracts": "<2.5",
+ "symfony/translation-contracts": "<2.5",
+ "symfony/var-dumper": "<8.1",
+ "symfony/web-profiler-bundle": "<8.1",
+ "twig/twig": "<3.21"
+ },
+ "provide": {
+ "psr/log-implementation": "1.0|2.0|3.0"
+ },
+ "require-dev": {
+ "psr/cache": "^1.0|^2.0|^3.0",
+ "symfony/browser-kit": "^7.4|^8.0",
+ "symfony/clock": "^7.4|^8.0",
+ "symfony/config": "^7.4|^8.0",
+ "symfony/console": "^7.4|^8.0",
+ "symfony/css-selector": "^7.4|^8.0",
+ "symfony/dependency-injection": "^8.1",
+ "symfony/dom-crawler": "^7.4|^8.0",
+ "symfony/expression-language": "^7.4|^8.0",
+ "symfony/finder": "^7.4|^8.0",
+ "symfony/http-client-contracts": "^2.5|^3",
+ "symfony/process": "^7.4|^8.0",
+ "symfony/property-access": "^7.4|^8.0",
+ "symfony/rate-limiter": "^7.4|^8.0",
+ "symfony/routing": "^7.4|^8.0",
+ "symfony/serializer": "^7.4|^8.0",
+ "symfony/stopwatch": "^7.4|^8.0",
+ "symfony/translation": "^7.4|^8.0",
+ "symfony/translation-contracts": "^2.5|^3",
+ "symfony/uid": "^7.4|^8.0",
+ "symfony/validator": "^7.4|^8.0",
+ "symfony/var-dumper": "^8.1",
+ "symfony/var-exporter": "^7.4|^8.0",
+ "twig/twig": "^3.21"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\HttpKernel\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides a structured process for converting a Request into a Response",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/http-kernel/tree/v8.1.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-29T08:46:08+00:00"
+ },
+ {
+ "name": "symfony/polyfill-deepclone",
+ "version": "v1.37.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-deepclone.git",
+ "reference": "2ca9e9e75ead5174f2b44613a646bdc9338b8eb4"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-deepclone/zipball/2ca9e9e75ead5174f2b44613a646bdc9338b8eb4",
+ "reference": "2ca9e9e75ead5174f2b44613a646bdc9338b8eb4",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1"
+ },
+ "provide": {
+ "ext-deepclone": "*"
+ },
+ "suggest": {
+ "ext-deepclone": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\DeepClone\\": ""
+ },
+ "classmap": [
+ "Resources/stubs"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for the deepclone extension",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "deepclone",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/polyfill-deepclone/tree/v1.37.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-04-26T13:03:27+00:00"
+ },
+ {
+ "name": "symfony/polyfill-intl-grapheme",
+ "version": "v1.38.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-intl-grapheme.git",
+ "reference": "e9247d281d694a5120554d9afaf54e070e88a603"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/e9247d281d694a5120554d9afaf54e070e88a603",
+ "reference": "e9247d281d694a5120554d9afaf54e070e88a603",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.2"
+ },
+ "suggest": {
+ "ext-intl": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Intl\\Grapheme\\": ""
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for intl's grapheme_* functions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "grapheme",
+ "intl",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.38.1"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-26T05:58:03+00:00"
+ },
+ {
+ "name": "symfony/polyfill-intl-normalizer",
+ "version": "v1.38.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-intl-normalizer.git",
+ "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/2d446c214bdbe5b71bde5011b060a05fece3ae6b",
+ "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.2"
+ },
+ "suggest": {
+ "ext-intl": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/polyfill",
+ "name": "symfony/polyfill"
+ }
+ },
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ],
+ "psr-4": {
+ "Symfony\\Polyfill\\Intl\\Normalizer\\": ""
+ },
+ "classmap": [
+ "Resources/stubs"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for intl's Normalizer class and related functions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "intl",
+ "normalizer",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.38.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-25T13:48:31+00:00"
+ },
+ {
+ "name": "symfony/service-contracts",
+ "version": "v3.7.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/service-contracts.git",
+ "reference": "d25d82433a80eba6aa0e6c24b61d7370d99e444a"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/service-contracts/zipball/d25d82433a80eba6aa0e6c24b61d7370d99e444a",
+ "reference": "d25d82433a80eba6aa0e6c24b61d7370d99e444a",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.1",
+ "psr/container": "^1.1|^2.0",
+ "symfony/deprecation-contracts": "^2.5|^3"
+ },
+ "conflict": {
+ "ext-psr": "<1.1|>=2"
+ },
+ "type": "library",
+ "extra": {
+ "thanks": {
+ "url": "https://github.com/symfony/contracts",
+ "name": "symfony/contracts"
+ },
+ "branch-alias": {
+ "dev-main": "3.7-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Contracts\\Service\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Test/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Generic abstractions related to writing services",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "abstractions",
+ "contracts",
+ "decoupling",
+ "interfaces",
+ "interoperability",
+ "standards"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/service-contracts/tree/v3.7.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-03-28T09:44:51+00:00"
+ },
+ {
+ "name": "symfony/stopwatch",
+ "version": "v8.1.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/stopwatch.git",
+ "reference": "21c07b026905d596e8379caeb115d87aa479499d"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/stopwatch/zipball/21c07b026905d596e8379caeb115d87aa479499d",
+ "reference": "21c07b026905d596e8379caeb115d87aa479499d",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.4.1",
+ "symfony/service-contracts": "^2.5|^3"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Stopwatch\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides a way to profile code",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/stopwatch/tree/v8.1.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-29T05:06:50+00:00"
+ },
+ {
+ "name": "symfony/string",
+ "version": "v8.1.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/string.git",
+ "reference": "afd5944f4005862d961efb85c8bbd5c523c4e3c9"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/string/zipball/afd5944f4005862d961efb85c8bbd5c523c4e3c9",
+ "reference": "afd5944f4005862d961efb85c8bbd5c523c4e3c9",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.4.1",
+ "symfony/polyfill-ctype": "^1.8",
+ "symfony/polyfill-intl-grapheme": "^1.33",
+ "symfony/polyfill-intl-normalizer": "^1.0",
+ "symfony/polyfill-mbstring": "^1.0"
+ },
+ "conflict": {
+ "symfony/translation-contracts": "<2.5"
+ },
+ "require-dev": {
+ "symfony/emoji": "^7.4|^8.0",
+ "symfony/http-client": "^7.4|^8.0",
+ "symfony/intl": "^7.4|^8.0",
+ "symfony/translation-contracts": "^2.5|^3.0",
+ "symfony/var-exporter": "^7.4|^8.0"
+ },
+ "type": "library",
+ "autoload": {
+ "files": [
+ "Resources/functions.php"
+ ],
+ "psr-4": {
+ "Symfony\\Component\\String\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "grapheme",
+ "i18n",
+ "string",
+ "unicode",
+ "utf-8",
+ "utf8"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/string/tree/v8.1.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-29T05:06:50+00:00"
+ },
+ {
+ "name": "symfony/var-dumper",
+ "version": "v8.1.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/var-dumper.git",
+ "reference": "c2c4df1d21477cc21c9f6dc1b14d07c3abc4963e"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/var-dumper/zipball/c2c4df1d21477cc21c9f6dc1b14d07c3abc4963e",
+ "reference": "c2c4df1d21477cc21c9f6dc1b14d07c3abc4963e",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.4.1",
+ "symfony/polyfill-mbstring": "^1.0"
+ },
+ "conflict": {
+ "symfony/console": "<7.4",
+ "symfony/error-handler": "<7.4"
+ },
+ "require-dev": {
+ "symfony/console": "^7.4|^8.0",
+ "symfony/http-kernel": "^7.4|^8.0",
+ "symfony/process": "^7.4|^8.0",
+ "symfony/uid": "^7.4|^8.0",
+ "twig/twig": "^3.12"
+ },
+ "bin": [
+ "Resources/bin/var-dump-server"
+ ],
+ "type": "library",
+ "autoload": {
+ "files": [
+ "Resources/functions/dump.php"
+ ],
+ "psr-4": {
+ "Symfony\\Component\\VarDumper\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides mechanisms for walking through any arbitrary PHP variable",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "debug",
+ "dump"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/var-dumper/tree/v8.1.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-29T05:06:50+00:00"
+ },
+ {
+ "name": "symfony/var-exporter",
+ "version": "v8.1.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/var-exporter.git",
+ "reference": "2dd18582c5f6c024db9fc0ff9c76d873af726f34"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/var-exporter/zipball/2dd18582c5f6c024db9fc0ff9c76d873af726f34",
+ "reference": "2dd18582c5f6c024db9fc0ff9c76d873af726f34",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.4.1",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-deepclone": "^1.37"
+ },
+ "require-dev": {
+ "symfony/property-access": "^7.4|^8.0",
+ "symfony/serializer": "^7.4|^8.0",
+ "symfony/var-dumper": "^7.4|^8.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\VarExporter\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Provides tools to export, instantiate, hydrate, clone and lazy-load PHP objects",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "clone",
+ "construct",
+ "deep-clone",
+ "export",
+ "hydrate",
+ "instantiate",
+ "lazy-loading",
+ "proxy",
+ "serialize"
+ ],
+ "support": {
+ "source": "https://github.com/symfony/var-exporter/tree/v8.1.0"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-29T05:06:50+00:00"
+ },
+ {
+ "name": "symfony/yaml",
+ "version": "v7.4.13",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/yaml.git",
+ "reference": "a7ec3b1156faf8815db7683ec7c1e7338e6f977c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/yaml/zipball/a7ec3b1156faf8815db7683ec7c1e7338e6f977c",
+ "reference": "a7ec3b1156faf8815db7683ec7c1e7338e6f977c",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=8.2",
+ "symfony/deprecation-contracts": "^2.5|^3",
+ "symfony/polyfill-ctype": "^1.8"
+ },
+ "conflict": {
+ "symfony/console": "<6.4"
+ },
+ "require-dev": {
+ "symfony/console": "^6.4|^7.0|^8.0"
+ },
+ "bin": [
+ "Resources/bin/yaml-lint"
+ ],
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Yaml\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Loads and dumps YAML files",
+ "homepage": "https://symfony.com",
+ "support": {
+ "source": "https://github.com/symfony/yaml/tree/v7.4.13"
+ },
+ "funding": [
+ {
+ "url": "https://symfony.com/sponsor",
+ "type": "custom"
+ },
+ {
+ "url": "https://github.com/fabpot",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/nicolas-grekas",
+ "type": "github"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2026-05-25T06:06:12+00:00"
+ },
+ {
+ "name": "symplify/monorepo-builder",
+ "version": "12.7.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symplify/monorepo-builder.git",
+ "reference": "a5ae1abc3ea97e540d1dec496f1b16f768d77562"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symplify/monorepo-builder/zipball/a5ae1abc3ea97e540d1dec496f1b16f768d77562",
+ "reference": "a5ae1abc3ea97e540d1dec496f1b16f768d77562",
+ "shasum": ""
+ },
+ "require": {
+ "nette/utils": "^4.0.5",
+ "phar-io/version": "^3.2",
+ "php": ">=8.2",
+ "sebastian/diff": "^6.0 || ^7.0 || ^8.0",
+ "symfony/config": "^7.0 || ^8.0",
+ "symfony/console": "^7.0 || ^8.0",
+ "symfony/dependency-injection": "^7.0 || ^8.0",
+ "symfony/filesystem": "^7.0 || ^8.0",
+ "symfony/finder": "^7.0 || ^8.0",
+ "symfony/http-kernel": "^7.0 || ^8.0",
+ "symfony/process": "^7.0 || ^8.0",
+ "webmozart/assert": "^1.11 || ^2.0"
+ },
+ "require-dev": {
+ "php-parallel-lint/php-parallel-lint": "^1.3",
+ "phpstan/extension-installer": "1.4.3",
+ "phpstan/phpstan": "^2.1.22",
+ "phpunit/phpunit": "^11.0",
+ "rector/rector": "^2.1.3",
+ "symplify/easy-ci": "^11.3",
+ "symplify/easy-coding-standard": "^12.0",
+ "symplify/phpstan-extensions": "^12.0.1",
+ "symplify/phpstan-rules": "^14.6.12",
+ "tomasvotruba/class-leak": "^2.0.5",
+ "tomasvotruba/unused-public": "^2.0.1",
+ "tracy/tracy": "^2.9"
+ },
+ "bin": [
+ "bin/monorepo-builder",
+ "src-deps/easy-testing/bin/easy-testing"
+ ],
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Symplify\\EasyTesting\\": "src-deps/easy-testing/src",
+ "Symplify\\PackageBuilder\\": "src-deps/package-builder/src",
+ "Symplify\\SymplifyKernel\\": "src-deps/symplify-kernel/src",
+ "Symplify\\MonorepoBuilder\\": [
+ "src",
+ "packages"
+ ],
+ "Symplify\\SmartFileSystem\\": "src-deps/smart-file-system/src",
+ "Symplify\\AutowireArrayParameter\\": "src-deps/autowire-array-parameter/src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "Not only Composer tools to build a Monorepo.",
+ "support": {
+ "issues": "https://github.com/symplify/monorepo-builder/issues",
+ "source": "https://github.com/symplify/monorepo-builder/tree/12.7.1"
+ },
+ "funding": [
+ {
+ "url": "https://www.paypal.me/rectorphp",
+ "type": "custom"
},
{
"url": "https://github.com/tomasvotruba",
"type": "github"
}
],
- "time": "2022-06-13T14:01:16+00:00"
+ "time": "2026-05-20T01:27:41+00:00"
},
{
"name": "theseer/tokenizer",
- "version": "1.2.2",
+ "version": "2.0.1",
"source": {
"type": "git",
"url": "https://github.com/theseer/tokenizer.git",
- "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96"
+ "reference": "7989e43bf381af0eac72e4f0ca5bcbfa81658be4"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b2ad5003ca10d4ee50a12da31de12a5774ba6b96",
- "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96",
+ "url": "https://api.github.com/repos/theseer/tokenizer/zipball/7989e43bf381af0eac72e4f0ca5bcbfa81658be4",
+ "reference": "7989e43bf381af0eac72e4f0ca5bcbfa81658be4",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*",
- "php": "^7.2 || ^8.0"
+ "php": "^8.1"
},
"type": "library",
"autoload": {
@@ -6324,7 +7703,7 @@
"description": "A small library for converting tokenized PHP source code into XML and potentially other formats",
"support": {
"issues": "https://github.com/theseer/tokenizer/issues",
- "source": "https://github.com/theseer/tokenizer/tree/1.2.2"
+ "source": "https://github.com/theseer/tokenizer/tree/2.0.1"
},
"funding": [
{
@@ -6332,34 +7711,42 @@
"type": "github"
}
],
- "time": "2023-11-20T00:12:19+00:00"
+ "time": "2025-12-08T11:19:18+00:00"
},
{
"name": "twig/twig",
- "version": "v3.8.0",
+ "version": "v3.27.0",
"source": {
"type": "git",
"url": "https://github.com/twigphp/Twig.git",
- "reference": "9d15f0ac07f44dc4217883ec6ae02fd555c6f71d"
+ "reference": "04ae1bfe9463c816cf72ca0abe7eae2c77a9a9ed"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/twigphp/Twig/zipball/9d15f0ac07f44dc4217883ec6ae02fd555c6f71d",
- "reference": "9d15f0ac07f44dc4217883ec6ae02fd555c6f71d",
+ "url": "https://api.github.com/repos/twigphp/Twig/zipball/04ae1bfe9463c816cf72ca0abe7eae2c77a9a9ed",
+ "reference": "04ae1bfe9463c816cf72ca0abe7eae2c77a9a9ed",
"shasum": ""
},
"require": {
- "php": ">=7.2.5",
+ "php": ">=8.1.0",
+ "symfony/deprecation-contracts": "^2.5|^3",
"symfony/polyfill-ctype": "^1.8",
- "symfony/polyfill-mbstring": "^1.3",
- "symfony/polyfill-php80": "^1.22"
+ "symfony/polyfill-mbstring": "^1.3"
},
"require-dev": {
+ "php-cs-fixer/shim": "^3.0@stable",
+ "phpstan/phpstan": "^2.0@stable",
"psr/container": "^1.0|^2.0",
- "symfony/phpunit-bridge": "^5.4.9|^6.3|^7.0"
+ "symfony/phpunit-bridge": "^5.4.9|^6.4|^7.0"
},
"type": "library",
"autoload": {
+ "files": [
+ "src/Resources/core.php",
+ "src/Resources/debug.php",
+ "src/Resources/escaper.php",
+ "src/Resources/string_loader.php"
+ ],
"psr-4": {
"Twig\\": "src/"
}
@@ -6392,7 +7779,7 @@
],
"support": {
"issues": "https://github.com/twigphp/Twig/issues",
- "source": "https://github.com/twigphp/Twig/tree/v3.8.0"
+ "source": "https://github.com/twigphp/Twig/tree/v3.27.0"
},
"funding": [
{
@@ -6404,23 +7791,153 @@
"type": "tidelift"
}
],
- "time": "2023-11-21T18:54:41+00:00"
+ "time": "2026-05-27T13:05:51+00:00"
+ },
+ {
+ "name": "webmozart/assert",
+ "version": "2.4.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/webmozarts/assert.git",
+ "reference": "9007ea6f45ecf352a9422b36644e4bfc039b9155"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/webmozarts/assert/zipball/9007ea6f45ecf352a9422b36644e4bfc039b9155",
+ "reference": "9007ea6f45ecf352a9422b36644e4bfc039b9155",
+ "shasum": ""
+ },
+ "require": {
+ "ext-ctype": "*",
+ "ext-date": "*",
+ "ext-filter": "*",
+ "php": "^8.2"
+ },
+ "suggest": {
+ "ext-intl": "",
+ "ext-simplexml": "",
+ "ext-spl": ""
+ },
+ "type": "library",
+ "extra": {
+ "psalm": {
+ "pluginClass": "Webmozart\\Assert\\PsalmPlugin"
+ },
+ "branch-alias": {
+ "dev-master": "2.0-dev",
+ "dev-feature/2-0": "2.0-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Webmozart\\Assert\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Bernhard Schussek",
+ "email": "bschussek@gmail.com"
+ },
+ {
+ "name": "Woody Gilk",
+ "email": "woody.gilk@gmail.com"
+ }
+ ],
+ "description": "Assertions to validate method input/output with nice error messages.",
+ "keywords": [
+ "assert",
+ "check",
+ "validate"
+ ],
+ "support": {
+ "issues": "https://github.com/webmozarts/assert/issues",
+ "source": "https://github.com/webmozarts/assert/tree/2.4.0"
+ },
+ "time": "2026-05-20T13:07:01+00:00"
+ },
+ {
+ "name": "yoast/phpunit-polyfills",
+ "version": "4.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/Yoast/PHPUnit-Polyfills.git",
+ "reference": "134921bfca9b02d8f374c48381451da1d98402f9"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/Yoast/PHPUnit-Polyfills/zipball/134921bfca9b02d8f374c48381451da1d98402f9",
+ "reference": "134921bfca9b02d8f374c48381451da1d98402f9",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.1",
+ "phpunit/phpunit": "^7.5 || ^8.0 || ^9.0 || ^11.0 || ^12.0"
+ },
+ "require-dev": {
+ "php-parallel-lint/php-console-highlighter": "^1.0.0",
+ "php-parallel-lint/php-parallel-lint": "^1.4.0",
+ "yoast/yoastcs": "^3.1.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-main": "4.x-dev"
+ }
+ },
+ "autoload": {
+ "files": [
+ "phpunitpolyfills-autoload.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-3-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Team Yoast",
+ "email": "support@yoast.com",
+ "homepage": "https://yoast.com"
+ },
+ {
+ "name": "Contributors",
+ "homepage": "https://github.com/Yoast/PHPUnit-Polyfills/graphs/contributors"
+ }
+ ],
+ "description": "Set of polyfills for changed PHPUnit functionality to allow for creating PHPUnit cross-version compatible tests",
+ "homepage": "https://github.com/Yoast/PHPUnit-Polyfills",
+ "keywords": [
+ "phpunit",
+ "polyfill",
+ "testing"
+ ],
+ "support": {
+ "issues": "https://github.com/Yoast/PHPUnit-Polyfills/issues",
+ "security": "https://github.com/Yoast/PHPUnit-Polyfills/security/policy",
+ "source": "https://github.com/Yoast/PHPUnit-Polyfills"
+ },
+ "time": "2025-02-09T18:58:54+00:00"
}
],
"aliases": [],
"minimum-stability": "dev",
- "stability-flags": [],
+ "stability-flags": {},
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
- "php": "^7.4 || ^8.0",
+ "php": "^8.3",
"ext-fileinfo": "*",
"ext-json": "*",
"ext-mbstring": "*",
"ext-pdo": "*",
+ "ext-pdo_mysql": "*",
"ext-simplexml": "*",
"ext-spl": "*"
},
- "platform-dev": [],
- "plugin-api-version": "2.6.0"
+ "platform-dev": {},
+ "plugin-api-version": "2.9.0"
}
diff --git a/monorepo b/monorepo
new file mode 100755
index 000000000..478d90581
--- /dev/null
+++ b/monorepo
@@ -0,0 +1,88 @@
+#!/bin/sh
+
+# Monorepo utility toolbox - Helper script for managing monorepo packages
+
+# Function to list all monorepo packages in pretty format
+packages_pretty() {
+ echo "Monorepo packages:"
+ find packages -maxdepth 2 -name "composer.json" -type f | while read -r composer_file; do
+ package_dir=$(dirname "$composer_file")
+ package_name=$(basename "$package_dir")
+ echo " - $package_name"
+ done
+}
+
+# Function to list packages as JSON array
+packages_json() {
+ packages=$(find packages -maxdepth 2 -name "composer.json" -type f | while read -r composer_file; do
+ package_dir=$(dirname "$composer_file")
+ basename "$package_dir"
+ done | awk 'BEGIN{printf "["} {printf "%s\"%s\"", (NR>1?",":""), $0} END{printf "]\n"}')
+ echo "$packages"
+}
+
+# Function to list package names only (space-separated) - default
+packages_default() {
+ find packages -maxdepth 2 -name "composer.json" -type f | while read -r composer_file; do
+ package_dir=$(dirname "$composer_file")
+ basename "$package_dir"
+ done | tr '\n' ' ' | sed 's/ $/\n/'
+}
+
+# Parse command and options
+command="${1:-}"
+type_flag=""
+
+# Parse flags for packages command
+if [ "$command" = "packages" ]; then
+ shift
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --type=*)
+ type_flag="${1#*=}"
+ shift
+ ;;
+ -t)
+ type_flag="$2"
+ shift 2
+ ;;
+ *)
+ echo "Unknown option: $1"
+ exit 1
+ ;;
+ esac
+ done
+fi
+
+# Execute command
+case "$command" in
+ packages)
+ case "$type_flag" in
+ json)
+ packages_json
+ ;;
+ pretty)
+ packages_pretty
+ ;;
+ "")
+ packages_default
+ ;;
+ *)
+ echo "Unknown type: $type_flag"
+ echo "Valid types: json, pretty"
+ exit 1
+ ;;
+ esac
+ ;;
+ *)
+ echo "Monorepo utility toolbox - Helper script for managing monorepo packages"
+ echo ""
+ echo "Usage: $0 packages [--type=TYPE|-t TYPE]"
+ echo "Commands:"
+ echo " packages List package names (space-separated, default)"
+ echo " packages -t json List packages as JSON array"
+ echo " packages -t pretty List all monorepo packages in pretty format"
+ exit 1
+ ;;
+esac
+
diff --git a/monorepo-builder.php b/monorepo-builder.php
index 86910891a..575f39d82 100644
--- a/monorepo-builder.php
+++ b/monorepo-builder.php
@@ -3,7 +3,7 @@
declare(strict_types=1);
use Charcoal\MonorepoBuilder\Release\ReleaseWorker\UpdateBranchAliasReleaseWorker;
-use Symplify\ComposerJsonManipulator\ValueObject\ComposerJsonSection;
+use Symplify\MonorepoBuilder\ComposerJsonManipulator\ValueObject\ComposerJsonSection;
use Symplify\MonorepoBuilder\Config\MBConfig;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\SetCurrentMutualDependenciesReleaseWorker;
@@ -13,11 +13,10 @@
// default value
__DIR__ . '/packages',
]);
-
// for "merge" command.
$mbConfig->dataToAppend([
ComposerJsonSection::REQUIRE_DEV => [
- 'phpunit/phpunit' => '^9.5',
+ 'phpunit/phpunit' => '^12.5',
],
]);
diff --git a/packages/admin/composer.json b/packages/admin/composer.json
index baef4cfc2..f39b02563 100644
--- a/packages/admin/composer.json
+++ b/packages/admin/composer.json
@@ -1,8 +1,11 @@
{
- "type": "library",
"name": "charcoal/admin",
"description": "The Charcoal Administration Dashboard",
- "keywords": ["charcoal", "admin", "cms"],
+ "keywords": [
+ "charcoal",
+ "admin",
+ "cms"
+ ],
"homepage": "https://charcoal.locomotive.ca",
"license": "MIT",
"authors": [
@@ -15,20 +18,10 @@
"homepage": "https://locomotive.ca"
}
],
- "config": {
- "sort-packages": true
- },
- "extra": {
- "branch-alias": {
- "dev-main": "5.x-dev"
- }
- },
+ "type": "library",
"require": {
- "php": "^7.4 || ^8.0",
+ "php": "^8.3",
"barryvdh/elfinder-flysystem-driver": "^0.3",
- "guzzlehttp/guzzle": "^6.0 || ^7.0",
- "kriswallsmith/assetic": "^1.4",
- "laminas/laminas-permissions-acl": "^2.8",
"charcoal/app": "^5.1",
"charcoal/cache": "^5.1",
"charcoal/cms": "^5.1",
@@ -38,25 +31,24 @@
"charcoal/translator": "^5.1",
"charcoal/ui": "^5.1",
"charcoal/user": "^5.1",
+ "guzzlehttp/guzzle": "^6.0 || ^7.0",
+ "kriswallsmith/assetic": "^1.4",
+ "laminas/laminas-permissions-acl": "^2.8",
"mcaskill/php-html-build-attributes": "^1.0",
- "psr/cache": "^1.0",
+ "psr/cache": "^2.0",
"psr/http-message": "^1.0",
"psr/log": "^1.0",
- "studio-42/elfinder": "2.1.64"
+ "studio-42/elfinder": "^2.1.64"
},
"require-dev": {
"league/csv": "^9.5",
"mockery/mockery": "^1.0",
"mustache/mustache": "^2.11",
"php-coveralls/php-coveralls": "^2.2",
- "phpunit/phpunit": "^9.5",
+ "phpunit/phpunit": "^12.5",
"seld/jsonlint": "^1.9",
"squizlabs/php_codesniffer": "^3.5",
- "tedivm/stash": "~0.16"
- },
- "suggest": {
- "league/csv": "To use the exporter (to CSV).",
- "fabpot/goutte": "To use the various crawler-based tools."
+ "tedivm/stash": "^1.1"
},
"autoload": {
"psr-4": {
@@ -68,8 +60,10 @@
"Charcoal\\Tests\\": "tests/Charcoal/"
}
},
- "replace": {
- "locomotivemtl/charcoal-admin": "*"
+ "extra": {
+ "branch-alias": {
+ "dev-main": "5.x-dev"
+ }
},
"scripts": {
"test": [
@@ -87,6 +81,16 @@
"phpcbf": "php vendor/bin/phpcbf -ps --colors src/ tests/",
"phpunit": "php vendor/bin/phpunit --coverage-text"
},
+ "suggest": {
+ "league/csv": "To use the exporter (to CSV).",
+ "fabpot/goutte": "To use the various crawler-based tools."
+ },
+ "config": {
+ "sort-packages": true
+ },
+ "replace": {
+ "locomotivemtl/charcoal-admin": "*"
+ },
"minimum-stability": "dev",
"prefer-stable": true
}
diff --git a/packages/admin/phpunit.xml.dist b/packages/admin/phpunit.xml.dist
index 5c94aaf08..93e59b0cb 100644
--- a/packages/admin/phpunit.xml.dist
+++ b/packages/admin/phpunit.xml.dist
@@ -1,32 +1,33 @@
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
-
-
- ./src/Charcoal
-
-
+
+
+ ./src/Charcoal
+
+
diff --git a/packages/admin/src/Charcoal/Admin/Action/Account/LostPasswordAction.php b/packages/admin/src/Charcoal/Admin/Action/Account/LostPasswordAction.php
index 2b4d5dd38..359531324 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Account/LostPasswordAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Account/LostPasswordAction.php
@@ -40,15 +40,11 @@ class LostPasswordAction extends AdminAction
{
/**
* Store the factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $emailFactory;
+ private ?\Charcoal\Factory\FactoryInterface $emailFactory = null;
- /**
- * @return boolean
- */
- public function authRequired()
+ #[\Override]
+ public function authRequired(): bool
{
return false;
}
@@ -65,7 +61,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
{
$translator = $this->translator();
- $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
+ $ip = ($_SERVER['REMOTE_ADDR'] ?? null);
$email = $request->getParam('email');
if (!$email) {
@@ -94,7 +90,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- $doneMessage = $translator->translate('If a registered user matches the given email address, instructions to reset your password will be sent to the email address registered with that account.');
+ $doneMessage = $translator->translate('If a registered user matches the given email address, instructions' .
+ ' to reset your password will be sent to the email address registered with that account.');
$failMessage = $translator->translate('An error occurred while processing the password reset request.');
$authenticator = $this->authenticator();
@@ -160,23 +157,20 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks(),
];
-
- return $ret;
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -187,13 +181,12 @@ protected function setDependencies(Container $container)
* Retrieve the email model factory.
*
* @throws RuntimeException If the model factory was not previously set.
- * @return FactoryInterface
*/
- protected function emailFactory()
+ protected function emailFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->emailFactory)) {
+ if (!$this->emailFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
- sprintf('Email Factory is not defined for "%s"', get_class($this))
+ sprintf('Email Factory is not defined for "%s"', static::class)
);
}
@@ -204,9 +197,8 @@ protected function emailFactory()
* Set an email model factory.
*
* @param FactoryInterface $factory The email factory, to create emails.
- * @return self
*/
- private function setEmailFactory(FactoryInterface $factory)
+ private function setEmailFactory(FactoryInterface $factory): static
{
$this->emailFactory = $factory;
@@ -231,9 +223,8 @@ private function generateLostPasswordToken(User $user)
* @todo Implement `$container['admin/config']['user.lost_password_email']`
* @param User $user The user to send the lost-password email to.
* @param string $token The lost-password token, as string.
- * @return void
*/
- private function sendLostPasswordEmail(User $user, $token)
+ private function sendLostPasswordEmail(User $user, $token): void
{
$translator = $this->translator();
$userEmail = $user['email'];
@@ -268,7 +259,7 @@ private function sendLostPasswordEmail(User $user, $token)
'adminUrl' => $this->adminUrl(),
'urlResetPassword' => $this->adminUrl() . 'account/reset-password/' . $token->id(),
'expiry' => $token->expiry()->format('Y-m-d H:i:s'),
- 'ipAddress' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
+ 'ipAddress' => ($_SERVER['REMOTE_ADDR'] ?? ''),
],
]);
$emailObj->send();
diff --git a/packages/admin/src/Charcoal/Admin/Action/Account/ResetPasswordAction.php b/packages/admin/src/Charcoal/Admin/Action/Account/ResetPasswordAction.php
index 37dd376ad..84737473f 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Account/ResetPasswordAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Account/ResetPasswordAction.php
@@ -34,10 +34,8 @@
*/
class ResetPasswordAction extends AdminAction
{
- /**
- * @return boolean
- */
- public function authRequired()
+ #[\Override]
+ public function authRequired(): bool
{
return false;
}
@@ -55,7 +53,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
{
$translator = $this->translator();
- $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
+ $ip = ($_SERVER['REMOTE_ADDR'] ?? null);
$token = $request->getParam('token');
$email = $request->getParam('email');
@@ -191,17 +189,13 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks(),
];
-
- return $ret;
}
/**
@@ -216,9 +210,8 @@ public function results()
* @see \Charcoal\Admin\Template\Account::validateToken()
* @param string $token The token to validate.
* @param string $userId The user ID that should match the token.
- * @return boolean
*/
- private function validateToken($token, $userId)
+ private function validateToken($token, $userId): bool
{
$obj = $this->modelFactory()->create(LostPasswordToken::class);
$sql = strtr('SELECT * FROM `%table` WHERE `token` = :token AND `user` = :userId AND `expiry` > NOW()', [
@@ -229,16 +222,15 @@ private function validateToken($token, $userId)
'userId' => $userId,
]);
- return !!$obj->token();
+ return (bool)$obj->token();
}
/**
* Delete the given password reset token.
*
* @param string $token The token to delete.
- * @return void
*/
- private function deleteToken($token)
+ private function deleteToken($token): void
{
$obj = $this->modelFactory()->create(LostPasswordToken::class);
$obj->setToken($token);
diff --git a/packages/admin/src/Charcoal/Admin/Action/ElfinderConnectorAction.php b/packages/admin/src/Charcoal/Admin/Action/ElfinderConnectorAction.php
index a1b37ca7d..1c0f7b642 100644
--- a/packages/admin/src/Charcoal/Admin/Action/ElfinderConnectorAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/ElfinderConnectorAction.php
@@ -34,6 +34,11 @@ class ElfinderConnectorAction extends AdminAction
{
use CallableResolverAwareTrait;
+ /**
+ * @var \elFinderConnector
+ */
+ public $connector;
+
/**
* The default relative path (from filesystem's root) to the storage directory.
*
@@ -123,9 +128,9 @@ class ElfinderConnectorAction extends AdminAction
* Sets the action data from a PSR Request object.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
- * @return self
*/
- protected function setDataFromRequest(RequestInterface $request)
+ #[\Override]
+ protected function setDataFromRequest(RequestInterface $request): static
{
$keys = $this->validDataFromRequest();
$data = $request->getParams($keys);
@@ -150,7 +155,8 @@ protected function setDataFromRequest(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return [
'obj_type',
@@ -162,9 +168,8 @@ protected function validDataFromRequest()
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -177,9 +182,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
* Setup the elFinder connector.
*
* @param array|null $extraOptions Additional settings to pass to elFinder.
- * @return elFinderConnector
*/
- public function setupElfinder(array $extraOptions = [])
+ public function setupElfinder(array $extraOptions = []): \elFinderConnector
{
if (!defined('ELFINDER_IMG_PARENT_URL')) {
// Ensure images injected by elFinder are relative to its assets directory
@@ -219,9 +223,8 @@ public function getConnectorOptions()
* your application's admin configuration.
*
* @param array $extraOptions Additional settings to pass to elFinder.
- * @return array
*/
- public function buildConnectorOptions(array $extraOptions = [])
+ public function buildConnectorOptions(array $extraOptions = []): array
{
$options = [
'debug' => false,
@@ -251,7 +254,7 @@ public function buildConnectorOptions(array $extraOptions = [])
* @param array $options2 The settings from which data is extracted.
* @return array The merged settings.
*/
- protected function mergeConnectorOptions(array $options1, array $options2)
+ protected function mergeConnectorOptions(array $options1, array $options2): array
{
return array_replace_recursive($options1, $options2);
}
@@ -262,7 +265,7 @@ protected function mergeConnectorOptions(array $options1, array $options2)
* @param array $options The admin settings to parse.
* @return array The parsed settings.
*/
- protected function parseAdminOptionsForConnectorBuild(array $options)
+ protected function parseAdminOptionsForConnectorBuild(array $options): array
{
// Root settings are already merged when retrieving available roots.
unset($options['roots']);
@@ -276,7 +279,7 @@ protected function parseAdminOptionsForConnectorBuild(array $options)
* @param array $options The extra settings to parse.
* @return array The parsed settings.
*/
- protected function parseExtraOptionsForConnectorBuild(array $options)
+ protected function parseExtraOptionsForConnectorBuild(array $options): array
{
// Resolve callbacks on extra options
if (isset($options['roots'])) {
@@ -290,10 +293,8 @@ protected function parseExtraOptionsForConnectorBuild(array $options)
* Retrieve the admin's elFinder Connector options.
*
* Path: `config.admin.elfinder.connector`
- *
- * @return array
*/
- public function getAdminConnectorOptions()
+ public function getAdminConnectorOptions(): array
{
$config = $this->elfinderConfig('connector');
if (!is_array($config)) {
@@ -305,10 +306,8 @@ public function getAdminConnectorOptions()
/**
* Retrieve the default elFinder Connector options.
- *
- * @return array
*/
- protected function getDefaultElfinderRootSettings()
+ protected function getDefaultElfinderRootSettings(): array
{
return [
'driver' => 'LocalFileSystem',
@@ -322,17 +321,15 @@ protected function getDefaultElfinderRootSettings()
'uploadDeny' => $this->defaultUploadDeny(),
'uploadAllow' => $this->defaultUploadAllow(),
'uploadOrder' => [ 'deny', 'allow' ],
- 'accessControl' => [ $this, 'checkAccess' ],
+ 'accessControl' => $this->checkAccess(...),
'duplicateSuffix' => '_%s_',
];
}
/**
* Retrieve the default Flysystem / elFinder options.
- *
- * @return array
*/
- protected function getDefaultFlysystemRootSettings()
+ protected function getDefaultFlysystemRootSettings(): array
{
return [
'driver' => 'Flysystem',
@@ -348,18 +345,13 @@ protected function getDefaultFlysystemRootSettings()
* Retrieve the default Flysystem / elFinder options.
*
* @param string $ident The disk identifier.
- * @return array
*/
- protected function resolveFallbackRootSettings($ident)
+ protected function resolveFallbackRootSettings($ident): array
{
$fsConfig = $this->getFilesystemConfig($ident);
$uploadPath = $this->defaultUploadPath();
- if (isset($fsConfig['base_url'])) {
- $baseUrl = rtrim($fsConfig['base_url'], '/') . '/';
- } else {
- $baseUrl = $this->baseUrl();
- }
+ $baseUrl = isset($fsConfig['base_url']) ? rtrim($fsConfig['base_url'], '/') . '/' : $this->baseUrl();
return [
'URL' => $baseUrl . '/' . $uploadPath,
@@ -378,14 +370,14 @@ protected function resolveFallbackRootSettings($ident)
* @param string $ident The disk identifier.
* @return array|null Returns an elFinder root structure or NULL.
*/
- public function getNamedRoot($ident)
+ public function getNamedRoot($ident): ?array
{
if ($this->hasFilesystem($ident) === false) {
return null;
}
- $filesystem = $this->getFilesystem($ident);
- $fsConfig = $this->getFilesystemConfig($ident);
+ $this->getFilesystem($ident);
+ $this->getFilesystemConfig($ident);
$elfConfig = $this->getFilesystemAdminConfig($ident);
$immutableSettings = [
@@ -410,10 +402,8 @@ public function getNamedRoot($ident)
/**
* Retrieve only the public elFinder root volumes.
- *
- * @return array
*/
- public function getPublicRoots()
+ public function getPublicRoots(): array
{
$roots = [];
foreach ($this->filesystems->keys() as $ident) {
@@ -430,10 +420,8 @@ public function getPublicRoots()
/**
* Retrieve all elFinder root volumes.
- *
- * @return array
*/
- public function getAllRoots()
+ public function getAllRoots(): array
{
$roots = [];
foreach ($this->filesystems->keys() as $ident) {
@@ -452,7 +440,7 @@ public function getAllRoots()
* @return array Returns all public root volumes
* or a subset if the context has a related form property.
*/
- public function getCurrentRoots()
+ public function getCurrentRoots(): array
{
$formProperty = $this->formProperty();
$targetFilesystem = $formProperty ? $formProperty['filesystem'] : null;
@@ -475,9 +463,7 @@ public function getCurrentRoots()
if ($acceptedMimetypes) {
$disk['uploadAllow'] = array_merge(
- isset($disk['uploadAllow'])
- ? $disk['uploadAllow']
- : [],
+ ($disk['uploadAllow'] ?? []),
$acceptedMimetypes
);
}
@@ -493,7 +479,7 @@ public function getCurrentRoots()
* @param array $roots One or many roots with possible unresolved callables.
* @return array Returns the root(s) with resolved callables.
*/
- protected function resolveCallbacksForRoots(array $roots)
+ protected function resolveCallbacksForRoots(array $roots): array
{
foreach ($roots as $i => $root) {
$roots[$i] = $this->resolveCallbacksForRoot($root);
@@ -508,7 +494,7 @@ protected function resolveCallbacksForRoots(array $roots)
* @param array $root A root structure with possible unresolved callables.
* @return array Returns the root with resolved callables.
*/
- protected function resolveCallbacksForRoot(array $root)
+ protected function resolveCallbacksForRoot(array $root): array
{
if (isset($root['accessControl'])) {
$callable = $root['accessControl'];
@@ -526,14 +512,14 @@ protected function resolveCallbacksForRoot(array $root)
* @param array $toResolve One or many pairs of callbacks.
* @return array Returns the parsed event listeners.
*/
- protected function resolveCallbacksForBindOption(array $toResolve)
+ protected function resolveCallbacksForBindOption(array $toResolve): array
{
$resolved = $toResolve;
foreach ($toResolve as $actions => $callables) {
foreach ($callables as $i => $callable) {
if (!is_callable($callable) && is_string($callable)) {
- if (0 === strpos($callable, 'Plugin.')) {
+ if (str_starts_with($callable, 'Plugin.')) {
continue;
}
@@ -557,9 +543,8 @@ protected function resolveCallbacksForBindOption(array $toResolve)
* @param array $args The command arguments from the client.
* @param object $elfinder The elFinder instance.
* @param object $volume The current volume instance.
- * @return void|bool|array
*/
- public function translateDirectoriesOnAnyCommand($cmd, &$result, $args, $elfinder, $volume)
+ public function translateDirectoriesOnAnyCommand($cmd, array &$result, $args, object $elfinder, $volume): void
{
// To please PHPCS
unset($cmd, $args, $volume);
@@ -587,7 +572,6 @@ public function translateDirectoriesOnAnyCommand($cmd, &$result, $args, $elfinde
* @param array $stat The directory reference.
* @param object $elfinder The elFinder instance or volume instance.
* @throws UnexpectedValueException If the related volume is not found.
- * @return array
*/
protected function translateDirectoryStat(array $stat, object $elfinder): array
{
@@ -608,7 +592,6 @@ protected function translateDirectoryStat(array $stat, object $elfinder): array
* @param object $elfinder The elFinder instance or volume instance.
* @throws InvalidArgumentException If the elFinder client or volume is not provided.
* @throws UnexpectedValueException If the related volume is not found.
- * @return ?string
*/
protected function getVolumeNameFromHash(string $hash, object $elfinder): ?string
{
@@ -635,7 +618,6 @@ protected function getVolumeNameFromHash(string $hash, object $elfinder): ?strin
* Attempts to retrieve the filesystem name.
*
* @param string $ident The filesystem identifier.
- * @return ?string
*/
protected function getFilesystemName(string $ident): ?string
{
@@ -655,7 +637,6 @@ protected function getFilesystemName(string $ident): ?string
* Attempts to localize the filesystem identifier.
*
* @param string $ident The filesystem identifier.
- * @return ?string
*/
protected function translateFilesystemName(string $ident): ?string
{
@@ -684,7 +665,7 @@ protected function translateFilesystemName(string $ident): ?string
* @param object $volume The current volume instance.
* @return void|bool|array
*/
- public function sanitizeOnUploadPreSave(&$path, &$name, $src, $elfinder, $volume)
+ public function sanitizeOnUploadPreSave(&$path, &$name, $src, $elfinder, $volume): bool
{
// To please PHPCS
unset($path, $src, $elfinder, $volume);
@@ -712,11 +693,7 @@ public function sanitizeOnUploadPreSave(&$path, &$name, $src, $elfinder, $volume
*/
protected function sanitizeFileName(string $name, array $options): string
{
- if (is_array($options['replace'])) {
- $mask = implode($options['replace']);
- } else {
- $mask = $options['replace'];
- }
+ $mask = is_array($options['replace']) ? implode('', $options['replace']) : $options['replace'];
$ext = '.' . pathinfo($name, PATHINFO_EXTENSION);
@@ -725,8 +702,8 @@ protected function sanitizeFileName(string $name, array $options): string
// Squeeze multiple delimiters and whitespace with a single separator
$name = preg_replace(
- '![' . preg_quote($mask, '!') . '\.\s]{2,}!',
- $options['replace'],
+ '![' . preg_quote((string)$mask, '!') . '\.\s]{2,}!',
+ (string)$options['replace'],
$name
);
@@ -751,7 +728,7 @@ protected function sanitizeFileName(string $name, array $options): string
* started with directory separator.
* @return boolean|null TRUE to allow, FALSE to deny, NULL to let elFinder decide.
**/
- public function checkAccess($attr, $path, $data, elFinderVolumeDriver $volume, $isDir, $relPath)
+ public function checkAccess($attr, $path, $data, elFinderVolumeDriver $volume, $isDir, $relPath): ?bool
{
unset($data, $volume, $isDir);
@@ -763,7 +740,7 @@ public function checkAccess($attr, $path, $data, elFinderVolumeDriver $volume, $
* set to NULL to let elFinder decide itself.
*/
return ($basename[0] === '.' && strlen($relPath) !== 1)
- ? !($attr === 'read' || $attr === 'write')
+ ? $attr !== 'read' && $attr !== 'write'
: null;
}
@@ -825,20 +802,16 @@ public function formProperty()
/**
* Retrieve the default root path.
- *
- * @return string
*/
- public function defaultUploadPath()
+ public function defaultUploadPath(): string
{
return self::DEFAULT_STORAGE_PATH;
}
/**
* Allow upload for a subset MIME types.
- *
- * @return array
*/
- protected function defaultUploadAllow()
+ protected function defaultUploadAllow(): array
{
// By default, all images, PDF, and plain-text files are allowed.
return [
@@ -850,10 +823,8 @@ protected function defaultUploadAllow()
/**
* Deny upload for all MIME types.
- *
- * @return array
*/
- protected function defaultUploadDeny()
+ protected function defaultUploadDeny(): array
{
// By default, all files are rejected.
return [
@@ -863,10 +834,8 @@ protected function defaultUploadDeny()
/**
* Default attributes for files and directories.
- *
- * @return array
*/
- protected function attributesForHiddenFiles()
+ protected function attributesForHiddenFiles(): array
{
return [
// Block access to all hidden files and directories (anything starting with ".")
@@ -882,9 +851,9 @@ protected function attributesForHiddenFiles()
* Inject dependencies from a DI Container.
*
* @param Container $container A dependencies container instance.
- * @return void
*/
- public function setDependencies(Container $container)
+ #[\Override]
+ public function setDependencies(Container $container): void
{
parent::setDependencies($container);
@@ -908,11 +877,7 @@ public function setDependencies(Container $container)
*/
protected function getFilesystem($ident)
{
- if (isset($this->filesystems[$ident])) {
- return $this->filesystems[$ident];
- }
-
- return null;
+ return ($this->filesystems[$ident] ?? null);
}
/**
@@ -921,7 +886,7 @@ protected function getFilesystem($ident)
* @param string $ident The filesystem identifier.
* @return boolean TRUE if the filesystem instance exists, otherwise FALSE.
*/
- protected function hasFilesystem($ident)
+ protected function hasFilesystem($ident): bool
{
return ($this->getFilesystem($ident) !== null);
}
@@ -939,11 +904,7 @@ protected function getFilesystemConfig($ident)
return null;
}
- if (isset($this->filesystemConfig['connections'][$ident])) {
- return $this->filesystemConfig['connections'][$ident];
- }
-
- return [];
+ return ($this->filesystemConfig['connections'][$ident] ?? []);
}
/**
@@ -959,11 +920,7 @@ protected function isFilesystemPublic($ident)
}
$config = $this->getFilesystemConfig($ident);
- if (isset($config['public']) && $config['public'] === false) {
- return false;
- }
-
- return true;
+ return !(isset($config['public']) && $config['public'] === false);
}
/**
@@ -980,11 +937,8 @@ protected function getFilesystemAdminConfig($ident)
}
$elfConfig = $this->getAdminConnectorOptions();
- if (isset($elfConfig['roots'][$ident])) {
- return $elfConfig['roots'][$ident];
- }
- return [];
+ return ($elfConfig['roots'][$ident] ?? []);
}
/**
@@ -1010,12 +964,10 @@ protected function elfinderConfig($key = null, $default = null)
if ($key) {
if (isset($this->elfinderConfig[$key])) {
return $this->elfinderConfig[$key];
+ } elseif (!is_string($default) && is_callable($default)) {
+ return $default();
} else {
- if (!is_string($default) && is_callable($default)) {
- return $default();
- } else {
- return $default;
- }
+ return $default;
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/Filesystem/LoadAction.php b/packages/admin/src/Charcoal/Admin/Action/Filesystem/LoadAction.php
index dbaebc91f..8a9b78882 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Filesystem/LoadAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Filesystem/LoadAction.php
@@ -72,10 +72,9 @@ class LoadAction extends AdminAction
/**
* Determine if user authentication is required.
- *
- * @return boolean
*/
- protected function authRequired()
+ #[\Override]
+ protected function authRequired(): bool
{
return true;
}
@@ -84,9 +83,9 @@ protected function authRequired()
* Sets the action data.
*
* @param array $data The action data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
$keys = $this->validDataFromRequest();
$data = array_intersect_key($data, array_flip($keys));
@@ -99,9 +98,9 @@ public function setData(array $data)
* Sets the action data from a PSR Request object.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
- * @return self
*/
- protected function setDataFromRequest(RequestInterface $request)
+ #[\Override]
+ protected function setDataFromRequest(RequestInterface $request): static
{
$keys = $this->validDataFromRequest();
$data = $request->getParams($keys);
@@ -114,9 +113,8 @@ protected function setDataFromRequest(RequestInterface $request)
* Add data to action, replacing existing items with the same data key.
*
* @param array $data The action data.
- * @return self
*/
- public function mergeData(array $data)
+ public function mergeData(array $data): static
{
$this->params = array_replace($this->params, $data);
@@ -128,7 +126,8 @@ public function mergeData(array $data)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return [ 'disk', 'disposition', 'path', 'name' ];
}
@@ -139,14 +138,14 @@ protected function validDataFromRequest()
* @param array|null $keys Subset of keys to retrieve.
* @return array|null
*/
- public function getParams(array $keys = null)
+ public function getParams(?array $keys = null)
{
$params = $this->params;
if ($keys) {
$subset = [];
foreach ($keys as $key) {
- if (array_key_exists($key, $params)) {
+ if (array_key_exists((string)$key, $params)) {
$subset[$key] = $params[$key];
}
}
@@ -168,12 +167,10 @@ public function getParam($key, $default = null)
$params = $this->params;
if (is_array($params) && isset($params[$key])) {
$result = $params[$key];
+ } elseif (!is_string($default) && is_callable($default)) {
+ $result = $default();
} else {
- if (!is_string($default) && is_callable($default)) {
- $result = $default();
- } else {
- $result = $default;
- }
+ $result = $default;
}
return $result;
@@ -189,7 +186,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
{
unset($request);
- $translator = $this->translator();
+ $this->translator();
try {
$disk = $this->getParam('disk', $this->filesystemConfig['default_connection']);
@@ -225,7 +222,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
try {
- $filename = isset($name) ? $name : basename($path);
+ $filename = ($name ?? basename((string)$path));
$disposition = $this->generateHttpDisposition($disp, $filename);
$resource = $handler->readStream();
$stream = new Stream($resource);
@@ -276,7 +273,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @throws InvalidArgumentException If the parameters are invalid.
* @return string A string suitable for use as a Content-Disposition field-value.
*/
- public function generateHttpDisposition($disposition, $filename, $filenameFallback = '')
+ public function generateHttpDisposition($disposition, $filename, $filenameFallback = ''): string
{
if (!in_array($disposition, [ self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE ])) {
throw new InvalidArgumentException(sprintf(
@@ -296,16 +293,16 @@ public function generateHttpDisposition($disposition, $filename, $filenameFallba
// }
// percent characters aren't safe in fallback.
- if (strpos($filenameFallback, '%') !== false) {
+ if (str_contains($filenameFallback, '%')) {
throw new InvalidArgumentException('The filename fallback cannot contain the "%" character.');
}
// path separators aren't allowed in either.
if (
- strpos($filename, '/') !== false ||
- strpos($filename, '\\') !== false ||
- strpos($filenameFallback, '/') !== false ||
- strpos($filenameFallback, '\\') !== false
+ str_contains($filename, '/') ||
+ str_contains($filename, '\\') ||
+ str_contains($filenameFallback, '/') ||
+ str_contains($filenameFallback, '\\')
) {
throw new InvalidArgumentException(
'The filename and the fallback cannot contain the "/" and "\\" characters.'
@@ -344,7 +341,7 @@ protected function assertValidDisk($disk)
}
if (!is_string($disk)) {
- $actualType = is_object($disk) ? get_class($disk) : gettype($disk);
+ $actualType = get_debug_type($disk);
$message = $translator->translate(
'{{ parameter }} must be a {{ expectedType }}, received {{ actualType }}',
[
@@ -388,7 +385,7 @@ protected function assertValidPath($path)
throw new InvalidArgumentException($message, 400);
} elseif (!is_string($path)) {
- $actualType = is_object($path) ? get_class($path) : gettype($path);
+ $actualType = get_debug_type($path);
$message = $translator->translate(
'{{ parameter }} must be a {{ expectedType }}, received {{ actualType }}',
[
@@ -412,7 +409,7 @@ protected function assertValidPath($path)
protected function assertValidName($name)
{
if (!is_string($name) && $name !== null) {
- $actualType = is_object($name) ? get_class($name) : gettype($name);
+ $actualType = get_debug_type($name);
$message = $this->translator()->translate(
'{{ parameter }} must be a {{ expectedType }}, received {{ actualType }}',
[
@@ -446,7 +443,7 @@ protected function assertValidDisposition($disposition)
}
if (!is_string($disposition) && $disposition !== null) {
- $actualType = is_object($disposition) ? get_class($disposition) : gettype($disposition);
+ $actualType = get_debug_type($disposition);
$message = $translator->translate(
'{{ parameter }} must be a {{ expectedType }}, received {{ actualType }}',
[
@@ -466,6 +463,7 @@ protected function assertValidDisposition($disposition)
* @param Container $container A service locator.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/LoginAction.php b/packages/admin/src/Charcoal/Admin/Action/LoginAction.php
index af3adbee4..3b3f9df99 100644
--- a/packages/admin/src/Charcoal/Admin/Action/LoginAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/LoginAction.php
@@ -41,10 +41,9 @@ class LoginAction extends AdminAction
* Authentication is required by default.
*
* Change to false in the login action controller; this is meant to be called before login.
- *
- * @return boolean
*/
- public function authRequired()
+ #[\Override]
+ public function authRequired(): bool
{
return false;
}
@@ -65,7 +64,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
'{{ errorMessage }}' => $failMessage
]);
- $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
+ $ip = ($_SERVER['REMOTE_ADDR'] ?? null);
$email = $request->getParam('email');
$password = $request->getParam('password');
@@ -125,8 +124,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
$this->addFeedback('success', $doneMessage);
$this->setSuccess(true);
- if (is_string($nextUrl) && !empty($nextUrl)) {
- $this->setSuccessUrl((string)$nextUrl);
+ if (is_string($nextUrl) && ($nextUrl !== '' && $nextUrl !== '0')) {
+ $this->setSuccessUrl($nextUrl);
} else {
$this->setSuccessUrl((string)$this->adminUrl());
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/LogoutAction.php b/packages/admin/src/Charcoal/Admin/Action/LogoutAction.php
index e521ed2b6..f054cbbbe 100644
--- a/packages/admin/src/Charcoal/Admin/Action/LogoutAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/LogoutAction.php
@@ -62,7 +62,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
/** Fail silently — Never confirm or deny the existence of an account. */
- $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
+ $ip = ($_SERVER['REMOTE_ADDR'] ?? null);
if ($ip) {
$logMessage = sprintf('[Admin] Logout attempt for unauthenticated user from %s', $ip);
} else {
@@ -78,9 +78,9 @@ public function run(RequestInterface $request, ResponseInterface $response)
/**
* @todo Provide feedback and redirection?
- * @return array
*/
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/AbstractSaveAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/AbstractSaveAction.php
index 48a232e56..29bce6964 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/AbstractSaveAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/AbstractSaveAction.php
@@ -43,11 +43,7 @@ public function setObj($obj)
{
$this->obj = $obj;
- if ($obj instanceof ModelInterface) {
- $this->objId = $obj->id();
- } else {
- $this->objId = null;
- }
+ $this->objId = $obj instanceof ModelInterface ? $obj->id() : null;
return $this;
}
@@ -145,7 +141,7 @@ public function addFeedbackFromModelValidatorResult(ValidatorResult $result, Mod
$propertyLabel = (string)$obj->property($prop)['label'];
$resultMessage = $result->message();
- if (strpos($resultMessage, $propertyLabel) === false) {
+ if (!str_contains((string)$resultMessage, $propertyLabel)) {
$resultMessage = strtr($this->translator()->translation('{{ errorMessage }}: {{ errorThrown }}'), [
'{{ errorMessage }}' => $propertyLabel,
'{{ errorThrown }}' => $resultMessage,
@@ -161,6 +157,7 @@ public function addFeedbackFromModelValidatorResult(ValidatorResult $result, Mod
/**
* @return array
*/
+ #[\Override]
public function results()
{
$results = [
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/DeleteAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/DeleteAction.php
index da13446d5..bb342f003 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/DeleteAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/DeleteAction.php
@@ -58,7 +58,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$objId = $request->getParam('obj_id');
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -70,7 +70,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
if (!$objId) {
- $actualType = is_object($objId) ? get_class($objId) : gettype($objId);
+ $actualType = get_debug_type($objId);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_id"',
'{{ expectedType }}' => 'string or numeric',
@@ -124,10 +124,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/ExportAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/ExportAction.php
index 89fcaba8a..a6bee833d 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/ExportAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/ExportAction.php
@@ -53,7 +53,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
set_time_limit(0);
$failMessage = $this->translator()->translation('Failed to export object(s)');
- $errorThrown = strtr($this->translator()->translation('{{ errorMessage }}: {{ errorThrown }}'), [
+ strtr($this->translator()->translation('{{ errorMessage }}: {{ errorThrown }}'), [
'{{ errorMessage }}' => $failMessage
]);
$reqMessage = $this->translator()->translation(
@@ -67,7 +67,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$exportIdent = $request->getParam('ident');
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -91,7 +91,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
if (isset($exportIdent)) {
if (!is_string($exportIdent)) {
- $actualType = is_object($exportIdent) ? get_class($exportIdent) : gettype($exportIdent);
+ $actualType = get_debug_type($exportIdent);
$this->addFeedback('error', strtr($typeMessage, [
'{{ parameter }}' => 'Export "ident"',
'{{ expectedType }}' => 'string',
@@ -113,10 +113,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
@@ -130,6 +128,7 @@ public function results()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/LoadAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/LoadAction.php
index 92c7d42fb..05f2326f0 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/LoadAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/LoadAction.php
@@ -43,17 +43,8 @@ class LoadAction extends AdminAction
{
/**
* Store the collection loader for the current class.
- *
- * @var CollectionLoader
*/
- private $collectionLoader;
-
- /**
- * Store the factory instance for the current class.
- *
- * @var \Charcoal\Factory\FactoryInterface
- */
- private $modelFactory;
+ private ?\Charcoal\Loader\CollectionLoader $collectionLoader = null;
/**
* @var string
@@ -70,7 +61,8 @@ class LoadAction extends AdminAction
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type', 'obj_id'
@@ -107,7 +99,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -125,21 +117,13 @@ public function run(RequestInterface $request, ResponseInterface $response)
$this->loadObjectCollection($objType);
$count = count($this->objCollection);
- switch ($count) {
- case 0:
- $doneMessage = $this->translator()->translation('No objects found.');
- break;
-
- case 1:
- $doneMessage = $this->translator()->translation('One object found.');
- break;
-
- default:
- $doneMessage = strtr($this->translator()->translation('{{ count }} objects found.'), [
- '{{ count }}' => $count
- ]);
- break;
- }
+ $doneMessage = match ($count) {
+ 0 => $this->translator()->translation('No objects found.'),
+ 1 => $this->translator()->translation('One object found.'),
+ default => strtr($this->translator()->translation('{{ count }} objects found.'), [
+ '{{ count }}' => $count
+ ]),
+ };
$this->addFeedback('success', $doneMessage);
$this->setSuccess(true);
@@ -157,7 +141,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
/**
* @return array The object collection parsed as array
*/
- public function objCollection()
+ public function objCollection(): array
{
if (!$this->objCollection) {
return [];
@@ -170,14 +154,13 @@ public function objCollection()
* Retrieve the model collection loader.
*
* @throws RuntimeException If the collection loader was not previously set.
- * @return CollectionLoader
*/
- public function collectionLoader()
+ public function collectionLoader(): \Charcoal\Loader\CollectionLoader
{
- if (!isset($this->collectionLoader)) {
+ if (!$this->collectionLoader instanceof \Charcoal\Loader\CollectionLoader) {
throw new RuntimeException(sprintf(
'Collection Loader is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -195,14 +178,13 @@ public function objType()
/**
* @param string $objType The object type as string.
* @throws InvalidArgumentException If the object type is not a string.
- * @return self
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
if (!is_string($objType)) {
throw new InvalidArgumentException(sprintf(
'Object type must be a string, received %s',
- is_object($objType) ? get_class($objType) : gettype($objType)
+ get_debug_type($objType)
));
}
@@ -211,10 +193,8 @@ public function setObjType($objType)
return $this;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
@@ -227,6 +207,7 @@ public function results()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -240,7 +221,7 @@ protected function setDependencies(Container $container)
* @param string $objType The object type as string.
* @return \Charcoal\Model\Collection
*/
- protected function loadObjectCollection($objType)
+ protected function loadObjectCollection($objType): \ArrayAccess|array
{
$proto = $this->modelFactory()->get($objType);
$loader = $this->collectionLoader();
@@ -256,9 +237,8 @@ protected function loadObjectCollection($objType)
* Set a model collection loader.
*
* @param CollectionLoader $loader The collection loader.
- * @return self
*/
- protected function setCollectionLoader(CollectionLoader $loader)
+ protected function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/ReorderAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/ReorderAction.php
index 1b0a4b6c7..b9718e773 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/ReorderAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/ReorderAction.php
@@ -45,7 +45,8 @@ class ReorderAction extends AdminAction implements ObjectContainerInterface
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type', 'obj_id'
@@ -79,7 +80,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
try {
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -95,7 +96,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$this->setObjType($objType);
if (!$objOrders || !is_array($objOrders)) {
- $actualType = is_object($objOrders) ? get_class($objOrders) : gettype($objOrders);
+ $actualType = get_debug_type($objOrders);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_orders"',
'{{ expectedType }}' => 'array of object IDs',
@@ -107,7 +108,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
if (!is_string($orderProperty)) {
- $actualType = is_object($orderProperty) ? get_class($orderProperty) : gettype($orderProperty);
+ $actualType = get_debug_type($orderProperty);
$this->addFeedback('error', strtr($typeMessage, [
'{{ parameter }}' => '"obj_property"',
'{{ expectedType }}' => 'string',
@@ -166,10 +167,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
@@ -181,6 +180,7 @@ public function results()
* @param Container $container A DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/RevertRevisionAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/RevertRevisionAction.php
index 3b320b310..92d2b7119 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/RevertRevisionAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/RevertRevisionAction.php
@@ -50,7 +50,8 @@ class RevertRevisionAction extends AdminAction implements ObjectContainerInterfa
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type',
@@ -66,12 +67,12 @@ protected function validDataFromRequest()
* @throws InvalidArgumentException If the given revision is invalid.
* @return ObjectContainerInterface Chainable
*/
- protected function setRevNum($revNum)
+ protected function setRevNum($revNum): static
{
if (!is_numeric($revNum)) {
throw new InvalidArgumentException(sprintf(
'Revision must be an integer, received %s.',
- (is_object($revNum) ? get_class($revNum) : gettype($revNum))
+ (get_debug_type($revNum))
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/SaveAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/SaveAction.php
index f87f55736..7203489ab 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/SaveAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/SaveAction.php
@@ -51,9 +51,9 @@ class SaveAction extends AbstractSaveAction
* This {@see self::$saveData subset} is merged onto the target model.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
- * @return self
*/
- protected function setDataFromRequest(RequestInterface $request)
+ #[\Override]
+ protected function setDataFromRequest(RequestInterface $request): static
{
parent::setDataFromRequest($request);
@@ -69,7 +69,8 @@ protected function setDataFromRequest(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type'
@@ -80,9 +81,8 @@ protected function validDataFromRequest()
* Filter the dataset used to create the target model.
*
* @param array $data The save data to filter.
- * @return array
*/
- public function filterSaveData(array $data)
+ public function filterSaveData(array $data): array
{
unset(
$data['widget_id'],
@@ -102,7 +102,7 @@ public function filterSaveData(array $data)
* @param array $data The save data.
* @return SaveAction Chainable
*/
- public function setSaveData(array $data)
+ public function setSaveData(array $data): static
{
$this->saveData = $data;
@@ -123,23 +123,22 @@ public function getSaveData()
* @param ModelInterface $obj The object to validate.
* @return boolean
*/
+ #[\Override]
public function validate(ModelInterface $obj)
{
$this->parsePrimaryKey($obj);
- $result = parent::validate($obj);
- return $result;
+ return parent::validate($obj);
}
/**
* Prepare the primary key for the object.
*
* @param ModelInterface $obj The object to validate.
- * @return void
*/
- public function parsePrimaryKey(ModelInterface $obj)
+ public function parsePrimaryKey(ModelInterface $obj): void
{
- if (($obj instanceof StorableInterface) && ($obj instanceof DescribablePropertyInterface)) {
+ if ($obj instanceof DescribablePropertyInterface) {
$pk = $obj->key();
$id = $obj[$pk];
@@ -168,7 +167,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$objType = $request->getParam('obj_type');
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -232,11 +231,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
} catch (PDOException $e) {
$this->setObj(null);
- if (isset($e->errorInfo[2])) {
- $message = $e->errorInfo[2];
- } else {
- $message = $e->getMessage();
- }
+ $message = ($e->errorInfo[2] ?? $e->getMessage());
$this->addFeedback('error', strtr($errorThrown, [
'{{ errorThrown }}' => $message
diff --git a/packages/admin/src/Charcoal/Admin/Action/Object/UpdateAction.php b/packages/admin/src/Charcoal/Admin/Action/Object/UpdateAction.php
index 1136dd539..283800deb 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Object/UpdateAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Object/UpdateAction.php
@@ -45,9 +45,9 @@ class UpdateAction extends AbstractSaveAction
* This {@see self::$updateData subset} is merged onto the target model.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
- * @return self
*/
- protected function setDataFromRequest(RequestInterface $request)
+ #[\Override]
+ protected function setDataFromRequest(RequestInterface $request): static
{
parent::setDataFromRequest($request);
@@ -63,7 +63,8 @@ protected function setDataFromRequest(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type', 'obj_id'
@@ -74,9 +75,8 @@ protected function validDataFromRequest()
* Filter the dataset used to update the target model.
*
* @param array $data The update data to filter.
- * @return array
*/
- public function filterUpdateData(array $data)
+ public function filterUpdateData(array $data): array
{
unset(
$data['widget_id'],
@@ -98,7 +98,7 @@ public function filterUpdateData(array $data)
* @param array $data The update data.
* @return UpdateAction Chainable
*/
- public function setUpdateData(array $data)
+ public function setUpdateData(array $data): static
{
$this->updateData = $data;
@@ -138,7 +138,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$objId = $request->getParam('obj_id');
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -150,7 +150,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
if (!$objId) {
- $actualType = is_object($objId) ? get_class($objId) : gettype($objId);
+ $actualType = get_debug_type($objId);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_id"',
'{{ expectedType }}' => 'ID',
diff --git a/packages/admin/src/Charcoal/Admin/Action/Selectize/LoadAction.php b/packages/admin/src/Charcoal/Admin/Action/Selectize/LoadAction.php
index 8ae9d176a..7c029e956 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Selectize/LoadAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Selectize/LoadAction.php
@@ -36,7 +36,8 @@ class LoadAction extends BaseLoadAction
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'selectize_prop_ident', 'selectize_property'
@@ -50,6 +51,7 @@ protected function validDataFromRequest()
* @throws UnexpectedValueException If "obj_id" is passed as $request option.
* @todo Implement obj_id support for load object action
*/
+ #[\Override]
public function run(RequestInterface $request, ResponseInterface $response)
{
unset($request);
@@ -75,14 +77,14 @@ public function run(RequestInterface $request, ResponseInterface $response)
$searchProperties = (array)$options['searchProperties'];
} elseif (
!empty($choiceMap['label']) &&
- strpos($choiceMap['label'], '{{') === false
+ !str_contains((string)$choiceMap['label'], '{{')
) {
$searchProperties = [ $choiceMap['label'] ];
} else {
$searchProperties = [];
}
- if ($searchProperties) {
+ if ($searchProperties !== []) {
$search = [
'conjunction' => 'OR',
'conditions' => [],
@@ -97,7 +99,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$filters = $property->filters();
if (is_array($filters)) {
- array_push($filters, $search);
+ $filters[] = $search;
} else {
$filters = [ $search ];
}
@@ -111,21 +113,13 @@ public function run(RequestInterface $request, ResponseInterface $response)
$this->setSelectizeCollection($this->selectizeVal($choices));
$count = count($choices);
- switch ($count) {
- case 0:
- $doneMessage = $this->translator()->translation('No objects found.');
- break;
-
- case 1:
- $doneMessage = $this->translator()->translation('One object found.');
- break;
-
- default:
- $doneMessage = strtr($this->translator()->translation('{{ count }} objects found.'), [
- '{{ count }}' => $count
- ]);
- break;
- }
+ $doneMessage = match ($count) {
+ 0 => $this->translator()->translation('No objects found.'),
+ 1 => $this->translator()->translation('One object found.'),
+ default => strtr($this->translator()->translation('{{ count }} objects found.'), [
+ '{{ count }}' => $count
+ ]),
+ };
$this->addFeedback('success', $doneMessage);
$this->setSuccess(true);
@@ -150,9 +144,8 @@ public function query()
/**
* @param string $query Query for LoadAction.
- * @return self
*/
- public function setQuery($query)
+ public function setQuery($query): static
{
$this->query = $query;
@@ -169,19 +162,16 @@ public function selectizeCollection()
/**
* @param array|mixed $selectizeCollection The collection to return.
- * @return self
*/
- public function setSelectizeCollection($selectizeCollection)
+ public function setSelectizeCollection($selectizeCollection): static
{
$this->selectizeCollection = $selectizeCollection;
return $this;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
@@ -195,6 +185,7 @@ public function results()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/Selectize/SaveAction.php b/packages/admin/src/Charcoal/Admin/Action/Selectize/SaveAction.php
index 6d6f4a7c5..04b08e5b2 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Selectize/SaveAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Selectize/SaveAction.php
@@ -20,7 +20,8 @@ class SaveAction extends BaseSaveAction
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'selectize_obj_type', 'selectize_prop_ident', 'selectize_property'
@@ -30,6 +31,7 @@ protected function validDataFromRequest()
/**
* @return array
*/
+ #[\Override]
public function results()
{
$results = parent::results();
@@ -46,6 +48,7 @@ public function results()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/Selectize/SelectizeRendererAwareTrait.php b/packages/admin/src/Charcoal/Admin/Action/Selectize/SelectizeRendererAwareTrait.php
index 3c1d01851..cc1905081 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Selectize/SelectizeRendererAwareTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Selectize/SelectizeRendererAwareTrait.php
@@ -77,7 +77,7 @@ public function setSelectizeProperty($struct)
protected function selectizeInput()
{
$prop = $this->selectizeProperty();
- $type = isset($prop['input_type']) ? $prop['input_type'] : SelectizeInput::class;
+ $type = ($prop['input_type'] ?? SelectizeInput::class);
$input = $this->propertyInputFactory()->create($type);
$input->setInputType($type);
@@ -93,9 +93,8 @@ protected function selectizeInput()
* Retrieves the output from SelectizeInput::selectizeVal.
*
* @param mixed $val The value(s) to parse as selectize choices.
- * @return array
*/
- protected function selectizeVal($val)
+ protected function selectizeVal($val): array
{
if ($val === null) {
return [];
@@ -139,7 +138,7 @@ public function propertyInputFactory()
if (!isset($this->propertyInputFactory)) {
throw new RuntimeException(sprintf(
'Property Input Factory is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
@@ -170,7 +169,7 @@ public function propertyFactory()
if (!isset($this->propertyFactory)) {
throw new RuntimeException(sprintf(
'Property Control Factory is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/Selectize/UpdateAction.php b/packages/admin/src/Charcoal/Admin/Action/Selectize/UpdateAction.php
index e0b7430d9..9cf32a020 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Selectize/UpdateAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Selectize/UpdateAction.php
@@ -20,7 +20,8 @@ class UpdateAction extends BaseUpdateAction
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'selectize_obj_type', 'selectize_prop_ident', 'selectize_property'
@@ -30,6 +31,7 @@ protected function validDataFromRequest()
/**
* @return array
*/
+ #[\Override]
public function results()
{
$results = parent::results();
@@ -46,6 +48,7 @@ public function results()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/AbstractCacheAction.php b/packages/admin/src/Charcoal/Admin/Action/System/AbstractCacheAction.php
index efbc5c979..247987653 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/AbstractCacheAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/AbstractCacheAction.php
@@ -67,6 +67,7 @@ public function getTwigEngine(): ?TwigEngine
/**
* @return array
*/
+ #[\Override]
public function results()
{
return [
@@ -81,6 +82,7 @@ public function results()
* @param Container $container A service locator.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -88,14 +90,14 @@ protected function setDependencies(Container $container)
$this->setCachePool($container['cache']);
$this->mustacheEngine = function () use ($container) {
- if (class_exists('\Mustache_Engine')) {
+ if (class_exists('\Mustache\Engine')) {
return $container['view/engine/mustache'];
}
return null;
};
$this->twigEngine = function () use ($container) {
- if (class_exists('\Twig\Environment')) {
+ if (class_exists(\Twig\Environment::class)) {
return $container['view/engine/twig'];
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/ClearCacheAction.php b/packages/admin/src/Charcoal/Admin/Action/System/ClearCacheAction.php
index 2573ebab4..721e600d1 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/ClearCacheAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/ClearCacheAction.php
@@ -24,7 +24,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$translator = $this->translator();
$cacheType = $request->getParam('cache_type');
- if (!is_string($cacheType) || empty($cacheType)) {
+ if (!is_string($cacheType) || ($cacheType === '' || $cacheType === '0')) {
$this->addFeedback('error', $translator->translate('Cache type not defined.'));
$this->setSuccess(false);
return $response->withStatus(400);
@@ -100,8 +100,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
private function clearGlobalCache()
{
$cache = $this->cachePool();
- $result = $cache->clear();
- return $result;
+ return $cache->clear();
}
/**
@@ -112,8 +111,7 @@ private function clearGlobalCache()
private function clearPagesCache()
{
$cache = $this->cachePool();
- $result = $cache->deleteItems([ 'request', 'template' ]);
- return $result;
+ return $cache->deleteItems([ 'request', 'template' ]);
}
/**
@@ -124,21 +122,18 @@ private function clearPagesCache()
private function clearObjectsCache()
{
$cache = $this->cachePool();
- $result = $cache->deleteItems([ 'object', 'metadata' ]);
- return $result;
+ return $cache->deleteItems([ 'object', 'metadata' ]);
}
private function clearTwigCache(): bool
{
$engine = $this->getTwigEngine();
- if (!$engine) {
+ if (!$engine instanceof \Charcoal\View\Twig\TwigEngine) {
return true;
}
$defaultCachePath = realpath($engine->cache());
- $cachePath = $defaultCachePath
- ? $defaultCachePath
- : realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
+ $cachePath = $defaultCachePath ?: realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
if (!is_dir($cachePath)) {
return false;
}
@@ -149,14 +144,12 @@ private function clearTwigCache(): bool
private function clearMustacheCache(): bool
{
$engine = $this->getMustacheEngine();
- if (!$engine) {
+ if (!$engine instanceof \Charcoal\View\Mustache\MustacheEngine) {
return true;
}
$defaultCachePath = realpath($engine->cache());
- $cachePath = $defaultCachePath
- ? $defaultCachePath
- : realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
+ $cachePath = $defaultCachePath ?: realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
if (!is_dir($cachePath)) {
return false;
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/ActivateAction.php b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/ActivateAction.php
index e196d5d54..0d0a7a909 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/ActivateAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/ActivateAction.php
@@ -1,5 +1,7 @@
request('GET', $url, [
'http_errors' => false
]);
- } catch (Exception $e) {
+ } catch (Exception) {
$this->setSuccess(false);
return $response->withStatus(404);
}
@@ -84,7 +84,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response->withStatus(404);
}
- if (strstr($headers['Content-Type'][0], 'text/html') !== false) {
+ if (str_contains($headers['Content-Type'][0], 'text/html')) {
$outputFile = $outputDir . '/index.html';
$prefix = '';
} else {
@@ -113,23 +113,20 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks()
];
-
- return $ret;
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeactivateAction.php b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeactivateAction.php
index c4c4a2644..a612ace58 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeactivateAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeactivateAction.php
@@ -1,5 +1,7 @@
$this->success(),
'feedbacks' => $this->feedbacks()
];
-
- return $ret;
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAction.php b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAction.php
index 66ac5cd1c..fc770f4aa 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAction.php
@@ -59,23 +59,20 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks()
];
-
- return $ret;
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllAction.php b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllAction.php
index 4009cdce8..4e5496e98 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllAction.php
@@ -43,23 +43,20 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks()
];
-
- return $ret;
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -69,9 +66,8 @@ protected function setDependencies(Container $container)
/**
* @param string $dir Directory to delete.
- * @return void
*/
- private function recursiveDelete($dir)
+ private function recursiveDelete(string $dir): void
{
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/PreviewAction.php b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/PreviewAction.php
index 00ea58008..ef5289d70 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/PreviewAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/PreviewAction.php
@@ -20,10 +20,7 @@ class PreviewAction extends AdminAction
*/
private $basePath;
- /**
- * @var string
- */
- private $fileContent = '';
+ private string|bool $fileContent = '';
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
@@ -34,7 +31,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
{
$url = $request->getParam('url');
$relativeUrl = str_replace($this->baseUrl(), '', $url);
- $url = $this->baseUrl() . $relativeUrl;
+ $this->baseUrl();
$outputDir = $this->basePath . DIRECTORY_SEPARATOR . 'cache/static/' . $relativeUrl;
if (!file_exists($outputDir)) {
@@ -59,24 +56,21 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response->withStatus(404);
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks(),
'content' => $this->fileContent
];
-
- return $ret;
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAction.php b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAction.php
index a9c6fa401..bee34396f 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAction.php
@@ -44,23 +44,20 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks()
];
-
- return $ret;
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -74,7 +71,7 @@ protected function setDependencies(Container $container)
* @param ResponseInterface $response PSR-7 response.
* @return boolean
*/
- protected function cacheUrl($url, $outputDir, ResponseInterface $response)
+ protected function cacheUrl($url, string $outputDir, ResponseInterface $response)
{
unset($response);
@@ -95,7 +92,7 @@ protected function cacheUrl($url, $outputDir, ResponseInterface $response)
try {
$guzzleClient = new GuzzleClient();
$static = $guzzleClient->request('GET', $url);
- } catch (Exception $e) {
+ } catch (Exception) {
$this->setSuccess(false);
return false;
}
@@ -112,7 +109,7 @@ protected function cacheUrl($url, $outputDir, ResponseInterface $response)
return false;
}
- if (strstr($headers['Content-Type'][0], 'text/html') !== false) {
+ if (str_contains($headers['Content-Type'][0], 'text/html')) {
$outputFile = $outputDir . '/index.html';
$prefix = '';
} else {
diff --git a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllAction.php b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllAction.php
index 9e0c6202e..5cf172193 100644
--- a/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllAction.php
@@ -18,9 +18,9 @@ class UpdateAllAction extends UpdateAction
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ #[\Override]
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -35,17 +35,13 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
- $ret = [
+ return [
'success' => $this->success(),
'feedbacks' => $this->feedbacks()
];
-
- return $ret;
}
/**
@@ -54,7 +50,7 @@ public function results()
* @param integer $flags Glob flags.
* @return array
*/
- protected function globRecursive($dir, $pattern, $flags = 0)
+ protected function globRecursive(string $dir, string $pattern, $flags = 0): array|false
{
$files = glob($dir . '/' . $pattern, $flags);
foreach (glob($dir . '/*', (GLOB_ONLYDIR | GLOB_NOSORT)) as $dir) {
diff --git a/packages/admin/src/Charcoal/Admin/Action/Tinymce/UploadImageAction.php b/packages/admin/src/Charcoal/Admin/Action/Tinymce/UploadImageAction.php
index b41d04adf..88ad43638 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Tinymce/UploadImageAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Tinymce/UploadImageAction.php
@@ -19,24 +19,18 @@ class UploadImageAction extends AdminAction
/**
* Whether uploaded files should be accessible from the web root.
- *
- * @var boolean
*/
- private $publicAccess = self::DEFAULT_PUBLIC_ACCESS;
+ private bool $publicAccess = self::DEFAULT_PUBLIC_ACCESS;
/**
* The relative path to the storage directory.
- *
- * @var string
*/
- private $uploadPath = self::DEFAULT_UPLOAD_PATH;
+ private string $uploadPath = self::DEFAULT_UPLOAD_PATH;
/**
* Whether existing destinations should be overwritten.
- *
- * @var boolean
*/
- private $overwrite = self::DEFAULT_OVERWRITE;
+ private bool $overwrite = self::DEFAULT_OVERWRITE;
/**
* The base path for the Charcoal installation.
@@ -52,10 +46,7 @@ class UploadImageAction extends AdminAction
*/
private $publicPath;
- /**
- * @var string
- */
- private $uploadedPath;
+ private ?string $uploadedPath = null;
/**
* Inject dependencies from a DI Container.
@@ -63,6 +54,7 @@ class UploadImageAction extends AdminAction
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -78,19 +70,18 @@ protected function setDependencies(Container $container)
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
$path = $request->getParam('upload_path');
- if (!!$path) {
+ if ((bool)$path) {
$this->setUploadPath($path);
}
$this->uploadedPath = $this->fileUpload($_FILES['file']);
- $this->setSuccess(!!$this->uploadedPath);
+ $this->setSuccess((bool)$this->uploadedPath);
return $response;
}
@@ -100,9 +91,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
*
* @param array $fileData The file data (from $_FILES, typically).
* @throws \InvalidArgumentException If the FILES data argument is missing `name` or `tmp_name`.
- * @return string
*/
- public function fileUpload(array $fileData)
+ public function fileUpload(array $fileData): string
{
if (!isset($fileData['name'])) {
throw new \InvalidArgumentException(
@@ -121,18 +111,16 @@ public function fileUpload(array $fileData)
} else {
$this->logger->notice(sprintf('File %s uploaded succesfully', $target));
$basePath = $this->basePath();
- $target = str_replace($basePath, '', $target);
- return $target;
+ return str_replace($basePath, '', $target);
}
}
/**
* @param string $filename Optional. The filename to save. If unset, a default filename will be generated.
* @throws \Exception If the target path is not writeable.
- * @return string
*/
- public function uploadTarget($filename = null)
+ public function uploadTarget($filename = null): string
{
$basePath = $this->basePath();
@@ -143,7 +131,7 @@ public function uploadTarget($filename = null)
// @todo: Feedback
$this->logger->debug(
'Path does not exist. Attempting to create path ' . $dir . '.',
- [get_called_class() . '::' . __FUNCTION__]
+ [static::class . '::' . __FUNCTION__]
);
mkdir($dir, 0777, true);
}
@@ -156,7 +144,7 @@ public function uploadTarget($filename = null)
$target = $dir . $filename;
if ($this->fileExists($target)) {
- if ($this->overwrite() === true) {
+ if ($this->overwrite()) {
return $target;
} else {
$target = $dir . $this->generateUniqueFilename($filename);
@@ -177,9 +165,8 @@ public function uploadTarget($filename = null)
*
* @param string $file The full file to check.
* @param boolean $caseInsensitive Case-insensitive by default.
- * @return boolean
*/
- public function fileExists($file, $caseInsensitive = true)
+ public function fileExists($file, $caseInsensitive = true): bool
{
if (!$this->isAbsolutePath($file)) {
$file = $this->basePath() . DIRECTORY_SEPARATOR . $file;
@@ -197,7 +184,7 @@ public function fileExists($file, $caseInsensitive = true)
if ($files) {
$pattern = preg_quote($file, '#');
foreach ($files as $f) {
- if (preg_match("#${pattern}#i", $f)) {
+ if (preg_match("#{$pattern}#i", $f)) {
return true;
}
}
@@ -216,7 +203,7 @@ public function fileExists($file, $caseInsensitive = true)
* @param string $file A file path.
* @return boolean Returns TRUE if the given path is absolute. Otherwise, returns FALSE.
*/
- protected function isAbsolutePath($file)
+ protected function isAbsolutePath($file): bool
{
return strspn($file, '/\\', 0, 1)
|| (strlen($file) > 3
@@ -232,7 +219,7 @@ protected function isAbsolutePath($file)
* @param string $filename The filename to sanitize.
* @return string The sanitized filename.
*/
- public function sanitizeFilename($filename)
+ public function sanitizeFilename($filename): string
{
// Remove blacklisted caharacters
$blacklist = ['/', '\\', '\0', '*', ':', '?', '"', '<', '>', '|', '#', '&', '!', '`', ' '];
@@ -249,22 +236,17 @@ public function sanitizeFilename($filename)
*
* @param string|array $filename The filename to alter.
* @throws \InvalidArgumentException If the given filename is invalid.
- * @return string
*/
- public function generateUniqueFilename($filename)
+ public function generateUniqueFilename($filename): string
{
if (!is_string($filename) && !is_array($filename)) {
throw new \InvalidArgumentException(sprintf(
'The target must be a string or an array from [pathfino()], received %s',
- (is_object($filename) ? get_class($filename) : gettype($filename))
+ (get_debug_type($filename))
));
}
- if (is_string($filename)) {
- $info = pathinfo($filename);
- } else {
- $info = $filename;
- }
+ $info = is_string($filename) ? pathinfo($filename) : $filename;
$filename = $info['filename'] . '-' . uniqid();
@@ -275,10 +257,7 @@ public function generateUniqueFilename($filename)
return $filename;
}
- /**
- * @return string
- */
- public function uploadPath()
+ public function uploadPath(): string
{
return $this->uploadPath;
}
@@ -290,9 +269,8 @@ public function uploadPath()
*
* @param string $path The destination directory, relative to project's root.
* @throws \InvalidArgumentException If the path is not a string.
- * @return self
*/
- public function setUploadPath($path)
+ public function setUploadPath($path): static
{
if (!is_string($path)) {
throw new \InvalidArgumentException(
@@ -310,21 +288,18 @@ public function setUploadPath($path)
* Set whether uploaded files should be publicly available.
*
* @param boolean $public Whether uploaded files should be accessible (TRUE) or not (FALSE) from the web root.
- * @return self
*/
- public function setPublicAccess($public)
+ public function setPublicAccess($public): static
{
- $this->publicAccess = !!$public;
+ $this->publicAccess = (bool)$public;
return $this;
}
/**
* Determine if uploaded files should be publicly available.
- *
- * @return boolean
*/
- public function publicAccess()
+ public function publicAccess(): bool
{
return $this->publicAccess;
}
@@ -333,21 +308,18 @@ public function publicAccess()
* Set whether existing destinations should be overwritten.
*
* @param boolean $overwrite Whether existing destinations should be overwritten (TRUE) or not (FALSE).
- * @return self
*/
- public function setOverwrite($overwrite)
+ public function setOverwrite($overwrite): static
{
- $this->overwrite = !!$overwrite;
+ $this->overwrite = (bool)$overwrite;
return $this;
}
/**
* Determine if existing destinations should be overwritten.
- *
- * @return boolean
*/
- public function overwrite()
+ public function overwrite(): bool
{
return $this->overwrite;
}
@@ -368,10 +340,9 @@ protected function basePath()
/**
* Default response stub.
- *
- * @return array
*/
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
diff --git a/packages/admin/src/Charcoal/Admin/Action/Widget/LoadAction.php b/packages/admin/src/Charcoal/Admin/Action/Widget/LoadAction.php
index 8fcf6d9f9..0556402b5 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Widget/LoadAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Widget/LoadAction.php
@@ -115,7 +115,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
try {
if (!$widgetType) {
- $actualType = is_object($widgetType) ? get_class($widgetType) : gettype($widgetType);
+ $actualType = get_debug_type($widgetType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"widget_type"',
'{{ expectedType }}' => 'string',
@@ -133,7 +133,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
if (isset($widgetOptions)) {
if (!is_array($widgetOptions)) {
- $actualType = is_object($widgetOptions) ? get_class($widgetOptions) : gettype($widgetOptions);
+ $actualType = get_debug_type($widgetOptions);
$this->addFeedback('error', strtr($typeMessage, [
'{{ parameter }}' => '"widget_options"',
'{{ expectedType }}' => 'array',
@@ -190,7 +190,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @throws InvalidArgumentException If the widget ID argument is not a string.
* @return LoadAction Chainable
*/
- public function setWidgetId($id)
+ public function setWidgetId($id): static
{
if (!is_string($id)) {
throw new InvalidArgumentException(
@@ -217,9 +217,8 @@ public function widgetId()
* Set the widget's DATA.
*
* @param array|mixed $widgetData WidgetData for LoadAction.
- * @return self
*/
- public function setWidgetData($widgetData)
+ public function setWidgetData($widgetData): static
{
$this->widgetData = $widgetData;
@@ -243,7 +242,7 @@ public function widgetData()
* @throws InvalidArgumentException If the widget type argument is not a string.
* @return LoadAction Chainable
*/
- public function setWidgetType($type)
+ public function setWidgetType($type): static
{
if (!is_string($type)) {
throw new InvalidArgumentException(
@@ -273,7 +272,7 @@ public function widgetType()
* @throws InvalidArgumentException If the widget HTML is not a string.
* @return LoadAction Chainable
*/
- public function setWidgetHtml($html)
+ public function setWidgetHtml($html): static
{
if (!is_string($html)) {
throw new InvalidArgumentException(
@@ -296,10 +295,8 @@ public function widgetHtml()
return $this->widgetHtml;
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
@@ -314,6 +311,7 @@ public function results()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setdependencies($container);
@@ -331,7 +329,7 @@ protected function setDependencies(Container $container)
*/
protected function widgetView()
{
- if (!isset($this->widgetView)) {
+ if ($this->widgetView === null) {
throw new RuntimeException('Widget Renderer is not defined');
}
@@ -346,7 +344,7 @@ protected function widgetView()
*/
protected function widgetFactory()
{
- if (!isset($this->widgetFactory)) {
+ if ($this->widgetFactory === null) {
throw new RuntimeException('Widget Factory is not defined');
}
@@ -357,9 +355,8 @@ protected function widgetFactory()
* Set the widget renderer.
*
* @param ViewInterface $view The view renderer to create widgets.
- * @return void
*/
- private function setWidgetView(ViewInterface $view)
+ private function setWidgetView(ViewInterface $view): void
{
$this->widgetView = $view;
}
@@ -368,9 +365,8 @@ private function setWidgetView(ViewInterface $view)
* Set the widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return void
*/
- private function setWidgetFactory(FactoryInterface $factory)
+ private function setWidgetFactory(FactoryInterface $factory): void
{
$this->widgetFactory = $factory;
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineAction.php b/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineAction.php
index 620910815..a52a7818c 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineAction.php
@@ -68,7 +68,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$reqMessage = $this->translator()->translation(
'{{ parameter }} required, must be a {{ expectedType }}, received {{ actualType }}'
);
- $typeMessage = $this->translator()->translation(
+ $this->translator()->translation(
'{{ parameter }} must be a {{ expectedType }}, received {{ actualType }}'
);
@@ -76,7 +76,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$objId = $request->getParam('obj_id');
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -88,7 +88,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
if (!$objId) {
- $actualType = is_object($objId) ? get_class($objId) : gettype($objId);
+ $actualType = get_debug_type($objId);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_id"',
'{{ expectedType }}' => 'string or numeric',
@@ -149,10 +149,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
@@ -165,6 +163,7 @@ public function results()
* @param Container $container DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -180,7 +179,7 @@ protected function setDependencies(Container $container)
*/
protected function widgetFactory()
{
- if (!isset($this->widgetFactory)) {
+ if ($this->widgetFactory === null) {
throw new RuntimeException('Widget Factory is not defined');
}
@@ -191,9 +190,8 @@ protected function widgetFactory()
* Set the widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return void
*/
- private function setWidgetFactory(FactoryInterface $factory)
+ private function setWidgetFactory(FactoryInterface $factory): void
{
$this->widgetFactory = $factory;
}
diff --git a/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineMultiAction.php b/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineMultiAction.php
index 9f540d378..8f9b313a7 100644
--- a/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineMultiAction.php
+++ b/packages/admin/src/Charcoal/Admin/Action/Widget/Table/InlineMultiAction.php
@@ -48,10 +48,8 @@ class InlineMultiAction extends AdminAction
/**
* Store the widget factory.
- *
- * @var FactoryInterface
*/
- private $widgetFactory;
+ private ?\Charcoal\Factory\FactoryInterface $widgetFactory = null;
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
@@ -68,7 +66,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$reqMessage = $this->translator()->translation(
'{{ parameter }} required, must be a {{ expectedType }}, received {{ actualType }}'
);
- $typeMessage = $this->translator()->translation(
+ $this->translator()->translation(
'{{ parameter }} must be a {{ expectedType }}, received {{ actualType }}'
);
@@ -76,7 +74,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$objIds = $request->getParam('obj_ids');
if (!$objType) {
- $actualType = is_object($objType) ? get_class($objType) : gettype($objType);
+ $actualType = get_debug_type($objType);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_type"',
'{{ expectedType }}' => 'string',
@@ -88,7 +86,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
if (!$objIds || !is_array($objIds)) {
- $actualType = is_object($objIds) ? get_class($objIds) : gettype($objIds);
+ $actualType = get_debug_type($objIds);
$this->addFeedback('error', strtr($reqMessage, [
'{{ parameter }}' => '"obj_ids"',
'{{ expectedType }}' => 'array of object IDs',
@@ -153,10 +151,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
}
- /**
- * @return array
- */
- public function results()
+ #[\Override]
+ public function results(): array
{
return [
'success' => $this->success(),
@@ -169,6 +165,7 @@ public function results()
* @param Container $container DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -180,11 +177,10 @@ protected function setDependencies(Container $container)
* Retrieve the widget factory.
*
* @throws RuntimeException If the widget factory was not previously set.
- * @return FactoryInterface
*/
- protected function widgetFactory()
+ protected function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->widgetFactory)) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException('Widget Factory is not defined');
}
@@ -195,9 +191,8 @@ protected function widgetFactory()
* Set the widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return void
*/
- private function setWidgetFactory(FactoryInterface $factory)
+ private function setWidgetFactory(FactoryInterface $factory): void
{
$this->widgetFactory = $factory;
}
diff --git a/packages/admin/src/Charcoal/Admin/AdminAction.php b/packages/admin/src/Charcoal/Admin/AdminAction.php
index d97ee1eec..d101689ef 100644
--- a/packages/admin/src/Charcoal/Admin/AdminAction.php
+++ b/packages/admin/src/Charcoal/Admin/AdminAction.php
@@ -57,17 +57,13 @@ abstract class AdminAction extends AbstractAction implements
/**
* Store the result from the last validation by Google reCAPTCHA API.
- *
- * @var array|null
*/
- private $recaptchaLastResult;
+ private ?array $recaptchaLastResult = null;
/**
* Store the model factory.
- *
- * @var FactoryInterface $modelFactory
*/
- private $modelFactory;
+ private ?\Charcoal\Factory\FactoryInterface $modelFactory = null;
/**
* Action's init method is called automatically from `charcoal-app`'s Action Route.
@@ -82,6 +78,7 @@ abstract class AdminAction extends AbstractAction implements
* @return boolean
* @see \Charcoal\App\Route\TemplateRoute::__invoke()
*/
+ #[\Override]
public function init(RequestInterface $request)
{
if (!session_id()) {
@@ -165,12 +162,11 @@ public function siteName()
*/
public function results()
{
- $results = [
+ return [
'success' => $this->success(),
'next_url' => $this->redirectUrl(),
'feedbacks' => $this->feedbacks()
];
- return $results;
}
/**
@@ -179,6 +175,7 @@ public function results()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -340,11 +337,11 @@ protected function validateCaptcha($token)
* with a new Response object that represents a client error.
* @return boolean Returns TRUE if the user response is valid, FALSE if it is invalid.
*/
- protected function validateCaptchaFromRequest(RequestInterface $request, ResponseInterface &$response = null)
+ protected function validateCaptchaFromRequest(RequestInterface $request, ?ResponseInterface &$response = null)
{
$token = $request->getParam('g-recaptcha-response', false);
if (empty($token)) {
- if ($response !== null) {
+ if ($response instanceof \Psr\Http\Message\ResponseInterface) {
$this->addFeedback('error', $this->translator()->translate('Missing CAPTCHA response.'));
$this->setSuccess(false);
@@ -355,7 +352,7 @@ protected function validateCaptchaFromRequest(RequestInterface $request, Respons
}
$result = $this->validateCaptcha($token);
- if ($result === false && $response !== null) {
+ if ($result === false && $response instanceof \Psr\Http\Message\ResponseInterface) {
$this->addFeedback('error', $this->translator()->translate('Invalid or malformed CAPTCHA response.'));
$this->setSuccess(false);
diff --git a/packages/admin/src/Charcoal/Admin/AdminModule.php b/packages/admin/src/Charcoal/Admin/AdminModule.php
index 3d32be4f8..07798bd0a 100644
--- a/packages/admin/src/Charcoal/Admin/AdminModule.php
+++ b/packages/admin/src/Charcoal/Admin/AdminModule.php
@@ -3,6 +3,7 @@
namespace Charcoal\Admin;
// From PSR-7
+use Pimple\Container;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
// From 'charcoal-app'
@@ -32,7 +33,8 @@ class AdminModule extends AbstractModule
*
* @return AdminModule Chainable
*/
- public function setUp()
+ #[\Override]
+ public function setUp(): static
{
// Hack: skip if the request does not start with '/admin'
$container = $this->app()->getContainer();
@@ -47,15 +49,13 @@ public function setUp()
$container->register(new AdminServiceProvider());
$module = $this;
- $container['charcoal/admin/module'] = function () use ($module) {
- return $module;
- };
+ $container['charcoal/admin/module'] = (fn(): static => $module);
$adminConfig = $container['admin/config'];
$this->setConfig($adminConfig);
- $groupIdent = '/' . trim($adminConfig['base_path'], '/');
+ $groupIdent = '/' . trim((string)$adminConfig['base_path'], '/');
// Add the route group
$this->app()->group($groupIdent, 'charcoal/admin/module:setupRoutes')
@@ -69,7 +69,8 @@ public function setUp()
*
* @return AdminModule Chainable
*/
- public function setupRoutes()
+ #[\Override]
+ public function setupRoutes(): static
{
if ($this->routeManager === null) {
parent::setupRoutes();
@@ -102,7 +103,7 @@ public function setupHandlers(
* @param object|HandlerInterface $handler An error handler instance.
* @return HandlerInterface
*/
- $container->extend('notFoundHandler', function ($handler, $container) {
+ $container->extend('notFoundHandler', function ($handler, Container $container) {
$appConfig = $container['config'];
$adminConfig = $container['admin/config'];
if ($handler instanceof HandlerInterface) {
@@ -125,7 +126,7 @@ public function setupHandlers(
* @param object|HandlerInterface $handler An error handler instance.
* @return HandlerInterface
*/
- $container->extend('notAllowedHandler', function ($handler, $container) {
+ $container->extend('notAllowedHandler', function ($handler, Container $container) {
$appConfig = $container['config'];
$adminConfig = $container['admin/config'];
if ($handler instanceof HandlerInterface) {
@@ -148,7 +149,7 @@ public function setupHandlers(
* @param object|HandlerInterface $handler An error handler instance.
* @return HandlerInterface
*/
- $container->extend('phpErrorHandler', function ($handler, $container) {
+ $container->extend('phpErrorHandler', function ($handler, Container $container) {
$appConfig = $container['config'];
$adminConfig = $container['admin/config'];
if ($handler instanceof HandlerInterface) {
@@ -171,7 +172,7 @@ public function setupHandlers(
* @param object|HandlerInterface $handler An error handler instance.
* @return HandlerInterface
*/
- $container->extend('errorHandler', function ($handler, $container) {
+ $container->extend('errorHandler', function ($handler, Container $container) {
$appConfig = $container['config'];
$adminConfig = $container['admin/config'];
if ($handler instanceof HandlerInterface) {
@@ -196,7 +197,7 @@ public function setupHandlers(
* @param object|HandlerInterface $handler An error handler instance.
* @return HandlerInterface
*/
- $container->extend('maintenanceHandler', function ($handler, $container) {
+ $container->extend('maintenanceHandler', function ($handler, Container $container) {
$appConfig = $container['config'];
$adminConfig = $container['admin/config'];
if ($handler instanceof HandlerInterface) {
@@ -226,11 +227,6 @@ private function isPathAdmin($path)
if ($path === 'admin') {
return true;
}
-
- if (substr($path, 0, 6) === 'admin/') {
- return true;
- }
-
- return false;
+ return str_starts_with($path, 'admin/');
}
}
diff --git a/packages/admin/src/Charcoal/Admin/AdminScript.php b/packages/admin/src/Charcoal/Admin/AdminScript.php
index 0d17d9304..22ccc2583 100644
--- a/packages/admin/src/Charcoal/Admin/AdminScript.php
+++ b/packages/admin/src/Charcoal/Admin/AdminScript.php
@@ -27,15 +27,14 @@ abstract class AdminScript extends AbstractScript
/**
* The model factory.
- *
- * @var FactoryInterface
*/
- private $modelFactory;
+ private ?\Charcoal\Factory\FactoryInterface $modelFactory = null;
/**
* @param Container $container Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -95,11 +94,10 @@ private function booleanInput(PropertyInterface $prop, $label)
1 => $prop->trueLabel(),
0 => $prop->falseLabel()
];
- $input = $climate->radio(
+ return $climate->radio(
$label,
$opts
);
- return $input;
}
/**
@@ -114,18 +112,15 @@ private function passwordInput(PropertyInterface $prop, $label)
unset($prop);
$climate = $this->climate();
-
- $input = $climate->password($label);
- return $input;
+ return $climate->password($label);
}
/**
* Set the model factory.
*
* @param FactoryInterface $factory The factory used to create models.
- * @return void
*/
- private function setModelFactory(FactoryInterface $factory)
+ private function setModelFactory(FactoryInterface $factory): void
{
$this->modelFactory = $factory;
}
diff --git a/packages/admin/src/Charcoal/Admin/AdminTemplate.php b/packages/admin/src/Charcoal/Admin/AdminTemplate.php
index 88beb929e..d4497c116 100644
--- a/packages/admin/src/Charcoal/Admin/AdminTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/AdminTemplate.php
@@ -78,20 +78,11 @@ class AdminTemplate extends AbstractTemplate implements
*/
protected $subtitle;
- /**
- * @var boolean
- */
- private $showSecondaryMenu = true;
+ private bool $showSecondaryMenu = true;
- /**
- * @var boolean
- */
- private $showMainMenu = true;
+ private bool $showMainMenu = true;
- /**
- * @var boolean
- */
- private $showSystemMenu = true;
+ private bool $showSystemMenu = true;
/**
* @var boolean
@@ -118,10 +109,7 @@ class AdminTemplate extends AbstractTemplate implements
*/
protected $secondaryMenu;
- /**
- * @var array
- */
- private $adminDataForJs;
+ private ?array $adminDataForJs = null;
/**
* @var \Charcoal\Ui\Menu\MenuBuilder $menuBuilder
@@ -133,15 +121,9 @@ class AdminTemplate extends AbstractTemplate implements
*/
private $menuItemBuilder;
- /**
- * @var FactoryInterface $modelFactory
- */
- private $modelFactory;
+ private ?\Charcoal\Factory\FactoryInterface $modelFactory = null;
- /**
- * @var FactoryInterface $widgetFactory
- */
- private $widgetFactory;
+ private ?\Charcoal\Factory\FactoryInterface $widgetFactory = null;
/**
* Template's init method is called automatically from `charcoal-app`'s Template Route.
@@ -156,6 +138,7 @@ class AdminTemplate extends AbstractTemplate implements
* @return boolean
* @see \Charcoal\App\Route\TemplateRoute::__invoke()
*/
+ #[\Override]
public function init(RequestInterface $request)
{
if (!session_id()) {
@@ -199,12 +182,11 @@ protected function authRedirect(RequestInterface $request)
* Sets the template data from a PSR Request object.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
- * @return self
*/
- protected function setDataFromRequest(RequestInterface $request)
+ protected function setDataFromRequest(RequestInterface $request): static
{
$keys = $this->validDataFromRequest();
- if (!empty($keys)) {
+ if ($keys !== []) {
$this->setData($request->getParams($keys));
}
@@ -216,7 +198,7 @@ protected function setDataFromRequest(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ protected function validDataFromRequest(): array
{
return [
// HTTP Handling
@@ -230,7 +212,7 @@ protected function validDataFromRequest()
* @param mixed $ident Template identifier.
* @return AdminTemplate Chainable
*/
- public function setIdent($ident)
+ public function setIdent($ident): static
{
$this->ident = $ident;
return $this;
@@ -248,7 +230,7 @@ public function ident()
* @param mixed $label Template label.
* @return AdminTemplate Chainable
*/
- public function setLabel($label)
+ public function setLabel($label): static
{
$this->label = $this->translator()->translation($label);
@@ -269,7 +251,7 @@ public function label()
* @param mixed $title Template title.
* @return AdminTemplate Chainable
*/
- public function setTitle($title)
+ public function setTitle($title): static
{
$this->title = $this->translator()->translation($title);
@@ -296,7 +278,7 @@ public function title()
* @param mixed $subtitle Template subtitle.
* @return AdminTemplate Chainable
*/
- public function setSubtitle($subtitle)
+ public function setSubtitle($subtitle): static
{
$this->subtitle = $this->translator()->translation($subtitle);
@@ -317,16 +299,13 @@ public function subtitle()
* @param boolean $show The show main menu flag.
* @return AdminTemplate Chainable
*/
- public function setShowMainMenu($show)
+ public function setShowMainMenu($show): static
{
- $this->showMainMenu = !!$show;
+ $this->showMainMenu = (bool)$show;
return $this;
}
- /**
- * @return boolean
- */
- public function showMainMenu()
+ public function showMainMenu(): bool
{
return ($this->isAuthorized() && $this->showMainMenu);
}
@@ -359,16 +338,13 @@ public function mainMenu()
* @param boolean $show The show footer menu flag.
* @return AdminTemplate Chainable
*/
- public function setShowSystemMenu($show)
+ public function setShowSystemMenu($show): static
{
- $this->showSystemMenu = !!$show;
+ $this->showSystemMenu = (bool)$show;
return $this;
}
- /**
- * @return boolean
- */
- public function showSystemMenu()
+ public function showSystemMenu(): bool
{
return ($this->isAuthorized() && $this->showSystemMenu && (count($this->systemMenu()) > 0));
}
@@ -376,7 +352,7 @@ public function showSystemMenu()
/**
* @return array
*/
- public function systemMenu()
+ public function systemMenu(): \ArrayIterator
{
if ($this->systemMenu === null) {
$this->systemMenu = $this->createSystemMenu();
@@ -389,16 +365,13 @@ public function systemMenu()
* @param boolean $show The show secondary menu flag.
* @return AdminTemplate Chainable
*/
- public function setShowSecondaryMenu($show)
+ public function setShowSecondaryMenu($show): static
{
- $this->showSecondaryMenu = !!$show;
+ $this->showSecondaryMenu = (bool)$show;
return $this;
}
- /**
- * @return boolean
- */
- public function showSecondaryMenu()
+ public function showSecondaryMenu(): bool
{
return ($this->isAuthorized() && $this->showSecondaryMenu);
}
@@ -430,10 +403,7 @@ public function mainMenuLogo()
return 'assets/admin/images/identicon.png';
}
- /**
- * @return string
- */
- public function navContainerCssClasses()
+ public function navContainerCssClasses(): string
{
$classes = [ 'has-nav-logo' ];
@@ -496,7 +466,7 @@ public function documentTitle()
$siteName = $this->siteName();
$pageTitle = strip_tags($this->title());
- if ($pageTitle) {
+ if ($pageTitle !== '' && $pageTitle !== '0') {
if ($pageTitle === $siteName) {
return sprintf('%1$s — Charcoal', $pageTitle);
} else {
@@ -509,10 +479,8 @@ public function documentTitle()
/**
* Retrieve the current language.
- *
- * @return string
*/
- public function lang()
+ public function lang(): string
{
return $this->translator()->getLocale();
}
@@ -580,20 +548,15 @@ public function recaptchaInvisible()
if ($hasSize && $recaptcha['size'] === 'invisible') {
return true;
}
-
- if (!$hasInvisible && !$hasSize) {
- return true;
- }
-
- return false;
+ return !$hasInvisible && !$hasSize;
}
/**
* Alias of {@see self::recaptchaSiteKey()}.
*
- * @deprecated
* @return string|null
*/
+ #[\Deprecated]
public function recaptchaKey()
{
return $this->recaptchaSiteKey();
@@ -623,7 +586,7 @@ public function recaptchaSiteKey()
*
* @return string[]
*/
- public function recaptchaParameters()
+ public function recaptchaParameters(): array
{
$apiConfig = $this->apiConfig('google.recaptcha');
$tplConfig = $this->get('recaptcha_options') ?: [];
@@ -658,10 +621,8 @@ public function recaptchaParameters()
/**
* Generate a string representation of HTML attributes for the Google reCAPTCHA tag.
- *
- * @return string
*/
- public function recaptchaHtmlAttr()
+ public function recaptchaHtmlAttr(): string
{
$params = $this->recaptchaParameters();
@@ -681,6 +642,7 @@ public function recaptchaHtmlAttr()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -715,11 +677,11 @@ protected function setDependencies(Container $container)
* @throws Exception If the factory is not set.
* @return FactoryInterface The model factory.
*/
- protected function modelFactory()
+ protected function modelFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!$this->modelFactory) {
+ if (!$this->modelFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new Exception(
- sprintf('Model factory is not set for template "%s".', get_class($this))
+ sprintf('Model factory is not set for template "%s".', static::class)
);
}
return $this->modelFactory;
@@ -727,11 +689,10 @@ protected function modelFactory()
/**
* @throws Exception If the widget factory dependency was not previously set / injected.
- * @return FactoryInterface
*/
- protected function widgetFactory()
+ protected function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->widgetFactory === null) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new Exception(
'Widget factory was not set.'
);
@@ -745,7 +706,7 @@ protected function widgetFactory()
* @param string $name Name of the project.
* @return AdminTemplate Chainable
*/
- protected function setSiteName($name)
+ protected function setSiteName($name): static
{
$this->siteName = $this->translator()->translation($name);
return $this;
@@ -756,9 +717,8 @@ protected function setSiteName($name)
*
* @param mixed $options The main menu widget ID or config.
* @throws InvalidArgumentException If the admin config is missing, invalid, or malformed.
- * @return array
*/
- protected function createMainMenu($options = null)
+ protected function createMainMenu($options = null): array
{
$mainMenuConfig = $this->adminConfig('main_menu');
@@ -791,7 +751,7 @@ protected function createMainMenu($options = null)
$menuItems[] = $this->parseMainMenuItem($menuItem, $menuIdent, $mainMenuIdent);
}
- usort($menuItems, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ usort($menuItems, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
return $menuItems;
}
@@ -822,7 +782,7 @@ private function mainMenuIdent($options = null)
}
// Get main menu from the obj_type
- $objType = filter_input(INPUT_GET, 'obj_type', FILTER_SANITIZE_STRING);
+ $objType = htmlspecialchars(trim(($_GET['obj_type'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($objType) {
$secondaryMenuItems = $this->adminConfig('secondary_menu');
foreach ($secondaryMenuItems as $main => $item) {
@@ -834,7 +794,7 @@ private function mainMenuIdent($options = null)
}
// Choose main menu with a get parameter
- $mainMenuFromRequest = filter_input(INPUT_GET, 'main_menu', FILTER_SANITIZE_STRING);
+ $mainMenuFromRequest = htmlspecialchars(trim(($_GET['main_menu'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($mainMenuFromRequest) {
$mainMenuIdent = $mainMenuFromRequest;
}
@@ -852,9 +812,8 @@ private function mainMenuIdent($options = null)
*
* @param string $objType The ObjType to search.
* @param array|mixed $item The secondary menu item to search in.
- * @return boolean
*/
- protected function isObjTypeInSecondaryMenuItem($objType, $item)
+ protected function isObjTypeInSecondaryMenuItem($objType, array $item): bool
{
if (isset($item['links'])) {
foreach ($item['links'] as $obj => $i) {
@@ -878,8 +837,9 @@ protected function isObjTypeInSecondaryMenuItem($objType, $item)
/**
* @throws InvalidArgumentException If the secondary menu widget is invalid.
* @return \Charcoal\Admin\Widget\SecondaryMenuWidgetInterface[]|
+ * @return mixed[]
*/
- protected function createSecondaryMenu()
+ protected function createSecondaryMenu(): array
{
$secondaryMenuItems = $this->adminConfig('secondary_menu');
@@ -909,7 +869,7 @@ protected function createSecondaryMenu()
}
}
- usort($menuItems, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ usort($menuItems, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
return $menuItems;
}
@@ -919,7 +879,7 @@ protected function createSecondaryMenu()
* @throws InvalidArgumentException If the menu is missing, invalid, or malformed.
* @return array|Generator
*/
- protected function createSystemMenu($options = null)
+ protected function createSystemMenu($options = null): array
{
$menuConfig = $this->adminConfig('system_menu');
@@ -964,7 +924,7 @@ protected function createSystemMenu($options = null)
$menuItems[$menuIdent] = $menuItem;
}
- usort($menuItems, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ usort($menuItems, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
return $menuItems;
}
@@ -973,18 +933,16 @@ protected function createSystemMenu($options = null)
* As a convenience, all admin templates have a model factory to easily create objects.
*
* @param FactoryInterface $factory The factory used to create models.
- * @return void
*/
- private function setModelFactory(FactoryInterface $factory)
+ private function setModelFactory(FactoryInterface $factory): void
{
$this->modelFactory = $factory;
}
/**
* @param FactoryInterface $factory The widget factory, to create the dashboard and secondary menu widgets.
- * @return void
*/
- private function setWidgetFactory(FactoryInterface $factory)
+ private function setWidgetFactory(FactoryInterface $factory): void
{
$this->widgetFactory = $factory;
}
@@ -995,7 +953,7 @@ private function setWidgetFactory(FactoryInterface $factory)
* @param string|null $currentIdent The current menu identifier.
* @return array Finalized menu structure.
*/
- private function parseMainMenuItem(array $menuItem, $menuIdent = null, $currentIdent = null)
+ private function parseMainMenuItem(array $menuItem, $menuIdent = null, $currentIdent = null): array
{
$svgUri = $this->baseUrl() . 'assets/admin/images/svgs.svg#icon-';
@@ -1007,7 +965,7 @@ private function parseMainMenuItem(array $menuItem, $menuIdent = null, $currentI
if (!empty($menuItem['url'])) {
$url = $menuItem['url'];
- if ($url && strpos($url, ':') === false && !in_array($url[0], [ '/', '#', '?' ])) {
+ if ($url && !str_contains((string)$url, ':') && !in_array($url[0], [ '/', '#', '?' ])) {
$url = $this->adminUrl() . $url;
}
} else {
@@ -1018,7 +976,7 @@ private function parseMainMenuItem(array $menuItem, $menuIdent = null, $currentI
if (isset($menuItem['icon'])) {
$icon = $menuItem['icon'];
- if ($icon && strpos($icon, ':') === false && !in_array($icon[0], [ '/', '#', '?' ])) {
+ if ($icon && !str_contains((string)$icon, ':') && !in_array($icon[0], [ '/', '#', '?' ])) {
$icon = $svgUri . $icon;
}
} else {
@@ -1037,7 +995,7 @@ private function parseMainMenuItem(array $menuItem, $menuIdent = null, $currentI
$menuItem['label'] = $this->translator()->translation($menuItem['label']);
}
- $menuItem['show_label'] = (isset($menuItem['show_label']) ? !!$menuItem['show_label'] : true);
+ $menuItem['show_label'] = (isset($menuItem['show_label']) ? (bool)$menuItem['show_label'] : true);
$menuItem['selected'] = ($menuItem['ident'] === $currentIdent);
@@ -1048,9 +1006,7 @@ private function parseMainMenuItem(array $menuItem, $menuIdent = null, $currentI
$secondaryMenuWidget = current(
array_filter(
$this->secondaryMenu(),
- function ($item) use ($menuIdent) {
- return $item->ident() === $menuIdent;
- }
+ fn($item): bool => $item->ident() === $menuIdent
)
);
@@ -1070,7 +1026,7 @@ function ($item) use ($menuIdent) {
* @param string|null $currentIdent The current menu identifier.
* @return array Finalized menu structure.
*/
- private function parseSystemMenuItem(array $menuItem, $menuIdent = null, $currentIdent = null)
+ private function parseSystemMenuItem(array $menuItem, $menuIdent = null, $currentIdent = null): array
{
if (!isset($menuItem['ident'])) {
$menuItem['ident'] = $menuIdent;
@@ -1078,7 +1034,7 @@ private function parseSystemMenuItem(array $menuItem, $menuIdent = null, $curren
if (!empty($menuItem['url'])) {
$url = $menuItem['url'];
- if ($url && strpos($url, ':') === false && !in_array($url[0], [ '/', '#', '?' ])) {
+ if ($url && !str_contains((string)$url, ':') && !in_array($url[0], [ '/', '#', '?' ])) {
$url = $this->adminUrl() . $url;
}
} else {
@@ -1125,10 +1081,8 @@ public function htmlAttr()
/**
* Generate an array containing a list of CSS classes to be used by the tag.
- *
- * @return array
*/
- public function htmlClasses()
+ public function htmlClasses(): array
{
$classes = [
'has-no-js'
@@ -1143,20 +1097,16 @@ public function htmlClasses()
/**
* Determine if main & secondary menu should appear as mobile in a desktop resolution.
- *
- * @return boolean
*/
- public function isFullscreenTemplate()
+ public function isFullscreenTemplate(): bool
{
return false;
}
/**
* Retrieve the default data to the global Admin JavaScript application.
- *
- * @return array
*/
- final protected function getDefaultAdminDataForJs()
+ final protected function getDefaultAdminDataForJs(): array
{
return [
'debug' => $this->debug(),
@@ -1169,10 +1119,8 @@ final protected function getDefaultAdminDataForJs()
/**
* Retrieve all data options for the global Admin JavaScript application.
- *
- * @return array
*/
- final protected function getAdminDataForJs()
+ final protected function getAdminDataForJs(): array
{
if ($this->adminDataForJs === null) {
$this->adminDataForJs = $this->getDefaultAdminDataForJs();
@@ -1185,9 +1133,8 @@ final protected function getAdminDataForJs()
* Add extra data to the global Admin JavaScript application.
*
* @param array $data Additional options.
- * @return self
*/
- final public function addAdminDataForJs(array $data)
+ final public function addAdminDataForJs(array $data): static
{
$this->adminDataForJs = array_merge($this->getAdminDataForJs(), $data);
@@ -1196,14 +1143,10 @@ final public function addAdminDataForJs(array $data)
/**
* Retrieve the resolved data options for the global Admin JavaScript application.
- *
- * @return array
*/
- final public function adminDataForJs()
+ final public function adminDataForJs(): array
{
- return array_map(function ($datum) {
- return is_callable($datum) ? $datum($this) : $datum;
- }, $this->getAdminDataForJs());
+ return array_map(fn($datum) => is_callable($datum) ? $datum($this) : $datum, $this->getAdminDataForJs());
}
/**
@@ -1216,7 +1159,7 @@ final public function adminDataForJsAsJson()
$options = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($this->debug()) {
- $options = ($options | JSON_PRETTY_PRINT);
+ $options |= JSON_PRETTY_PRINT;
}
return json_encode($this->adminDataForJs(), $options);
@@ -1227,7 +1170,7 @@ final public function adminDataForJsAsJson()
*
* @return string Returns a stringified JSON object, protected from Mustache rendering.
*/
- final public function escapedAdminDataForJsAsJson()
+ final public function escapedAdminDataForJsAsJson(): string
{
return '{{=<% %>=}}' . $this->adminDataForJsAsJson() . '<%={{ }}=%>';
}
diff --git a/packages/admin/src/Charcoal/Admin/AdminWidget.php b/packages/admin/src/Charcoal/Admin/AdminWidget.php
index 02d15bef2..d63806cef 100644
--- a/packages/admin/src/Charcoal/Admin/AdminWidget.php
+++ b/packages/admin/src/Charcoal/Admin/AdminWidget.php
@@ -50,20 +50,11 @@ class AdminWidget extends AbstractWidget implements
*/
public $widgetId;
- /**
- * @var string $type
- */
- private $type;
+ private ?string $type = null;
- /**
- * @var string $template
- */
- private $template;
+ private ?string $template = null;
- /**
- * @var string $ident
- */
- private $ident = '';
+ private ?string $ident = '';
/**
* @var Translation|string|null $label
@@ -75,15 +66,9 @@ class AdminWidget extends AbstractWidget implements
*/
private $lang;
- /**
- * @var boolean $showLabel
- */
- private $showLabel;
+ private ?bool $showLabel = null;
- /**
- * @var boolean $showActions
- */
- private $showActions;
+ private ?bool $showActions = null;
/**
* The widget's conditional logic.
@@ -101,22 +86,15 @@ class AdminWidget extends AbstractWidget implements
/**
* Extra data sources to merge when setting data on an entity.
- *
- * @var array
*/
- private $dataSources;
+ private ?array $dataSources = null;
/**
* Associative array of source identifiers and options to apply when merging.
- *
- * @var array
*/
- private $dataSourceFilters = [];
+ private array $dataSourceFilters = [];
- /**
- * @var FactoryInterface $modelFactory
- */
- private $modelFactory;
+ private ?\Charcoal\Factory\FactoryInterface $modelFactory = null;
/**
* Enable / Disable the widget.
@@ -126,13 +104,10 @@ class AdminWidget extends AbstractWidget implements
* @param mixed $active The active flag or condition.
* @return self
*/
+ #[\Override]
public function setActive($active)
{
- if (is_callable($active) || is_string($active)) {
- $condition = $active;
- } else {
- $condition = null;
- }
+ $condition = is_callable($active) || is_string($active) ? $active : null;
$this->activeCondition = $condition;
@@ -142,6 +117,7 @@ public function setActive($active)
/**
* @return boolean
*/
+ #[\Override]
public function active()
{
if ($this->activeCondition !== null) {
@@ -154,9 +130,8 @@ public function active()
/**
* @param string $template The UI item's template (identifier).
* @throws InvalidArgumentException If the template identifier is not a string.
- * @return self
*/
- public function setTemplate($template)
+ public function setTemplate($template): static
{
if ($template === null) {
$this->template = null;
@@ -177,7 +152,7 @@ public function setTemplate($template)
/**
* @return string
*/
- public function template()
+ public function template(): ?string
{
if ($this->template === null) {
return $this->type();
@@ -188,9 +163,8 @@ public function template()
/**
* @param string $widgetId The widget identifier.
- * @return self
*/
- public function setWidgetId($widgetId)
+ public function setWidgetId($widgetId): static
{
$this->widgetId = $widgetId;
@@ -212,9 +186,8 @@ public function widgetId()
/**
* @param string $type The widget type.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setType($type)
+ public function setType($type): static
{
if ($type === null) {
$this->type = null;
@@ -235,7 +208,7 @@ public function setType($type)
/**
* @return string
*/
- public function type()
+ public function type(): ?string
{
return $this->type;
}
@@ -245,7 +218,7 @@ public function type()
* @throws InvalidArgumentException If the ident is not a string.
* @return AdminWidget (Chainable)
*/
- public function setIdent($ident)
+ public function setIdent($ident): static
{
if ($ident === null) {
$this->ident = null;
@@ -266,7 +239,7 @@ public function setIdent($ident)
/**
* @return string
*/
- public function ident()
+ public function ident(): ?string
{
return $this->ident;
}
@@ -277,9 +250,8 @@ public function ident()
* @param mixed $sources One or more data source identifiers to merge data from.
* Pass NULL to reset the entity back to default sources.
* Pass FALSE, an empty string or array to disable extra sources.
- * @return self
*/
- public function setDataSources($sources)
+ public function setDataSources($sources): static
{
if ($sources === null) {
$this->dataSources = null;
@@ -327,19 +299,13 @@ public function dataSourceFilter($sourceIdent)
$filters = array_merge($this->defaultDataSourceFilters(), $this->dataSourceFilters);
- if (isset($filters[$sourceIdent])) {
- return $filters[$sourceIdent];
- }
-
- return null;
+ return ($filters[$sourceIdent] ?? null);
}
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ public function widgetDataForJs(): array
{
return [];
}
@@ -354,7 +320,7 @@ final public function widgetDataForJsAsJson()
$options = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($this->debug()) {
- $options = ($options | JSON_PRETTY_PRINT);
+ $options |= JSON_PRETTY_PRINT;
}
return json_encode($this->widgetDataForJs(), $options);
@@ -365,16 +331,15 @@ final public function widgetDataForJsAsJson()
*
* @return string Returns a stringified JSON object, protected from Mustache rendering.
*/
- final public function escapedWidgetDataForJsAsJson()
+ final public function escapedWidgetDataForJsAsJson(): string
{
return '{{=<% %>=}}' . $this->widgetDataForJsAsJson() . '<%={{ }}=%>';
}
/**
* @param mixed $label The label.
- * @return self
*/
- public function setLabel($label)
+ public function setLabel($label): static
{
$this->label = $this->translator()->translation($label);
@@ -389,21 +354,17 @@ public function label()
return $this->label;
}
- /**
- * @return array
- */
- public function actions()
+ public function actions(): array
{
return [];
}
/**
* @param boolean $show The show actions flag.
- * @return self
*/
- public function setShowActions($show)
+ public function setShowActions($show): static
{
- $this->showActions = !!$show;
+ $this->showActions = (bool)$show;
return $this;
}
@@ -421,11 +382,10 @@ public function showActions()
/**
* @param boolean $show The show label flag.
- * @return self
*/
- public function setShowLabel($show)
+ public function setShowLabel($show): static
{
- $this->showLabel = !!$show;
+ $this->showLabel = (bool)$show;
return $this;
}
@@ -435,7 +395,7 @@ public function setShowLabel($show)
public function showLabel()
{
if ($this->showLabel !== false) {
- return !!strval($this->label());
+ return (bool)strval($this->label());
} else {
return false;
}
@@ -447,6 +407,7 @@ public function showLabel()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -483,7 +444,7 @@ protected function setModelFactory(FactoryInterface $factory)
/**
* @return FactoryInterface The model factory.
*/
- protected function modelFactory()
+ protected function modelFactory(): ?\Charcoal\Factory\FactoryInterface
{
return $this->modelFactory;
}
@@ -492,19 +453,18 @@ protected function modelFactory()
* Parse the widget's conditional logic.
*
* @param callable|string $condition The callable or renderable condition.
- * @return boolean
*/
- protected function resolveConditionalLogic($condition)
+ protected function resolveConditionalLogic($condition): bool
{
if (is_callable([ $this, $condition ])) {
- return !!$this->{$condition}();
+ return (bool)$this->{$condition}();
} elseif (is_callable($condition)) {
- return !!$condition();
- } elseif ($this->view()) {
- return !!$this->renderTemplate($condition);
+ return (bool)$condition();
+ } elseif ($this->view() instanceof \Charcoal\View\ViewInterface) {
+ return (bool)$this->renderTemplate($condition);
}
- return !!$condition;
+ return (bool)$condition;
}
/**
@@ -513,9 +473,8 @@ protected function resolveConditionalLogic($condition)
* @param mixed $sourceIdent The data source identifier.
* @param mixed $sourceFilter Optional filter to apply to the source's data.
* @throws InvalidArgumentException If the data source is invalid.
- * @return self
*/
- protected function addDataSources($sourceIdent, $sourceFilter = null)
+ protected function addDataSources($sourceIdent, $sourceFilter = null): static
{
$validSources = $this->acceptedDataSources();
@@ -552,7 +511,7 @@ protected function addDataSources($sourceIdent, $sourceFilter = null)
*
* @return string[]
*/
- protected function acceptedDataSources()
+ protected function acceptedDataSources(): array
{
return [ static::DATA_SOURCE_REQUEST, static::DATA_SOURCE_OBJECT, static::DATA_SOURCE_METADATA ];
}
@@ -562,17 +521,15 @@ protected function acceptedDataSources()
*
* @return string[]
*/
- protected function defaultDataSources()
+ protected function defaultDataSources(): array
{
return [];
}
/**
* Retrieve the default data source filters (when setting data on an entity).
- *
- * @return array
*/
- protected function defaultDataSourceFilters()
+ protected function defaultDataSourceFilters(): array
{
return [];
}
@@ -625,9 +582,8 @@ protected function resolveDataSourceFilter($toResolve)
* Retrieve the available data sources (when setting data on an entity).
*
* @param array|mixed $dataset The entity data.
- * @return self
*/
- protected function mergeDataSources($dataset = null)
+ protected function mergeDataSources($dataset = null): static
{
$sources = $this->dataSources();
foreach ($sources as $sourceIdent) {
diff --git a/packages/admin/src/Charcoal/Admin/AssetsConfig.php b/packages/admin/src/Charcoal/Admin/AssetsConfig.php
index 77e66aa65..dccf6e9c2 100644
--- a/packages/admin/src/Charcoal/Admin/AssetsConfig.php
+++ b/packages/admin/src/Charcoal/Admin/AssetsConfig.php
@@ -1,5 +1,7 @@
collections = $collections;
diff --git a/packages/admin/src/Charcoal/Admin/Config.php b/packages/admin/src/Charcoal/Admin/Config.php
index 0f750216a..d417a566d 100644
--- a/packages/admin/src/Charcoal/Admin/Config.php
+++ b/packages/admin/src/Charcoal/Admin/Config.php
@@ -18,20 +18,15 @@ class Config extends AbstractConfig
/**
* The base path for the admin module's route group.
- *
- * @var string $basePath
*/
- private $basePath = self::DEFAULT_BASE_PATH;
+ private string $basePath = self::DEFAULT_BASE_PATH;
/**
* @var array
*/
public $routes = [];
- /**
- * @var array
- */
- private $handlers = [];
+ private array $handlers = [];
/**
* @var array
@@ -50,6 +45,7 @@ class Config extends AbstractConfig
*
* @return array
*/
+ #[\Override]
public function defaults()
{
$baseDir = rtrim(realpath(__DIR__ . '/../../../'), '/');
@@ -63,9 +59,8 @@ public function defaults()
*
* @param string $path The admin module base path.
* @throws InvalidArgumentException If the route group is invalid.
- * @return self
*/
- public function setBasePath($path)
+ public function setBasePath($path): static
{
if (!is_string($path)) {
throw new InvalidArgumentException(
@@ -74,7 +69,7 @@ public function setBasePath($path)
}
// Can not be empty
- if ($path == '') {
+ if ($path === '') {
throw new InvalidArgumentException(
'Path can not be empty'
);
@@ -86,10 +81,8 @@ public function setBasePath($path)
/**
* Retrieve the admin module's route group.
- *
- * @return string
*/
- public function basePath()
+ public function basePath(): string
{
return $this->basePath;
}
@@ -99,9 +92,8 @@ public function basePath()
*
* @see \Charcoal\App\AppConfig::setRoutes() For a similar implementation.
* @param array $routes The route configuration structure to set.
- * @return self
*/
- public function setRoutes(array $routes)
+ public function setRoutes(array $routes): static
{
$toIterate = RouteConfig::defaultRouteTypes();
foreach ($routes as $key => $val) {
@@ -126,9 +118,8 @@ public function setRoutes(array $routes)
* - "phpErrorHandler"
*
* @param array $handlers The handlers configuration structure to set.
- * @return self
*/
- public function setHandlers(array $handlers)
+ public function setHandlers(array $handlers): static
{
$this->handlers = array_fill_keys(HandlerConfig::defaultHandlerTypes(), []);
$this->handlers['defaults'] = [];
@@ -143,10 +134,7 @@ public function setHandlers(array $handlers)
return $this;
}
- /**
- * @return array
- */
- public function handlers()
+ public function handlers(): array
{
return $this->handlers;
}
@@ -156,9 +144,8 @@ public function handlers()
*
* @param array $view The global configset for the application's view service.
* @throws InvalidArgumentException If the argument is not a configset.
- * @return self
*/
- public function setView(array $view)
+ public function setView(array $view): static
{
$this->view = $view;
return $this;
diff --git a/packages/admin/src/Charcoal/Admin/Decorator/GridStackWidgetDecorator.php b/packages/admin/src/Charcoal/Admin/Decorator/GridStackWidgetDecorator.php
index c4b3860d1..f60fa0484 100644
--- a/packages/admin/src/Charcoal/Admin/Decorator/GridStackWidgetDecorator.php
+++ b/packages/admin/src/Charcoal/Admin/Decorator/GridStackWidgetDecorator.php
@@ -21,18 +21,12 @@ class GridStackWidgetDecorator
*/
protected $gridStack = [];
- /**
- * @var WidgetInterface
- */
- protected $widget;
-
/**
* GridStackWidgetDecorator constructor.
* @param WidgetInterface $widget The widget to decorate.
*/
- public function __construct(WidgetInterface $widget)
+ public function __construct(protected \Charcoal\App\Template\WidgetInterface $widget)
{
- $this->widget = $widget;
}
/**
@@ -60,10 +54,8 @@ public function gridStack()
/**
* The default Grid Stack dataset.
- *
- * @return array
*/
- private function defaultGridStack()
+ private function defaultGridStack(): array
{
return [
'width' => self::GS_WIDTH,
diff --git a/packages/admin/src/Charcoal/Admin/Docs/Template/Object/DocTemplate.php b/packages/admin/src/Charcoal/Admin/Docs/Template/Object/DocTemplate.php
index a3f8bdee5..9d701d449 100644
--- a/packages/admin/src/Charcoal/Admin/Docs/Template/Object/DocTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Docs/Template/Object/DocTemplate.php
@@ -22,12 +22,15 @@ class DocTemplate extends AdminTemplate implements
use DashboardContainerTrait;
use ObjectContainerTrait;
+ public $headerMenu;
+
/**
* Retrieve the list of parameters to extract from the HTTP request.
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type'
@@ -59,9 +62,10 @@ public function headerMenu()
*
* @return \Charcoal\Translator\Translation
*/
+ #[\Override]
public function title()
{
- if (isset($this->title)) {
+ if ($this->title !== null) {
return $this->title;
}
@@ -81,10 +85,10 @@ public function title()
$metadata = $obj->metadata();
$objLabel = null;
- if (!$objLabel && isset($metadata['admin']['forms'])) {
+ if (isset($metadata['admin']['forms'])) {
$adminMetadata = $metadata['admin'];
- $formIdent = filter_input(INPUT_GET, 'form_ident', FILTER_SANITIZE_STRING);
+ $formIdent = htmlspecialchars(trim(($_GET['form_ident'] ?? '')), ENT_QUOTES, 'UTF-8');
if (!$formIdent) {
if (isset($adminMetadata['defaultForm'])) {
$fomIdent = $adminMetadata['defaultForm'];
@@ -113,11 +117,7 @@ public function title()
}
}
- if ($this->isObjRenderable($obj)) {
- $this->title = $obj->render((string)$objLabel, $obj);
- } else {
- $this->title = (string)$objLabel;
- }
+ $this->title = $this->isObjRenderable($obj) ? $obj->render((string)$objLabel, $obj) : (string)$objLabel;
return $this->title;
}
@@ -126,6 +126,7 @@ public function title()
* @param Container $container DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -147,13 +148,11 @@ protected function createDashboardConfig()
$dashboardIdent = $this->dashboardIdent();
if (empty($dashboardIdent)) {
- $dashboardIdent = filter_input(INPUT_GET, 'dashboard_ident', FILTER_SANITIZE_STRING);
+ $dashboardIdent = htmlspecialchars(trim(($_GET['dashboard_ident'] ?? '')), ENT_QUOTES, 'UTF-8');
}
- if (empty($dashboardIdent)) {
- if (isset($adminMetadata['default_doc_dashboard'])) {
- $dashboardIdent = $adminMetadata['default_doc_dashboard'];
- }
+ if (empty($dashboardIdent) && isset($adminMetadata['default_doc_dashboard'])) {
+ $dashboardIdent = $adminMetadata['default_doc_dashboard'];
}
$overrideType = false;
@@ -162,7 +161,7 @@ protected function createDashboardConfig()
if (!isset($adminMetadata['default_edit_dashboard'])) {
throw new Exception(sprintf(
'No default doc dashboard defined in admin metadata for %s',
- get_class($this->obj())
+ $this->obj()::class
));
}
$overrideType = true;
@@ -199,11 +198,11 @@ protected function objAdminMetadata()
$objMetadata = $obj->metadata();
- $adminMetadata = isset($objMetadata['admin']) ? $objMetadata['admin'] : null;
+ $adminMetadata = ($objMetadata['admin'] ?? null);
if ($adminMetadata === null) {
throw new Exception(sprintf(
'The object %s does not have an admin metadata.',
- get_class($obj)
+ $obj::class
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Docs/Widget/DocFormPropertyWidget.php b/packages/admin/src/Charcoal/Admin/Docs/Widget/DocFormPropertyWidget.php
index 18fc3ab6e..30f2efcd7 100644
--- a/packages/admin/src/Charcoal/Admin/Docs/Widget/DocFormPropertyWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Docs/Widget/DocFormPropertyWidget.php
@@ -19,12 +19,9 @@ class DocFormPropertyWidget extends FormPropertyWidget
*/
protected $displayOptions;
- /**
- * @return boolean
- */
- public function hasExtraData()
+ public function hasExtraData(): bool
{
- return !!count($this->extraData());
+ return (bool)count($this->extraData());
}
/**
@@ -34,7 +31,7 @@ public function collapsible()
{
$displayOps = $this->displayOptions();
- return isset($displayOps['collapsible']) ? $displayOps['collapsible'] : false;
+ return ($displayOps['collapsible'] ?? false);
}
/**
@@ -44,7 +41,7 @@ public function collapsed()
{
$displayOps = $this->displayOptions();
- return isset($displayOps['collapsed']) ? $displayOps['collapsed'] : false;
+ return ($displayOps['collapsed'] ?? false);
}
/**
@@ -54,7 +51,7 @@ public function parented()
{
$displayOps = $this->displayOptions();
- return isset($displayOps['parented']) ? $displayOps['parented'] : false;
+ return ($displayOps['parented'] ?? false);
}
/**
@@ -64,34 +61,25 @@ public function typeDescription()
{
$type = $this->prop()->type();
- switch ($type) {
- case 'boolean':
- return $this->translator()->translation('
+ return match ($type) {
+ 'boolean' => $this->translator()->translation('
The field is a TRUE | FALSE statement
- ');
- case 'image':
- case 'audio':
- case 'file':
- return $this->translator()->translation('
+ '),
+ 'image', 'audio', 'file' => $this->translator()->translation('
The field will ask to upload a file using the file manager
- ');
- case 'string':
- case 'text':
- return $this->translator()->translation('
+ '),
+ 'string', 'text' => $this->translator()->translation('
The field is a simple text input
- ');
- case 'object':
- return $this->translator()->translation('
+ '),
+ 'object' => $this->translator()->translation('
The field is a relation to another object in the back-end (ex: a category object)
- ');
- case 'date-time':
- return $this->translator()->translation('
+ '),
+ 'date-time' => $this->translator()->translation('
The field requires a date and will prompt a date picker
as an easy way to provide it in a supported format
- ');
- default:
- return '';
- }
+ '),
+ default => '',
+ };
}
/**
@@ -99,7 +87,7 @@ public function typeDescription()
*/
public function extraData()
{
- if (isset($this->extraData)) {
+ if ($this->extraData !== null) {
return $this->extraData;
}
@@ -147,9 +135,8 @@ public function displayOptions()
/**
* @param array|mixed $displayOptions The display options array.
* @throws \InvalidArgumentException If argument is not of type "array".
- * @return self
*/
- public function setDisplayOptions($displayOptions)
+ public function setDisplayOptions($displayOptions): static
{
if (!is_array($displayOptions)) {
throw new \InvalidArgumentException('display_options should be of type array');
diff --git a/packages/admin/src/Charcoal/Admin/Docs/Widget/FormGroup/DocFormGroup.php b/packages/admin/src/Charcoal/Admin/Docs/Widget/FormGroup/DocFormGroup.php
index a21352a26..151d94264 100644
--- a/packages/admin/src/Charcoal/Admin/Docs/Widget/FormGroup/DocFormGroup.php
+++ b/packages/admin/src/Charcoal/Admin/Docs/Widget/FormGroup/DocFormGroup.php
@@ -1,5 +1,7 @@
description() || $this->notes() || count($this->groupProperties())) {
- return false;
- }
-
- return true;
+ return !($this->description() || $this->notes() || count($this->groupProperties()));
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Mustache/AssetsHelpers.php b/packages/admin/src/Charcoal/Admin/Mustache/AssetsHelpers.php
index 21e8ef86a..ad33af132 100644
--- a/packages/admin/src/Charcoal/Admin/Mustache/AssetsHelpers.php
+++ b/packages/admin/src/Charcoal/Admin/Mustache/AssetsHelpers.php
@@ -7,7 +7,7 @@
use Assetic\Asset\AssetReference;
use Assetic\Asset\StringAsset;
use Assetic\AssetManager;
-use Mustache_LambdaHelper as LambdaHelper;
+use Mustache\LambdaHelper as LambdaHelper;
// From charcoal-view
use Charcoal\View\Mustache\HelpersInterface;
@@ -19,27 +19,18 @@ class AssetsHelpers implements HelpersInterface
/**
* @var AssetManager|mixed $assets The assetic assets manager.
*/
- private $assets;
+ private ?\Assetic\AssetManager $assets = null;
- /**
- * @var string $action
- */
- private $action;
+ private ?string $action = null;
- /**
- * @var string $collection
- */
- private $collection;
+ private ?string $collection = null;
- /**
- * @var string $ident
- */
- private $ident;
+ private ?string $ident = null;
/**
* @param array $data Class Dependencies.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
if (isset($data['assets']) && $data['assets'] instanceof AssetManager) {
$this->assets = $data['assets'];
@@ -48,8 +39,6 @@ public function __construct(array $data = null)
/**
* Get the collection of helpers as a plain array.
- *
- * @return array
*/
public function toArray(): array
{
@@ -80,17 +69,21 @@ protected function reset()
* @param LambdaHelper|null $helper For rendering strings in the current context.
* @return string
*/
- public function __invoke($text = null, LambdaHelper $helper = null)
+ public function __invoke($text = null, ?LambdaHelper $helper = null)
{
- if ($helper) {
+ if ($helper instanceof LambdaHelper) {
$text = $helper->render($text);
}
+ if ($this->action === null) {
+ return $text;
+ }
+
$return = $this->{$this->action}($this->collection, $text);
$text = $return;
$this->reset();
- if ($helper) {
+ if ($helper instanceof LambdaHelper) {
return $helper->render($text);
}
@@ -105,7 +98,7 @@ public function __invoke($text = null, LambdaHelper $helper = null)
* @param string $macro A domain, locale, or number.
* @return boolean
*/
- public function __isset($macro)
+ public function __isset(string $macro)
{
return boolval($macro);
}
@@ -116,9 +109,8 @@ public function __isset($macro)
* Required by Mustache.
*
* @param string $macro A domain, locale, or number.
- * @return mixed
*/
- public function __get($macro)
+ public function __get(string $macro): mixed
{
if (!$this->action) {
$macro = '__' . $macro;
@@ -154,7 +146,7 @@ public function __get($macro)
* @param string $text Asset string to inject.
* @return string
*/
- protected function __inject($collection, $text)
+ protected function __inject($collection, $text): null
{
if (!$this->assets->has($collection)) {
$this->assets->set($collection, new AssetCollection());
@@ -180,9 +172,8 @@ protected function __enqueue($collection)
/**
* @param string $collection The collection ident.
- * @return string
*/
- protected function __output($collection)
+ protected function __output($collection): string
{
$dump = $this->assets->get($collection)->dump();
return '{{=<<<<% %>>>>=}}' . $dump . '<<<<%={{ }}=%>>>>';
diff --git a/packages/admin/src/Charcoal/Admin/Object/Notification.php b/packages/admin/src/Charcoal/Admin/Object/Notification.php
index aa1da3ffb..a35ad7d44 100644
--- a/packages/admin/src/Charcoal/Admin/Object/Notification.php
+++ b/packages/admin/src/Charcoal/Admin/Object/Notification.php
@@ -1,5 +1,7 @@
users = [];
@@ -58,14 +56,11 @@ public function setUsers($users)
'Users must be an array or a comma-separated string.'
);
}
- $this->users = array_map('trim', $users);
+ $this->users = array_map(trim(...), $users);
return $this;
}
- /**
- * @return array
- */
- public function users()
+ public function users(): array
{
return $this->users;
}
@@ -75,7 +70,7 @@ public function users()
* @throws InvalidArgumentException If the types are not an array or a comma-separated string.
* @return Notification Chainable
*/
- public function setTargetTypes($targetTypes)
+ public function setTargetTypes($targetTypes): static
{
if ($targetTypes === null) {
$this->targetTypes = null;
@@ -89,14 +84,11 @@ public function setTargetTypes($targetTypes)
'Object types must be an array or a comma-separated string.'
);
}
- $this->targetTypes = array_map('trim', $targetTypes);
+ $this->targetTypes = array_map(trim(...), $targetTypes);
return $this;
}
- /**
- * @return array|null
- */
- public function targetTypes()
+ public function targetTypes(): ?array
{
return $this->targetTypes;
}
@@ -106,7 +98,7 @@ public function targetTypes()
* @throws InvalidArgumentException If the emails are not an array or a comma-separated string.
* @return Notification Chainable
*/
- public function setExtraEmails($extraEmails)
+ public function setExtraEmails($extraEmails): static
{
if ($extraEmails === null) {
$this->extraEmails = [];
@@ -120,14 +112,11 @@ public function setExtraEmails($extraEmails)
'Extra emails must be an array or a comma-separated string.'
);
}
- $this->extraEmails = array_map('trim', $extraEmails);
+ $this->extraEmails = array_map(trim(...), $extraEmails);
return $this;
}
- /**
- * @return array|null
- */
- public function extraEmails()
+ public function extraEmails(): array
{
return $this->extraEmails;
}
@@ -137,7 +126,7 @@ public function extraEmails()
* @throws InvalidArgumentException If the frequency is not a valid mode.
* @return Notification Chainable
*/
- public function setFrequency($frequency)
+ public function setFrequency($frequency): static
{
if ($frequency === null) {
$this->frequency = null;
@@ -162,7 +151,7 @@ public function setFrequency($frequency)
/**
* @return boolean
*/
- public function frequency()
+ public function frequency(): ?string
{
return $this->frequency;
}
@@ -171,16 +160,13 @@ public function frequency()
* @param boolean $active The active flag.
* @return Notification Chainable
*/
- public function setActive($active)
+ public function setActive($active): static
{
- $this->active = !!$active;
+ $this->active = (bool)$active;
return $this;
}
- /**
- * @return boolean
- */
- public function active()
+ public function active(): bool
{
return $this->active;
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/AbstractProperty.php b/packages/admin/src/Charcoal/Admin/Property/AbstractProperty.php
index 2b03c9f7d..c685e86de 100644
--- a/packages/admin/src/Charcoal/Admin/Property/AbstractProperty.php
+++ b/packages/admin/src/Charcoal/Admin/Property/AbstractProperty.php
@@ -32,6 +32,7 @@
/**
* Base Admin model property decorator
*/
+#[\AllowDynamicProperties]
abstract class AbstractProperty implements
AdminPropertyInterface,
DescribableInterface,
@@ -51,6 +52,8 @@ abstract class AbstractProperty implements
*/
private $property;
+ protected $inputName;
+
/**
* @var array $propertyData
*/
@@ -371,9 +374,7 @@ public function parseEscapeOptions($escape)
*/
protected function wrapEscapeFunction(callable $callback)
{
- return function ($value) use ($callback) {
- return call_user_func_array($callback, func_get_args());
- };
+ return fn($value): mixed => call_user_func_array($callback, func_get_args());
}
/**
@@ -385,19 +386,17 @@ protected function wrapEscapeFunction(callable $callback)
*/
protected function assertValidEscapeFunction($escape)
{
- if (is_string($escape)) {
- if (!function_exists($escape)) {
- throw new InvalidArgumentException(sprintf(
- 'Undefined escape function named "%s"',
- $escape
- ));
- }
+ if (is_string($escape) && !function_exists($escape)) {
+ throw new InvalidArgumentException(sprintf(
+ 'Undefined escape function named "%s"',
+ $escape
+ ));
}
if (!is_callable($escape)) {
throw new InvalidArgumentException(sprintf(
'Expected escape function name or function expression, received "%s"',
- is_object($escape) ? get_class($escape) : gettype($escape)
+ get_debug_type($escape)
));
}
}
@@ -420,7 +419,7 @@ public function getDefaultEscapeOptions()
*/
public function setMultiple($multiple)
{
- $this->multiple = !!$multiple;
+ $this->multiple = (bool)$multiple;
return $this;
}
@@ -449,13 +448,11 @@ public function renderTranslatableTemplate($templateString)
continue;
}
$translation = $templateString[$lang];
- $isBlank = empty($translation) && !is_numeric($translation);
+ $isBlank = ($translation === '' || $translation === '0') && !is_numeric($translation);
if (!$isBlank) {
$this->translator()->setLocale($lang);
$translation = $this->renderTemplate($translation);
- if ($translation !== null) {
- $templateString[$lang] = $translation;
- }
+ $templateString[$lang] = $translation;
}
}
$this->translator()->setLocale($origLang);
@@ -463,7 +460,7 @@ public function renderTranslatableTemplate($templateString)
return $templateString;
} elseif (is_string($templateString)) {
- $isBlank = empty($templateString) && !is_numeric($templateString);
+ $isBlank = ($templateString === '' || $templateString === '0') && !is_numeric($templateString);
if (!$isBlank) {
return $this->renderTemplate($templateString);
}
@@ -495,7 +492,7 @@ protected function isObjRenderable($obj, $toString = false)
return false;
}
- $key = get_class($obj);
+ $key = $obj::class;
if (isset(static::$objRenderableCache[$key])) {
return static::$objRenderableCache[$key];
@@ -542,7 +539,7 @@ protected function setDependencies(Container $container)
* @param array $data Optional metadata to merge on the object.
* @return PropertyMetadata
*/
- protected function createMetadata(array $data = null)
+ protected function createMetadata(?array $data = null)
{
$class = $this->metadataClass();
return new $class($data);
@@ -576,7 +573,7 @@ protected function getter($key)
* @param string $key The key to get the setter from.
* @return string The setter method name, for a given key.
*/
- protected function setter($key)
+ protected function setter(string $key)
{
$setter = 'set_' . $key;
return $this->camelize($setter);
@@ -588,8 +585,8 @@ protected function setter($key)
* @param string $str The snake_case string to camelize.
* @return string The camelCase string.
*/
- private function camelize($str)
+ private function camelize($str): string
{
- return lcfirst(implode('', array_map('ucfirst', explode('_', $str))));
+ return lcfirst(implode('', array_map(ucfirst(...), explode('_', $str))));
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyDisplay.php b/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyDisplay.php
index 886255d5c..2b84786f3 100644
--- a/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyDisplay.php
@@ -56,6 +56,7 @@ abstract class AbstractPropertyDisplay extends AbstractProperty implements
* @param PropertyInterface $property The property.
* @return self
*/
+ #[\Override]
public function setProperty(PropertyInterface $property)
{
parent::setProperty($property);
@@ -165,11 +166,7 @@ public function setDisplayName($displayName)
*/
public function displayName()
{
- if ($this->displayName) {
- $name = $this->displayName;
- } else {
- $name = $this->propertyIdent();
- }
+ $name = $this->displayName ?: $this->propertyIdent();
if ($this->p()['l10n']) {
$name .= '[' . $this->lang() . ']';
@@ -206,11 +203,7 @@ public function getDisplayOption($key, $default = null)
{
$options = $this->getDisplayOptions();
- if (isset($options[$key])) {
- return $options[$key];
- }
-
- return $default;
+ return ($options[$key] ?? $default);
}
/**
@@ -291,6 +284,7 @@ public function getDisplayEscapeOptions()
* @throws InvalidArgumentException If the value to escape is not a string.
* @return string
*/
+ #[\Override]
public function escapeVal($val, array $options = [])
{
if (!is_string($val)) {
@@ -342,7 +336,7 @@ public function displayVal()
if (!is_scalar($val)) {
throw new UnexpectedValueException(sprintf(
'Property Display Value must be a string, received %s',
- (is_object($val) ? get_class($val) : gettype($val))
+ (get_debug_type($val))
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyInput.php b/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyInput.php
index cc220d2d8..a44274f81 100644
--- a/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/AbstractPropertyInput.php
@@ -97,6 +97,7 @@ abstract class AbstractPropertyInput extends AbstractProperty implements
* @param PropertyInterface $property The property.
* @return self
*/
+ #[\Override]
public function setProperty(PropertyInterface $property)
{
parent::setProperty($property);
@@ -212,11 +213,7 @@ public function setInputName($inputName)
*/
public function inputName()
{
- if ($this->inputName) {
- $name = $this->inputName;
- } else {
- $name = $this->propertyIdent();
- }
+ $name = $this->inputName ?: $this->propertyIdent();
if ($this->p()['l10n']) {
$name .= '[' . $this->lang() . ']';
@@ -253,11 +250,7 @@ public function getInputOption($key, $default = null)
{
$options = $this->getInputOptions();
- if (isset($options[$key])) {
- return $options[$key];
- }
-
- return $default;
+ return ($options[$key] ?? $default);
}
/**
@@ -342,6 +335,7 @@ public function getInputEscapeOptions()
* @throws InvalidArgumentException If the value to escape is not a string.
* @return string
*/
+ #[\Override]
public function escapeVal($val, array $options = [])
{
if (!is_string($val)) {
@@ -379,8 +373,6 @@ public function escapeVal($val, array $options = [])
/**
* Overridable.
* Makes it easier to pass InputVal options from children input types.
- *
- * @return array
**/
public function getInputValOptions(): array
{
@@ -409,7 +401,7 @@ public function inputVal()
if (!is_scalar($val)) {
throw new UnexpectedValueException(sprintf(
'Property Input Value must be a string, received %s',
- (is_object($val) ? get_class($val) : gettype($val))
+ (get_debug_type($val))
));
}
@@ -510,7 +502,7 @@ public function hasInputPrefix()
public function inputPrefix()
{
if ($this->inputPrefix instanceof Translation) {
- if (isset($this->inputPrefix->isRendered) && $this->inputPrefix->isRendered === false) {
+ if (property_exists($this->inputPrefix, 'isRendered') && $this->inputPrefix->isRendered !== null && $this->inputPrefix->isRendered === false) {
$this->inputPrefix = $this->renderTranslatableTemplate($this->inputPrefix);
}
@@ -561,7 +553,7 @@ public function hasInputSuffix()
public function inputSuffix()
{
if ($this->inputSuffix instanceof Translation) {
- if (isset($this->inputSuffix->isRendered) && $this->inputSuffix->isRendered === false) {
+ if (property_exists($this->inputSuffix, 'isRendered') && $this->inputSuffix->isRendered !== null && $this->inputSuffix->isRendered === false) {
$this->inputSuffix = $this->renderTranslatableTemplate($this->inputSuffix);
}
@@ -578,13 +570,7 @@ public function inputSuffix()
*/
public function hidden()
{
- if ($this->p()['l10n']) {
- if ($this->lang() != $this->translator()->getLocale()) {
- return true;
- }
- }
-
- return false;
+ return $this->p()['l10n'] && $this->lang() != $this->translator()->getLocale();
}
/**
@@ -593,7 +579,7 @@ public function hidden()
*/
public function setReadOnly($readOnly)
{
- $this->readOnly = !!$readOnly;
+ $this->readOnly = (bool)$readOnly;
return $this;
}
@@ -611,7 +597,7 @@ public function readOnly()
*/
public function setRequired($required)
{
- $this->required = !!$required;
+ $this->required = (bool)$required;
return $this;
}
@@ -629,7 +615,7 @@ public function required()
*/
public function setDisabled($disabled)
{
- $this->disabled = !!$disabled;
+ $this->disabled = (bool)$disabled;
return $this;
}
@@ -689,7 +675,7 @@ public function placeholder()
}
if ($this->placeholder instanceof Translation) {
- if (isset($this->placeholder->isRendered) && $this->placeholder->isRendered === false) {
+ if (property_exists($this->placeholder, 'isRendered') && $this->placeholder->isRendered !== null && $this->placeholder->isRendered === false) {
$this->placeholder = $this->renderTranslatableTemplate($this->placeholder);
}
@@ -721,7 +707,7 @@ final public function controlDataForJsAsJson()
$options = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($this->debug()) {
- $options = ($options | JSON_PRETTY_PRINT);
+ $options |= JSON_PRETTY_PRINT;
}
return json_encode($this->controlDataForJs(), $options);
diff --git a/packages/admin/src/Charcoal/Admin/Property/AbstractSelectableInput.php b/packages/admin/src/Charcoal/Admin/Property/AbstractSelectableInput.php
index 97ed1631b..dfd202bd2 100644
--- a/packages/admin/src/Charcoal/Admin/Property/AbstractSelectableInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/AbstractSelectableInput.php
@@ -140,7 +140,7 @@ public function parsedVal()
// Doing this in the parseVal method of abstract property
// was causing multiple && l10n properties not to save.
if (!is_array($val) && $this->p()['multiple']) {
- $val = explode($this->p()->multipleSeparator(), $val);
+ $val = explode($this->p()->multipleSeparator(), (string)$val);
}
$this->parsedVal[$this->lang()] = $val;
@@ -196,7 +196,7 @@ public function setEmptyChoice($choice)
} else {
throw new InvalidArgumentException(sprintf(
'Empty choice must be an array, received %s',
- (is_object($choice) ? get_class($choice) : gettype($choice))
+ (get_debug_type($choice))
));
}
@@ -256,7 +256,7 @@ protected function renderChoiceObjMap($obj, $prop)
return '';
}
- if (strpos($prop, '{{') === false) {
+ if (!str_contains($prop, '{{')) {
if (isset($obj[$prop])) {
return $this->parseChoiceVal($obj[$prop]);
}
@@ -268,7 +268,7 @@ protected function renderChoiceObjMap($obj, $prop)
return $obj->renderTemplate($prop);
} else {
$callback = function ($matches) use ($obj) {
- $prop = trim($matches[1]);
+ $prop = trim((string)$matches[1]);
if (isset($obj[$prop])) {
return $this->parseChoiceVal($obj[$prop]);
}
@@ -341,7 +341,7 @@ public function choiceObjMap()
public function inputNameFallback()
{
$name = $this->inputName();
- if (substr($name, -2, 2) === '[]') {
+ if (str_ends_with($name, '[]')) {
return substr($name, 0, -2);
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/AbstractTickableInput.php b/packages/admin/src/Charcoal/Admin/Property/AbstractTickableInput.php
index 99c90a766..7a0bbca7c 100644
--- a/packages/admin/src/Charcoal/Admin/Property/AbstractTickableInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/AbstractTickableInput.php
@@ -18,10 +18,8 @@ abstract class AbstractTickableInput extends AbstractSelectableInput
/**
* How radio controls should be displayed.
- *
- * @var string|null
*/
- private $inputLayout;
+ private ?string $inputLayout = null;
/**
* Prepare a single tickable option for output.
@@ -30,6 +28,7 @@ abstract class AbstractTickableInput extends AbstractSelectableInput
* @param array|object $choice The choice structure.
* @return array|null
*/
+ #[\Override]
protected function parseChoice($ident, $choice)
{
$choice = parent::parseChoice($ident, $choice);
@@ -63,7 +62,7 @@ public function setInputLayout($layout)
if (!is_string($layout)) {
throw new InvalidArgumentException(sprintf(
'Layout must be a string, received %s',
- (is_object($layout) ? get_class($layout) : gettype($layout))
+ (get_debug_type($layout))
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Display/BooleanDisplay.php b/packages/admin/src/Charcoal/Admin/Property/Display/BooleanDisplay.php
index 50b93c8df..ce09a3910 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Display/BooleanDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Display/BooleanDisplay.php
@@ -1,5 +1,7 @@
'',
@@ -91,6 +92,7 @@ protected function defaultEmptyChoice()
*
* @return string
*/
+ #[\Override]
public function displayVal()
{
$prop = $this->p();
diff --git a/packages/admin/src/Charcoal/Admin/Property/Display/ColorSwatchDisplay.php b/packages/admin/src/Charcoal/Admin/Property/Display/ColorSwatchDisplay.php
index da3ae4cbf..2cd596706 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Display/ColorSwatchDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Display/ColorSwatchDisplay.php
@@ -1,5 +1,7 @@
p();
$pad = str_repeat($this->indentation(), ($this->currentLevel() - 1));
@@ -51,7 +45,7 @@ public function displayVal()
* @throws InvalidArgumentException If the indentation is not a string.
* @return AbstractConfig Chainable
*/
- public function setIndentation($indent)
+ public function setIndentation($indent): static
{
if (!is_string($indent)) {
throw new InvalidArgumentException(
@@ -66,10 +60,8 @@ public function setIndentation($indent)
/**
* Retrieve the indentation string.
- *
- * @return integer
*/
- public function indentation()
+ public function indentation(): string
{
return $this->indentation;
}
@@ -81,9 +73,8 @@ public function indentation()
*
* @param integer $level The level of depth.
* @throws InvalidArgumentException If the level is not an integer.
- * @return self
*/
- public function setCurrentLevel($level)
+ public function setCurrentLevel($level): static
{
if (!is_int($level)) {
throw new InvalidArgumentException(
@@ -98,10 +89,8 @@ public function setCurrentLevel($level)
/**
* Retrieve the current level for output of the associated object.
- *
- * @return integer
*/
- public function currentLevel()
+ public function currentLevel(): int
{
return $this->currentLevel;
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Display/ImageDisplay.php b/packages/admin/src/Charcoal/Admin/Property/Display/ImageDisplay.php
index 0af14cadf..7317077f7 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Display/ImageDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Display/ImageDisplay.php
@@ -28,6 +28,7 @@ class ImageDisplay extends AbstractPropertyDisplay
* @see \Charcoal\Admin\Property\Display\LinkDisplay::hrefVal()
* @return string
*/
+ #[\Override]
public function displayVal()
{
$val = parent::displayVal();
@@ -38,8 +39,8 @@ public function displayVal()
$parts = parse_url($val);
if (empty($parts['scheme']) && !in_array($val[0], [ '/', '#', '?' ])) {
$path = isset($parts['path']) ? ltrim($parts['path'], '/') : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
$val = $this->baseUrl->withPath($path)->withQuery($query)->withFragment($hash);
}
@@ -52,6 +53,7 @@ public function displayVal()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Property/Display/LinkDisplay.php b/packages/admin/src/Charcoal/Admin/Property/Display/LinkDisplay.php
index 38d1a07a4..7898dc034 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Display/LinkDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Display/LinkDisplay.php
@@ -29,6 +29,7 @@ class LinkDisplay extends AbstractPropertyDisplay
/**
* @return string
*/
+ #[\Override]
public function displayVal()
{
$prop = $this->property();
@@ -86,9 +87,8 @@ public function displayValList()
*
* @param string $url The link URL.
* @param string $text The link text.
- * @return string
*/
- protected function formatHtmlLink($url, $text = null)
+ protected function formatHtmlLink($url, $text = null): string
{
if ($text === null) {
$text = $url;
@@ -99,13 +99,11 @@ protected function formatHtmlLink($url, $text = null)
$text = $format($text);
}
- $link = sprintf(
+ return sprintf(
'%s',
$this->getLocalUrl($url),
$text
);
-
- return $link;
}
/**
@@ -117,14 +115,12 @@ protected function formatHtmlLink($url, $text = null)
protected function getLocalUrl($path)
{
$prop = $this->property();
- if ($prop instanceof FileProperty) {
- if ($prop['publicAccess'] === false) {
- $query = http_build_query([
- 'disk' => $prop['filesystem'],
- 'path' => $path,
- ]);
- return $this->adminUrl('filesystem/download')->withQuery($query);
- }
+ if ($prop instanceof FileProperty && $prop['publicAccess'] === false) {
+ $query = http_build_query([
+ 'disk' => $prop['filesystem'],
+ 'path' => $path,
+ ]);
+ return $this->adminUrl('filesystem/download')->withQuery($query);
}
return $this->baseUrl($path);
@@ -133,9 +129,8 @@ protected function getLocalUrl($path)
/**
* @param callable|string|null $format The link textt format.
* @throws InvalidArgumentException If the format is not a valid callable.
- * @return self
*/
- public function setLinkTextFormat($format)
+ public function setLinkTextFormat($format): static
{
if ($format !== null && !function_exists($format)) {
throw new InvalidArgumentException(
@@ -161,6 +156,7 @@ public function getLinkTextFormat()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Property/Display/MessageDisplay.php b/packages/admin/src/Charcoal/Admin/Property/Display/MessageDisplay.php
index 2954d1480..3999a0c62 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Display/MessageDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Display/MessageDisplay.php
@@ -44,9 +44,8 @@ class MessageDisplay extends AbstractPropertyDisplay implements
/**
* @param mixed $message The message to display.
- * @return self
*/
- public function setMessage($message)
+ public function setMessage($message): static
{
$this->message = $this->translator()->translation($message);
if ($this->message instanceof Translation) {
@@ -56,12 +55,9 @@ public function setMessage($message)
return $this;
}
- /**
- * @return bool
- */
- public function hasMessage()
+ public function hasMessage(): bool
{
- return !!$this->message;
+ return (bool)$this->message;
}
/**
@@ -78,7 +74,7 @@ public function getMessage()
public function displayMessage()
{
if ($this->message instanceof Translation) {
- if (isset($this->message->isRendered) && $this->message->isRendered === false) {
+ if (property_exists($this->message, 'isRendered') && $this->message->isRendered !== null && $this->message->isRendered === false) {
$this->message = $this->renderTranslatableTemplate($this->message);
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Display/ObjectDisplay.php b/packages/admin/src/Charcoal/Admin/Property/Display/ObjectDisplay.php
index f8609270e..91aa8e0d6 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Display/ObjectDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Display/ObjectDisplay.php
@@ -1,5 +1,7 @@
propertyVal() ? static::STATE_SUCCESS : static::STATE_DEFAULT;
+ return $this->propertyVal() ? static::STATE_SUCCESS : static::STATE_DEFAULT;
}
/**
@@ -88,7 +89,7 @@ private function fallbackStatus()
* @throws UnexpectedValueException When an unsupported operator is used.
* @return boolean
*/
- private function testConditionWithOperator($condition)
+ private function testConditionWithOperator($condition): ?bool
{
$value = $condition;
$operator = null;
@@ -101,7 +102,7 @@ private function testConditionWithOperator($condition)
throw new UnexpectedValueException(sprintf(
'The operator [%s] is not supported in [%s]',
$operator,
- get_class($this)
+ static::class
));
}
@@ -139,13 +140,12 @@ private function calculateState()
if (is_array($state)) {
foreach ($state as $stateIdent => $conditions) {
- $result = is_string($conditions) ?
- $result = $this->testConditionWithOperator($conditions) : false;
+ $result = is_string($conditions) && $result = $this->testConditionWithOperator($conditions);
$result = !$result && is_array($conditions) ?
- !!count(array_filter($conditions, [$this, 'testConditionWithOperator'])) : $result;
+ (bool)count(array_filter($conditions, $this->testConditionWithOperator(...))) : $result;
- if (!!$result && in_array($stateIdent, static::SUPPORTED_STATES)) {
+ if ($result && in_array($stateIdent, static::SUPPORTED_STATES)) {
return $stateIdent;
}
};
@@ -177,9 +177,8 @@ public function state()
/**
* @param array|callable $state State for StatusDisplay.
- * @return self
*/
- public function setState($state)
+ public function setState($state): static
{
$this->state = $state;
diff --git a/packages/admin/src/Charcoal/Admin/Property/Display/TextDisplay.php b/packages/admin/src/Charcoal/Admin/Property/Display/TextDisplay.php
index 874ef842e..8cb2ae448 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Display/TextDisplay.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Display/TextDisplay.php
@@ -1,5 +1,7 @@
objId = $objId;
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/AudioInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/AudioInput.php
index df44ac2e0..06f9ef30c 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/AudioInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/AudioInput.php
@@ -12,18 +12,15 @@ class AudioInput extends FileInput
{
/**
* Retrieve list of default file type specifiers.
- *
- * @return string
*/
- public function getDefaultAccept()
+ #[\Override]
+ public function getDefaultAccept(): string
{
return 'audio/*';
}
- /**
- * @return string|null
- */
- public function filePreview()
+ #[\Override]
+ public function filePreview(): string
{
$value = $this->inputVal();
if ($value) {
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/AudioWidgetInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/AudioWidgetInput.php
index 7974d7e69..ac8dc5a03 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/AudioWidgetInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/AudioWidgetInput.php
@@ -2,10 +2,11 @@
namespace Charcoal\Admin\Property\Input;
+use Aws\signer\signerClient;
use InvalidArgumentException;
use UnexpectedValueException;
// From Mustache
-use Mustache_LambdaHelper as LambdaHelper;
+use Mustache\LambdaHelper as LambdaHelper;
// From 'charcoal-view'
use Charcoal\View\ViewableInterface;
// From 'charcoal-property'
@@ -24,24 +25,18 @@ class AudioWidgetInput extends AudioInput
/**
* Whether text-to-speech is enabled.
- *
- * @var boolean
*/
- private $textEnabled = true;
+ private bool $textEnabled = true;
/**
* Whether audio recording is enabled.
- *
- * @var boolean
*/
- private $captureEnabled = true;
+ private bool $captureEnabled = true;
/**
* Whether file upload is enabled.
- *
- * @var boolean
*/
- private $uploadEnabled = true;
+ private bool $uploadEnabled = true;
/**
* URL for the "audio recorder" plugin.
@@ -59,10 +54,8 @@ class AudioWidgetInput extends AudioInput
/**
* The text property for TTS.
- *
- * @var PropertyInterface
*/
- private $textProperty;
+ private ?\Charcoal\Property\PropertyInterface $textProperty = null;
/**
* The HTML input name attribute for TTS.
@@ -87,125 +80,98 @@ class AudioWidgetInput extends AudioInput
/**
* Retrieve the control type for the HTML element ``.
- *
- * @return string
*/
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'hidden';
}
- /**
- * @return boolean
- */
- public function displayAudioWidget()
+ public function displayAudioWidget(): bool
{
return $this->textEnabled() || $this->captureEnabled() || $this->uploadEnabled();
}
/**
* @param boolean $textEnabled If TTS is enabled or not for this widget.
- * @return self
*/
- public function setTextEnabled($textEnabled)
+ public function setTextEnabled($textEnabled): static
{
- $this->textEnabled = !!$textEnabled;
+ $this->textEnabled = (bool)$textEnabled;
return $this;
}
- /**
- * @return boolean
- */
- public function textEnabled()
+ public function textEnabled(): bool
{
return $this->textEnabled;
}
/**
* @param boolean $captureEnabled If recording is enabled or not for this widget.
- * @return self
*/
- public function setCaptureEnabled($captureEnabled)
+ public function setCaptureEnabled($captureEnabled): static
{
- $this->captureEnabled = !!$captureEnabled;
+ $this->captureEnabled = (bool)$captureEnabled;
return $this;
}
- /**
- * @return boolean
- */
- public function captureEnabled()
+ public function captureEnabled(): bool
{
return $this->captureEnabled;
}
/**
- * @deprecated In favour of {@see self::setCaptureEnabled()}
*
* @param boolean $recordingEnabled If recording is enabled or not for this widget.
- * @return self
*/
- public function setRecordingEnabled($recordingEnabled)
+ #[\Deprecated(message: 'In favour of {@see self::setCaptureEnabled()}')]
+ public function setRecordingEnabled($recordingEnabled): static
{
- $this->captureEnabled = !!$recordingEnabled;
+ $this->captureEnabled = (bool)$recordingEnabled;
return $this;
}
- /**
- * @deprecated In favour of {@see self::captureEnabled()}
- *
- * @return boolean
- */
- public function recordingEnabled()
+ #[\Deprecated(message: 'In favour of {@see self::captureEnabled()}')]
+ public function recordingEnabled(): bool
{
return $this->captureEnabled;
}
/**
* @param boolean $uploadEnabled If file upload is enabled or not for this widget.
- * @return self
*/
- public function setUploadEnabled($uploadEnabled)
+ public function setUploadEnabled($uploadEnabled): static
{
- $this->uploadEnabled = !!$uploadEnabled;
+ $this->uploadEnabled = (bool)$uploadEnabled;
return $this;
}
- /**
- * @return boolean
- */
- public function uploadEnabled()
+ public function uploadEnabled(): bool
{
return $this->uploadEnabled;
}
/**
- * @deprecated In favour of {@see self::setUploadEnabled()}
*
* @param boolean $fileEnabled If file upload is enabled or not for this widget.
- * @return self
*/
- public function setFileEnabled($fileEnabled)
+ #[\Deprecated(message: 'In favour of {@see self::setUploadEnabled()}')]
+ public function setFileEnabled($fileEnabled): static
{
- $this->uploadEnabled = !!$fileEnabled;
+ $this->uploadEnabled = (bool)$fileEnabled;
return $this;
}
- /**
- * @deprecated In favour of {@see self::uploadEnabled()}
- *
- * @return boolean
- */
- public function fileEnabled()
+ #[\Deprecated(message: 'In favour of {@see self::uploadEnabled()}')]
+ public function fileEnabled(): bool
{
return $this->uploadEnabled;
}
/**
* @param string $url The recording/exporting plugin URL.
- * @return self
*/
- public function setRecorderPluginUrl($url)
+ public function setRecorderPluginUrl($url): static
{
$this->recorderPluginUrl = $url;
return $this;
@@ -238,7 +204,7 @@ public function prepareRecorderPluginUrl()
{
$uri = $this->getRecorderPluginUrlTemplate();
- return function ($noop, LambdaHelper $helper) use ($uri) {
+ return function ($noop, LambdaHelper $helper) use ($uri): null {
$uri = $helper->render($uri);
$this->setRecorderPluginUrl($uri);
@@ -251,15 +217,12 @@ public function prepareRecorderPluginUrl()
*
* This method is overriden to change the `callback` value to reflect
* the correct input control ID.
- *
- * @return string
*/
- protected function getRecorderPluginUrlTemplate()
+ protected function getRecorderPluginUrlTemplate(): string
{
$uri = 'assets/admin/scripts/vendors/recorderjs/recorder.js';
- $uri = '{{# withBaseUrl }}' . $uri . '{{/ withBaseUrl }}';
- return $uri;
+ return '{{# withBaseUrl }}' . $uri . '{{/ withBaseUrl }}';
}
/**
@@ -267,9 +230,8 @@ protected function getRecorderPluginUrlTemplate()
*
* @param string $activePane The active widget pane.
* @throws InvalidArgumentException If the provided argument is not a string.
- * @return self
*/
- public function setActivePane($activePane)
+ public function setActivePane($activePane): static
{
if ($activePane === null || $activePane === '') {
$this->activePane = null;
@@ -325,9 +287,8 @@ public function activePane()
* Alias of {@see AbstractPropertyInput::setPropertyVal()}.
*
* @param mixed $val The audio property value.
- * @return self
*/
- public function setAudioPropertyVal($val)
+ public function setAudioPropertyVal($val): static
{
$this->setPropertyVal($val);
return $this;
@@ -343,10 +304,7 @@ public function audioPropertyVal()
return $this->propertyVal();
}
- /**
- * @return boolean
- */
- public function hasAudioPropertyVal()
+ public function hasAudioPropertyVal(): bool
{
$prop = $this->audioProperty();
$val = $prop->inputVal($this->audioPropertyVal(), [
@@ -360,9 +318,8 @@ public function hasAudioPropertyVal()
* Alias of {@see AbstractPropertyInput::setProperty()}.
*
* @param PropertyInterface $p The property for TTS.
- * @return self
*/
- public function setAudioProperty(PropertyInterface $p)
+ public function setAudioProperty(PropertyInterface $p): static
{
$this->setProperty($p);
return $this;
@@ -392,9 +349,8 @@ public function audioPropertyIdent()
* Alias of {@see AbstractPropertyInput::setInputName()}.
*
* @param string $inputName HTML input id attribute.
- * @return self
*/
- public function setAudioInputName($inputName)
+ public function setAudioInputName($inputName): static
{
$this->setInputName($inputName);
@@ -425,9 +381,8 @@ public function audioInputVal()
* Set the property value for TTS.
*
* @param mixed $val The property value.
- * @return self
*/
- public function setTextPropertyVal($val)
+ public function setTextPropertyVal($val): static
{
$this->textPropertyVal = $val;
return $this;
@@ -443,10 +398,7 @@ public function textPropertyVal()
return $this->textPropertyVal;
}
- /**
- * @return boolean
- */
- public function hasTextPropertyVal()
+ public function hasTextPropertyVal(): bool
{
$prop = $this->textProperty();
$val = $prop->inputVal($this->textPropertyVal(), [
@@ -460,9 +412,8 @@ public function hasTextPropertyVal()
* Set the property instance for TTS.
*
* @param PropertyInterface $p The property for TTS.
- * @return self
*/
- public function setTextProperty(PropertyInterface $p)
+ public function setTextProperty(PropertyInterface $p): static
{
$this->textProperty = $p;
return $this;
@@ -473,7 +424,7 @@ public function setTextProperty(PropertyInterface $p)
*
* @return PropertyInterface
*/
- public function textProperty()
+ public function textProperty(): ?\Charcoal\Property\PropertyInterface
{
return $this->textProperty;
}
@@ -493,9 +444,8 @@ public function textPropertyIdent()
*
* @see AbstractPropertyInput::setInputName()
* @param string $inputName HTML input name attribute.
- * @return self
*/
- public function setTextInputName($inputName)
+ public function setTextInputName($inputName): static
{
$this->textInputName = $inputName;
return $this;
@@ -509,11 +459,7 @@ public function setTextInputName($inputName)
*/
public function textInputName()
{
- if ($this->textInputName) {
- $name = $this->textInputName;
- } else {
- $name = $this->textPropertyIdent();
- }
+ $name = $this->textInputName ?: $this->textPropertyIdent();
if ($this->textProperty()['l10n']) {
$name .= '[' . $this->lang() . ']';
@@ -529,7 +475,7 @@ public function textInputName()
* @throws UnexpectedValueException If the value is invalid.
* @return string
*/
- public function textInputVal()
+ public function textInputVal(): int|float|string|bool
{
$prop = $this->textProperty();
$val = $prop->inputVal($this->textPropertyVal(), [
@@ -543,7 +489,7 @@ public function textInputVal()
if (!is_scalar($val)) {
throw new UnexpectedValueException(sprintf(
'Property Input Value must be a string, received %s',
- (is_object($val) ? get_class($val) : gettype($val))
+ (get_debug_type($val))
));
}
@@ -552,40 +498,32 @@ public function textInputVal()
/**
* Retrieve the input ID for the TTS property.
- *
- * @return string
*/
- public function textInputId()
+ public function textInputId(): string
{
return 'audio_text_' . $this->inputId();
}
/**
* Retrieve the input ID for the audio recorder property.
- *
- * @return string
*/
- public function captureInputId()
+ public function captureInputId(): string
{
return 'audio_capture_' . $this->inputId();
}
/**
* Retrieve the input ID for the audio file property.
- *
- * @return string
*/
- public function uploadInputId()
+ public function uploadInputId(): string
{
return 'audio_upload_' . $this->inputId();
}
/**
* Retrieve the input ID for the widget's hidden property.
- *
- * @return string
*/
- public function hiddenInputId()
+ public function hiddenInputId(): string
{
return 'audio_hidden_' . $this->inputId();
}
@@ -595,7 +533,7 @@ public function hiddenInputId()
*
* @return callable|null
*/
- public function textPropertyContext()
+ public function textPropertyContext(): ?\Closure
{
if (!$this->textEnabled() || $this->currentContext) {
return null;
@@ -622,7 +560,7 @@ public function textPropertyContext()
*
* @return callable|null
*/
- public function capturePropertyContext()
+ public function capturePropertyContext(): ?\Closure
{
if (!$this->captureEnabled() || $this->currentContext) {
return null;
@@ -649,7 +587,7 @@ public function capturePropertyContext()
*
* @return callable|null
*/
- public function uploadPropertyContext()
+ public function uploadPropertyContext(): ?\Closure
{
if (!$this->uploadEnabled() || $this->currentContext) {
return null;
@@ -676,25 +614,22 @@ public function uploadPropertyContext()
*
* This method is overriden to change the `callback` value to reflect
* the correct input control ID.
- *
- * @return string
*/
- protected function getFilePickerUrlTemplate()
+ #[\Override]
+ protected function getFilePickerUrlTemplate(): string
{
$uri = 'obj_type={{ objType }}&obj_id={{ objId }}&property={{ p.ident }}&callback={{ uploadInputId }}';
- $uri = '{{# withAdminUrl }}elfinder?' . $uri . '{{/ withAdminUrl }}';
- return $uri;
+ return '{{# withAdminUrl }}elfinder?' . $uri . '{{/ withAdminUrl }}';
}
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
- public function controlDataForJs()
+ #[\Override]
+ public function controlDataForJs(): array
{
- $inputId = $this->inputId();
+ $this->inputId();
$data = parent::controlDataForJs();
return array_replace($data, [
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/CheckboxBtnGroupInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/CheckboxBtnGroupInput.php
index 444ede0c4..5e4b69413 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/CheckboxBtnGroupInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/CheckboxBtnGroupInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ public function type(): string
{
return 'checkbox';
}
/**
* Always accept multiple values.
- *
- * @return boolean
*/
- public function multiple()
+ #[\Override]
+ public function multiple(): bool
{
return true;
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/ColorPickerInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/ColorPickerInput.php
index f268dc581..22bb2414c 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/ColorPickerInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/ColorPickerInput.php
@@ -12,17 +12,13 @@ class ColorPickerInput extends AbstractPropertyInput
{
/**
* Settings for {@link https://github.com/claviska/jquery-minicolors/ jQuery MiniColors}.
- *
- * @var array
*/
- private $pickerOptions;
+ private ?array $pickerOptions = null;
/**
* Retrieve the control type for the HTML element ``.
- *
- * @return string
*/
- public function type()
+ public function type(): string
{
return 'color';
}
@@ -35,7 +31,7 @@ public function type()
* @param array $settings The color picker options.
* @return ColorpickerInput Chainable
*/
- public function setPickerOptions(array $settings)
+ public function setPickerOptions(array $settings): static
{
$this->pickerOptions = array_merge($this->defaultPickerOptions(), $settings);
@@ -48,7 +44,7 @@ public function setPickerOptions(array $settings)
* @param array $settings The color picker options.
* @return ColorpickerInput Chainable
*/
- public function mergePickerOptions(array $settings)
+ public function mergePickerOptions(array $settings): static
{
$this->pickerOptions = array_merge($this->pickerOptions, $settings);
@@ -63,7 +59,7 @@ public function mergePickerOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return ColorpickerInput Chainable
*/
- public function addPickerOption($key, $val)
+ public function addPickerOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -83,10 +79,8 @@ public function addPickerOption($key, $val)
/**
* Retrieve the color picker's options.
- *
- * @return array
*/
- public function pickerOptions()
+ public function pickerOptions(): array
{
if ($this->pickerOptions === null) {
$this->pickerOptions = $this->defaultPickerOptions();
@@ -97,10 +91,8 @@ public function pickerOptions()
/**
* Retrieve the default color picker options.
- *
- * @return array
*/
- public function defaultPickerOptions()
+ public function defaultPickerOptions(): array
{
return [
'format' => 'hex',
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/DateTimePickerInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/DateTimePickerInput.php
index 72650319a..0185af601 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/DateTimePickerInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/DateTimePickerInput.php
@@ -19,17 +19,13 @@ class DateTimePickerInput extends AbstractPropertyInput
/**
* Settings for {@link https://eonasdan.github.io/bootstrap-datetimepicker/ Bootstrap Datepicker}.
- *
- * @var array
*/
- private $pickerOptions;
+ private ?array $pickerOptions = null;
/**
* Retrieve the control type for the HTML element ``.
- *
- * @return string
*/
- public function type()
+ public function type(): string
{
return 'datetime-local';
}
@@ -37,9 +33,8 @@ public function type()
/**
* @param string $class The input group class attribute.
* @throws InvalidArgumentException If the class is not a string.
- * @return self
*/
- public function setInputGroupClass($class)
+ public function setInputGroupClass($class): static
{
if (!is_string($class)) {
throw new InvalidArgumentException('CSS Class(es) must be a string');
@@ -64,7 +59,7 @@ public function inputGroupClass()
* @param array $settings The color picker options.
* @return ColorpickerInput Chainable
*/
- public function setPickerOptions(array $settings)
+ public function setPickerOptions(array $settings): static
{
$this->pickerOptions = array_merge($this->defaultPickerOptions(), $settings);
@@ -77,7 +72,7 @@ public function setPickerOptions(array $settings)
* @param array $settings The color picker options.
* @return ColorpickerInput Chainable
*/
- public function mergePickerOptions(array $settings)
+ public function mergePickerOptions(array $settings): static
{
$this->pickerOptions = array_merge($this->pickerOptions, $settings);
@@ -92,7 +87,7 @@ public function mergePickerOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return ColorpickerInput Chainable
*/
- public function addPickerOption($key, $val)
+ public function addPickerOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -112,10 +107,8 @@ public function addPickerOption($key, $val)
/**
* Retrieve the color picker's options.
- *
- * @return array
*/
- public function pickerOptions()
+ public function pickerOptions(): array
{
if ($this->pickerOptions === null) {
$this->pickerOptions = $this->defaultPickerOptions();
@@ -126,10 +119,8 @@ public function pickerOptions()
/**
* Retrieve the default color picker options.
- *
- * @return array
*/
- public function defaultPickerOptions()
+ public function defaultPickerOptions(): array
{
$date = null;
@@ -139,7 +130,7 @@ public function defaultPickerOptions()
return [
'format' => self::DEFAULT_JS_FORMAT,
- 'defaultDate' => $date ? $date->format(\DateTime::ISO8601) : null
+ 'defaultDate' => $date instanceof \DateTime ? $date->format(\DateTime::ISO8601) : null
];
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/DualSelectInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/DualSelectInput.php
index 06847f268..a4a100c10 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/DualSelectInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/DualSelectInput.php
@@ -23,10 +23,8 @@ class DualSelectInput extends AbstractSelectableInput
/**
* How the dual-select controls should be displayed.
- *
- * @var string|null
*/
- private $inputLayout;
+ private ?string $inputLayout = null;
/**
* Whether the lists can be filtered.
@@ -44,10 +42,8 @@ class DualSelectInput extends AbstractSelectableInput
/**
* Settings for {@link http://crlcu.github.io/multiselect/ Multiselect}.
- *
- * @var array
*/
- private $dualSelectOptions;
+ private ?array $dualSelectOptions = null;
/**
* Retrieve the unselected options.
@@ -123,11 +119,7 @@ public function searchable()
$placeholder = $searchable['placeholder'];
}
- if (isset($placeholder)) {
- $searchable[$ident]['placeholder'] = $this->translator()->translation($placeholder);
- } else {
- $searchable[$ident]['placeholder'] = $label;
- }
+ $searchable[$ident]['placeholder'] = isset($placeholder) ? $this->translator()->translation($placeholder) : $label;
}
} else {
$searchable = false;
@@ -168,7 +160,7 @@ public function reorderable()
* @throws OutOfBoundsException If the given layout is unsupported.
* @return AbstractTickableInput Chainable
*/
- public function setInputLayout($layout)
+ public function setInputLayout($layout): static
{
if ($layout === null) {
$this->inputLayout = null;
@@ -179,7 +171,7 @@ public function setInputLayout($layout)
if (!is_string($layout)) {
throw new InvalidArgumentException(sprintf(
'Layout must be a string, received %s',
- (is_object($layout) ? get_class($layout) : gettype($layout))
+ (get_debug_type($layout))
));
}
@@ -213,10 +205,8 @@ public function inputLayout()
/**
* Retrieve the input layouts; for templating.
- *
- * @return array
*/
- public function inputLayouts()
+ public function inputLayouts(): array
{
$supported = $this->supportedInputLayouts();
$layouts = [];
@@ -229,10 +219,8 @@ public function inputLayouts()
/**
* Retrieve the supported input layouts.
- *
- * @return array
*/
- protected function supportedInputLayouts()
+ protected function supportedInputLayouts(): array
{
return [
self::COLS_INPUT_LAYOUT,
@@ -258,7 +246,7 @@ protected function defaultInputLayout()
* @param array $settings The dual-select options.
* @return Selectinput Chainable
*/
- public function setDualSelectOptions(array $settings)
+ public function setDualSelectOptions(array $settings): static
{
$this->dualSelectOptions = array_merge($this->defaultDualSelectOptions(), $settings);
@@ -271,7 +259,7 @@ public function setDualSelectOptions(array $settings)
* @param array $settings The dual-select options.
* @return Selectinput Chainable
*/
- public function mergeDualSelectOptions(array $settings)
+ public function mergeDualSelectOptions(array $settings): static
{
$this->dualSelectOptions = array_merge($this->dualSelectOptions, $settings);
@@ -286,7 +274,7 @@ public function mergeDualSelectOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return Selectinput Chainable
*/
- public function addSelectOption($key, $val)
+ public function addSelectOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -306,10 +294,8 @@ public function addSelectOption($key, $val)
/**
* Retrieve the dual-select's options.
- *
- * @return array
*/
- public function dualSelectOptions()
+ public function dualSelectOptions(): array
{
if ($this->dualSelectOptions === null) {
$this->dualSelectOptions = $this->defaultDualSelectOptions();
@@ -320,10 +306,8 @@ public function dualSelectOptions()
/**
* Retrieve the default dual-select options.
- *
- * @return array
*/
- public function defaultDualSelectOptions()
+ public function defaultDualSelectOptions(): array
{
return [];
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/EmailInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/EmailInput.php
index 410ebe205..2fca5bc6a 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/EmailInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/EmailInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'email';
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/FileInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/FileInput.php
index b3e76b526..8f8ede750 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/FileInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/FileInput.php
@@ -5,7 +5,7 @@
// From Pimple
use Pimple\Container;
// From Mustache
-use Mustache_LambdaHelper as LambdaHelper;
+use Mustache\LambdaHelper as LambdaHelper;
// // From 'charcoal-admin'
use Charcoal\Admin\Property\AbstractPropertyInput;
@@ -30,24 +30,18 @@ class FileInput extends AbstractPropertyInput
/**
* Flag wether the "file preview" should be displayed.
- *
- * @var boolean
*/
- private $showFilePreview = true;
+ private bool $showFilePreview = true;
/**
* Flag wether the "file upload" input should be displayed.
- *
- * @var boolean
*/
- private $showFileUpload;
+ private ?bool $showFileUpload = null;
/**
* Flag wether the "file picker" popup button should be displaed.
- *
- * @var boolean
*/
- private $showFilePicker;
+ private ?bool $showFilePicker = null;
/**
* URL for the "file picker" popup.
@@ -79,10 +73,8 @@ class FileInput extends AbstractPropertyInput
/**
* Retrieve the control type for the HTML element ``.
- *
- * @return string
*/
- public function type()
+ public function type(): string
{
return 'file';
}
@@ -92,9 +84,8 @@ public function type()
*
* @link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file
* @param string|string[] $types The accepted MIME types.
- * @return self
*/
- public function setAccept($types)
+ public function setAccept($types): static
{
if (is_array($types)) {
$types = implode(',', $types);
@@ -108,10 +99,8 @@ public function setAccept($types)
* Retrieve a comma-separated list of default file type specifiers.
*
* This method concatenates the file property's "acceptedMimetypes".
- *
- * @return string
*/
- public function getDefaultAccept()
+ public function getDefaultAccept(): string
{
$types = $this->property()['acceptedMimetypes'];
return implode(',', $types);
@@ -134,14 +123,14 @@ public function accept()
/**
* @return string|null
*/
- public function abridgedInputVal()
+ public function abridgedInputVal(): string|array|null
{
$val = (string)$this->inputVal();
- $val = preg_replace('!^' . preg_quote($this->p()['uploadPath'], '!') . '!', '', $val);
+ $val = preg_replace('!^' . preg_quote((string)$this->p()['uploadPath'], '!') . '!', '', $val);
- if (strpos($val, '://') !== false) {
- $host = parse_url($val, PHP_URL_HOST);
- $path = ltrim(substr($val, (strpos($val, $host) + strlen($host) + 1)), '/');
+ if (str_contains((string)$val, '://')) {
+ $host = parse_url((string)$val, PHP_URL_HOST);
+ $path = ltrim(substr((string)$val, (strpos((string)$val, (string)$host) + strlen($host) + 1)), '/');
if (mb_strlen($path) > 30) {
$a = 12;
$z = 12;
@@ -153,10 +142,7 @@ public function abridgedInputVal()
return $val;
}
- /**
- * @return string|null
- */
- public function filePreview()
+ public function filePreview(): string
{
$value = $this->inputVal();
if ($value) {
@@ -181,8 +167,8 @@ public function placeholderVal()
$parts = parse_url($val);
if (empty($parts['scheme']) && !in_array($val[0], [ '/', '#', '?' ])) {
$path = isset($parts['path']) ? ltrim($parts['path'], '/') : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
$val = $this->baseUrl->withPath($path)->withQuery($query)->withFragment($hash);
}
@@ -204,8 +190,8 @@ public function previewVal()
$parts = parse_url($val);
if (empty($parts['scheme']) && !in_array($val[0], [ '/', '#', '?' ])) {
$path = isset($parts['path']) ? ltrim($parts['path'], '/') : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
$val = $this->baseUrl->withPath($path)->withQuery($query)->withFragment($hash);
}
@@ -216,17 +202,14 @@ public function previewVal()
* @param boolean $show The show file preview flag.
* @return FileInput Chainable
*/
- public function setShowFilePreview($show)
+ public function setShowFilePreview($show): static
{
- $this->showFilePreview = !!$show;
+ $this->showFilePreview = (bool)$show;
return $this;
}
- /**
- * @return boolean
- */
- public function showFilePreview()
+ public function showFilePreview(): bool
{
return $this->showFilePreview;
}
@@ -235,9 +218,9 @@ public function showFilePreview()
* @param boolean $show The show file upload flag.
* @return FileInput Chainable
*/
- public function setShowFileUpload($show)
+ public function setShowFileUpload($show): static
{
- $this->showFileUpload = !!$show;
+ $this->showFileUpload = (bool)$show;
return $this;
}
@@ -258,29 +241,23 @@ public function showFileUpload()
* @param boolean $show The show file picker flag.
* @return FileInput Chainable
*/
- public function setShowFilePicker($show)
+ public function setShowFilePicker($show): static
{
- $this->showFilePicker = !!$show;
+ $this->showFilePicker = (bool)$show;
return $this;
}
- /**
- * @return boolean
- */
- public function showFilePicker()
+ public function showFilePicker(): bool
{
if ($this->showFilePicker === null) {
- return !($this->showFileUpload === true);
+ return $this->showFileUpload !== true;
}
return $this->showFilePicker && $this->hasFilePicker();
}
- /**
- * @return boolean
- */
- public function hasFilePicker()
+ public function hasFilePicker(): bool
{
return class_exists('\\elFinder');
}
@@ -289,7 +266,7 @@ public function hasFilePicker()
* @param string $url The file picker AJAX URL.
* @return FileInput Chainable
*/
- public function setFilePickerUrl($url)
+ public function setFilePickerUrl($url): static
{
$this->filePickerUrl = $url;
return $this;
@@ -317,7 +294,7 @@ public function filePickerUrl()
*
* @return callable|null
*/
- public function prepareFilePickerUrl()
+ public function prepareFilePickerUrl(): ?\Closure
{
if (!$this->showFilePicker()) {
return null;
@@ -325,7 +302,7 @@ public function prepareFilePickerUrl()
$uri = $this->getFilePickerUrlTemplate();
- return function ($noop, LambdaHelper $helper) use ($uri) {
+ return function ($noop, LambdaHelper $helper) use ($uri): null {
$uri = $helper->render($uri);
$this->setFilePickerUrl($uri);
@@ -335,24 +312,20 @@ public function prepareFilePickerUrl()
/**
* Retrieve the elFinder connector URL template for rendering.
- *
- * @return string
*/
- protected function getFilePickerUrlTemplate()
+ protected function getFilePickerUrlTemplate(): string
{
$uri = 'obj_type={{ objType }}&obj_id={{ objId }}&property={{ p.ident }}&callback={{ inputId }}';
- $uri = '{{# withAdminUrl }}elfinder?' . $uri . '{{/ withAdminUrl }}';
- return $uri;
+ return '{{# withAdminUrl }}elfinder?' . $uri . '{{/ withAdminUrl }}';
}
/**
* Set the title for the file picker dialog.
*
* @param string|string[] $title The dialog title.
- * @return self
*/
- public function setDialogTitle($title)
+ public function setDialogTitle($title): static
{
$this->dialogTitle = $this->translator()->translation($title);
@@ -377,9 +350,8 @@ public function dialogTitle()
* Set the label for the file picker button.
*
* @param string|string[] $label The button label.
- * @return self
*/
- public function setChooseButtonLabel($label)
+ public function setChooseButtonLabel($label): static
{
$this->chooseButtonLabel = $this->translator()->translation($label);
@@ -404,9 +376,8 @@ public function chooseButtonLabel()
* Set the label for the file removal button.
*
* @param string|string[] $label The button label.
- * @return self
*/
- public function setRemoveButtonLabel($label)
+ public function setRemoveButtonLabel($label): static
{
$this->removeButtonLabel = $this->translator()->translation($label);
@@ -433,6 +404,7 @@ public function removeButtonLabel()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -445,7 +417,7 @@ protected function setDependencies(Container $container)
*
* @return \Charcoal\Translator\Translation|string|null
*/
- protected function defaultDialogTitle()
+ protected function defaultDialogTitle(): ?\Charcoal\Translator\Translation
{
return $this->translator()->translation('filesystem.library.media');
}
@@ -455,7 +427,7 @@ protected function defaultDialogTitle()
*
* @return \Charcoal\Translator\Translation|string|null
*/
- protected function defaultChooseButtonLabel()
+ protected function defaultChooseButtonLabel(): ?\Charcoal\Translator\Translation
{
if ($this->property()['multiple']) {
return $this->translator()->translation('Choose files…');
@@ -469,7 +441,7 @@ protected function defaultChooseButtonLabel()
*
* @return \Charcoal\Translator\Translation|string|null
*/
- protected function defaultRemoveButtonLabel()
+ protected function defaultRemoveButtonLabel(): ?\Charcoal\Translator\Translation
{
if ($this->property()['multiple']) {
return $this->translator()->translation('Clear selected files');
@@ -480,10 +452,9 @@ protected function defaultRemoveButtonLabel()
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
- public function controlDataForJs()
+ #[\Override]
+ public function controlDataForJs(): array
{
return [
'input_name' => $this->inputName(),
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/HiddenInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/HiddenInput.php
index d182cabf3..eb1b55000 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/HiddenInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/HiddenInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'hidden';
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/ImageInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/ImageInput.php
index d4b5f4ff1..20608e4f8 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/ImageInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/ImageInput.php
@@ -15,18 +15,15 @@ class ImageInput extends FileInput
/**
* Retrieve list of default file type specifiers.
- *
- * @return string
*/
- public function getDefaultAccept()
+ #[\Override]
+ public function getDefaultAccept(): string
{
return 'image/*';
}
- /**
- * @return string|null
- */
- public function filePreview()
+ #[\Override]
+ public function filePreview(): string
{
$value = $this->inputVal();
if ($value) {
@@ -41,7 +38,8 @@ public function filePreview()
*
* @return \Charcoal\Translator\Translation|string|null
*/
- protected function defaultChooseButtonLabel()
+ #[\Override]
+ protected function defaultChooseButtonLabel(): ?\Charcoal\Translator\Translation
{
if ($this->property()['multiple']) {
return $this->translator()->translation('Choose images…');
@@ -56,7 +54,7 @@ protected function defaultChooseButtonLabel()
* @param string|string[] $classes A space-separated list of CSS classes.
* @return ImageDisplay Chainable
*/
- public function setClassAttr($classes)
+ public function setClassAttr($classes): static
{
if (is_array($classes)) {
$classes = implode(' ', $classes);
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/JsonEditorInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/JsonEditorInput.php
index a87d41f68..72186408b 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/JsonEditorInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/JsonEditorInput.php
@@ -27,7 +27,7 @@ class JsonEditorInput extends TextareaInput
* @param array $settings The editor options.
* @return Tinymce Chainable
*/
- public function setEditorOptions(array $settings)
+ public function setEditorOptions(array $settings): static
{
$this->editorOptions = array_merge($this->defaultEditorOptions(), $settings);
@@ -40,7 +40,7 @@ public function setEditorOptions(array $settings)
* @param array $settings The editor options.
* @return Tinymce Chainable
*/
- public function mergeEditorOptions(array $settings)
+ public function mergeEditorOptions(array $settings): static
{
$this->editorOptions = array_merge($this->editorOptions, $settings);
@@ -55,7 +55,7 @@ public function mergeEditorOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return Tinymce Chainable
*/
- public function addEditorOption($key, $val)
+ public function addEditorOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -96,16 +96,10 @@ public function defaultEditorOptions()
{
$defaultData = $this->metadata()->defaultData();
- if (isset($defaultData['editor_options'])) {
- return $defaultData['editor_options'];
- }
-
- return [];
+ return ($defaultData['editor_options'] ?? []);
}
- /**
- * @return array
- */
+ #[\Override]
public function getInputValOptions(): array
{
return [
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/MapWidgetInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/MapWidgetInput.php
index b9f80d917..21888746a 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/MapWidgetInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/MapWidgetInput.php
@@ -22,18 +22,15 @@ class MapWidgetInput extends AbstractPropertyInput
/**
* Settings for the map widget.
- *
- * @var array
*/
- private $mapOptions;
+ private ?array $mapOptions = null;
/**
* Sets the API key for the mapping service.
*
* @param string $key An API key.
- * @return self
*/
- public function setApiKey($key)
+ public function setApiKey($key): static
{
$this->apiKey = $key;
@@ -58,7 +55,7 @@ public function apiKey()
* @param array $settings The map widget options.
* @return MapWidgetInput Chainable
*/
- public function setMapOptions(array $settings)
+ public function setMapOptions(array $settings): static
{
if (isset($settings['api_key'])) {
$this->setApiKey($settings['api_key']);
@@ -79,7 +76,7 @@ public function setMapOptions(array $settings)
* @param array $settings The map widget options.
* @return MapWidgetInput Chainable
*/
- public function mergeMapOptions(array $settings)
+ public function mergeMapOptions(array $settings): static
{
if (isset($settings['api_key'])) {
$this->setApiKey($settings['api_key']);
@@ -98,7 +95,7 @@ public function mergeMapOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return MapWidgetInput Chainable
*/
- public function addMapOption($key, $val)
+ public function addMapOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -122,10 +119,8 @@ public function addMapOption($key, $val)
/**
* Retrieve the map widget's options.
- *
- * @return array
*/
- public function mapOptions()
+ public function mapOptions(): array
{
if ($this->mapOptions === null) {
$this->mapOptions = $this->defaultMapOptions();
@@ -135,10 +130,8 @@ public function mapOptions()
/**
* Retrieve the default map widget options.
- *
- * @return array
*/
- public function defaultMapOptions()
+ public function defaultMapOptions(): array
{
return [ 'api_key' => $this->apiKey() ];
}
@@ -159,6 +152,7 @@ public function mapOptionsAsJson()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/NestedWidgetInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/NestedWidgetInput.php
index 3f0411686..879eab382 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/NestedWidgetInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/NestedWidgetInput.php
@@ -34,24 +34,18 @@ class NestedWidgetInput extends AbstractPropertyInput implements
/**
* Store the widget factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $widgetFactory;
+ private ?\Charcoal\Factory\FactoryInterface $widgetFactory = null;
/**
* Store the form group widget factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $formGroupFactory;
+ private ?\Charcoal\Factory\FactoryInterface $formGroupFactory = null;
/**
* The form group the input belongs to.
- *
- * @var FormGroupInterface
*/
- private $formGroup;
+ private ?\Charcoal\Ui\FormGroup\FormGroupInterface $formGroup = null;
/**
* Set the form input's parent group.
@@ -59,7 +53,7 @@ class NestedWidgetInput extends AbstractPropertyInput implements
* @param FormGroupInterface $formGroup The parent form group object.
* @return FormInputInterface Chainable
*/
- public function setFormGroup(FormGroupInterface $formGroup)
+ public function setFormGroup(FormGroupInterface $formGroup): static
{
$this->formGroup = $formGroup;
@@ -71,7 +65,7 @@ public function setFormGroup(FormGroupInterface $formGroup)
*
* @return FormGroupInterface
*/
- public function formGroup()
+ public function formGroup(): ?\Charcoal\Ui\FormGroup\FormGroupInterface
{
return $this->formGroup;
}
@@ -82,6 +76,7 @@ public function formGroup()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -94,9 +89,8 @@ protected function setDependencies(Container $container)
* Set the widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return self
*/
- protected function setWidgetFactory(FactoryInterface $factory)
+ protected function setWidgetFactory(FactoryInterface $factory): static
{
$this->widgetFactory = $factory;
@@ -107,14 +101,13 @@ protected function setWidgetFactory(FactoryInterface $factory)
* Retrieve the widget factory.
*
* @throws RuntimeException If the widget factory was not previously set.
- * @return FactoryInterface
*/
- protected function widgetFactory()
+ protected function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->widgetFactory === null) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Widget Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -125,9 +118,8 @@ protected function widgetFactory()
* Set the form group factory.
*
* @param FactoryInterface $factory The factory to create form groups.
- * @return self
*/
- protected function setFormGroupFactory(FactoryInterface $factory)
+ protected function setFormGroupFactory(FactoryInterface $factory): static
{
$this->formGroupFactory = $factory;
@@ -138,14 +130,13 @@ protected function setFormGroupFactory(FactoryInterface $factory)
* Retrieve the form group factory.
*
* @throws RuntimeException If the form group factory was not previously set.
- * @return FactoryInterface
*/
- protected function formGroupFactory()
+ protected function formGroupFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->formGroupFactory === null) {
+ if (!$this->formGroupFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Form Group Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/NumberInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/NumberInput.php
index 4b43977da..b4bb9496b 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/NumberInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/NumberInput.php
@@ -1,5 +1,7 @@
min = null;
@@ -56,18 +52,12 @@ public function setMin($min)
return $this;
}
- /**
- * @return boolean
- */
- public function hasMin()
+ public function hasMin(): bool
{
return !(empty($this->min) && !is_numeric($this->min));
}
- /**
- * @return integer|float|null
- */
- public function min()
+ public function min(): int|float|null
{
return $this->min;
}
@@ -77,7 +67,7 @@ public function min()
* @throws InvalidArgumentException If the argument is not a number.
* @return Text Chainable
*/
- public function setMax($max)
+ public function setMax($max): static
{
if ($max === null || $max === '') {
$this->max = null;
@@ -94,18 +84,12 @@ public function setMax($max)
return $this;
}
- /**
- * @return boolean
- */
- public function hasMax()
+ public function hasMax(): bool
{
return !(empty($this->max) && !is_numeric($this->max));
}
- /**
- * @return integer|float|null
- */
- public function max()
+ public function max(): int|float|null
{
return $this->max;
}
@@ -115,7 +99,7 @@ public function max()
* @throws InvalidArgumentException If the value is not a number.
* @return Text Chainable
*/
- public function setStep($step)
+ public function setStep($step): static
{
if ($step === null || $step === '') {
$this->step = null;
@@ -137,18 +121,12 @@ public function setStep($step)
return $this;
}
- /**
- * @return boolean
- */
- public function hasStep()
+ public function hasStep(): bool
{
return !(empty($this->step) && !is_numeric($this->step));
}
- /**
- * @return string|integer|float|null
- */
- public function step()
+ public function step(): string|int|float|null
{
return $this->step;
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/PasswordInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/PasswordInput.php
index 19d206109..200db6481 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/PasswordInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/PasswordInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'password';
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/PermalinkInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/PermalinkInput.php
index 9c30149f5..91520639c 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/PermalinkInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/PermalinkInput.php
@@ -42,6 +42,7 @@ class PermalinkInput extends TextInput
* @param Container $container A service locator.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -55,9 +56,9 @@ protected function setDependencies(Container $container)
* Used for the HTML "ID" attribute.
*
* @param string $inputId HTML input id attribute.
- * @return self
*/
- public function setInputId($inputId)
+ #[\Override]
+ public function setInputId($inputId): static
{
parent::setInputId($inputId);
$this->sampleId = $inputId;
@@ -66,10 +67,8 @@ public function setInputId($inputId)
/**
* Get the permalink's absolute URI.
- *
- * @return string|null
*/
- public function viewLink()
+ public function viewLink(): string
{
$link = null;
$locale = $this->lang();
@@ -88,9 +87,8 @@ public function viewLink()
* Set the permalink's immutable base.
*
* @param mixed $route The base URI.
- * @return self
*/
- protected function setBaseRoute($route)
+ protected function setBaseRoute($route): static
{
$this->baseRoute = $this->translator()->translation($route);
return $this;
@@ -98,10 +96,8 @@ protected function setBaseRoute($route)
/**
* Get the permalink's immutable base.
- *
- * @return string|null
*/
- public function baseRoute()
+ public function baseRoute(): string
{
if ($this->baseRoute === null) {
$this->baseRoute = $this->baseUrl();
@@ -117,7 +113,7 @@ public function baseRoute()
$translator->setLocale($origLocale);
}
- return rtrim((string)$link, '/') . '/';
+ return rtrim($link, '/') . '/';
}
/**
@@ -128,7 +124,7 @@ public function baseRoute()
public function editableRoute()
{
$link = $this->inputVal();
- if (empty($link)) {
+ if (in_array($link, [null, '', '0'], true)) {
$link = $this->placeholder();
}
@@ -139,9 +135,8 @@ public function editableRoute()
* Set the base URI of the project.
*
* @param UriInterface $uri The base URI.
- * @return self
*/
- protected function setBaseUrl(UriInterface $uri)
+ protected function setBaseUrl(UriInterface $uri): static
{
$this->baseUrl = $uri;
return $this;
@@ -155,10 +150,10 @@ protected function setBaseUrl(UriInterface $uri)
*/
public function baseUrl()
{
- if (!isset($this->baseUrl)) {
+ if ($this->baseUrl === null) {
throw new RuntimeException(sprintf(
'The base URI is not defined for [%s]',
- get_class($this)
+ static::class
));
}
@@ -195,9 +190,8 @@ public function samples()
* Used for the HTML "ID" attribute.
*
* @param string $id HTML sample ID attribute.
- * @return self
*/
- public function setSampleId($id)
+ public function setSampleId($id): static
{
$this->sampleId = $id;
return $this;
@@ -221,10 +215,8 @@ public function sampleId()
/**
* Generate a unique sample ID.
- *
- * @return string
*/
- protected function generateSampleId()
+ protected function generateSampleId(): string
{
return 'sample_' . uniqid();
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/PhoneInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/PhoneInput.php
index e9faf80d3..c9d623803 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/PhoneInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/PhoneInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'tel';
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/RadioBtnGroupInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/RadioBtnGroupInput.php
index 84311e0a9..c14504e2f 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/RadioBtnGroupInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/RadioBtnGroupInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ public function type(): string
{
return 'radio';
}
/**
* Never accept multiple values.
- *
- * @return boolean
*/
- public function multiple()
+ #[\Override]
+ public function multiple(): bool
{
return false;
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/RangeInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/RangeInput.php
index 709ca214d..571a0a4aa 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/RangeInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/RangeInput.php
@@ -1,5 +1,7 @@
showRangeValue = (bool)$show;
$this->setRangeValueLocation($show);
@@ -39,10 +38,8 @@ public function setShowRangeValue($show)
/**
* Determine if the property's value should be displayed.
- *
- * @return boolean
*/
- public function showRangeValue()
+ public function showRangeValue(): bool
{
return $this->showRangeValue;
}
@@ -56,9 +53,8 @@ public function showRangeValue()
* CSS selector, the query selector lookup will be done with the input's
* ID prefix (e.g., "my_range_output" → `#input_5db6fc900736b_my_range_output`).
* @throws InvalidArgumentException If the show flag is invalid.
- * @return self
*/
- public function setRangeValueLocation($location)
+ public function setRangeValueLocation($location): static
{
switch ($location) {
case false:
@@ -79,7 +75,7 @@ public function setRangeValueLocation($location)
throw new InvalidArgumentException(sprintf(
'Invalid range value location: %s ',
- (is_object($location) ? get_class($location) : gettype($location))
+ (get_debug_type($location))
));
}
@@ -95,10 +91,9 @@ public function rangeValueLocation()
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
- public function controlDataForJs()
+ #[\Override]
+ public function controlDataForJs(): array
{
return [
// Base Control
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlyInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlyInput.php
index 74b8fa780..a46b9c108 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlyInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlyInput.php
@@ -40,17 +40,13 @@ class ReadonlyInput extends AbstractPropertyInput
/**
* Whether the placeholder text should be shown when the value is empty.
- *
- * @var boolean
*/
- private $showPlaceholder = false;
+ private bool $showPlaceholder = false;
/**
* Store the factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $propertyDisplayFactory;
+ private ?\Charcoal\Factory\FactoryInterface $propertyDisplayFactory = null;
/**
* @return string
@@ -113,6 +109,7 @@ public function displayVal()
* @throws UnexpectedValueException If the value is invalid.
* @return string
*/
+ #[\Override]
public function inputVal()
{
$property = $this->property();
@@ -139,7 +136,7 @@ public function inputVal()
if (!is_scalar($val)) {
throw new UnexpectedValueException(sprintf(
'Property Input Value must be a string, received %s',
- (is_object($val) ? get_class($val) : gettype($val))
+ (get_debug_type($val))
));
}
@@ -149,6 +146,7 @@ public function inputVal()
/**
* @return boolean
*/
+ #[\Override]
public function hasPropertyVal()
{
if ($this->hasPropertyVal === null) {
@@ -164,9 +162,9 @@ public function hasPropertyVal()
* @param boolean $show Show (TRUE) or hide (FALSE) the notes.
* @return UiItemInterface Chainable
*/
- public function setShowPlaceholder($show)
+ public function setShowPlaceholder($show): static
{
- $this->showPlaceholder = !!$show;
+ $this->showPlaceholder = (bool)$show;
return $this;
}
@@ -201,7 +199,7 @@ public function maybeSerializeValue($input)
return $output;
}
}
- } catch (JsonException $e) {
+ } catch (JsonException) {
// do nothing
}
}
@@ -223,7 +221,7 @@ public function maybeUnserializeValue($input)
if (!is_scalar($output) && !is_null($output)) {
return $output;
}
- } catch (JsonException $e) {
+ } catch (JsonException) {
// do nothing
}
}
@@ -263,10 +261,9 @@ public function getRenderType()
/**
* Retrieve the default display options.
- *
- * @return array
*/
- public function getDefaultInputOptions()
+ #[\Override]
+ public function getDefaultInputOptions(): array
{
return [
'maybe_input_is_serialized' => static::DEFAULT_MAYBE_INPUT_IS_SERIALIZED,
@@ -279,6 +276,7 @@ public function getDefaultInputOptions()
* @param Container $container Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -302,13 +300,12 @@ protected function setPropertyDisplayFactory(FactoryInterface $factory)
* Retrieve the property display factory.
*
* @throws RuntimeException If the property display factory was not previously set.
- * @return FactoryInterface
*/
- protected function getPropertyDisplayFactory()
+ protected function getPropertyDisplayFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->propertyDisplayFactory)) {
+ if (!$this->propertyDisplayFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
- sprintf('Property Display Factory is not defined for "%s"', get_class($this))
+ sprintf('Property Display Factory is not defined for "%s"', static::class)
);
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlySelectInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlySelectInput.php
index cb7b57e45..0e613688b 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlySelectInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/ReadonlySelectInput.php
@@ -1,5 +1,7 @@
p()['allowNull'] && !$this->p()['multiple']) {
@@ -52,6 +51,7 @@ public function choices()
* @param array|object $choice The choice structure.
* @return array|null
*/
+ #[\Override]
protected function parseChoice($ident, $choice)
{
$choice = parent::parseChoice($ident, $choice);
@@ -85,7 +85,7 @@ protected function parseChoice($ident, $choice)
* @param array $settings The select picker options.
* @return Selectinput Chainable
*/
- public function setSelectOptions(array $settings)
+ public function setSelectOptions(array $settings): static
{
$this->selectOptions = array_merge($this->defaultSelectOptions(), $settings);
@@ -98,7 +98,7 @@ public function setSelectOptions(array $settings)
* @param array $settings The select picker options.
* @return Selectinput Chainable
*/
- public function mergeSelectOptions(array $settings)
+ public function mergeSelectOptions(array $settings): static
{
$this->selectOptions = array_merge($this->selectOptions, $settings);
@@ -113,7 +113,7 @@ public function mergeSelectOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return Selectinput Chainable
*/
- public function addSelectOption($key, $val)
+ public function addSelectOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -133,10 +133,8 @@ public function addSelectOption($key, $val)
/**
* Retrieve the select picker's options.
- *
- * @return array
*/
- public function selectOptions()
+ public function selectOptions(): array
{
if ($this->selectOptions === null) {
$this->selectOptions = $this->defaultSelectOptions();
@@ -147,10 +145,8 @@ public function selectOptions()
/**
* Retrieve the default select picker options.
- *
- * @return array
*/
- public function defaultSelectOptions()
+ public function defaultSelectOptions(): array
{
return [
'style' => '',
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/ListInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/ListInput.php
index e6f7887a4..d62ba53b2 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/ListInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/ListInput.php
@@ -1,5 +1,7 @@
inputName) {
- $name = $this->inputName;
- } else {
- $name = $this->propertyIdent();
- }
+ $name = $this->inputName ?: $this->propertyIdent();
if ($this->p()['l10n']) {
$name .= '[' . $this->lang() . ']';
@@ -86,6 +79,7 @@ public function inputName()
* @todo [^1]: With PHP7 we can simply do `yield from $choices;`.
* @return \Generator
*/
+ #[\Override]
public function choices()
{
if ($this->p()['allowNull'] && !$this->p()['multiple']) {
@@ -112,9 +106,8 @@ public function formWidget()
/**
* @param string $formWidget The form widget for object creation and modification.
- * @return self
*/
- public function setFormWidget($formWidget)
+ public function setFormWidget($formWidget): static
{
$this->formWidget = $formWidget;
@@ -125,11 +118,10 @@ public function setFormWidget($formWidget)
* Show/hide the "Copy to Clipboard" button.
*
* @param boolean $flag Show (TRUE) or hide (FALSE) the copy button.
- * @return self
*/
- public function setAllowClipboardCopy($flag)
+ public function setAllowClipboardCopy($flag): static
{
- $this->allowClipboardCopy = !!$flag;
+ $this->allowClipboardCopy = (bool)$flag;
return $this;
}
@@ -152,7 +144,7 @@ public function allowClipboardCopy()
* @param array $settings The selectize picker options.
* @return TagsInput Chainable
*/
- public function setSelectizeOptions(array $settings)
+ public function setSelectizeOptions(array $settings): static
{
$this->selectizeOptions = array_merge(
$this->defaultSelectizeOptions(),
@@ -168,7 +160,7 @@ public function setSelectizeOptions(array $settings)
* @param array $settings The selectize picker options.
* @return TagsInput Chainable
*/
- public function mergeSelectizeOptions(array $settings)
+ public function mergeSelectizeOptions(array $settings): static
{
$this->selectizeOptions = array_merge(
$this->selectizeOptions,
@@ -186,7 +178,7 @@ public function mergeSelectizeOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return self Chainable
*/
- public function addSelectizeOption($key, $val)
+ public function addSelectizeOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -260,10 +252,9 @@ public function selectizeOptionsAsJson()
/**
* Retrieve the default object-to-choice data map.
- *
- * @return array
*/
- public function defaultChoiceObjMap()
+ #[\Override]
+ public function defaultChoiceObjMap(): array
{
return [
'value' => 'id',
@@ -274,10 +265,9 @@ public function defaultChoiceObjMap()
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
- public function controlDataForJs()
+ #[\Override]
+ public function controlDataForJs(): array
{
$prop = $this->property();
@@ -298,11 +288,9 @@ public function controlDataForJs()
'multiple_options' => $this->property()['multipleOptions'],
];
- if ($prop instanceof ObjectProperty) {
- if ($prop['objType']) {
- $data['pattern'] = $prop['pattern'];
- $data['obj_type'] = $prop['objType'];
- }
+ if ($prop instanceof ObjectProperty && $prop['objType']) {
+ $data['pattern'] = $prop['pattern'];
+ $data['obj_type'] = $prop['objType'];
}
return $data;
@@ -314,6 +302,7 @@ public function controlDataForJs()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -326,14 +315,13 @@ protected function setDependencies(Container $container)
* Retrieve the object model factory.
*
* @throws RuntimeException If the model factory was not previously set.
- * @return FactoryInterface
*/
- protected function modelFactory()
+ protected function modelFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->modelFactory)) {
+ if (!$this->modelFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Model Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -346,7 +334,7 @@ protected function modelFactory()
* @param array $settings The selectize picker options.
* @return array Returns the parsed options.
*/
- protected function parseSelectizeOptions(array $settings)
+ protected function parseSelectizeOptions(array $settings): array
{
return $settings;
}
@@ -355,9 +343,8 @@ protected function parseSelectizeOptions(array $settings)
* Set an object model factory.
*
* @param FactoryInterface $factory The model factory, to create objects.
- * @return self
*/
- private function setModelFactory(FactoryInterface $factory)
+ private function setModelFactory(FactoryInterface $factory): static
{
$this->modelFactory = $factory;
@@ -368,9 +355,8 @@ private function setModelFactory(FactoryInterface $factory)
* Set a model collection loader.
*
* @param CollectionLoader $loader The collection loader.
- * @return self
*/
- private function setCollectionLoader(CollectionLoader $loader)
+ private function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
@@ -382,7 +368,7 @@ private function setCollectionLoader(CollectionLoader $loader)
*
* @return CollectionLoader
*/
- private function collectionLoader()
+ private function collectionLoader(): ?\Charcoal\Loader\CollectionLoader
{
return $this->collectionLoader;
}
@@ -392,9 +378,8 @@ private function collectionLoader()
*
* @param mixed $val The value to parse into selectize choices.
* @param array $options Optional structure options.
- * @return array
*/
- private function selectizeVal($val = null, array $options = [])
+ private function selectizeVal($val = null, array $options = []): array
{
/** @todo Find a use for this */
unset($options);
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/Template/SpriteTemplate.php b/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/Template/SpriteTemplate.php
index 0dc45e5ee..0c1d11717 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/Template/SpriteTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/Selectize/Template/SpriteTemplate.php
@@ -30,6 +30,7 @@ class SpriteTemplate extends AbstractTemplate
* @param Container $container A Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -47,9 +48,8 @@ public function showSpriteId()
/**
* @param boolean $flag Show the sprite id besides the icon.
- * @return self
*/
- public function setShowSpriteId($flag)
+ public function setShowSpriteId($flag): static
{
$this->showSpriteId = $flag;
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/SelectizeInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/SelectizeInput.php
index 06f60e543..e707c6db2 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/SelectizeInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/SelectizeInput.php
@@ -48,24 +48,18 @@ class SelectizeInput extends SelectInput
/**
* Store the factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $modelFactory;
+ private ?\Charcoal\Factory\FactoryInterface $modelFactory = null;
/**
* Store the collection loader for the current class.
- *
- * @var CollectionLoader
*/
- private $collectionLoader;
+ private ?\Charcoal\Loader\CollectionLoader $collectionLoader = null;
/**
* Should the object be loaded in deferred mode.
- *
- * @var boolean
*/
- private $deferred;
+ private ?bool $deferred = null;
/**
* Whether to show a button to allow update items.
@@ -104,10 +98,8 @@ class SelectizeInput extends SelectInput
* The form data to use while creating objects through Selectize.
*
* Must be an array
- *
- * @var array|null
*/
- private $formData;
+ private ?array $formData = null;
/**
* Label for the create item dialog.
@@ -130,20 +122,14 @@ class SelectizeInput extends SelectInput
*/
protected $isChoiceObjMapFinalized = false;
- /**
- * @var array
- */
- private $selectizeTemplates;
+ private object|array|null $selectizeTemplates = null;
/**
* @var SelectizeRenderer
*/
private $selectizeRenderer;
- /**
- * @var array
- */
- private $disabledFields = [];
+ private array $disabledFields = [];
/**
* @var string $remoteSource
@@ -162,10 +148,8 @@ class SelectizeInput extends SelectInput
/**
* Check used to parse multi Optgroup map against the obj properties.
- *
- * @var boolean
*/
- private $isOptgroupObjMapFinalized = false;
+ private bool $isOptgroupObjMapFinalized = false;
/**
* This function takes an array and fill the model object with its value.
@@ -179,9 +163,9 @@ class SelectizeInput extends SelectInput
* on the metadata object, because the method `set_foobar()` does not exist.
*
* @param array $data The input data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
// Push selectize options back at the end of the data container.
if (isset($data['selectizeOptions'])) {
@@ -199,14 +183,13 @@ public function setData(array $data)
* Retrieve the object model factory.
*
* @throws RuntimeException If the model factory was not previously set.
- * @return FactoryInterface
*/
- public function modelFactory()
+ public function modelFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->modelFactory)) {
+ if (!$this->modelFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Model Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -217,9 +200,8 @@ public function modelFactory()
* Set a model collection loader.
*
* @param CollectionLoader $loader The collection loader.
- * @return self
*/
- private function setCollectionLoader(CollectionLoader $loader)
+ private function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
@@ -230,14 +212,13 @@ private function setCollectionLoader(CollectionLoader $loader)
* Retrieve the model collection loader.
*
* @throws RuntimeException If the collection loader was not previously set.
- * @return CollectionLoader
*/
- protected function collectionLoader()
+ protected function collectionLoader(): \Charcoal\Loader\CollectionLoader
{
- if (!isset($this->collectionLoader)) {
+ if (!$this->collectionLoader instanceof \Charcoal\Loader\CollectionLoader) {
throw new RuntimeException(sprintf(
'Collection Loader is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -246,10 +227,9 @@ protected function collectionLoader()
/**
* Retrieve the default empty option structure.
- *
- * @return array
*/
- protected function defaultEmptyChoice()
+ #[\Override]
+ protected function defaultEmptyChoice(): array
{
return [
'value' => '',
@@ -265,6 +245,7 @@ protected function defaultEmptyChoice()
* @todo [^1]: With PHP7 we can simply do `yield from $choices;`.
* @return \Generator|array
*/
+ #[\Override]
public function choices()
{
if ($this->p()['allowNull'] && !$this->p()['multiple']) {
@@ -273,11 +254,7 @@ public function choices()
}
// When deferred, we want to fetch choices for current values only.
- if ($this->deferred()) {
- $choices = $this->selectizeVal($this->propertyVal());
- } else {
- $choices = $this->selectizeVal($this->p()->choices());
- }
+ $choices = $this->deferred() ? $this->selectizeVal($this->propertyVal()) : $this->selectizeVal($this->p()->choices());
/* Pass along the Generator from the parent method [^1] */
/* Filter the all options down to those *not* selected */
@@ -291,22 +268,20 @@ public function choices()
/**
* Create an input group to nest extra inputs alongside selectize
- * @return boolean
*/
- public function inputGroup()
+ public function inputGroup(): bool
{
- return !!($this->allowClipboardCopy() || $this->allowUpdate() || $this->allowCreate());
+ return $this->allowClipboardCopy() || $this->allowUpdate() || $this->allowCreate();
}
/**
* Show/hide the "Copy to Clipboard" button.
*
* @param boolean $flag Show (TRUE) or hide (FALSE) the copy button.
- * @return self
*/
- public function setAllowClipboardCopy($flag)
+ public function setAllowClipboardCopy($flag): static
{
- $this->allowClipboardCopy = !!$flag;
+ $this->allowClipboardCopy = (bool)$flag;
return $this;
}
@@ -323,11 +298,10 @@ public function allowClipboardCopy()
/**
* @param boolean $allowUpdate Show (TRUE) or hide (FALSE) the update button.
- * @return self
*/
- public function setAllowUpdate($allowUpdate)
+ public function setAllowUpdate($allowUpdate): static
{
- $this->allowUpdate = !!$allowUpdate;
+ $this->allowUpdate = (bool)$allowUpdate;
return $this;
}
@@ -344,11 +318,10 @@ public function allowUpdate()
/**
* @param boolean $allowCreate Show (TRUE) or hide (FALSE) the create button.
- * @return self
*/
- public function setAllowCreate($allowCreate)
+ public function setAllowCreate($allowCreate): static
{
- $this->allowCreate = !!$allowCreate;
+ $this->allowCreate = (bool)$allowCreate;
return $this;
}
@@ -366,18 +339,17 @@ public function allowCreate()
/**
* @return boolean
*/
- public function deferred()
+ public function deferred(): ?bool
{
return $this->deferred;
}
/**
* @param boolean $deferred Should the object be loaded in deferred mode.
- * @return self
*/
- public function setDeferred($deferred)
+ public function setDeferred($deferred): static
{
- $this->deferred = ($this->property() instanceof ObjectProperty || $this->remoteSource()) ? $deferred : false;
+ $this->deferred = ($this->property() instanceof ObjectProperty || $this->remoteSource()) && $deferred;
return $this;
}
@@ -392,9 +364,8 @@ public function formWidget()
/**
* @param string $formWidget The form widget for object creation and modification.
- * @return self
*/
- public function setFormWidget($formWidget)
+ public function setFormWidget($formWidget): static
{
$this->formWidget = $formWidget;
@@ -411,18 +382,14 @@ public function formIdent()
/**
* @param mixed $formIdent The form ident(s) for object creation and modification.
- * @return self
*/
- public function setFormIdent($formIdent)
+ public function setFormIdent($formIdent): static
{
$this->formIdent = $formIdent;
return $this;
}
- /**
- * @return array|null
- */
public function getFormData(): ?array
{
return $this->formData;
@@ -430,7 +397,6 @@ public function getFormData(): ?array
/**
* @param array|null $formData FormData for SelectizeInput.
- * @return self
*/
public function setFormData(?array $formData): self
{
@@ -451,9 +417,8 @@ public function formIdentAsJson()
* Set the title for the create item dialog.
*
* @param string|string[] $title The dialog title.
- * @return self
*/
- public function setDialogTitleCreate($title)
+ public function setDialogTitleCreate($title): static
{
$this->dialogTitleCreate = $this->translator()->translation($title);
@@ -474,9 +439,8 @@ public function getDialogTitleCreate()
* Set the title for the update item dialog.
*
* @param string|string[] $title The dialog title.
- * @return self
*/
- public function setDialogTitleUpdate($title)
+ public function setDialogTitleUpdate($title): static
{
$this->dialogTitleUpdate = $this->translator()->translation($title);
@@ -501,7 +465,7 @@ public function getDialogTitleUpdate()
* @param array $settings The selectize picker options.
* @return self Chainable
*/
- public function setSelectizeOptions(array $settings)
+ public function setSelectizeOptions(array $settings): static
{
$this->selectizeOptions = array_merge(
$this->defaultSelectizeOptions(),
@@ -517,7 +481,7 @@ public function setSelectizeOptions(array $settings)
* @param array $settings The selectize picker options.
* @return self Chainable
*/
- public function mergeSelectizeOptions(array $settings)
+ public function mergeSelectizeOptions(array $settings): static
{
$this->selectizeOptions = array_merge(
$this->selectizeOptions,
@@ -535,7 +499,7 @@ public function mergeSelectizeOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return self Chainable
*/
- public function addSelectizeOption($key, $val)
+ public function addSelectizeOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -582,11 +546,7 @@ public function defaultSelectizeOptions()
$options = $this->parseSelectizeOptions($options);
}
- if ($this->deferred()) {
- $placeholder = $this->translator()->trans('Search…');
- } else {
- $placeholder = $this->translator()->trans('Select…');
- }
+ $placeholder = $this->deferred() ? $this->translator()->trans('Search…') : $this->translator()->trans('Select…');
$options['placeholder'] = $placeholder;
$prop = $this->property();
@@ -598,7 +558,7 @@ public function defaultSelectizeOptions()
$optgroupProp = $model->p($this->optgroupProperty());
if ($optgroupProp instanceof ObjectProperty) {
- $method = [ $this, 'mapObjToOptgroup' ];
+ $method = $this->mapObjToOptgroup(...);
$loader = $this->collectionLoader()->setModel($optgroupProp['objType']);
@@ -621,7 +581,7 @@ public function defaultSelectizeOptions()
$optgroups = array_values($optgroupProp->choices());
// Make sure label is converted to string.
- array_walk($optgroups, function (&$item) {
+ array_walk($optgroups, function (array &$item): void {
$item['label'] = (string)$item['label'];
});
@@ -632,14 +592,10 @@ public function defaultSelectizeOptions()
if ($prop instanceof SelectablePropertyInterface) {
$choices = iterator_to_array($this->choices());
- if (isset($options['options'])) {
- $options['options'] = array_merge($options['options'], $choices);
- } else {
- $options['options'] = $choices;
- }
+ $options['options'] = isset($options['options']) ? array_merge($options['options'], $choices) : $choices;
// L10n properties is not supported through selectize items array,
- $items = !$prop['l10n'] ? $this->propertyVal() : null;
+ $items = $prop['l10n'] ? null : $this->propertyVal();
if ($items !== null && $prop instanceof AbstractProperty) {
$items = $this->property()->inputVal($items);
@@ -691,7 +647,7 @@ public function selectizeOptionsAsJson()
* @param array $settings The selectize picker options.
* @return array Returns the parsed options.
*/
- protected function parseSelectizeOptions(array $settings)
+ protected function parseSelectizeOptions(array $settings): array
{
// Translate labels
$settings = $this->recursiveTranslation($settings);
@@ -701,9 +657,8 @@ protected function parseSelectizeOptions(array $settings)
/**
* @param array $array The array of possible translation.
- * @return array
*/
- private function recursiveTranslation(array $array)
+ private function recursiveTranslation(array $array): array
{
foreach ($array as &$item) {
if (is_array($item)) {
@@ -719,12 +674,9 @@ private function recursiveTranslation(array $array)
return $array;
}
- /**
- * @return boolean
- */
- public function isObject()
+ public function isObject(): bool
{
- return !!($this->p() instanceof ObjectProperty);
+ return $this->p() instanceof ObjectProperty;
}
/**
@@ -734,13 +686,10 @@ public function isObject()
*
* @return string
*/
+ #[\Override]
public function inputName()
{
- if ($this->inputName) {
- $name = $this->inputName;
- } else {
- $name = $this->propertyIdent();
- }
+ $name = $this->inputName ?: $this->propertyIdent();
if ($this->p()['l10n']) {
$name .= '[' . $this->lang() . ']';
@@ -756,7 +705,7 @@ public function inputName()
/**
* @return array
*/
- public function selectizeTemplates()
+ public function selectizeTemplates(): object|array|null
{
return $this->selectizeTemplates;
}
@@ -764,9 +713,8 @@ public function selectizeTemplates()
/**
* @param array|object|mixed $selectizeTemplates Selectize Templates array.
* @throws \InvalidArgumentException If the supplied argument is not of type object.
- * @return self
*/
- public function setSelectizeTemplates($selectizeTemplates)
+ public function setSelectizeTemplates($selectizeTemplates): static
{
if (!is_object($selectizeTemplates) && !is_array($selectizeTemplates)) {
$selectizeTemplates = [
@@ -795,9 +743,8 @@ public function selectizeTemplatesAsJson()
* @param mixed $val The value to parse into selectize choices.
* @param array $options Optional structure options.
* @throws InvalidArgumentException If the choice structure is missing a value.
- * @return array
*/
- public function selectizeVal($val, array $options = [])
+ public function selectizeVal($val, array $options = []): array
{
/** @todo Find a use for this */
unset($options);
@@ -822,10 +769,10 @@ public function selectizeVal($val, array $options = [])
}
$selectizeTemplates = $this->selectizeTemplates();
- $itemTemplate = isset($selectizeTemplates['item']) ? $selectizeTemplates['item'] : null;
- $optionTemplate = isset($selectizeTemplates['option']) ? $selectizeTemplates['option'] : null;
- $selectizeController = isset($selectizeTemplates['controller']) ? $selectizeTemplates['controller'] : null;
- $selectizeData = isset($selectizeTemplates['data']) ? $selectizeTemplates['data'] : [];
+ $itemTemplate = ($selectizeTemplates['item'] ?? null);
+ $optionTemplate = ($selectizeTemplates['option'] ?? null);
+ $selectizeController = ($selectizeTemplates['controller'] ?? null);
+ $selectizeData = ($selectizeTemplates['data'] ?? []);
if ($prop instanceof ObjectProperty) {
foreach ($val as &$v) {
@@ -945,6 +892,7 @@ public function sortObjects($objects)
*
* @return array Returns a data map to abide.
*/
+ #[\Override]
public function choiceObjMap()
{
$map = parent::choiceObjMap();
@@ -963,7 +911,7 @@ public function choiceObjMap()
}
foreach ($map as &$mapProp) {
- $props = explode(':', $mapProp);
+ $props = explode(':', (string)$mapProp);
foreach ($props as $p) {
if (isset($objProperties[$p])) {
$mapProp = $p;
@@ -981,10 +929,9 @@ public function choiceObjMap()
/**
* Retrieve the default object-to-choice data map.
- *
- * @return array
*/
- public function defaultChoiceObjMap()
+ #[\Override]
+ public function defaultChoiceObjMap(): array
{
return [
'value' => 'id',
@@ -995,9 +942,8 @@ public function defaultChoiceObjMap()
/**
* @param array|\ArrayAccess|ModelInterface $obj The object to map to a optgroup.
- * @return array
*/
- public function mapObjToOptgroup($obj)
+ public function mapObjToOptgroup($obj): array
{
$map = $this->optgroupObjMap();
@@ -1029,9 +975,8 @@ public function optgroupObjMap()
/**
* @param array|null $optgroupObjMap OptgroupObjMap for SelectizeInput.
- * @return self
*/
- public function setOptgroupObjMap($optgroupObjMap)
+ public function setOptgroupObjMap($optgroupObjMap): static
{
$map = $optgroupObjMap ?: $this->defaultOptgroupObjMap();
@@ -1057,7 +1002,7 @@ public function setOptgroupObjMap($optgroupObjMap)
}
foreach ($map as &$mapProp) {
- $props = explode(':', $mapProp);
+ $props = explode(':', (string)$mapProp);
foreach ($props as $p) {
if (isset($objProperties[$p])) {
$mapProp = $p;
@@ -1077,10 +1022,8 @@ public function setOptgroupObjMap($optgroupObjMap)
/**
* Retrieve the default object-to-optgroup data map.
- *
- * @return array
*/
- public function defaultOptgroupObjMap()
+ public function defaultOptgroupObjMap(): array
{
return [
'value' => 'id',
@@ -1091,10 +1034,9 @@ public function defaultOptgroupObjMap()
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
- public function controlDataForJs()
+ #[\Override]
+ public function controlDataForJs(): array
{
$prop = $this->property();
@@ -1130,29 +1072,23 @@ public function controlDataForJs()
'multiple_options' => $this->property()['multipleOptions'],
];
- if ($prop instanceof ObjectProperty) {
- if ($prop['objType']) {
- $data['pattern'] = $prop['pattern'];
- $data['obj_type'] = $prop['objType'];
- }
+ if ($prop instanceof ObjectProperty && $prop['objType']) {
+ $data['pattern'] = $prop['pattern'];
+ $data['obj_type'] = $prop['objType'];
}
return $data;
}
- /**
- * @return array
- */
- public function disabledFields()
+ public function disabledFields(): array
{
return $this->disabledFields;
}
/**
* @param array $disabledFields DisabledFields for SelectizeInput.
- * @return self
*/
- public function setDisabledFields(array $disabledFields)
+ public function setDisabledFields(array $disabledFields): static
{
$this->disabledFields = $disabledFields;
@@ -1169,9 +1105,8 @@ public function remoteSource()
/**
* @param string $remoteSource RemoteSource for SelectizeInput.
- * @return self
*/
- public function setRemoteSource($remoteSource)
+ public function setRemoteSource($remoteSource): static
{
$this->remoteSource = $remoteSource;
@@ -1192,9 +1127,8 @@ public function optgroupProperty()
/**
* @param string|null $optgroupProperty OptgroupProperty for SelectizeInput.
- * @return self
*/
- public function setOptgroupProperty($optgroupProperty)
+ public function setOptgroupProperty($optgroupProperty): static
{
$this->optgroupProperty = $optgroupProperty;
@@ -1207,6 +1141,7 @@ public function setOptgroupProperty($optgroupProperty)
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/StructureWidgetInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/StructureWidgetInput.php
index 7561e3057..4bd467e07 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/StructureWidgetInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/StructureWidgetInput.php
@@ -20,6 +20,7 @@ class StructureWidgetInput extends NestedWidgetInput
* @throws DomainException If the widget is not a structure widget.
* @return WidgetInterface
*/
+ #[\Override]
protected function createWidget()
{
$widget = parent::createWidget();
@@ -30,7 +31,7 @@ protected function createWidget()
throw new DomainException(sprintf(
'Widget must an instance of %s, received %s',
StructureFormGroup::class,
- get_class($widget)
+ $widget::class
));
}
@@ -39,10 +40,9 @@ protected function createWidget()
/**
* Retrieve the default structure widget options.
- *
- * @return array
*/
- public function defaultWidgetData()
+ #[\Override]
+ public function defaultWidgetData(): array
{
return [
'type' => StructureFormGroup::class
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/SwitchInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/SwitchInput.php
index d89ea67df..927ef3a83 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/SwitchInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/SwitchInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ public function type(): string
{
return 'checkbox';
}
- /**
- * @return boolean
- */
- public function checked()
+ public function checked(): bool
{
- return !!$this->inputVal();
+ return (bool)$this->inputVal();
}
- /**
- * @return integer
- */
- public function value()
+ public function value(): int
{
return $this->inputVal() ? 1 : 0;
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/TabulatorInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/TabulatorInput.php
index b767638a5..e2e69cf67 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/TabulatorInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/TabulatorInput.php
@@ -27,6 +27,7 @@ class TabulatorInput extends AbstractPropertyInput
*
* @param array $options The input options.
*/
+ #[\Override]
public function setInputOptions(array $options): self
{
parent::setInputOptions($options);
@@ -79,6 +80,7 @@ public function addInputOption(string $key, $val): self
*
* @return array
*/
+ #[\Override]
public function getDefaultInputOptions(): array
{
$translator = $this->translator();
@@ -175,9 +177,8 @@ public function getDefaultTabulatorOptions(): array
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
+ #[\Override]
public function controlDataForJs(): array
{
$inputOptions = $this->getInputOptions();
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/TextInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/TextInput.php
index d314e9211..506ce455e 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/TextInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/TextInput.php
@@ -10,10 +10,7 @@
*/
class TextInput extends AbstractPropertyInput
{
- /**
- * @var integer $size
- */
- private $size = 0;
+ private int $size = 0;
/**
* The minimum number of characters allowed.
@@ -21,10 +18,8 @@ class TextInput extends AbstractPropertyInput
* Note:
* - In Unicode code points.
* - If zero or a negative value is specified, the length is ignored.
- *
- * @var integer
*/
- private $minLength = 0;
+ private int $minLength = 0;
/**
* The maximum number of characters allowed.
@@ -33,22 +28,15 @@ class TextInput extends AbstractPropertyInput
* - In UTF-16 code units.
* - If it is not specified, the control allows an unlimited number of characters.
* - If zero or a negative value is specified, the length is ignored.
- *
- * @var integer
*/
- private $maxLength = 0;
+ private int $maxLength = 0;
- /**
- * @var string $pattern
- */
- private $pattern = '';
+ private string $pattern = '';
/**
* Retrieve the control type for the HTML element ``.
- *
- * @return string
*/
- public function type()
+ public function type(): string
{
return 'text';
}
@@ -61,7 +49,8 @@ public function type()
* @see AbstractPropertyInput::inputVal()
* @return string
*/
- public function inputVal()
+ #[\Override]
+ public function inputVal(): ?string
{
return preg_replace('~[\n\r]~', '', parent::inputVal());
}
@@ -71,7 +60,7 @@ public function inputVal()
* @throws InvalidArgumentException If the argument is not a number.
* @return Text Chainable
*/
- public function setMinLength($minLength)
+ public function setMinLength($minLength): static
{
if (!is_numeric($minLength)) {
throw new InvalidArgumentException(
@@ -83,10 +72,7 @@ public function setMinLength($minLength)
return $this;
}
- /**
- * @return integer
- */
- public function minLength()
+ public function minLength(): int
{
return $this->minLength;
}
@@ -96,7 +82,7 @@ public function minLength()
* @throws InvalidArgumentException If the argument is not a number.
* @return Text Chainable
*/
- public function setMaxLength($maxLength)
+ public function setMaxLength($maxLength): static
{
if (!is_numeric($maxLength)) {
throw new InvalidArgumentException(
@@ -108,10 +94,7 @@ public function setMaxLength($maxLength)
return $this;
}
- /**
- * @return integer
- */
- public function maxLength()
+ public function maxLength(): int
{
return $this->maxLength;
}
@@ -121,7 +104,7 @@ public function maxLength()
* @throws InvalidArgumentException If the argument is not a number.
* @return Text Chainable
*/
- public function setSize($size)
+ public function setSize($size): static
{
if (!is_numeric($size)) {
throw new InvalidArgumentException(
@@ -132,10 +115,7 @@ public function setSize($size)
return $this;
}
- /**
- * @return integer
- */
- public function size()
+ public function size(): int
{
return $this->size;
}
@@ -145,7 +125,7 @@ public function size()
* @throws InvalidArgumentException If the argument is not a string.
* @return Text Chainable
*/
- public function setPattern($pattern)
+ public function setPattern($pattern): static
{
if (!is_string($pattern)) {
throw new InvalidArgumentException(
@@ -156,20 +136,16 @@ public function setPattern($pattern)
return $this;
}
- /**
- * @return string
- */
- public function pattern()
+ public function pattern(): string
{
return $this->pattern;
}
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
- public function controlDataForJs()
+ #[\Override]
+ public function controlDataForJs(): array
{
return [
// Text Control
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/TextareaInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/TextareaInput.php
index 03f0432d0..15a83a1a9 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/TextareaInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/TextareaInput.php
@@ -1,5 +1,7 @@
cols;
}
@@ -60,7 +50,7 @@ public function cols()
* @throws InvalidArgumentException If the argument is not a number.
* @return Text Chainable
*/
- public function setRows($rows)
+ public function setRows($rows): static
{
if (!is_numeric($rows)) {
throw new InvalidArgumentException(
@@ -74,7 +64,7 @@ public function setRows($rows)
/**
* @return integer
*/
- public function rows()
+ public function rows(): ?int
{
return $this->rows;
}
@@ -84,7 +74,7 @@ public function rows()
* @throws InvalidArgumentException If the argument is not a number.
* @return Text Chainable
*/
- public function setMinLength($minLength)
+ public function setMinLength($minLength): static
{
if (!is_numeric($minLength)) {
throw new InvalidArgumentException(
@@ -95,10 +85,7 @@ public function setMinLength($minLength)
return $this;
}
- /**
- * @return integer
- */
- public function minLength()
+ public function minLength(): int
{
return $this->minLength;
}
@@ -108,7 +95,7 @@ public function minLength()
* @throws InvalidArgumentException If the argument is not a number.
* @return Text Chainable
*/
- public function setMaxLength($maxLength)
+ public function setMaxLength($maxLength): static
{
if (!is_numeric($maxLength)) {
throw new InvalidArgumentException(
@@ -119,9 +106,7 @@ public function setMaxLength($maxLength)
return $this;
}
- /**
- * @return array
- */
+ #[\Override]
public function getInputValOptions(): array
{
return [
@@ -129,10 +114,7 @@ public function getInputValOptions(): array
];
}
- /**
- * @return integer
- */
- public function maxLength()
+ public function maxLength(): int
{
return $this->maxLength;
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/Tinymce/BasicInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/Tinymce/BasicInput.php
index 9875f5ebe..887f38960 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/Tinymce/BasicInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/Tinymce/BasicInput.php
@@ -15,7 +15,7 @@ class BasicInput extends TinymceInput
*
* @param array $data Dependencies.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
parent::__construct($data);
@@ -25,10 +25,8 @@ public function __construct(array $data = null)
}
}
- /**
- * @return string
- */
- public function inputType()
+ #[\Override]
+ public function inputType(): string
{
return 'charcoal/admin/property/input/tinymce';
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/TinymceInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/TinymceInput.php
index e0e6fb396..713cb7724 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/TinymceInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/TinymceInput.php
@@ -4,7 +4,7 @@
use InvalidArgumentException;
// From Mustache
-use Mustache_LambdaHelper as LambdaHelper;
+use Mustache\LambdaHelper as LambdaHelper;
// From 'charcoal-admin'
use Charcoal\Admin\Property\Input\TextareaInput;
@@ -29,10 +29,8 @@ class TinymceInput extends TextareaInput
/**
* Flag wether the "file picker" popup button should be displaed.
- *
- * @var boolean
*/
- private $showFilePicker;
+ private ?bool $showFilePicker = null;
/**
* URL for the "file picker" popup.
@@ -49,7 +47,7 @@ class TinymceInput extends TextareaInput
* @param array $settings The editor options.
* @return Tinymce Chainable
*/
- public function setEditorOptions(array $settings)
+ public function setEditorOptions(array $settings): static
{
$this->editorOptions = array_merge($this->defaultEditorOptions(), $settings);
@@ -62,7 +60,7 @@ public function setEditorOptions(array $settings)
* @param array $settings The editor options.
* @return Tinymce Chainable
*/
- public function mergeEditorOptions(array $settings)
+ public function mergeEditorOptions(array $settings): static
{
$this->editorOptions = array_merge($this->editorOptions, $settings);
@@ -77,7 +75,7 @@ public function mergeEditorOptions(array $settings)
* @throws InvalidArgumentException If the identifier is not a string.
* @return Tinymce Chainable
*/
- public function addEditorOption($key, $val)
+ public function addEditorOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -118,11 +116,7 @@ public function defaultEditorOptions()
{
$defaultData = $this->metadata()->defaultData();
- if (isset($defaultData['editor_options'])) {
- return $defaultData['editor_options'];
- }
-
- return [];
+ return ($defaultData['editor_options'] ?? []);
}
/**
@@ -139,9 +133,8 @@ public function editorOptionsAsJson()
* Set the title for the file picker dialog.
*
* @param mixed $title The dialog title.
- * @return self
*/
- public function setDialogTitle($title)
+ public function setDialogTitle($title): static
{
$this->dialogTitle = $this->translator()->translation($title);
@@ -153,7 +146,7 @@ public function setDialogTitle($title)
*
* @return \Charcoal\Translator\Translation|string|null
*/
- protected function defaultDialogTitle()
+ protected function defaultDialogTitle(): ?\Charcoal\Translator\Translation
{
return $this->translator()->translation('filesystem.library.media');
}
@@ -176,9 +169,9 @@ public function dialogTitle()
* @param boolean $show The show file picker flag.
* @return FileInput Chainable
*/
- public function setShowFilePicker($show)
+ public function setShowFilePicker($show): static
{
- $this->showFilePicker = !!$show;
+ $this->showFilePicker = (bool)$show;
return $this;
}
@@ -195,10 +188,7 @@ public function showFilePicker()
return $this->showFilePicker;
}
- /**
- * @return boolean
- */
- public function hasFilePicker()
+ public function hasFilePicker(): bool
{
return class_exists('\\elFinder');
}
@@ -207,7 +197,7 @@ public function hasFilePicker()
* @param string $url The file picker AJAX URL.
* @return FileInput Chainable
*/
- public function setFilePickerUrl($url)
+ public function setFilePickerUrl($url): static
{
$this->filePickerUrl = $url;
return $this;
@@ -235,7 +225,7 @@ public function filePickerUrl()
*
* @return callable|null
*/
- public function prepareFilePickerUrl()
+ public function prepareFilePickerUrl(): ?\Closure
{
if (!$this->showFilePicker()) {
return null;
@@ -243,7 +233,7 @@ public function prepareFilePickerUrl()
$uri = $this->getFilePickerUrlTemplate();
- return function ($noop, LambdaHelper $helper) use ($uri) {
+ return function ($noop, LambdaHelper $helper) use ($uri): null {
$uri = $helper->render($uri);
$this->setFilePickerUrl($uri);
@@ -253,23 +243,19 @@ public function prepareFilePickerUrl()
/**
* Retrieve the elFinder connector URL template for rendering.
- *
- * @return string
*/
- protected function getFilePickerUrlTemplate()
+ protected function getFilePickerUrlTemplate(): string
{
$uri = 'obj_type={{ objType }}&obj_id={{ objId }}&property={{ p.ident }}&callback={{ inputId }}';
- $uri = '{{# withAdminUrl }}elfinder?' . $uri . '{{/ withAdminUrl }}';
- return $uri;
+ return '{{# withAdminUrl }}elfinder?' . $uri . '{{/ withAdminUrl }}';
}
/**
* Retrieve the control's data options for JavaScript components.
- *
- * @return array
*/
- public function controlDataForJs()
+ #[\Override]
+ public function controlDataForJs(): array
{
return [
'editor_options' => $this->editorOptions(),
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/UrlInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/UrlInput.php
index bb8ea6d70..a5ad5829a 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/UrlInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/UrlInput.php
@@ -1,5 +1,7 @@
`.
- *
- * @return string
*/
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'url';
}
diff --git a/packages/admin/src/Charcoal/Admin/Property/Input/VideoInput.php b/packages/admin/src/Charcoal/Admin/Property/Input/VideoInput.php
index 0b58728c6..f0a5645b0 100644
--- a/packages/admin/src/Charcoal/Admin/Property/Input/VideoInput.php
+++ b/packages/admin/src/Charcoal/Admin/Property/Input/VideoInput.php
@@ -12,18 +12,15 @@ class VideoInput extends FileInput
{
/**
* Retrieve list of default file type specifiers.
- *
- * @return string
*/
- public function getDefaultAccept()
+ #[\Override]
+ public function getDefaultAccept(): string
{
return 'video/*';
}
- /**
- * @return string|null
- */
- public function filePreview()
+ #[\Override]
+ public function filePreview(): string
{
$value = $this->inputVal();
if ($value) {
diff --git a/packages/admin/src/Charcoal/Admin/Property/PropertyDisplayInterface.php b/packages/admin/src/Charcoal/Admin/Property/PropertyDisplayInterface.php
index 5c3fa340d..30acfadd7 100644
--- a/packages/admin/src/Charcoal/Admin/Property/PropertyDisplayInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Property/PropertyDisplayInterface.php
@@ -1,5 +1,7 @@
'now'
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
@@ -78,7 +76,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$this->startLock();
- $climate = $this->climate();
+ $this->climate();
$frequency = $this->frequency();
@@ -101,6 +99,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @param Container $container Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -141,7 +140,7 @@ abstract protected function emailData(Notification $notification, array $objects
* @param string $frequency The frequency type to load.
* @return Charcoal\Model\CollectionInterface
*/
- private function loadNotifications($frequency)
+ private function loadNotifications($frequency): \ArrayAccess|array
{
$loader = new CollectionLoader([
'logger' => $this->logger,
@@ -152,35 +151,33 @@ private function loadNotifications($frequency)
'property' => 'frequency',
'val' => $frequency
]);
- $notifications = $loader->load();
- return $notifications;
+ return $loader->load();
}
/**
* Handle a notification request
*
* @param Notification $notification The notification object to handle.
- * @return void
*/
- private function handleNotification(Notification $notification)
+ private function handleNotification(Notification $notification): void
{
- if (empty($notification->targetTypes())) {
+ if (in_array($notification->targetTypes(), [null, []], true)) {
return;
}
$objectsByTypes = [];
$numTotal = 0;
foreach ($notification->targetTypes() as $objType) {
- $objType = trim($objType);
+ $objType = trim((string)$objType);
$objects = $this->updatedObjects($objType);
$num = count($objects);
- if ($num == 0) {
+ if ($num === 0) {
continue;
}
$obj = [];
$obj['objects'] = $objects;
$obj['num'] = $num;
$obj['type'] = $objType;
- $obj['typeLabel'] = isset($objects[0]['targetTypeLabel']) ? $objects[0]['targetTypeLabel'] : $objType;
+ $obj['typeLabel'] = ($objects[0]['targetTypeLabel'] ?? $objType);
$objectsByTypes[$objType] = $obj;
$numTotal += $num;
@@ -192,11 +189,10 @@ private function handleNotification(Notification $notification)
* @param Notification $notification The notification object.
* @param array $objects The objects that were modified.
* @param integer $numTotal Total number of modified objects.
- * @return void
*/
- private function sendEmail(Notification $notification, array $objects, $numTotal)
+ private function sendEmail(Notification $notification, array $objects, int $numTotal): void
{
- if ($numTotal == 0) {
+ if ($numTotal === 0) {
return;
}
@@ -237,7 +233,7 @@ private function sendEmail(Notification $notification, array $objects, $numTotal
* @param string $objType The object (target) type to process.
* @return CollectionInterface
*/
- private function updatedObjects($objType)
+ private function updatedObjects(string $objType): \ArrayAccess|array
{
$loader = new CollectionLoader([
'logger' => $this->logger,
@@ -266,7 +262,7 @@ private function updatedObjects($objType)
$userFactory = $this->userFactory;
$baseUrl = $this->baseUrl();
- $loader->setCallback(function (&$obj) use ($objFactory, $userFactory, $baseUrl) {
+ $loader->setCallback(function (array &$obj) use ($objFactory, $userFactory, $baseUrl): void {
$diff = $obj->dataDiff();
$obj->updatedProperties = isset($diff[0]) ? array_keys($diff[0]) : [];
$obj->dateStr = $obj['rev_ts']->format('Y-m-d H:i:s');
@@ -296,9 +292,8 @@ private function updatedObjects($objType)
/**
* @param FactoryInterface $factory The factory used to create queue items.
- * @return void
*/
- private function setNotificationFactory(FactoryInterface $factory)
+ private function setNotificationFactory(FactoryInterface $factory): void
{
$this->notificationFactory = $factory;
}
@@ -306,16 +301,15 @@ private function setNotificationFactory(FactoryInterface $factory)
/**
* @return FactoryInterface
*/
- private function notificationFactory()
+ private function notificationFactory(): ?\Charcoal\Factory\FactoryInterface
{
return $this->notificationFactory;
}
/**
* @param FactoryInterface $factory The factory used to create queue items.
- * @return void
*/
- private function setRevisionFactory(FactoryInterface $factory)
+ private function setRevisionFactory(FactoryInterface $factory): void
{
$this->revisionFactory = $factory;
}
diff --git a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessDailyScript.php b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessDailyScript.php
index ad5987bcc..495887fae 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessDailyScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessDailyScript.php
@@ -1,5 +1,7 @@
setTime(0, 0, 0);
@@ -35,9 +34,8 @@ protected function startDate()
/**
* Retrieve the "maximal" date that the revisions should have been made for this script.
- * @return DateTime
*/
- protected function endDate()
+ protected function endDate(): \DateTime
{
$d = new DateTime('today');
$d->setTime(0, 0, 0);
@@ -47,9 +45,8 @@ protected function endDate()
/**
* @param Notification $notification The notification object.
* @param array $objects The objects that were modified.
- * @return array
*/
- protected function emailData(Notification $notification, array $objects)
+ protected function emailData(Notification $notification, array $objects): array
{
unset($notification, $objects);
diff --git a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessHourlyScript.php b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessHourlyScript.php
index 97e6f4be6..17d7d1bfa 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessHourlyScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessHourlyScript.php
@@ -14,19 +14,16 @@ class ProcessHourlyScript extends AbstractNotificationScript
{
/**
* Get the frequency type of this script.
- *
- * @return string
*/
- protected function frequency()
+ protected function frequency(): string
{
return 'hourly';
}
/**
- * Retrieve the "minimal" date that the revisions should have been made for this script.
- * @return DateTime
- */
- protected function startDate()
+ * Retrieve the "minimal" date that the revisions should have been made for this script.
+ */
+ protected function startDate(): \DateTime
{
$d = new DateTime('1 hour ago');
$d->setTime($d->format('H'), 0, 0);
@@ -35,9 +32,8 @@ protected function startDate()
/**
* Retrieve the "maximal" date that the revisions should have been made for this script.
- * @return DateTime
*/
- protected function endDate()
+ protected function endDate(): \DateTime
{
$d = new DateTime('now');
$d->setTime($d->format('H'), 0, 0);
@@ -47,9 +43,8 @@ protected function endDate()
/**
* @param Notification $notification The notification object.
* @param array $objects The objects that were modified.
- * @return array
*/
- protected function emailData(Notification $notification, array $objects)
+ protected function emailData(Notification $notification, array $objects): array
{
unset($notification, $objects);
diff --git a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMinuteScript.php b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMinuteScript.php
index b250536ec..7063820ca 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMinuteScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMinuteScript.php
@@ -14,19 +14,16 @@ class ProcessMinuteScript extends AbstractNotificationScript
{
/**
* Get the frequency type of this script.
- *
- * @return string
*/
- protected function frequency()
+ protected function frequency(): string
{
return 'minute';
}
/**
* Retrieve the "minimal" date that the revisions should have been made for this script.
- * @return DateTime
*/
- protected function startDate()
+ protected function startDate(): \DateTime
{
$d = new DateTime('1 minute ago');
$d->setTime(0, 0, 0);
@@ -35,20 +32,17 @@ protected function startDate()
/**
* Retrieve the "maximal" date that the revisions should have been made for this script.
- * @return DateTime
*/
- protected function endDate()
+ protected function endDate(): \DateTime
{
- $d = new DateTime($this->starDate() . ' +1 minute');
- return $d;
+ return new DateTime($this->starDate() . ' +1 minute');
}
/**
* @param Notification $notification The notification object.
* @param array $objects The objects that were modified.
- * @return array
*/
- protected function emailData(Notification $notification, array $objects)
+ protected function emailData(Notification $notification, array $objects): array
{
unset($notification, $objects);
diff --git a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMonthlyScript.php b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMonthlyScript.php
index 12ceaf6bd..62c4ee275 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMonthlyScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessMonthlyScript.php
@@ -1,5 +1,7 @@
setTime(0, 0, 0);
@@ -35,9 +34,8 @@ protected function startDate()
/**
* Retrieve the "minimal" date that the revisions should have been made for this script.
- * @return DateTime
*/
- protected function endDate()
+ protected function endDate(): \DateTime
{
$d = new DateTime('first day of this month');
$d->setTime(0, 0, 0);
@@ -47,9 +45,8 @@ protected function endDate()
/**
* @param Notification $notification The notification object.
* @param array $objects The objects that were modified.
- * @return array
*/
- protected function emailData(Notification $notification, array $objects)
+ protected function emailData(Notification $notification, array $objects): array
{
unset($notification, $objects);
diff --git a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessWeeklyScript.php b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessWeeklyScript.php
index 47f95d6be..eafe5fa14 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessWeeklyScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Notification/ProcessWeeklyScript.php
@@ -1,5 +1,7 @@
setTime(0, 0, 0);
@@ -35,9 +34,8 @@ protected function startDate()
/**
* Retrieve the "maximal" date that the revisions should have been made for this script.
- * @return DateTime
*/
- protected function endDate()
+ protected function endDate(): \DateTime
{
$d = new DateTime('last monday');
$d->setTime(0, 0, 0);
@@ -47,9 +45,8 @@ protected function endDate()
/**
* @param Notification $notification The notification object.
* @param array $objects The objects that were modified.
- * @return array
*/
- protected function emailData(Notification $notification, array $objects)
+ protected function emailData(Notification $notification, array $objects): array
{
unset($notification, $objects);
diff --git a/packages/admin/src/Charcoal/Admin/Script/Object/CreateScript.php b/packages/admin/src/Charcoal/Admin/Script/Object/CreateScript.php
index 56e5a7a66..0a38cbc72 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Object/CreateScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Object/CreateScript.php
@@ -13,10 +13,8 @@
*/
class CreateScript extends AdminScript
{
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'obj-type' => [
@@ -30,17 +28,14 @@ public function defaultArguments()
'defaultValue' => ''
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
diff --git a/packages/admin/src/Charcoal/Admin/Script/Object/ProcessSchedulesScript.php b/packages/admin/src/Charcoal/Admin/Script/Object/ProcessSchedulesScript.php
index e2740c42b..3402f9447 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Object/ProcessSchedulesScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Object/ProcessSchedulesScript.php
@@ -26,15 +26,10 @@ class ProcessSchedulesScript extends AdminScript implements CronScriptInterface
{
use CronScriptTrait;
- /**
- * @var FactoryInterface $scheduleFactory
- */
- private $scheduleFactory;
+ private ?\Charcoal\Factory\FactoryInterface $scheduleFactory = null;
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'obj-type' => [
@@ -49,17 +44,14 @@ public function defaultArguments()
'defaultValue' => ''
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -72,17 +64,17 @@ public function run(RequestInterface $request, ResponseInterface $response)
$scheduled = $this->loadSchedules($objType, $objId);
- $callback = function ($obj) use ($climate) {
+ $callback = function ($obj): void {
// No default callback
};
- $successCallback = function ($obj) use ($climate) {
+ $successCallback = function ($obj) use ($climate): void {
$climate->green()->out(
sprintf('Object %s : %s schedule was successfully ran.', $obj->targetType(), $obj->targetId())
);
};
- $failureCallback = function ($obj) use ($climate) {
+ $failureCallback = function ($obj) use ($climate): void {
$climate->red()->out(
sprintf('Object %s : %s schedule could not be ran.', $obj->targetType(), $obj->targetId())
);
@@ -102,6 +94,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @param Container $container Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -112,16 +105,15 @@ protected function setDependencies(Container $container)
/**
* @return FactoryInterface
*/
- protected function scheduleFactory()
+ protected function scheduleFactory(): ?\Charcoal\Factory\FactoryInterface
{
return $this->scheduleFactory;
}
/**
* @param FactoryInterface $factory The factory used to create queue items.
- * @return void
*/
- private function setScheduleFactory(FactoryInterface $factory)
+ private function setScheduleFactory(FactoryInterface $factory): void
{
$this->scheduleFactory = $factory;
}
@@ -139,7 +131,7 @@ private function scheduleProto()
* @param string $objId Optional object id to loader.
* @return \Charcoal\Model\Collection|array
*/
- private function loadSchedules($objType = null, $objId = null)
+ private function loadSchedules($objType = null, $objId = null): \ArrayAccess|array
{
$loader = new CollectionLoader([
'logger' => $this->logger,
@@ -173,7 +165,6 @@ private function loadSchedules($objType = null, $objId = null)
'property' => 'scheduled_date',
'mode' => 'asc'
]);
- $schedules = $loader->load();
- return $schedules;
+ return $loader->load();
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterPrimaryKeyScript.php b/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterPrimaryKeyScript.php
index e80af22d9..69b27ed14 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterPrimaryKeyScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterPrimaryKeyScript.php
@@ -78,6 +78,7 @@ class AlterPrimaryKeyScript extends AdminScript
/**
* @return void
*/
+ #[\Override]
protected function init()
{
parent::init();
@@ -93,9 +94,8 @@ protected function init()
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -110,10 +110,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
/**
* Execute the prime directive.
- *
- * @return self
*/
- public function start()
+ public function start(): static
{
$cli = $this->climate();
@@ -235,7 +233,7 @@ public function start()
* @throws RuntimeException If the $oldKey does not exist.
* @return IdProperty[]
*/
- protected function prepareProperties($oldKey, $newKey, &$oldProp = null, &$newProp = null)
+ protected function prepareProperties($oldKey, $newKey, &$oldProp = null, &$newProp = null): array
{
$model = $this->targetModel();
$source = $model->source();
@@ -282,11 +280,11 @@ protected function prepareProperties($oldKey, $newKey, &$oldProp = null, &$newPr
);
}
- if (preg_match('~\bINT\(?(?:$|\b)~i', $col['Type'])) {
+ if (preg_match('~\bINT\(?(?:$|\b)~i', (string)$col['Type'])) {
$oldProp->setMode(IdProperty::MODE_AUTO_INCREMENT);
- } elseif (preg_match('~(?:^|\b)(?:VAR)?CHAR\(13\)(?:$|\b)~i', $col['Type'])) {
+ } elseif (preg_match('~(?:^|\b)(?:VAR)?CHAR\(13\)(?:$|\b)~i', (string)$col['Type'])) {
$oldProp->setMode(IdProperty::MODE_UNIQID);
- } elseif (preg_match('~(?:^|\b)(?:VAR)?CHAR\(36\)(?:$|\b)~i', $col['Type'])) {
+ } elseif (preg_match('~(?:^|\b)(?:VAR)?CHAR\(36\)(?:$|\b)~i', (string)$col['Type'])) {
$oldProp->setMode(IdProperty::MODE_UUID);
} else {
$oldProp->setMode(IdProperty::MODE_CUSTOM);
@@ -299,7 +297,7 @@ protected function prepareProperties($oldKey, $newKey, &$oldProp = null, &$newPr
throw new RuntimeException(
sprintf(
'The model [%1$s] does not have the target field [%2$s]',
- get_class($model),
+ $model::class,
$oldKey
)
);
@@ -316,41 +314,30 @@ protected function prepareProperties($oldKey, $newKey, &$oldProp = null, &$newPr
*
* @param string|IdProperty $mode The mode or property to resolve.
* @throws UnexpectedValueException If the ID mode is invalid.
- * @return string
*/
- protected function labelFromMode($mode)
+ protected function labelFromMode($mode): string
{
if ($mode instanceof IdProperty) {
$mode = $mode->getMode();
}
-
- switch ($mode) {
- case IdProperty::MODE_AUTO_INCREMENT:
- return 'auto-increment';
-
- case IdProperty::MODE_UNIQID:
- return 'uniqid()';
-
- case IdProperty::MODE_UUID:
- return 'RFC-4122 UUID';
-
- case IdProperty::MODE_CUSTOM:
- return 'custom';
- }
-
- throw new UnexpectedValueException(sprintf(
- 'The ID mode was not recognized: %s',
- is_object($mode) ? get_class($mode) : gettype($mode)
- ));
+ return match ($mode) {
+ IdProperty::MODE_AUTO_INCREMENT => 'auto-increment',
+ IdProperty::MODE_UNIQID => 'uniqid()',
+ IdProperty::MODE_UUID => 'RFC-4122 UUID',
+ IdProperty::MODE_CUSTOM => 'custom',
+ default => throw new UnexpectedValueException(sprintf(
+ 'The ID mode was not recognized: %s',
+ get_debug_type($mode)
+ )),
+ };
}
/**
* Retrieve a label for the property.
*
* @param IdProperty $prop The new ID property to analyse.
- * @return string|null
*/
- protected function labelFromProp(IdProperty $prop)
+ protected function labelFromProp(IdProperty $prop): ?string
{
$mode = $prop->getMode();
switch ($mode) {
@@ -362,7 +349,7 @@ protected function labelFromProp(IdProperty $prop)
default:
$label = $this->labelFromMode($mode);
- if ($label) {
+ if ($label !== '' && $label !== '0') {
return sprintf('auto-generated ID (%s)', $label);
} else {
return 'auto-generated ID';
@@ -377,11 +364,10 @@ protected function labelFromProp(IdProperty $prop)
*
* @param IdProperty $newProp The new ID property to analyse.
* @param IdProperty $oldProp The previous ID property to analyse.
- * @return self
*/
- protected function describeConversion(IdProperty $newProp, IdProperty $oldProp = null)
+ protected function describeConversion(IdProperty $newProp, ?IdProperty $oldProp = null): static
{
- if ($oldProp) {
+ if ($oldProp instanceof \Charcoal\Property\IdProperty) {
$new = $this->labelFromProp($newProp);
$old = $this->labelFromProp($oldProp);
$desc = sprintf('Converting to %s from %s.', $new, $old);
@@ -401,7 +387,7 @@ protected function describeConversion(IdProperty $newProp, IdProperty $oldProp =
* @param IdProperty $prop The property to retrieve the field from.
* @return PropertyField
*/
- protected function propertyField(IdProperty $prop)
+ protected function propertyField(IdProperty $prop): \Charcoal\Property\PropertyField|false
{
$fields = $prop->fields();
@@ -447,12 +433,7 @@ private function isPrimaryKeyDifferent()
private function oldPrimaryKey()
{
if ($this->oldPrimaryKey === null) {
- if ($this->isPrimaryKeyDifferent()) {
- $oldKey = $this->climate()->arguments->get('old_key');
- } else {
- $oldKey = $this->targetModel()->key();
- }
-
+ $oldKey = $this->isPrimaryKeyDifferent() ? $this->climate()->arguments->get('old_key') : $this->targetModel()->key();
$this->oldPrimaryKey = $oldKey;
}
@@ -469,11 +450,7 @@ private function newPrimaryKey()
if ($this->newPrimaryKey === null) {
$model = $this->targetModel();
- if ($this->isPrimaryKeyDifferent()) {
- $newKey = $model->key();
- } else {
- $newKey = sprintf('%s_new', $model->key());
- }
+ $newKey = $this->isPrimaryKeyDifferent() ? $model->key() : sprintf('%s_new', $model->key());
$this->newPrimaryKey = $newKey;
}
@@ -486,9 +463,8 @@ private function newPrimaryKey()
*
* @param array|Traversable $rows The target model's existing rows.
* @throws InvalidArgumentException If the given argument is not iterable.
- * @return boolean
*/
- private function describeCount($rows = null)
+ private function describeCount($rows = null): bool
{
if ($rows === null) {
$rows = $this->fetchTargetRows();
@@ -498,7 +474,7 @@ private function describeCount($rows = null)
throw new InvalidArgumentException(
sprintf(
'The rows must be iterable; received %s',
- is_object($rows) ? get_class($rows) : gettype($rows)
+ get_debug_type($rows)
)
);
}
@@ -506,7 +482,7 @@ private function describeCount($rows = null)
$cli = $this->climate();
$model = $this->targetModel();
- if (is_array($rows) || $rows instanceof Countable) {
+ if (is_countable($rows)) {
$count = count($rows);
} elseif ($rows instanceof PDOStatement) {
$count = $rows->rowCount();
@@ -525,12 +501,10 @@ private function describeCount($rows = null)
if (!$this->quiet()) {
$cli->comment('The object table has 1 row.');
}
- } else {
- if (!$this->quiet()) {
- $cli->comment(
- sprintf('The object table has %s rows.', $count)
- );
- }
+ } elseif (!$this->quiet()) {
+ $cli->comment(
+ sprintf('The object table has %s rows.', $count)
+ );
}
return true;
@@ -541,9 +515,8 @@ private function describeCount($rows = null)
*
* @param PropertyField $field The new ID field.
* @param IdProperty $prop The new ID property.
- * @return self
*/
- private function insertNewField(PropertyField $field, IdProperty $prop)
+ private function insertNewField(PropertyField $field, IdProperty $prop): static
{
unset($prop);
@@ -588,9 +561,8 @@ private function insertNewField(PropertyField $field, IdProperty $prop)
*
* @param PropertyField $field The previous ID field.
* @param IdProperty $prop The previous ID property.
- * @return self
*/
- private function dropPrimaryKey(PropertyField $field, IdProperty $prop)
+ private function dropPrimaryKey(PropertyField $field, IdProperty $prop): static
{
$keepId = $this->climate()->arguments->defined('keep_id');
$model = $this->targetModel();
@@ -628,9 +600,8 @@ private function dropPrimaryKey(PropertyField $field, IdProperty $prop)
*
* @param PropertyField $field The new ID field.
* @param IdProperty $prop The new ID property.
- * @return self
*/
- private function applyPrimaryKey(PropertyField $field, IdProperty $prop)
+ private function applyPrimaryKey(PropertyField $field, IdProperty $prop): static
{
unset($prop);
@@ -655,9 +626,8 @@ private function applyPrimaryKey(PropertyField $field, IdProperty $prop)
* @param PropertyField $field The field to rename.
* @param string $from The original field key.
* @param string $to The new field key.
- * @return self
*/
- private function renameColumn(PropertyField $field, $from, $to)
+ private function renameColumn(PropertyField $field, $from, $to): static
{
$model = $this->targetModel();
$source = $model->source();
@@ -681,9 +651,8 @@ private function renameColumn(PropertyField $field, $from, $to)
* Remove the given field.
*
* @param PropertyField $field The field to remove.
- * @return self
*/
- private function removeColumn(PropertyField $field)
+ private function removeColumn(PropertyField $field): static
{
$source = $this->targetModel()->source();
@@ -707,21 +676,20 @@ private function removeColumn(PropertyField $field)
* @param IdProperty $oldProp The previous ID property.
* @param PropertyField $oldField The previous ID field.
* @throws InvalidArgumentException If the new property does not implement the proper mode.
- * @return self
*/
protected function convertIdField(
IdProperty $newProp,
PropertyField $newField,
IdProperty $oldProp,
PropertyField $oldField
- ) {
+ ): static {
$cli = $this->climate();
$keepId = $cli->arguments->defined('keep_id');
$model = $this->targetModel();
$source = $model->source();
$table = $source->table();
- $dbh = $source->db();
+ $source->db();
$newKey = $newProp->getIdent();
$oldKey = $oldProp->getIdent();
@@ -739,7 +707,7 @@ protected function convertIdField(
switch ($mode) {
case IdProperty::MODE_AUTO_INCREMENT:
$pool = 0;
- $ids = function () use (&$pool) {
+ $ids = function () use (&$pool): int {
return ++$pool;
};
break;
@@ -750,7 +718,7 @@ protected function convertIdField(
$generator = $this->idGenerator();
$pool = [];
- $ids = function () use (&$pool, $model, $generator) {
+ $ids = function () use (&$pool, $generator) {
$id = $generator();
while (in_array($id, $pool)) {
$id = $generator();
@@ -764,7 +732,7 @@ protected function convertIdField(
default:
$pool = [];
- $ids = function () use (&$pool, $newProp) {
+ $ids = function () use (&$pool, $newProp): ?string {
$id = $newProp->autoGenerate();
while (in_array($id, $pool)) {
$id = $newProp->autoGenerate();
@@ -830,14 +798,13 @@ protected function convertIdField(
* @param IdProperty $oldProp The previous ID property.
* @param PropertyField $oldField The previous ID field.
* @throws InvalidArgumentException If the new property does not implement the proper mode.
- * @return self
*/
protected function syncRelatedFields(
IdProperty $newProp,
PropertyField $newField,
IdProperty $oldProp,
PropertyField $oldField
- ) {
+ ): static {
unset($newProp, $oldProp, $oldField);
$cli = $this->climate();
@@ -907,21 +874,18 @@ protected function syncRelatedFields(
*
* @return array
*/
+ #[\Override]
public function defaultArguments()
{
static $arguments;
if ($arguments === null) {
- $validateFieldName = function ($response) {
- return is_string($response) && strlen($response) > 0;
- };
+ $validateFieldName = (fn($response): bool => is_string($response) && $response !== '');
- $validateCallback = function ($response) {
- return is_string($response) && (strpos($callable, '::') > 1 || function_exists($response));
- };
+ $validateCallback = (fn($response): bool => is_string($response) && (strpos($callable, '::') > 1 || function_exists($response)));
- $validateModel = function ($response) {
- if (strlen($response) === 0) {
+ $validateModel = function ($response): bool {
+ if ((string)$response === '') {
return false;
}
@@ -936,8 +900,8 @@ public function defaultArguments()
return true;
};
- $validateModels = function ($response) {
- if (strlen($response) === 0) {
+ $validateModels = function ($response): bool {
+ if ((string)$response === '') {
return false;
}
@@ -1018,9 +982,8 @@ public function parentArguments()
*
* @param mixed $callable A function or method.
* @throws InvalidArgumentException If the given argument is not a callable function.
- * @return self
*/
- public function setIdGenerator($callable)
+ public function setIdGenerator($callable): static
{
$this->idGenerator = $this->parseIdGenerator($callable);
@@ -1047,16 +1010,16 @@ public function parseIdGenerator($callable)
$bail = false;
if (is_array($callable) && count($callable) === 2) {
- list($class, $func) = $callable;
+ [$class, $func] = $callable;
$isMethod = ($class && $func);
} elseif (is_string($callable) && strpos($callable, '::') > 1) {
- list($class, $func) = explode('::', $callable);
+ [$class, $func] = explode('::', $callable);
$isMethod = ($class && $func);
}
if ($isMethod) {
$model = $this->targetModel();
- $isModel = is_a($model, $class);
+ $isModel = $model instanceof $class;
$method = new ReflectionMethod($class, $func);
if ($isModel && $method->isPublic()) {
@@ -1073,7 +1036,7 @@ public function parseIdGenerator($callable)
sprintf(
'The ID generator must be callable, received: %s',
is_object($callable)
- ? get_class($callable)
+ ? $callable::class
: (is_string($callable)
? $callable
: gettype($callable)
@@ -1093,7 +1056,7 @@ public function parseIdGenerator($callable)
*/
public function idGenerator()
{
- if (!isset($this->idGenerator)) {
+ if ($this->idGenerator === null) {
throw new RuntimeException('A function to generate a unique ID must be provided.');
}
@@ -1105,9 +1068,8 @@ public function idGenerator()
*
* @param string|ModelInterface $model An object model.
* @throws InvalidArgumentException If the given argument is not a model.
- * @return self
*/
- public function setTargetModel($model)
+ public function setTargetModel($model): static
{
if (is_string($model)) {
$model = $this->modelFactory()->get($model);
@@ -1135,7 +1097,7 @@ public function setTargetModel($model)
*/
public function targetModel()
{
- if (!isset($this->targetModel)) {
+ if ($this->targetModel === null) {
throw new RuntimeException('A model must be targeted.');
}
@@ -1147,14 +1109,13 @@ public function targetModel()
*
* @param string|array $models One or more object models.
* @throws InvalidArgumentException If the given argument is not a model.
- * @return self
*/
- public function setRelatedModels($models)
+ public function setRelatedModels($models): static
{
$models = $this->parseAsArray($models);
foreach ($models as $i => $model) {
if (is_string($model)) {
- list($model, $prop) = $this->resolveRelatedModel($model);
+ [$model, $prop] = $this->resolveRelatedModel($model);
$models[$i] = $model;
$this->relatedProperties[$model->objType()] = $prop;
} elseif ($model instanceof ModelInterface) {
@@ -1162,7 +1123,7 @@ public function setRelatedModels($models)
throw new InvalidArgumentException(
sprintf(
'The related model [%s] requires a target property',
- get_class($model)
+ $model::class
)
);
}
@@ -1189,16 +1150,16 @@ public function setRelatedModels($models)
* @throws InvalidArgumentException If the identifier is invalid.
* @return array Returns an array containing a ModelInterface and a property identifier.
*/
- protected function resolveRelatedModel($pattern)
+ protected function resolveRelatedModel($pattern): array
{
- list($class, $prop) = array_pad($this->parseAsArray($pattern, ':'), 2, null);
+ [$class, $prop] = array_pad($this->parseAsArray($pattern, ':'), 2, null);
$model = $this->modelFactory()->get($class);
if (!$prop) {
throw new InvalidArgumentException(
sprintf(
'The related model [%s] requires a target property',
- get_class($model)
+ $model::class
)
);
}
diff --git a/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterScript.php b/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterScript.php
index 37df8a738..e510413b6 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Object/Table/AlterScript.php
@@ -13,10 +13,8 @@
*/
class AlterScript extends AdminScript
{
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'obj-type' => [
@@ -25,17 +23,14 @@ public function defaultArguments()
'defaultValue' => ''
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -86,7 +81,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- $ret = $source->alterTable();
+ $source->alterTable();
$climate->green()->out(
"\n" . 'Success!'
diff --git a/packages/admin/src/Charcoal/Admin/Script/Object/Table/CreateScript.php b/packages/admin/src/Charcoal/Admin/Script/Object/Table/CreateScript.php
index 0cc9ecb37..b06cf7726 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Object/Table/CreateScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Object/Table/CreateScript.php
@@ -13,10 +13,8 @@
*/
class CreateScript extends AdminScript
{
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'obj-type' => [
@@ -25,17 +23,14 @@ public function defaultArguments()
'defaultValue' => ''
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -86,7 +81,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- $ret = $source->createTable();
+ $source->createTable();
$climate->green()->out(
"\n" . 'Success!'
diff --git a/packages/admin/src/Charcoal/Admin/Script/ObjectsScript.php b/packages/admin/src/Charcoal/Admin/Script/ObjectsScript.php
index 4591678ae..5b1d606d3 100644
--- a/packages/admin/src/Charcoal/Admin/Script/ObjectsScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/ObjectsScript.php
@@ -28,10 +28,8 @@ class ObjectsScript extends AdminScript implements CollectionContainerInterface
{
use CollectionContainerTrait;
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'obj-type' => [
@@ -54,17 +52,14 @@ public function defaultArguments()
'castTo' => 'int'
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -94,7 +89,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$collection = $this->collection();
$table = [];
- $rows = $this->objectRows();
+ $this->objectRows();
foreach ($collection as $c) {
$obj = [];
diff --git a/packages/admin/src/Charcoal/Admin/Script/Tools/CheckLinksScript.php b/packages/admin/src/Charcoal/Admin/Script/Tools/CheckLinksScript.php
index f86325828..e9b05c170 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Tools/CheckLinksScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Tools/CheckLinksScript.php
@@ -16,10 +16,7 @@
*/
class CheckLinksScript extends AdminScript
{
- /**
- * @var string
- */
- private $startUrl;
+ private ?string $startUrl = null;
/**
* @var array
@@ -36,10 +33,7 @@ class CheckLinksScript extends AdminScript
*/
private $processedUrls = [];
- /**
- * @var GuzzleClient
- */
- private $guzzleClient;
+ private readonly \GuzzleHttp\Client $guzzleClient;
/**
* @var GoutteClient
@@ -58,10 +52,8 @@ public function __construct($data = null)
$this->goutteClient->setClient($this->guzzleClient);
}
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'url' => [
@@ -81,17 +73,14 @@ public function defaultArguments()
'defaultValue' => true
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request PSR-7 request.
* @param ResponseInterface $response PSR-7 response.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -114,9 +103,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
/**
* @param string $url The URL to check.
- * @return void
*/
- private function checkUrl($url)
+ private function checkUrl($url): void
{
$rawUrl = $url;
$this->processedUrls[] = $url;
@@ -132,7 +120,7 @@ private function checkUrl($url)
try {
$response = $this->guzzleClient->request('GET', $url, [
'http_errors' => false,
- 'on_stats' => function (TransferStats $stats) {
+ 'on_stats' => function (TransferStats $stats): void {
if ($stats->hasResponse()) {
$code = $stats->getResponse()->getStatusCode();
$transferTime = (1000 * $stats->getTransferTime());
@@ -162,7 +150,7 @@ private function checkUrl($url)
}
}
]);
- } catch (Exception $e) {
+ } catch (Exception) {
// Do nothing
$this->climate()->error('-- Error retrieving ' . $url);
}
@@ -174,13 +162,12 @@ private function checkUrl($url)
/**
* @param string $url The URL to retrieve links from.
* @param integer $level The current level.
- * @return void
*/
- private function retrieveLinks($url, $level)
+ private function retrieveLinks($url, int|float $level): void
{
$crawler = $this->goutteClient->request('GET', $url);
- $crawler->filter('a')->each(function ($item) use ($level) {
+ $crawler->filter('a')->each(function ($item) use ($level): void {
$href = $item->attr('href');
if (in_array($href, $this->processedUrls)) {
return;
@@ -202,19 +189,15 @@ private function isInternalLink($url)
if (!isset($parsed['host'])) {
return true;
}
- if ($parsed['host'] === $this->parsedStartUrl['host']) {
- return true;
- }
- return false;
+ return $parsed['host'] === $this->parsedStartUrl['host'];
}
/**
* @param string $url The URL to convert to absolute.
- * @return string
*/
- private function absoluteLink($url)
+ private function absoluteLink($url): string
{
- if (strstr($url, 'http') === false) {
+ if (!str_contains($url, 'http')) {
return $this->startUrl . ltrim($url, '/');
} else {
return $url;
@@ -223,16 +206,10 @@ private function absoluteLink($url)
/**
* @param string $url The URL to valdate.
- * @return boolean
*/
- private function validateLink($url)
+ private function validateLink($url): bool
{
$parsed = parse_url($url);
- if (isset($parsed['scheme'])) {
- if (!in_array($parsed['scheme'], ['http', 'https'])) {
- return false;
- }
- }
- return true;
+ return !(isset($parsed['scheme']) && !in_array($parsed['scheme'], ['http', 'https']));
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Script/Tools/CopyAssetsScript.php b/packages/admin/src/Charcoal/Admin/Script/Tools/CopyAssetsScript.php
index 3b55aaa07..e8b3fca24 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Tools/CopyAssetsScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Tools/CopyAssetsScript.php
@@ -15,15 +15,14 @@
*/
class CopyAssetsScript extends AdminScript
{
+ public $basePath;
/**
* @var string
*/
private $dir;
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'dir' => [
@@ -32,17 +31,14 @@ public function defaultArguments()
'defaultValue' => 'www/assets/admin/'
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request PSR-7 request.
* @param ResponseInterface $response PSR-7 response.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -91,6 +87,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -109,7 +106,7 @@ protected function setDependencies(Container $container)
* @param integer $permissions New folder creation permissions.
* @return boolean Returns true on success, false on failure.
*/
- private function copy($source, $dest, $permissions = 0755)
+ private function copy(string $source, string $dest, $permissions = 0755)
{
// Check for symlinks
if (is_link($source)) {
@@ -130,7 +127,7 @@ private function copy($source, $dest, $permissions = 0755)
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
- if ($entry == '.' || $entry == '..') {
+ if ($entry === '.' || $entry === '..') {
continue;
}
diff --git a/packages/admin/src/Charcoal/Admin/Script/Tools/OptimizeImagesScript.php b/packages/admin/src/Charcoal/Admin/Script/Tools/OptimizeImagesScript.php
index c7147c730..8f1570250 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Tools/OptimizeImagesScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Tools/OptimizeImagesScript.php
@@ -32,10 +32,8 @@ class OptimizeImagesScript extends AdminScript
*/
private $dir;
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'jpg' => [
@@ -54,17 +52,14 @@ public function defaultArguments()
'defaultValue' => 'www/uploads/'
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request PSR-7 request.
* @param ResponseInterface $response PSR-7 response.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -117,6 +112,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -142,9 +138,8 @@ private function getOptipngCmd()
/**
* @param string $cmd The jpegoptim command.
- * @return void
*/
- private function runJpegoptim($cmd)
+ private function runJpegoptim($cmd): void
{
$cmdName = sprintf(
'cd %s && \
@@ -172,9 +167,8 @@ private function runJpegoptim($cmd)
/**
* @param string $cmd The jpegoptim command.
- * @return void
*/
- private function runOptipng($cmd)
+ private function runOptipng($cmd): void
{
$cmdName = sprintf(
'cd %s && \
@@ -197,11 +191,11 @@ private function runOptipng($cmd)
* @param string $cmdName The binary name to search.
* @return string
*/
- private function findCmd($cmdName)
+ private function findCmd(string $cmdName)
{
$cmd = exec('type -p ' . $cmdName);
$cmd = str_replace($cmdName . ' is ', '', $cmd);
- if (!$cmd) {
+ if ($cmd === '' || $cmd === '0') {
$cmd = exec('where ' . $cmdName);
}
if (!$cmd) {
diff --git a/packages/admin/src/Charcoal/Admin/Script/Tools/ResizeImagesScript.php b/packages/admin/src/Charcoal/Admin/Script/Tools/ResizeImagesScript.php
index 1f2ecf868..3c03935d6 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Tools/ResizeImagesScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Tools/ResizeImagesScript.php
@@ -32,10 +32,8 @@ class ResizeImagesScript extends AdminScript
*/
private $dir;
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'width' => [
@@ -54,17 +52,14 @@ public function defaultArguments()
'defaultValue' => 'www/uploads/'
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request PSR-7 request.
* @param ResponseInterface $response PSR-7 response.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -175,6 +170,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -186,11 +182,11 @@ protected function setDependencies(Container $container)
* @param string $cmdName The binary name to search.
* @return string
*/
- private function findCmd($cmdName)
+ private function findCmd(string $cmdName)
{
$cmd = exec('type -p ' . $cmdName);
$cmd = str_replace($cmdName . ' is ', '', $cmd);
- if (!$cmd) {
+ if ($cmd === '' || $cmd === '0') {
$cmd = exec('where ' . $cmdName);
}
if (!$cmd) {
diff --git a/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/CrawlScript.php b/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/CrawlScript.php
index 6a00bbfa3..09eecc502 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/CrawlScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/CrawlScript.php
@@ -20,25 +20,16 @@
*/
class CrawlScript extends AdminScript
{
- /**
- * @var string
- */
- private $startUrl;
+ private ?string $startUrl = null;
- /**
- * @var array
- */
- private $parsedStartUrl;
+ private array|bool|null $parsedStartUrl = null;
/**
* @var string
*/
private $basePath;
- /**
- * @var string
- */
- private $outputDir;
+ private ?string $outputDir = null;
/**
* @var integer
@@ -50,10 +41,7 @@ class CrawlScript extends AdminScript
*/
private $processedUrls = [];
- /**
- * @var GuzzleClient
- */
- private $guzzleClient;
+ private readonly \GuzzleHttp\Client $guzzleClient;
/**
* @var GoutteClient
@@ -72,10 +60,8 @@ public function __construct($data = null)
$this->goutteClient->setClient($this->guzzleClient);
}
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'url' => [
@@ -94,17 +80,14 @@ public function defaultArguments()
'defaultValue' => 2
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request PSR-7 Request.
* @param ResponseInterface $response PSR-7 Response.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -132,6 +115,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -141,9 +125,8 @@ protected function setDependencies(Container $container)
/**
* @param string $url The URL to cache. The base (start) URL will be prefixed to relative URLs.
- * @return void
*/
- private function cacheUrl($url)
+ private function cacheUrl(string|array $url): void
{
if (in_array($url, $this->processedUrls)) {
return;
@@ -169,7 +152,7 @@ private function cacheUrl($url)
return;
}
- if (strstr($headers['Content-Type'][0], 'text/html') !== false) {
+ if (str_contains($headers['Content-Type'][0], 'text/html')) {
$outputFile = $outputDir . '/index.html';
$prefix = '';
} else {
@@ -191,12 +174,11 @@ private function cacheUrl($url)
/**
* @param string $url The URL to retrieve links from.
* @param integer $level Current level.
- * @return void
*/
- private function retrieveLinks($url, $level)
+ private function retrieveLinks(string|null|array $url, int|float $level): void
{
$crawler = $this->goutteClient->request('GET', $url);
- $crawler->filter('a')->each(function ($item) use ($level) {
+ $crawler->filter('a')->each(function ($item) use ($level): void {
$href = $item->attr('href');
$parsedHref = parse_url($href);
if (isset($parsedHref['host']) && ($parsedHref['host'] !== $this->parsedStartUrl['host'])) {
@@ -217,9 +199,8 @@ private function retrieveLinks($url, $level)
/**
* @param string $dir The directory to recursively delete.
* @throws InvalidArgumentException If the argument is empty.
- * @return mixed
*/
- private function recursiveDelete($dir)
+ private function recursiveDelete(string $dir): bool
{
if (!is_string($dir)) {
throw new InvalidArgumentException(
diff --git a/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/UpdateScript.php b/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/UpdateScript.php
index b7c2b46dd..be1a7a6e8 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/UpdateScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Tools/StaticWebsite/UpdateScript.php
@@ -24,15 +24,10 @@ class UpdateScript extends AdminScript
*/
private $basePath;
- /**
- * @var \GuzzleHttp\Client
- */
- private $guzzleClient;
+ private ?\GuzzleHttp\Client $guzzleClient = null;
- /**
- * @return array
- */
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'url' => [
@@ -46,17 +41,14 @@ public function defaultArguments()
'noValue' => true
],
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request PSR-7 Request.
* @param ResponseInterface $response PSR-7 Response.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
$this->guzzleClient = new GuzzleClient();
@@ -96,6 +88,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -106,9 +99,8 @@ protected function setDependencies(Container $container)
/**
* @param string $url The URL to cache. The base (start) URL will be prefixed to relative URLs.
* @param string $outputDir The output directory.
- * @return void
*/
- private function cacheUrl($url, $outputDir)
+ private function cacheUrl(string $url, string $outputDir): void
{
$relativeUrl = str_replace($this->baseUrl(), '', $url);
$url = $this->baseUrl() . $relativeUrl;
@@ -130,7 +122,7 @@ private function cacheUrl($url, $outputDir)
return;
}
- if (strstr($headers['Content-Type'][0], 'text/html') !== false) {
+ if (str_contains($headers['Content-Type'][0], 'text/html')) {
$outputFile = $outputDir . '/index.html';
$prefix = '';
} else {
@@ -154,7 +146,7 @@ private function cacheUrl($url, $outputDir)
* @param integer $flags Glob flags.
* @return array
*/
- private function globRecursive($dir, $pattern, $flags = 0)
+ private function globRecursive(string $dir, string $pattern, $flags = 0): array|false
{
$files = glob($dir . '/' . $pattern, $flags);
foreach (glob($dir . '/*', (GLOB_ONLYDIR | GLOB_NOSORT)) as $dir) {
diff --git a/packages/admin/src/Charcoal/Admin/Script/Translation/TranslateScript.php b/packages/admin/src/Charcoal/Admin/Script/Translation/TranslateScript.php
index 3d43c86fb..45611e49c 100644
--- a/packages/admin/src/Charcoal/Admin/Script/Translation/TranslateScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/Translation/TranslateScript.php
@@ -37,10 +37,9 @@ class TranslateScript extends AdminScript
* Valid arguments:
* - path : path/to/files
* - type : mustache | php
- *
- * @return array
*/
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'path' => [
@@ -59,17 +58,14 @@ public function defaultArguments()
'defaultValue' => ''
]
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
// Unused
unset($request);
@@ -85,6 +81,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
switch ($type) {
case 'mustache':
+ default:
$regex = '/{{\s*#\s*_t\s*}}((.|\n|\r|\n\r)*?){{\s*\/\s*_t\s*}}/i';
$file = '*.mustache';
$index = 1;
@@ -94,11 +91,6 @@ public function run(RequestInterface $request, ResponseInterface $response)
$index = 'text';
$file = '*.php';
break;
- default:
- $regex = '/{{\s*#\s*_t\s*}}((.|\n|\r|\n\r)*?){{\s*\/\s*_t\s*}}/i';
- $file = '*.mustache';
- $index = 1;
- break;
}
// Remove vendor/charcoal/app
@@ -123,7 +115,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
// Loop files to get original text.
- foreach ($glob as $k => $f) {
+ foreach ($glob as $f) {
$text = file_get_contents($f);
if (preg_match($regex, $text)) {
preg_match_all($regex, $text, $array);
@@ -156,7 +148,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
* @return array
* @see http://in.php.net/manual/en/function.glob.php#106595
*/
- public function globRecursive($pattern, $flags = 0)
+ public function globRecursive($pattern, $flags = 0): array|false
{
$max = $this->maxRecursiveLevel();
$i = 1;
@@ -174,9 +166,8 @@ public function globRecursive($pattern, $flags = 0)
/**
* BASE URL
* Realpath
- * @return string
*/
- public function base()
+ public function base(): string
{
return realpath($this->app()->config()->get('base_path') . DIRECTORY_SEPARATOR . '../../../') . '/';
}
@@ -185,7 +176,7 @@ public function base()
* ARGUMENTS
* @return TranslateScript Chainable
*/
- public function getPath()
+ public function getPath(): static
{
$path = $this->argOrInput('path');
$this->path = $path;
@@ -206,7 +197,7 @@ public function path()
/**
* @return TranslateScript Chainable
*/
- public function getFileType()
+ public function getFileType(): static
{
$type = $this->argOrInput('type');
$this->fileType = $type;
@@ -240,10 +231,8 @@ public function file()
/**
* Returns associative array
* 'original text' => [ 'translation' => 'translation text', 'context' => 'filename' ]
- *
- * @return array
*/
- public function fromCSV()
+ public function fromCSV(): array
{
$output = $this->file();
$base = $this->base();
@@ -255,10 +244,10 @@ public function fromCSV()
$results = [];
$row = 0;
- while (($data = fgetcsv($file, 0, ',')) !== false) {
+ while (($data = fgetcsv($file, 0, ',', escape: '\\')) !== false) {
$row++;
// Skip column names
- if ($row == 1) {
+ if ($row === 1) {
continue;
}
/**
@@ -267,7 +256,7 @@ public function fromCSV()
* data[2] = CONTEXT
*/
$translation = $this->translateCSV($data);
- if (!empty($translation)) {
+ if ($translation !== []) {
$results[$translation[0]] = $translation[1];
}
}
@@ -279,7 +268,7 @@ public function fromCSV()
* @param array $translations The translations to save in CSV.
* @return TranslateScript Chainable
*/
- public function toCSV(array $translations)
+ public function toCSV(array $translations): static
{
$base = $this->base();
$output = $this->file();
@@ -298,11 +287,11 @@ public function toCSV(array $translations)
// Wtf happened?
return $this;
}
- fputcsv($file, $columns, $separator, $enclosure);
+ fputcsv($file, $columns, $separator, $enclosure, escape: '\\');
foreach ($translations as $orig => $translation) {
$data = [ $orig, $translation['translation'], $translation['context'] ];
- fputcsv($file, $data, $separator, $enclosure);
+ fputcsv($file, $data, $separator, $enclosure, escape: '\\');
}
fclose($file);
@@ -312,34 +301,31 @@ public function toCSV(array $translations)
/**
* @param array $data The translation data.
- * @return array
* @todo multiple langs
* data[0] = ORIGINAL
* data[1] = TRANSLATION
* data[2] = CONTEXT
*/
- public function translateCSV(array $data)
+ public function translateCSV(array $data): array
{
if (count($data) < 3) {
return [];
}
- $output = [
+ return [
$data[0],
[
'translation' => $data[1],
'context' => $data[2]
]
];
-
- return $output;
}
/**
* @todo make this optional
* @return string lang ident
*/
- public function origLanguage()
+ public function origLanguage(): string
{
return 'fr';
}
@@ -348,10 +334,11 @@ public function origLanguage()
* Get opposite languages from DATABASE
*
* @return [type] [description]
+ * @return mixed[]
*/
- public function oppositeLanguages()
+ public function oppositeLanguages(): array
{
- $cfg = $this->app()->config();
+ $this->app()->config();
$locales = $this->locales();
$languages = $locales['languages'];
@@ -379,11 +366,11 @@ public function locales()
}
$cfg = $this->app()->config();
- $locales = isset($cfg['locales']) ? $cfg['locales'] : [];
- $languages = isset($locales['languages']) ? $locales['languages'] : [];
- $file = isset($locales['file']) ? $locales['file'] : $this->argOrInput('output');
+ $locales = ($cfg['locales'] ?? []);
+ $languages = ($locales['languages'] ?? []);
+ $file = ($locales['file'] ?? $this->argOrInput('output'));
// Default to FR
- $default = isset($locales['default_language']) ? $locales['default_language'] : 'fr';
+ $default = ($locales['default_language'] ?? 'fr');
$this->locales = [
'languages' => $languages,
@@ -396,10 +383,8 @@ public function locales()
/**
* Columns of CSV file
* This is already built to take multiple languages
- *
- * @return array
*/
- public function columns()
+ public function columns(): array
{
$orig = $this->origLanguage();
$opposites = $this->oppositeLanguages();
@@ -416,26 +401,17 @@ public function columns()
return $columns;
}
- /**
- * @return string
- */
- public function enclosure()
+ public function enclosure(): string
{
return '"';
}
- /**
- * @return string
- */
- public function separator()
+ public function separator(): string
{
return ',';
}
- /**
- * @return integer
- */
- public function maxRecursiveLevel()
+ public function maxRecursiveLevel(): int
{
return 4;
}
diff --git a/packages/admin/src/Charcoal/Admin/Script/User/AclRole/CreateScript.php b/packages/admin/src/Charcoal/Admin/Script/User/AclRole/CreateScript.php
index ce397f0ee..08261ab64 100644
--- a/packages/admin/src/Charcoal/Admin/Script/User/AclRole/CreateScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/User/AclRole/CreateScript.php
@@ -18,9 +18,8 @@ class CreateScript extends AdminScript
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -72,10 +71,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
return $response;
}
- /**
- * @return boolean
- */
- public function authRequired()
+ public function authRequired(): bool
{
return false;
}
diff --git a/packages/admin/src/Charcoal/Admin/Script/User/CreateScript.php b/packages/admin/src/Charcoal/Admin/Script/User/CreateScript.php
index 67872af55..e732e054c 100644
--- a/packages/admin/src/Charcoal/Admin/Script/User/CreateScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/User/CreateScript.php
@@ -40,6 +40,7 @@ public function __construct($data = null)
* @param Container $container Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -52,10 +53,9 @@ protected function setDependencies(Container $container)
* Retrieve the available default arguments of this action.
*
* @link http://climate.thephpleague.com/arguments/ For descriptions of the options for CLImate.
- *
- * @return array
*/
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'email' => [
@@ -81,17 +81,14 @@ public function defaultArguments()
]
];
- $arguments = array_merge(parent::defaultArguments(), $arguments);
-
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -107,9 +104,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
/**
* Create a new user in the database
- * @return void
*/
- private function createUser()
+ private function createUser(): void
{
$authenticator = $this->authenticator();
@@ -148,11 +144,7 @@ private function createUser()
$prompt = $prompts[$prop->ident()];
- if ($prompt['property']) {
- $v = $prompt['property'];
- } else {
- $v = $this->promptProperty($prop, $prompt['label']);
- }
+ $v = $prompt['property'] ?: $this->promptProperty($prop, $prompt['label']);
if (isset($prompt['validation'])) {
call_user_func($prompt['validation'], $v);
}
@@ -175,10 +167,7 @@ private function createUser()
}
}
- /**
- * @return array
- */
- private function userPrompts()
+ private function userPrompts(): array
{
$translator = $this->translator();
$climate = $this->climate();
@@ -187,12 +176,12 @@ private function userPrompts()
'email' => [
'label' => $translator->translate('Please enter email: '),
'property' => $climate->arguments->get('email'),
- 'validation' => [ $this, 'validateEmail' ],
+ 'validation' => $this->validateEmail(...),
],
'password' => [
'label' => $translator->translate('Please enter password: '),
'property' => $climate->arguments->get('password'),
- 'validation' => [ $this, 'validatePassword' ],
+ 'validation' => $this->validatePassword(...),
],
'roles' => [
'label' => $translator->translate('Please enter role(s) [ex: admin], comma separated: '),
@@ -227,9 +216,8 @@ private function promptProperty($prop, $label)
* @param string $email The email, from input.
* @throws Exception If the email is empty or invalid (validated with php's filters)
* or already exists in the database.
- * @return void
*/
- private function validateEmail($email)
+ private function validateEmail($email): void
{
if (!$email) {
throw new Exception(
@@ -256,9 +244,8 @@ private function validateEmail($email)
/**
* @param string $password The password, from input.
* @throws Exception If the password is empty or too small.
- * @return void
*/
- private function validatePassword($password)
+ private function validatePassword($password): void
{
if (!$password) {
throw new Exception(
diff --git a/packages/admin/src/Charcoal/Admin/Script/User/ResetPasswordScript.php b/packages/admin/src/Charcoal/Admin/Script/User/ResetPasswordScript.php
index 3b59f2e4d..e6c25cf94 100644
--- a/packages/admin/src/Charcoal/Admin/Script/User/ResetPasswordScript.php
+++ b/packages/admin/src/Charcoal/Admin/Script/User/ResetPasswordScript.php
@@ -37,6 +37,7 @@ public function __construct($data = null)
* @param Container $container Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -49,10 +50,9 @@ protected function setDependencies(Container $container)
* Retrieve the available default arguments of this action.
*
* @link http://climate.thephpleague.com/arguments/ For descriptions of the options for CLImate.
- *
- * @return array
*/
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'email' => [
@@ -74,17 +74,14 @@ public function defaultArguments()
]
];
- $arguments = array_merge(parent::defaultArguments(), $arguments);
-
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -114,7 +111,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$authenticator->changeUserPassword($user, $password);
if ($climate->arguments->get('sendEmail')) {
- $this->sendResetPasswordEmail($email, $password);
+ $this->sendResetPasswordEmail();
}
$climate->red()->out(
@@ -125,12 +122,10 @@ public function run(RequestInterface $request, ResponseInterface $response)
}
/**
- * @param string $email The user email.
- * @param string $password The new, plain-text password.
* @return void
* @todo Implement reset password email dispatch.
*/
- private function sendResetPasswordEmail($email, $password)
+ private function sendResetPasswordEmail()
{
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Service/AssetsBuilder.php b/packages/admin/src/Charcoal/Admin/Service/AssetsBuilder.php
index f6b7aacab..64edad4c8 100644
--- a/packages/admin/src/Charcoal/Admin/Service/AssetsBuilder.php
+++ b/packages/admin/src/Charcoal/Admin/Service/AssetsBuilder.php
@@ -19,23 +19,13 @@
*/
final class AssetsBuilder
{
- /**
- * @var AssetManager|null
- */
- private $assetManager = null;
-
- /**
- * @var string|null
- */
- private $basePath = null;
+ private ?\Assetic\AssetManager $assetManager = null;
/**
* @param string|null $basePath The assets base path.
- * @return void
*/
- public function __construct($basePath = null)
+ public function __construct(private $basePath = null)
{
- $this->basePath = $basePath;
}
/**
@@ -44,7 +34,7 @@ public function __construct($basePath = null)
* @param AssetsConfig $config The assets management config.
* @return AssetManager
*/
- public function __invoke(AssetsConfig $config)
+ public function __invoke(AssetsConfig $config): ?\Assetic\AssetManager
{
return $this->build($config);
}
@@ -53,7 +43,7 @@ public function __invoke(AssetsConfig $config)
* @param AssetsConfig $config The assets management config.
* @return AssetManager
*/
- public function build(AssetsConfig $config)
+ public function build(AssetsConfig $config): ?\Assetic\AssetManager
{
$this->assetManager = new AssetManager();
$this->parseCollections($config->collections());
@@ -63,14 +53,13 @@ public function build(AssetsConfig $config)
/**
* @param array $collections Assets collections.
- * @return void
*/
- private function parseCollections(array $collections)
+ private function parseCollections(array $collections): void
{
foreach ($collections as $collectionIdent => $actions) {
$files = ($actions['files'] ?? []);
// Parse scoped files. Solves merging issues.
- array_walk($actions, function ($scope) use (&$files) {
+ array_walk($actions, function (array $scope) use (&$files): void {
if (isset($scope['files']) && !empty($scope['files'])) {
$files = array_merge($files, $scope['files']);
}
@@ -88,7 +77,7 @@ private function parseCollections(array $collections)
* @param string[] $files Files to convert to Collection assets.
* @return AssetInterface[]
*/
- private function extractFiles(array $files = [])
+ private function extractFiles(array $files = []): array
{
$collection = [];
@@ -107,7 +96,7 @@ private function extractFiles(array $files = [])
}
// Files with asterisks should be treated as glob.
- if (strpos($file, '*') !== false) {
+ if (str_contains($file, '*')) {
$collection[] = new GlobAsset($file);
continue;
}
@@ -128,7 +117,7 @@ private function extractFiles(array $files = [])
* @param string $file A file path.
* @return boolean Returns TRUE if the given path is absolute. Otherwise, returns FALSE.
*/
- private function isAbsolutePath($file)
+ private function isAbsolutePath($file): bool
{
$file = (string)$file;
diff --git a/packages/admin/src/Charcoal/Admin/Service/Exporter.php b/packages/admin/src/Charcoal/Admin/Service/Exporter.php
index f9411be72..cfc1c753c 100644
--- a/packages/admin/src/Charcoal/Admin/Service/Exporter.php
+++ b/packages/admin/src/Charcoal/Admin/Service/Exporter.php
@@ -28,6 +28,8 @@ class Exporter
{
use TranslatorAwareTrait;
+ public $logger;
+
/**
* Output file name
* @var string $filename
@@ -43,16 +45,14 @@ class Exporter
/**
* Options
* Booleans
- * @var boolean $convertBrToNewlines
*/
- private $convertBrToNewlines;
+ private ?bool $convertBrToNewlines = null;
/**
* Options
* Booleans
- * @var boolean $stripTags
*/
- private $stripTags;
+ private ?bool $stripTags = null;
/**
* Export ident for metadata
@@ -62,21 +62,18 @@ class Exporter
/**
* Output properties
- * @var array $properties
*/
- private $properties = [];
+ private array $properties = [];
/**
* CollectionConfig
- * @var array $collectionConfig
*/
- private $collectionConfig;
+ private ?array $collectionConfig = null;
/**
* Model factory
- * @var FactoryInterface $modelFactory
*/
- private $modelFactory;
+ private \Charcoal\Factory\FactoryInterface $modelFactory;
/**
* Property factory used
@@ -134,7 +131,7 @@ public function __construct(array $data)
* Init function
* @return Exporter Chainable.
*/
- public function process()
+ public function process(): static
{
$this->prepareOptions();
$this->export();
@@ -143,9 +140,8 @@ public function process()
/**
* Export to CSV
- * @return void
*/
- public function export()
+ public function export(): void
{
$headers = $this->fileHeaders();
$rows = $this->rows();
@@ -177,7 +173,7 @@ public function collection()
if (!$this->collectionConfig()) {
throw new RuntimeException(sprintf(
'Collection Config required for "%s"',
- get_class($this)
+ static::class
));
}
@@ -230,7 +226,7 @@ private function proto()
*/
private function metadata()
{
- $proto = $this->proto();
+ $this->proto();
return $this->proto()->metadata();
}
@@ -241,7 +237,7 @@ private function metadata()
* @throws InvalidArgumentException If no properties are defined.
* @return Exporter Chainable.
*/
- private function prepareOptions()
+ private function prepareOptions(): static
{
$metadata = $this->metadata();
@@ -252,7 +248,7 @@ private function prepareOptions()
throw new InvalidArgumentException(sprintf(
'No export ident defined for "%s" in %s',
$this->objType(),
- get_class($this)
+ static::class
));
}
@@ -265,7 +261,7 @@ private function prepareOptions()
'No export data defined for "%s" at "%s" in %s',
$this->objType(),
$this->exportIdent(),
- get_class($this)
+ static::class
));
}
@@ -275,7 +271,7 @@ private function prepareOptions()
throw new InvalidArgumentException(sprintf(
'No export data defined for "%s" in %s',
$this->objType(),
- get_class($this)
+ static::class
));
}
}
@@ -284,7 +280,7 @@ private function prepareOptions()
throw new InvalidArgumentException(sprintf(
'No properties defined to export "%s" in %s',
$this->objType(),
- get_class($this)
+ static::class
));
}
@@ -326,7 +322,7 @@ private function prepareOptions()
/**
* @return array File headers.
*/
- private function fileHeaders()
+ private function fileHeaders(): array
{
$metadata = $this->metadata();
$properties = $this->properties();
@@ -339,11 +335,7 @@ private function fileHeaders()
continue;
}
- if (isset($prop['label'])) {
- $label = $this->translator()->translation($prop['label']);
- } else {
- $label = ucfirst($p);
- }
+ $label = isset($prop['label']) ? $this->translator()->translation($prop['label']) : ucfirst((string)$p);
$out[] = $label;
}
@@ -394,7 +386,7 @@ private function rows()
* @param string $filename Output filename.
* @return Exporter (chainable).
*/
- private function setFilename($filename)
+ private function setFilename($filename): static
{
$this->filename = $filename;
return $this;
@@ -404,7 +396,7 @@ private function setFilename($filename)
* @param string $objType Object to be exported.
* @return Exporter (chainable).
*/
- private function setObjType($objType)
+ private function setObjType($objType): static
{
$this->objType = $objType;
return $this;
@@ -415,9 +407,9 @@ private function setObjType($objType)
* @param boolean $bool Convert br to newline.
* @return Exporter (chainable)
*/
- private function setConvertBrToNewlines($bool)
+ private function setConvertBrToNewlines($bool): static
{
- $this->convertBrToNewlines = !!$bool;
+ $this->convertBrToNewlines = (bool)$bool;
return $this;
}
@@ -426,9 +418,9 @@ private function setConvertBrToNewlines($bool)
* @param boolean $bool Strip tags.
* @return Exporter (chainable)
*/
- private function setStripTags($bool)
+ private function setStripTags($bool): static
{
- $this->stripTags = !!$bool;
+ $this->stripTags = (bool)$bool;
return $this;
}
@@ -439,7 +431,7 @@ private function setStripTags($bool)
* @param string $ident Config ident.
* @return Exporter (chainable)
*/
- public function setExportIdent($ident)
+ public function setExportIdent($ident): static
{
$this->exportIdent = $ident;
return $this;
@@ -451,14 +443,14 @@ public function setExportIdent($ident)
* @throws InvalidArgumentException If the array is not a list of strings.
* @return Exporter Chainable.
*/
- private function setProperties(array $properties)
+ private function setProperties(array $properties): static
{
$p = reset($properties);
if (!is_string($p)) {
throw new InvalidArgumentException(sprintf(
'Invalid properties to export "%s" in %s',
$this->objType(),
- get_class($this)
+ static::class
));
}
@@ -471,7 +463,7 @@ private function setProperties(array $properties)
* @param array $cfg Collection config.
* @return Exporter Chainable.
*/
- private function setCollectionConfig(array $cfg)
+ private function setCollectionConfig(array $cfg): static
{
$this->collectionConfig = $cfg;
return $this;
@@ -482,7 +474,7 @@ private function setCollectionConfig(array $cfg)
* @param FactoryInterface $factory Model factory.
* @return Exporter (chainable)
*/
- private function setModelFactory(FactoryInterface $factory)
+ private function setModelFactory(FactoryInterface $factory): static
{
$this->modelFactory = $factory;
return $this;
@@ -492,7 +484,7 @@ private function setModelFactory(FactoryInterface $factory)
* @param FactoryInterface $factory The property factory, to create properties.
* @return TableWidget Chainable
*/
- private function setPropertyFactory(FactoryInterface $factory)
+ private function setPropertyFactory(FactoryInterface $factory): static
{
$this->propertyFactory = $factory;
return $this;
@@ -521,7 +513,7 @@ private function objType()
/**
* @return boolean Convert to newlines.
*/
- private function convertBrToNewlines()
+ private function convertBrToNewlines(): ?bool
{
return $this->convertBrToNewlines;
}
@@ -529,7 +521,7 @@ private function convertBrToNewlines()
/**
* @return boolean Striptags.
*/
- private function stripTags()
+ private function stripTags(): ?bool
{
return $this->stripTags;
}
@@ -545,7 +537,7 @@ private function exportIdent()
/**
* @return array Properties.
*/
- private function properties()
+ private function properties(): array
{
return $this->properties;
}
@@ -553,7 +545,7 @@ private function properties()
/**
* @return array CollectionConfig.
*/
- private function collectionConfig()
+ private function collectionConfig(): ?array
{
return $this->collectionConfig;
}
@@ -561,7 +553,7 @@ private function collectionConfig()
/**
* @return ModelFactory Model factory.
*/
- private function modelFactory()
+ private function modelFactory(): \Charcoal\Factory\FactoryInterface
{
return $this->modelFactory;
}
@@ -588,11 +580,10 @@ private function propertyFactory()
* @param string $text Text.
* @return string Text with newlines.
*/
- private function brToNewline($text)
+ private function brToNewline($text): string
{
$breaks = [ ' ', ' ', ' ' ];
- $text = str_ireplace($breaks, "\r\n", $text);
- return $text;
+ return str_ireplace($breaks, "\r\n", $text);
}
/**
diff --git a/packages/admin/src/Charcoal/Admin/Service/SelectizeRenderer.php b/packages/admin/src/Charcoal/Admin/Service/SelectizeRenderer.php
index 43e369d42..ffc2568c3 100644
--- a/packages/admin/src/Charcoal/Admin/Service/SelectizeRenderer.php
+++ b/packages/admin/src/Charcoal/Admin/Service/SelectizeRenderer.php
@@ -64,15 +64,14 @@ public function __construct(array $data)
* @param ModelInterface|array|null $context The context as Model or array.
* @param string|null $controllerIdent The ControllerIdent string to override Object context.
* @throws \InvalidArgumentException If the callable id not callable.
- * @return string
*/
- public function renderTemplate($templateIdent, $context, $controllerIdent = null)
+ public function renderTemplate(string $templateIdent, $context, $controllerIdent = null): string
{
$template = null;
if ($controllerIdent && is_string($controllerIdent)) {
$controllerIdent = explode('::', $controllerIdent);
- $controllerCallable = isset($controllerIdent[1]) ? $controllerIdent[1] : null;
+ $controllerCallable = ($controllerIdent[1] ?? null);
$controllerIdent = $controllerIdent[0];
$template = $this->templateFactory->create($controllerIdent);
@@ -84,7 +83,7 @@ public function renderTemplate($templateIdent, $context, $controllerIdent = null
'%s::%s supplied in %s::%s is not a callable method.',
$controllerIdent,
$controllerCallable,
- __CLASS__,
+ self::class,
__FUNCTION__
));
}
@@ -103,8 +102,8 @@ public function renderTemplate($templateIdent, $context, $controllerIdent = null
} else {
throw new \InvalidArgumentException(sprintf(
'%s supplied in %s::%s is not callable.',
- get_class($template),
- __CLASS__,
+ $template::class,
+ self::class,
__FUNCTION__
));
}
diff --git a/packages/admin/src/Charcoal/Admin/ServiceProvider/AclServiceProvider.php b/packages/admin/src/Charcoal/Admin/ServiceProvider/AclServiceProvider.php
index 7e3aebc59..c15a395a5 100644
--- a/packages/admin/src/Charcoal/Admin/ServiceProvider/AclServiceProvider.php
+++ b/packages/admin/src/Charcoal/Admin/ServiceProvider/AclServiceProvider.php
@@ -31,9 +31,8 @@ class AclServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container Pimple DI Container.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
/**
* Use an AclManager to load default permissions from config and database.
@@ -41,7 +40,7 @@ public function register(Container $container)
* @param Container $container Pimple DI container
* @return Acl
*/
- $container['admin/acl'] = function (Container $container) {
+ $container['admin/acl'] = function (Container $container): \Laminas\Permissions\Acl\Acl {
$adminConfig = $container['admin/config'];
@@ -75,8 +74,6 @@ public function register(Container $container)
* @todo Do this right!
* @return Acl
*/
- $container['authorizer/acl'] = function () {
- return $container['admin/acl'];
- };
+ $container['authorizer/acl'] = (fn(): \Closure => $container['admin/acl']);
}
}
diff --git a/packages/admin/src/Charcoal/Admin/ServiceProvider/AdminServiceProvider.php b/packages/admin/src/Charcoal/Admin/ServiceProvider/AdminServiceProvider.php
index fb236ce02..e780712fd 100644
--- a/packages/admin/src/Charcoal/Admin/ServiceProvider/AdminServiceProvider.php
+++ b/packages/admin/src/Charcoal/Admin/ServiceProvider/AdminServiceProvider.php
@@ -16,7 +16,7 @@
// From Slim
use Slim\Http\Uri;
// From Mustache
-use Mustache_LambdaHelper as LambdaHelper;
+use Mustache\LambdaHelper as LambdaHelper;
// From 'charcoal-config'
use Charcoal\Config\ConfigInterface;
use Charcoal\Config\GenericConfig as Config;
@@ -66,9 +66,8 @@ class AdminServiceProvider implements ServiceProviderInterface
* It should not get services.
*
* @param Container $container The Pimple DI container.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
// Ensure dependencies are set
$container->register(new EmailServiceProvider());
@@ -102,7 +101,7 @@ protected function registerAdminServices(Container $container)
* @param Container $container The Pimple DI Container.
* @return AdminConfig
*/
- $container['admin/config'] = function (Container $container) {
+ $container['admin/config'] = function (Container $container): \Charcoal\Admin\Config {
$appConfig = $container['config'];
$extraConfigs = [];
@@ -124,12 +123,10 @@ protected function registerAdminServices(Container $container)
array_push($extraConfigs, ...$appAdminConfigs);
}
- if (!empty($extraConfigs)) {
- foreach ($extraConfigs as $path) {
- $configPath = $appConfig['base_path'] . DIRECTORY_SEPARATOR . ltrim($path, '/');
+ foreach ($extraConfigs as $path) {
+ $configPath = $appConfig['base_path'] . DIRECTORY_SEPARATOR . ltrim($path, '/');
- $appConfig->addFile($configPath);
- }
+ $appConfig->addFile($configPath);
}
$adminConfig = $appConfig['admin'];
@@ -157,7 +154,7 @@ protected function registerAdminServices(Container $container)
$adminUrl = clone $container['base-url'];
if ($adminConfig['base_path']) {
$basePath = rtrim($adminUrl->getBasePath(), '/');
- $adminPath = ltrim($adminConfig['base_path'], '/');
+ $adminPath = ltrim((string)$adminConfig['base_path'], '/');
$adminUrl = $adminUrl->withBasePath($basePath . '/' . $adminPath);
}
}
@@ -181,11 +178,9 @@ protected function registerAdminServices(Container $container)
* @param Container $container A container instance.
* @return ViewInterface
*/
- $container->extend('view', function (GenericView $view, Container $container): ViewInterface {
- return new GenericView([
- 'engine' => $container['view/engine/mustache']
- ]);
- });
+ $container->extend('view', fn(GenericView $view, Container $container): ViewInterface => new GenericView([
+ 'engine' => $container['view/engine/mustache']
+ ]));
/**
* Extend view/config.
@@ -216,11 +211,10 @@ protected function registerMetadataExtensions(Container $container)
/**
* @return MetadataConfig
*/
- $container['metadata/config'] = function (Container $container) {
+ $container['metadata/config'] = function (Container $container): \Charcoal\Model\Service\MetadataConfig {
$settings = $container['admin/config']['metadata'];
- $metaConfig = new MetadataConfig($settings);
- return $metaConfig;
+ return new MetadataConfig($settings);
};
} else {
/**
@@ -232,9 +226,9 @@ protected function registerMetadataExtensions(Container $container)
* @param Container $container The Pimple DI container.
* @return MetadataConfig
*/
- $container->extend('metadata/config', function (MetadataConfig $metaConfig, Container $container) {
+ $container->extend('metadata/config', function (MetadataConfig $metaConfig, Container $container): \Charcoal\Model\Service\MetadataConfig {
$settings = $container['admin/config']['metadata'];
- if (is_array($settings) && !empty($settings)) {
+ if (is_array($settings) && $settings !== []) {
$metaConfig->merge($settings);
}
@@ -276,16 +270,16 @@ protected function registerMetadataExtensions(Container $container)
* @param Container $container The Pimple DI container.
* @return MetadataConfig
*/
- $container->extend('metadata/config', function (MetadataConfig $metaConfig, Container $container) {
+ $container->extend('metadata/config', function (MetadataConfig $metaConfig, Container $container): \Charcoal\Model\Service\MetadataConfig {
$adminConfig = $container['admin/config'];
- $adminDir = '/' . trim($adminConfig['base_path'], '/');
+ $adminDir = '/' . trim((string)$adminConfig['base_path'], '/');
$metaPaths = $metaConfig->paths();
$parsedPaths = [];
foreach ($metaPaths as $basePath) {
$adminPath = rtrim($basePath, '/') . $adminDir;
-
- array_push($parsedPaths, $adminPath, $basePath);
+ $parsedPaths[] = $adminPath;
+ $parsedPaths[] = $basePath;
}
$metaConfig->setPaths($parsedPaths);
@@ -306,15 +300,13 @@ protected function registerAuthExtensions(Container $container)
* @param Container $container The Pimple DI Container.
* @return Authenticator
*/
- $container['admin/authenticator'] = function (Container $container) {
- return new Authenticator([
- 'logger' => $container['logger'],
- 'user_type' => User::class,
- 'user_factory' => $container['model/factory'],
- 'token_type' => AuthToken::class,
- 'token_factory' => $container['model/factory']
- ]);
- };
+ $container['admin/authenticator'] = (fn(Container $container): \Charcoal\User\Authenticator => new Authenticator([
+ 'logger' => $container['logger'],
+ 'user_type' => User::class,
+ 'user_factory' => $container['model/factory'],
+ 'token_type' => AuthToken::class,
+ 'token_factory' => $container['model/factory']
+ ]));
/**
* Replace default Authenticator ('charcoal-ui') with the Admin Authenticator.
@@ -323,21 +315,17 @@ protected function registerAuthExtensions(Container $container)
* @param Container $container The Pimple DI Container.
* @return Authenticator
*/
- $container['authenticator'] = function (Container $container) {
- return $container['admin/authenticator'];
- };
+ $container['authenticator'] = (fn(Container $container): mixed => $container['admin/authenticator']);
/**
* @param Container $container The Pimple DI container.
* @return Authorizer
*/
- $container['admin/authorizer'] = function (Container $container) {
- return new Authorizer([
- 'logger' => $container['logger'],
- 'acl' => $container['admin/acl'],
- 'resource' => 'admin'
- ]);
- };
+ $container['admin/authorizer'] = (fn(Container $container): \Charcoal\User\Authorizer => new Authorizer([
+ 'logger' => $container['logger'],
+ 'acl' => $container['admin/acl'],
+ 'resource' => 'admin'
+ ]));
/**
* Replace default Authorizer ('charcoal-ui') with the Admin Authorizer.
@@ -346,9 +334,7 @@ protected function registerAuthExtensions(Container $container)
* @param Container $container The Pimple DI Container.
* @return Authorizer
*/
- $container['authorizer'] = function (Container $container) {
- return $container['admin/authorizer'];
- };
+ $container['authorizer'] = (fn(Container $container): mixed => $container['admin/authorizer']);
}
/**
@@ -360,9 +346,7 @@ protected function registerAuthExtensions(Container $container)
protected function registerViewExtensions(Container $container)
{
if (!isset($container['view/mustache/helpers'])) {
- $container['view/mustache/helpers'] = function () {
- return [];
- };
+ $container['view/mustache/helpers'] = (fn(): array => []);
}
/**
@@ -370,7 +354,7 @@ protected function registerViewExtensions(Container $container)
*
* @return array
*/
- $container->extend('view/mustache/helpers', function (array $helpers, Container $container) {
+ $container->extend('view/mustache/helpers', function (array $helpers, Container $container): array {
$adminUrl = $container['admin/base-url'];
$urls = [
@@ -387,8 +371,8 @@ protected function registerViewExtensions(Container $container)
* @param string $uri A URI path to wrap.
* @return UriInterface|null
*/
- 'withAdminUrl' => function ($uri, LambdaHelper $helper = null) use ($adminUrl) {
- if ($helper) {
+ 'withAdminUrl' => function ($uri, ?LambdaHelper $helper = null) use ($adminUrl) {
+ if ($helper instanceof LambdaHelper) {
$uri = $helper->render($uri);
}
@@ -397,16 +381,13 @@ protected function registerViewExtensions(Container $container)
$uri = $adminUrl->withPath('');
} else {
$parts = parse_url($uri);
- if (!isset($parts['scheme'])) {
- if (!in_array($uri[0], ['/', '#', '?'])) {
- $path = isset($parts['path']) ? ltrim($parts['path'], '/') : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
-
- return $adminUrl->withPath($path)
- ->withQuery($query)
- ->withFragment($hash);
- }
+ if (!isset($parts['scheme']) && !in_array($uri[0], ['/', '#', '?'])) {
+ $path = isset($parts['path']) ? ltrim($parts['path'], '/') : '';
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
+ return $adminUrl->withPath($path)
+ ->withQuery($query)
+ ->withFragment($hash);
}
}
@@ -432,7 +413,7 @@ protected function registerElfinderServices(Container $container)
* @param AdminConfig $adminConfig The admin configset.
* @return AdminConfig
*/
- $container->extend('admin/config', function (AdminConfig $adminConfig) {
+ $container->extend('admin/config', function (AdminConfig $adminConfig): \Charcoal\Admin\Config {
$adminConfig['elfinder'] = new Config($adminConfig['elfinder']);
return $adminConfig;
@@ -444,9 +425,7 @@ protected function registerElfinderServices(Container $container)
* @param Container $container The Pimple DI Container.
* @return ConfigInterface
*/
- $container['elfinder/config'] = function (Container $container) {
- return $container['admin/config']['elfinder'];
- };
+ $container['elfinder/config'] = (fn(Container $container): mixed => $container['admin/config']['elfinder']);
}
/**
@@ -463,14 +442,12 @@ protected function registerSelectizeServices(Container $container)
* @param Container $container The Pimple DI container.
* @return SelectizeRenderer
*/
- $container['selectize/renderer'] = function (Container $container) {
- return new SelectizeRenderer([
- 'logger' => $container['logger'],
- 'translator' => $container['translator'],
- 'template_factory' => $container['template/factory'],
- 'view' => $container['view']
- ]);
- };
+ $container['selectize/renderer'] = (fn(Container $container): \Charcoal\Admin\Service\SelectizeRenderer => new SelectizeRenderer([
+ 'logger' => $container['logger'],
+ 'translator' => $container['translator'],
+ 'template_factory' => $container['template/factory'],
+ 'view' => $container['view']
+ ]));
}
/**
@@ -479,7 +456,7 @@ protected function registerSelectizeServices(Container $container)
*/
protected function registerAssetsManager(Container $container)
{
- $container['assets/config'] = function (Container $container) {
+ $container['assets/config'] = function (Container $container): \Charcoal\Admin\AssetsConfig {
$config = $container['admin/config']->get('assets');
return new AssetsConfig($config);
@@ -498,54 +475,48 @@ protected function registerFactoryServices(Container $container)
* @param Container $container The Pimple DI container.
* @return FactoryInterface
*/
- $container['property/input/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => PropertyInputInterface::class,
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger']
- ]],
- 'resolver_options' => [
- 'suffix' => 'Input'
- ]
- ]);
- };
+ $container['property/input/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => PropertyInputInterface::class,
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger']
+ ]],
+ 'resolver_options' => [
+ 'suffix' => 'Input'
+ ]
+ ]));
/**
* @param Container $container The Pimple DI container.
* @return FactoryInterface
*/
- $container['property/display/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => PropertyDisplayInterface::class,
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger']
- ]],
- 'resolver_options' => [
- 'suffix' => 'Display'
- ]
- ]);
- };
+ $container['property/display/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => PropertyDisplayInterface::class,
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger']
+ ]],
+ 'resolver_options' => [
+ 'suffix' => 'Display'
+ ]
+ ]));
/**
* @param Container $container A Pimple DI container.
* @return FactoryInterface
*/
- $container['secondary-menu/group/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => SecondaryMenuGroupInterface::class,
- 'default_class' => GenericSecondaryMenuGroup::class,
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger'],
- 'view' => $container['view'],
- 'layout_builder' => $container['layout/builder']
- ]],
- 'resolver_options' => [
- 'suffix' => 'SecondaryMenuGroup'
- ]
- ]);
- };
+ $container['secondary-menu/group/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => SecondaryMenuGroupInterface::class,
+ 'default_class' => GenericSecondaryMenuGroup::class,
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger'],
+ 'view' => $container['view'],
+ 'layout_builder' => $container['layout/builder']
+ ]],
+ 'resolver_options' => [
+ 'suffix' => 'SecondaryMenuGroup'
+ ]
+ ]));
}
}
diff --git a/packages/admin/src/Charcoal/Admin/ServiceProvider/AssetsManagerServiceProvider.php b/packages/admin/src/Charcoal/Admin/ServiceProvider/AssetsManagerServiceProvider.php
index a57520303..3132925d8 100644
--- a/packages/admin/src/Charcoal/Admin/ServiceProvider/AssetsManagerServiceProvider.php
+++ b/packages/admin/src/Charcoal/Admin/ServiceProvider/AssetsManagerServiceProvider.php
@@ -21,9 +21,8 @@ class AssetsManagerServiceProvider implements ServiceProviderInterface
* It should not get services.
*
* @param Container $container A container instance.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
$this->registerAssetsManager($container);
$this->registerMustacheHelpersServices($container);
@@ -36,9 +35,7 @@ public function register(Container $container)
protected function registerMustacheHelpersServices(Container $container)
{
if (!isset($container['view/mustache/helpers'])) {
- $container['view/mustache/helpers'] = function () {
- return [];
- };
+ $container['view/mustache/helpers'] = (fn(): array => []);
}
/**
@@ -47,11 +44,9 @@ protected function registerMustacheHelpersServices(Container $container)
* @param Container $container Pimple DI container.
* @return AssetsHelpers
*/
- $container['view/mustache/helpers/assets-manager'] = function (Container $container) {
- return new AssetsHelpers([
- 'assets' => $container['assets']
- ]);
- };
+ $container['view/mustache/helpers/assets-manager'] = (fn(Container $container): \Charcoal\Admin\Mustache\AssetsHelpers => new AssetsHelpers([
+ 'assets' => $container['assets']
+ ]));
/**
* Extend global helpers for the Mustache Engine.
@@ -60,12 +55,10 @@ protected function registerMustacheHelpersServices(Container $container)
* @param Container $container A container instance.
* @return array
*/
- $container->extend('view/mustache/helpers', function (array $helpers, Container $container) {
- return array_merge(
- $helpers,
- $container['view/mustache/helpers/assets-manager']->toArray()
- );
- });
+ $container->extend('view/mustache/helpers', fn(array $helpers, Container $container): array => array_merge(
+ $helpers,
+ $container['view/mustache/helpers/assets-manager']->toArray()
+ ));
}
/**
@@ -76,13 +69,13 @@ protected function registerMustacheHelpersServices(Container $container)
*/
protected function registerAssetsManager(Container $container)
{
- $container['assets/config'] = function (Container $container) {
+ $container['assets/config'] = function (Container $container): \Charcoal\Admin\AssetsConfig {
$config = $container['view/config']->get('assets');
return new AssetsConfig($config);
};
- $container['assets/builder'] = function (Container $container) {
+ $container['assets/builder'] = function (Container $container): \Charcoal\Admin\Service\AssetsBuilder {
$appConfig = $container['config'];
return new AssetsBuilder($appConfig['base_path']);
diff --git a/packages/admin/src/Charcoal/Admin/Support/AdminTrait.php b/packages/admin/src/Charcoal/Admin/Support/AdminTrait.php
index 33227c31e..d46b7c273 100644
--- a/packages/admin/src/Charcoal/Admin/Support/AdminTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Support/AdminTrait.php
@@ -49,12 +49,10 @@ protected function adminConfig($key = null, $default = null)
if ($key) {
if (isset($this->adminConfig[$key])) {
return $this->adminConfig[$key];
+ } elseif (!is_string($default) && is_callable($default)) {
+ return $default();
} else {
- if (!is_string($default) && is_callable($default)) {
- return $default();
- } else {
- return $default;
- }
+ return $default;
}
}
@@ -84,12 +82,10 @@ protected function appConfig($key = null, $default = null)
if ($key) {
if (isset($this->appConfig[$key])) {
return $this->appConfig[$key];
+ } elseif (!is_string($default) && is_callable($default)) {
+ return $default();
} else {
- if (!is_string($default) && is_callable($default)) {
- return $default();
- } else {
- return $default;
- }
+ return $default;
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Support/BaseUrlTrait.php b/packages/admin/src/Charcoal/Admin/Support/BaseUrlTrait.php
index b66c8c610..01ea85ac9 100644
--- a/packages/admin/src/Charcoal/Admin/Support/BaseUrlTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Support/BaseUrlTrait.php
@@ -50,7 +50,7 @@ public function baseUrl($targetPath = null)
if (!isset($this->baseUrl)) {
throw new RuntimeException(sprintf(
'The base URI is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
@@ -86,7 +86,7 @@ public function adminUrl($targetPath = null)
if (!isset($this->adminUrl)) {
throw new RuntimeException(sprintf(
'The Admin URI is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
@@ -101,17 +101,10 @@ public function adminUrl($targetPath = null)
* Determine if the given URI is relative.
*
* @param string $uri A URI path to test.
- * @return boolean
*/
- protected function isRelativeUri($uri)
+ protected function isRelativeUri($uri): bool
{
- if ($uri && !parse_url($uri, PHP_URL_SCHEME)) {
- if (!in_array($uri[0], [ '/', '#', '?' ])) {
- return true;
- }
- }
-
- return false;
+ return $uri && !parse_url($uri, PHP_URL_SCHEME) && !in_array($uri[0], [ '/', '#', '?' ]);
}
/**
@@ -126,14 +119,12 @@ protected function createAbsoluteUrl(UriInterface $basePath, $targetPath)
$targetPath = strval($targetPath);
if ($targetPath === '') {
return $basePath->withPath('');
- } else {
- if ($this->isRelativeUri($targetPath)) {
- $parts = parse_url($targetPath);
- $path = isset($parts['path']) ? ltrim($parts['path'], '/') : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
- $targetPath = $basePath->withPath($path)->withQuery($query)->withFragment($hash);
- }
+ } elseif ($this->isRelativeUri($targetPath)) {
+ $parts = parse_url($targetPath);
+ $path = isset($parts['path']) ? ltrim($parts['path'], '/') : '';
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
+ $targetPath = $basePath->withPath($path)->withQuery($query)->withFragment($hash);
}
return $targetPath;
diff --git a/packages/admin/src/Charcoal/Admin/Support/HttpAwareTrait.php b/packages/admin/src/Charcoal/Admin/Support/HttpAwareTrait.php
index 090f313af..24e2a324b 100644
--- a/packages/admin/src/Charcoal/Admin/Support/HttpAwareTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Support/HttpAwareTrait.php
@@ -38,7 +38,7 @@ public function httpRequest()
if ($this->httpRequest === null) {
throw new RuntimeException(sprintf(
'PSR-7 HTTP Request is not defined for "%s"',
- get_class($this)
+ $this::class
));
}
@@ -47,10 +47,8 @@ public function httpRequest()
/**
* Determine if a HTTP request object is set.
- *
- * @return boolean
*/
- public function hasHttpRequest()
+ public function hasHttpRequest(): bool
{
return $this->httpRequest instanceof RequestInterface;
}
@@ -77,7 +75,7 @@ public function httpResponse()
if ($this->httpResponse === null) {
throw new RuntimeException(sprintf(
'PSR-7 HTTP Response is not defined for "%s"',
- get_class($this)
+ $this::class
));
}
@@ -86,10 +84,8 @@ public function httpResponse()
/**
* Determine if a HTTP response object is set.
- *
- * @return boolean
*/
- public function hasHttpResponse()
+ public function hasHttpResponse(): bool
{
return $this->httpResponse instanceof ResponseInterface;
}
@@ -124,10 +120,8 @@ protected function updateHttpResponseStatus($code, $reasonPhrase = '')
/**
* Is this response successful?
- *
- * @return boolean
*/
- protected function isHttpResponseSuccessful()
+ protected function isHttpResponseSuccessful(): bool
{
$response = $this->httpResponse();
diff --git a/packages/admin/src/Charcoal/Admin/Support/SecurityTrait.php b/packages/admin/src/Charcoal/Admin/Support/SecurityTrait.php
index 86712e71e..23dbb0209 100644
--- a/packages/admin/src/Charcoal/Admin/Support/SecurityTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Support/SecurityTrait.php
@@ -15,10 +15,8 @@ trait SecurityTrait
*
* For example, the "Login" / "Reset Password" templates
* should return `false`.
- *
- * @return boolean
*/
- protected function authRequired()
+ protected function authRequired(): bool
{
return true;
}
diff --git a/packages/admin/src/Charcoal/Admin/Support/Sorter.php b/packages/admin/src/Charcoal/Admin/Support/Sorter.php
index c8c172b0d..5e3ab906c 100644
--- a/packages/admin/src/Charcoal/Admin/Support/Sorter.php
+++ b/packages/admin/src/Charcoal/Admin/Support/Sorter.php
@@ -1,5 +1,7 @@
$b);
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/Account/LostPasswordTemplate.php b/packages/admin/src/Charcoal/Admin/Template/Account/LostPasswordTemplate.php
index 9cef74fe5..1eb08d053 100644
--- a/packages/admin/src/Charcoal/Admin/Template/Account/LostPasswordTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/Account/LostPasswordTemplate.php
@@ -21,9 +21,9 @@ class LostPasswordTemplate extends AdminTemplate
* Determine if the password token is valid.
*
* @param RequestInterface $request The PSR-7 HTTP request.
- * @return boolean
*/
- public function init(RequestInterface $request)
+ #[\Override]
+ public function init(RequestInterface $request): bool
{
$translator = $this->translator();
@@ -52,10 +52,8 @@ public function init(RequestInterface $request)
return true;
}
- /**
- * @return boolean
- */
- public function authRequired()
+ #[\Override]
+ public function authRequired(): bool
{
return false;
}
@@ -73,6 +71,7 @@ public function urlLostPasswordAction()
*
* @return \Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -87,7 +86,8 @@ public function title()
*
* @return string[]
*/
- public function recaptchaParameters()
+ #[\Override]
+ public function recaptchaParameters(): array
{
$params = parent::recaptchaParameters();
$params['tabindex'] = 2;
@@ -103,13 +103,11 @@ public function recaptchaParameters()
// Templating
// =========================================================================
-
/**
* Determine if main & secondary menu should appear as mobile in a desktop resolution.
- *
- * @return boolean
*/
- public function isFullscreenTemplate()
+ #[\Override]
+ public function isFullscreenTemplate(): bool
{
return true;
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/Account/ResetPasswordTemplate.php b/packages/admin/src/Charcoal/Admin/Template/Account/ResetPasswordTemplate.php
index d46c70b53..ddd5d47c9 100644
--- a/packages/admin/src/Charcoal/Admin/Template/Account/ResetPasswordTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/Account/ResetPasswordTemplate.php
@@ -30,18 +30,14 @@ class ResetPasswordTemplate extends AdminTemplate
* Determine if the password token is valid.
*
* @param RequestInterface $request The PSR-7 HTTP request.
- * @return boolean
*/
- public function init(RequestInterface $request)
+ #[\Override]
+ public function init(RequestInterface $request): bool
{
// Undocumented Slim 3 feature: The route attributes are stored in routeInfo[2].
$routeInfo = $request->getAttribute('routeInfo');
- if (isset($routeInfo[2]['token'])) {
- $this->lostPasswordToken = $routeInfo[2]['token'];
- } else {
- $this->lostPasswordToken = $request->getParam('token');
- }
+ $this->lostPasswordToken = ($routeInfo[2]['token'] ?? $request->getParam('token'));
if ($this->lostPasswordToken && $this->validateToken($this->lostPasswordToken)) {
return true;
@@ -60,10 +56,8 @@ public function lostPasswordToken()
return $this->lostPasswordToken;
}
- /**
- * @return boolean
- */
- public function authRequired()
+ #[\Override]
+ public function authRequired(): bool
{
return false;
}
@@ -86,9 +80,8 @@ public function urlResetPasswordAction()
*
* @see \Charcoal\Admin\Action\Account\ResetPasswordAction::validateToken()
* @param string $token The token to validate.
- * @return boolean
*/
- private function validateToken($token)
+ private function validateToken($token): bool
{
$obj = $this->modelFactory()->create(LostPasswordToken::class);
$sql = strtr('SELECT * FROM `%table` WHERE `token` = :token AND `expiry` > NOW()', [
@@ -98,7 +91,7 @@ private function validateToken($token)
'token' => $token
]);
- return !!$obj->token();
+ return (bool)$obj->token();
}
/**
@@ -106,6 +99,7 @@ private function validateToken($token)
*
* @return \Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -120,7 +114,8 @@ public function title()
*
* @return string[]
*/
- public function recaptchaParameters()
+ #[\Override]
+ public function recaptchaParameters(): array
{
$params = parent::recaptchaParameters();
$params['tabindex'] = 5;
@@ -136,13 +131,11 @@ public function recaptchaParameters()
// Templating
// =========================================================================
-
/**
* Determine if main & secondary menu should appear as mobile in a desktop resolution.
- *
- * @return boolean
*/
- public function isFullscreenTemplate()
+ #[\Override]
+ public function isFullscreenTemplate(): bool
{
return true;
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/AuthTemplateTrait.php b/packages/admin/src/Charcoal/Admin/Template/AuthTemplateTrait.php
index ab2c8b3fe..023686dda 100644
--- a/packages/admin/src/Charcoal/Admin/Template/AuthTemplateTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Template/AuthTemplateTrait.php
@@ -65,7 +65,7 @@ public function urlResetPassword()
* TRUE to use the default label,
* or FALSE to disable the link.
*/
- public function returnToSiteLabel()
+ public function returnToSiteLabel(): false|string
{
$label = $this->adminConfig('login.visit_site');
if ($label === false) {
diff --git a/packages/admin/src/Charcoal/Admin/Template/ElfinderTemplate.php b/packages/admin/src/Charcoal/Admin/Template/ElfinderTemplate.php
index f578f0f48..8162f5c5f 100644
--- a/packages/admin/src/Charcoal/Admin/Template/ElfinderTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/ElfinderTemplate.php
@@ -10,7 +10,7 @@
// From Pimple
use Pimple\Container;
// From Mustache
-use Mustache_LambdaHelper as LambdaHelper;
+use Mustache\LambdaHelper as LambdaHelper;
// From 'charcoal-factory'
use Charcoal\Factory\FactoryInterface;
// From 'charcoal-translator'
@@ -44,45 +44,35 @@ class ElfinderTemplate extends AdminTemplate
/**
* The related object type.
- *
- * @var string
*/
- private $objType;
+ private string|bool|null $objType = null;
/**
* The related object ID.
- *
- * @var string
*/
- private $objId;
+ private string|bool|null $objId = null;
/**
* The related property identifier.
- *
- * @var string
*/
- private $propertyIdent;
+ private string|bool|null $propertyIdent = null;
/**
* Whether to output JS/CSS assets for initializing elFinder.
- *
- * @var boolean
*/
- private $showAssets = true;
+ private bool $showAssets = true;
/**
* Custom localization messages.
*
* @var array|null
*/
- private $localizations;
+ private \ArrayIterator|array|null $localizations = null;
/**
* The related JS callback ID.
- *
- * @var string
*/
- private $callbackIdent = '';
+ private string|bool $callbackIdent = '';
/**
* URL for the elFinder connector.
@@ -95,31 +85,31 @@ class ElfinderTemplate extends AdminTemplate
* Sets the template data from a PSR Request object.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
- * @return self
*/
- protected function setDataFromRequest(RequestInterface $request)
+ #[\Override]
+ protected function setDataFromRequest(RequestInterface $request): static
{
$keys = $this->validDataFromRequest();
$data = $request->getParams($keys);
if (isset($data['obj_type'])) {
- $this->objType = filter_var($data['obj_type'], FILTER_SANITIZE_STRING);
+ $this->objType = htmlspecialchars(trim($data['obj_type']), ENT_QUOTES, 'UTF-8');
}
if (isset($data['obj_id'])) {
- $this->objId = filter_var($data['obj_id'], FILTER_SANITIZE_STRING);
+ $this->objId = htmlspecialchars(trim($data['obj_id']), ENT_QUOTES, 'UTF-8');
}
if (isset($data['property'])) {
- $this->propertyIdent = filter_var($data['property'], FILTER_SANITIZE_STRING);
+ $this->propertyIdent = htmlspecialchars(trim($data['property']), ENT_QUOTES, 'UTF-8');
}
if (isset($data['assets'])) {
- $this->showAssets = !!$data['assets'];
+ $this->showAssets = (bool)$data['assets'];
}
if (isset($data['callback'])) {
- $this->callbackIdent = filter_var($data['callback'], FILTER_SANITIZE_STRING);
+ $this->callbackIdent = htmlspecialchars(trim($data['callback']), ENT_QUOTES, 'UTF-8');
}
if (isset($this->elfinderConfig['translations'])) {
@@ -137,7 +127,8 @@ protected function setDataFromRequest(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
// Current object
@@ -152,6 +143,7 @@ protected function validDataFromRequest()
*
* @return Translation
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -165,9 +157,8 @@ public function title()
* Set the custom localization messages.
*
* @param array $localizations An associative array of localizations.
- * @return self
*/
- public function setLocalizations(array $localizations)
+ public function setLocalizations(array $localizations): static
{
$this->localizations = new ArrayIterator();
@@ -184,14 +175,13 @@ public function setLocalizations(array $localizations)
* @param string $ident The message ID.
* @param mixed $translations The message translations.
* @throws InvalidArgumentException If the message ID is not a string or the translations are invalid.
- * @return self
*/
- public function addLocalization($ident, $translations)
+ public function addLocalization($ident, $translations): static
{
if (!is_string($ident)) {
throw new InvalidArgumentException(sprintf(
'Translation key must be a string, received %s',
- (is_object($ident) ? get_class($ident) : gettype($ident))
+ (get_debug_type($ident))
));
}
@@ -205,14 +195,13 @@ public function addLocalization($ident, $translations)
*
* @param string $ident The message ID to remove.
* @throws InvalidArgumentException If the message ID is not a string.
- * @return self
*/
- public function removeLocalization($ident)
+ public function removeLocalization($ident): static
{
if (!is_string($ident)) {
throw new InvalidArgumentException(sprintf(
'Translation key must be a string, received %s',
- (is_object($ident) ? get_class($ident) : gettype($ident))
+ (get_debug_type($ident))
));
}
@@ -223,22 +212,18 @@ public function removeLocalization($ident)
/**
* Count the number of localizations.
- *
- * @return integer
*/
- public function numLocalizations()
+ public function numLocalizations(): int
{
return count($this->localizations());
}
/**
* Determine if there are any localizations.
- *
- * @return boolean
*/
- public function hasLocalizations()
+ public function hasLocalizations(): bool
{
- return !!$this->numLocalizations();
+ return (bool)$this->numLocalizations();
}
/**
@@ -246,7 +231,7 @@ public function hasLocalizations()
*
* @return array
*/
- public function localizations()
+ public function localizations(): \ArrayIterator|array|null
{
if ($this->localizations === null) {
$this->setLocalizations($this->defaultLocalizations());
@@ -267,15 +252,11 @@ public function localization($ident)
if (!is_string($ident)) {
throw new InvalidArgumentException(sprintf(
'Translation key must be a string, received %s',
- (is_object($ident) ? get_class($ident) : gettype($ident))
+ (get_debug_type($ident))
));
}
- if (isset($this->localizations[$ident])) {
- return $this->localizations[$ident];
- }
-
- return $ident;
+ return ($this->localizations[$ident] ?? $ident);
}
/**
@@ -283,7 +264,7 @@ public function localization($ident)
*
* @return array>
*/
- public function elfinderLocalizations()
+ public function elfinderLocalizations(): array
{
$i18n = [];
@@ -310,7 +291,7 @@ public function elfinderLocalizationsAsJson()
$options = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($this->debug()) {
- $options = ($options | JSON_PRETTY_PRINT);
+ $options |= JSON_PRETTY_PRINT;
}
return json_encode($this->elfinderLocalizations(), $options);
@@ -321,7 +302,7 @@ public function elfinderLocalizationsAsJson()
*
* @return string Returns a stringified JSON object, protected from Mustache rendering.
*/
- final public function escapedElfinderLocalizationsAsJson()
+ final public function escapedElfinderLocalizationsAsJson(): string
{
return '{{=<% %>=}}' . $this->elfinderLocalizationsAsJson() . '<%={{ }}=%>';
}
@@ -342,10 +323,7 @@ public function elfinderAssetsUrl()
return $this->baseUrl(static::ELFINDER_ASSETS_REL_PATH);
}
- /**
- * @return string
- */
- public function elfinderAssets()
+ public function elfinderAssets(): bool
{
return $this->showAssets;
}
@@ -355,16 +333,15 @@ public function elfinderAssets()
*
* @return string|null
*/
- public function elfinderCallback()
+ public function elfinderCallback(): string|bool
{
return $this->callbackIdent;
}
/**
* @param string $url The elFinder connector AJAX URL.
- * @return self
*/
- public function setElfinderConnectorUrl($url)
+ public function setElfinderConnectorUrl($url): static
{
$this->elfinderConnectorUrl = $url;
return $this;
@@ -392,7 +369,7 @@ public function prepareElfinderConnectorUrl()
{
$uri = $this->getElfinderConnectorUrlTemplate();
- return function ($noop, LambdaHelper $helper) use ($uri) {
+ return function ($noop, LambdaHelper $helper) use ($uri): null {
$uri = $helper->render($uri);
$this->setElfinderConnectorUrl($uri);
@@ -402,15 +379,12 @@ public function prepareElfinderConnectorUrl()
/**
* Retrieve the elFinder connector URL template for rendering.
- *
- * @return string
*/
- protected function getElfinderConnectorUrlTemplate()
+ protected function getElfinderConnectorUrlTemplate(): string
{
$uri = 'obj_type={{ objType }}&obj_id={{ objId }}&property={{ propertyIdent }}';
- $uri = '{{# withAdminUrl }}elfinder-connector?' . $uri . '{{/ withAdminUrl }}';
- return $uri;
+ return '{{# withAdminUrl }}elfinder-connector?' . $uri . '{{/ withAdminUrl }}';
}
/**
@@ -418,7 +392,7 @@ protected function getElfinderConnectorUrlTemplate()
*
* @return string|null
*/
- public function objType()
+ public function objType(): string|bool|null
{
return $this->objType;
}
@@ -428,7 +402,7 @@ public function objType()
*
* @return string|null
*/
- public function objId()
+ public function objId(): string|bool|null
{
return $this->objId;
}
@@ -438,7 +412,7 @@ public function objId()
*
* @return string|null
*/
- public function propertyIdent()
+ public function propertyIdent(): string|bool|null
{
return $this->propertyIdent;
}
@@ -476,24 +450,20 @@ public function formProperty()
*/
public function elfinderClientConfig()
{
- if (empty($this->elfinderConfig['client'])) {
- $settings = [];
- } else {
- $settings = $this->elfinderConfig['client'];
- }
+ $settings = empty($this->elfinderConfig['client']) ? [] : $this->elfinderConfig['client'];
$settings['lang'] = $this->translator()->getLocale();
$property = $this->formProperty();
if ($property) {
- $mimeTypes = filter_input(INPUT_GET, 'filetype', FILTER_SANITIZE_STRING);
+ $mimeTypes = htmlspecialchars(trim(($_GET['filetype'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($mimeTypes) {
if ($mimeTypes === 'file') {
$mimeTypes = [];
} elseif (!is_array($mimeTypes)) {
$mimeTypes = explode(',', $mimeTypes);
- $mimeTypes = array_filter($mimeTypes, 'strlen');
+ $mimeTypes = array_filter($mimeTypes, strlen(...));
}
$settings['onlyMimes'] = $mimeTypes;
@@ -517,7 +487,7 @@ public function elfinderClientConfigAsJson()
$options = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($this->debug()) {
- $options = ($options | JSON_PRETTY_PRINT);
+ $options |= JSON_PRETTY_PRINT;
}
return json_encode($this->elfinderClientConfig(), $options);
@@ -528,7 +498,7 @@ public function elfinderClientConfigAsJson()
*
* @return string Returns a stringified JSON object, protected from Mustache rendering.
*/
- final public function escapedElfinderClientConfigAsJson()
+ final public function escapedElfinderClientConfigAsJson(): string
{
return '{{=<% %>=}}' . $this->elfinderClientConfigAsJson() . '<%={{ }}=%>';
}
@@ -539,6 +509,7 @@ final public function escapedElfinderClientConfigAsJson()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -551,7 +522,7 @@ protected function setDependencies(Container $container)
*
* @return array
*/
- protected function defaultLocalizations()
+ protected function defaultLocalizations(): array
{
$t = $this->translator();
@@ -569,13 +540,11 @@ protected function defaultLocalizations()
// Templating
// =========================================================================
-
/**
* Determine if main & secondary menu should appear as mobile in a desktop resolution.
- *
- * @return boolean
*/
- public function isFullscreenTemplate()
+ #[\Override]
+ public function isFullscreenTemplate(): bool
{
return false;
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/HandlerTemplate.php b/packages/admin/src/Charcoal/Admin/Template/HandlerTemplate.php
index 235eea173..b87e87717 100644
--- a/packages/admin/src/Charcoal/Admin/Template/HandlerTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/HandlerTemplate.php
@@ -14,10 +14,8 @@ class HandlerTemplate extends AdminTemplate
{
use HandlerAwareTrait;
- /**
- * @return string
- */
- public function ident()
+ #[\Override]
+ public function ident(): string
{
return 'error';
}
@@ -27,6 +25,7 @@ public function ident()
*
* @return string|null
*/
+ #[\Override]
public function title()
{
return $this->appHandler()->getSummary();
@@ -34,10 +33,9 @@ public function title()
/**
* Error handler response is available to all users, no login required.
- *
- * @return boolean
*/
- protected function authRequired()
+ #[\Override]
+ protected function authRequired(): bool
{
return false;
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/HelpTemplate.php b/packages/admin/src/Charcoal/Admin/Template/HelpTemplate.php
index f1d62f01a..1e49057ac 100644
--- a/packages/admin/src/Charcoal/Admin/Template/HelpTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/HelpTemplate.php
@@ -1,5 +1,7 @@
title === null) {
diff --git a/packages/admin/src/Charcoal/Admin/Template/HomeTemplate.php b/packages/admin/src/Charcoal/Admin/Template/HomeTemplate.php
index 6737361a1..ea9fe663a 100644
--- a/packages/admin/src/Charcoal/Admin/Template/HomeTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/HomeTemplate.php
@@ -1,5 +1,7 @@
translator();
@@ -51,11 +51,10 @@ public function init(RequestInterface $request)
/**
* @todo Implement using PSR Request object
- * @return boolean
*/
- private function isHttps()
+ private function isHttps(): bool
{
- if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on') {
+ if (isset($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) === 'on') {
return true;
} elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
return true;
@@ -86,10 +85,9 @@ public function rememberMeEnabled()
/**
* Authentication is obviously never required for the login page.
- *
- * @return boolean
*/
- protected function authRequired()
+ #[\Override]
+ protected function authRequired(): bool
{
return false;
}
@@ -107,6 +105,7 @@ public function urlLoginAction()
*
* @return \Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -121,7 +120,8 @@ public function title()
*
* @return string[]
*/
- public function recaptchaParameters()
+ #[\Override]
+ public function recaptchaParameters(): array
{
$params = parent::recaptchaParameters();
$params['tabindex'] = 4;
@@ -137,13 +137,11 @@ public function recaptchaParameters()
// Templating
// =========================================================================
-
/**
* Determine if main & secondary menu should appear as mobile in a desktop resolution.
- *
- * @return boolean
*/
- public function isFullscreenTemplate()
+ #[\Override]
+ public function isFullscreenTemplate(): bool
{
return true;
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/LogoutTemplate.php b/packages/admin/src/Charcoal/Admin/Template/LogoutTemplate.php
index 66a8f2da7..dc2801fbd 100644
--- a/packages/admin/src/Charcoal/Admin/Template/LogoutTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/LogoutTemplate.php
@@ -1,5 +1,7 @@
authenticator();
@@ -34,10 +37,9 @@ public function init(RequestInterface $request)
/**
* Authentication is obviously never required for the login page.
- *
- * @return boolean
*/
- protected function authRequired()
+ #[\Override]
+ protected function authRequired(): bool
{
return false;
}
@@ -62,6 +64,7 @@ public function avatarImage()
*
* @return \Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -75,13 +78,11 @@ public function title()
// Templating
// =========================================================================
-
/**
* Determine if main & secondary menu should appear as mobile in a desktop resolution.
- *
- * @return boolean
*/
- public function isFullscreenTemplate()
+ #[\Override]
+ public function isFullscreenTemplate(): bool
{
return true;
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/Object/CollectionTemplate.php b/packages/admin/src/Charcoal/Admin/Template/Object/CollectionTemplate.php
index d7e213814..ab379e63a 100644
--- a/packages/admin/src/Charcoal/Admin/Template/Object/CollectionTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/Object/CollectionTemplate.php
@@ -42,9 +42,9 @@ class CollectionTemplate extends AdminTemplate implements
/**
* @param RequestInterface $request PSR-7 request.
- * @return boolean
*/
- public function init(RequestInterface $request)
+ #[\Override]
+ public function init(RequestInterface $request): bool
{
parent::init($request);
$this->createObjTable();
@@ -57,7 +57,8 @@ public function init(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type'
@@ -105,11 +106,7 @@ protected function createSearchWidget()
$widgetData = [];
}
- if (isset($widgetData['type'])) {
- $widgetType = $widgetData['type'];
- } else {
- $widgetType = SearchWidget::class;
- }
+ $widgetType = ($widgetData['type'] ?? SearchWidget::class);
$widget = $this->widgetFactory()->create($widgetType);
$widget->setObjType($this->objType());
@@ -127,9 +124,10 @@ protected function createSearchWidget()
*
* @return \Charcoal\Translator\Translation
*/
+ #[\Override]
public function title()
{
- if (isset($this->title)) {
+ if ($this->title !== null) {
return $this->title;
}
@@ -151,10 +149,10 @@ public function title()
$metadata = $model->metadata();
$objLabel = null;
- if (!$objLabel && isset($metadata['admin']['lists'])) {
+ if (isset($metadata['admin']['lists'])) {
$adminMetadata = $metadata['admin'];
- $listIdent = filter_input(INPUT_GET, 'collection_ident', FILTER_SANITIZE_STRING);
+ $listIdent = htmlspecialchars(trim(($_GET['collection_ident'] ?? '')), ENT_QUOTES, 'UTF-8');
if (!$listIdent) {
$listIdent = $this->collectionIdent();
}
@@ -190,11 +188,7 @@ public function title()
}
}
- if ($hasView) {
- $this->title = $model->render((string)$objLabel, $model);
- } else {
- $this->title = (string)$objLabel;
- }
+ $this->title = $hasView ? $model->render((string)$objLabel, $model) : (string)$objLabel;
return $this->title;
}
@@ -203,6 +197,7 @@ public function title()
* @param Container $container DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -234,15 +229,10 @@ protected function createDashboardConfig()
);
}
- $dashboardConfig = $adminMetadata['dashboards'][$dashboardIdent];
-
- return $dashboardConfig;
+ return $adminMetadata['dashboards'][$dashboardIdent];
}
- /**
- * @return void
- */
- private function createObjTable()
+ private function createObjTable(): void
{
$obj = $this->proto();
if (!$obj) {
@@ -289,7 +279,7 @@ private function metadataListIdent()
*/
private function metadataDashboardIdent()
{
- $dashboardIdent = filter_input(INPUT_GET, 'dashboard_ident', FILTER_SANITIZE_STRING);
+ $dashboardIdent = htmlspecialchars(trim(($_GET['dashboard_ident'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($dashboardIdent) {
return $dashboardIdent;
}
@@ -304,7 +294,7 @@ private function metadataDashboardIdent()
// You've reached error.
throw new Exception(sprintf(
'No default collection dashboard defined in admin metadata for %s.',
- get_class($this->proto())
+ $this->proto()::class
));
}
@@ -315,7 +305,6 @@ private function metadataDashboardIdent()
protected function objAdminMetadata()
{
$objMetadata = $this->proto()->metadata();
- $adminMetadata = isset($objMetadata['admin']) ? $objMetadata['admin'] : [];
- return $adminMetadata;
+ return ($objMetadata['admin'] ?? []);
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/Object/CreateTemplate.php b/packages/admin/src/Charcoal/Admin/Template/Object/CreateTemplate.php
index 4fa387bcf..79a26df09 100644
--- a/packages/admin/src/Charcoal/Admin/Template/Object/CreateTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/Object/CreateTemplate.php
@@ -28,13 +28,14 @@ class CreateTemplate extends AdminTemplate implements
* @param RequestInterface $request PSR-7 HTTP Server Request.
* @return boolean
*/
+ #[\Override]
public function init(RequestInterface $request)
{
$ret = parent::init($request);
if ($this->obj()->id()) {
$path = str_replace('object/create', 'object/edit', $request->getUri()->getPath());
- header('Location: ' . (string)$request->getUri()->withPath($path));
+ header('Location: ' . $request->getUri()->withPath($path));
die();
}
return $ret;
@@ -45,7 +46,8 @@ public function init(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type',
@@ -58,6 +60,7 @@ protected function validDataFromRequest()
*
* @return \Charcoal\Translator\Translation
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -79,10 +82,10 @@ public function title()
$objType = $this->objType();
$metadata = $obj->metadata();
- if (!$title && isset($metadata['admin']['forms'])) {
+ if (isset($metadata['admin']['forms'])) {
$adminMetadata = $metadata['admin'];
- $formIdent = filter_input(INPUT_GET, 'form_ident', FILTER_SANITIZE_STRING);
+ $formIdent = htmlspecialchars(trim(($_GET['form_ident'] ?? '')), ENT_QUOTES, 'UTF-8');
if (!$formIdent) {
if (isset($adminMetadata['defaultForm'])) {
$fomIdent = $adminMetadata['defaultForm'];
@@ -140,6 +143,7 @@ public function title()
*
* @return Translation|string|null
*/
+ #[\Override]
public function subtitle()
{
if ($this->subtitle === null) {
@@ -150,11 +154,7 @@ public function subtitle()
$config = [];
}
- if (isset($config['subtitle'])) {
- $title = $this->translator()->translation($config['subtitle']);
- } else {
- $title = '';
- }
+ $title = isset($config['subtitle']) ? $this->translator()->translation($config['subtitle']) : '';
$this->subtitle = $title;
}
@@ -166,6 +166,7 @@ public function subtitle()
* @param Container $container DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -194,7 +195,7 @@ protected function createDashboardConfig()
} else {
throw new Exception(sprintf(
'Can not show object creation dashboard: No default create dashboard defined in admin metadata for %s',
- get_class($this->obj())
+ $this->obj()::class
));
}
}
@@ -205,9 +206,7 @@ protected function createDashboardConfig()
);
}
- $dashboardConfig = $adminMetadata['dashboards'][$dashboardIdent];
-
- return $dashboardConfig;
+ return $adminMetadata['dashboards'][$dashboardIdent];
}
@@ -221,11 +220,11 @@ protected function objAdminMetadata()
$objMetadata = $obj->metadata();
- $adminMetadata = isset($objMetadata['admin']) ? $objMetadata['admin'] : null;
+ $adminMetadata = ($objMetadata['admin'] ?? null);
if ($adminMetadata === null) {
throw new Exception(sprintf(
'The object %s does not have an admin metadata.',
- get_class($obj)
+ $obj::class
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/Object/EditTemplate.php b/packages/admin/src/Charcoal/Admin/Template/Object/EditTemplate.php
index 9aedc36f5..1e81215ac 100644
--- a/packages/admin/src/Charcoal/Admin/Template/Object/EditTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/Object/EditTemplate.php
@@ -27,13 +27,14 @@ class EditTemplate extends AdminTemplate implements
* @param RequestInterface $request PSR-7 HTTP Server Request.
* @return boolean
*/
+ #[\Override]
public function init(RequestInterface $request)
{
$ret = parent::init($request);
if (!$this->obj()->id()) {
$path = str_replace('object/edit', 'object/create', $request->getUri()->getPath());
- header('Location: ' . (string)$request->getUri()->withPath($path));
+ header('Location: ' . $request->getUri()->withPath($path));
die();
}
return $ret;
@@ -44,7 +45,8 @@ public function init(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type',
@@ -57,6 +59,7 @@ protected function validDataFromRequest()
*
* @return \Charcoal\Translator\Translation
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -79,10 +82,10 @@ public function title()
$objType = $this->objType();
$metadata = $obj->metadata();
- if (!$title && isset($metadata['admin']['forms'])) {
+ if (isset($metadata['admin']['forms'])) {
$adminMetadata = $metadata['admin'];
- $formIdent = filter_input(INPUT_GET, 'form_ident', FILTER_SANITIZE_STRING);
+ $formIdent = htmlspecialchars(trim(($_GET['form_ident'] ?? '')), ENT_QUOTES, 'UTF-8');
if (!$formIdent) {
if (isset($adminMetadata['defaultForm'])) {
$fomIdent = $adminMetadata['defaultForm'];
@@ -128,6 +131,7 @@ public function title()
*
* @return Translation|string|null
*/
+ #[\Override]
public function subtitle()
{
if ($this->subtitle === null) {
@@ -138,11 +142,7 @@ public function subtitle()
$config = [];
}
- if (isset($config['subtitle'])) {
- $title = $this->translator()->translation($config['subtitle']);
- } else {
- $title = '';
- }
+ $title = isset($config['subtitle']) ? $this->translator()->translation($config['subtitle']) : '';
$this->subtitle = $this->renderTitle($title);
}
@@ -154,6 +154,7 @@ public function subtitle()
* @param Container $container DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -175,7 +176,7 @@ protected function createDashboardConfig()
$dashboardIdent = $this->dashboardIdent();
if (empty($dashboardIdent)) {
- $dashboardIdent = filter_input(INPUT_GET, 'dashboard_ident', FILTER_SANITIZE_STRING);
+ $dashboardIdent = htmlspecialchars(trim(($_GET['dashboard_ident'] ?? '')), ENT_QUOTES, 'UTF-8');
}
if (empty($dashboardIdent)) {
@@ -186,7 +187,7 @@ protected function createDashboardConfig()
} else {
throw new Exception(sprintf(
'No default edit dashboard defined in admin metadata for %s',
- get_class($this->obj())
+ $this->obj()::class
));
}
}
@@ -197,9 +198,7 @@ protected function createDashboardConfig()
);
}
- $dashboardConfig = $adminMetadata['dashboards'][$dashboardIdent];
-
- return $dashboardConfig;
+ return $adminMetadata['dashboards'][$dashboardIdent];
}
/**
@@ -228,11 +227,11 @@ protected function objAdminMetadata()
$objMetadata = $obj->metadata();
- $adminMetadata = isset($objMetadata['admin']) ? $objMetadata['admin'] : null;
+ $adminMetadata = ($objMetadata['admin'] ?? null);
if ($adminMetadata === null) {
throw new Exception(sprintf(
'The object %s does not have an admin metadata.',
- get_class($obj)
+ $obj::class
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/System/ClearCacheTemplate.php b/packages/admin/src/Charcoal/Admin/Template/System/ClearCacheTemplate.php
index f1f497b92..8bc64aadf 100644
--- a/packages/admin/src/Charcoal/Admin/Template/System/ClearCacheTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/System/ClearCacheTemplate.php
@@ -38,10 +38,8 @@ class ClearCacheTemplate extends AdminTemplate
/**
* Summary of cache.
- *
- * @var array
*/
- private $cacheInfo;
+ private ?array $cacheInfo = null;
/**
* Cache service config.
@@ -59,10 +57,8 @@ class ClearCacheTemplate extends AdminTemplate
/**
* Regular expression pattern to match a Stash / APC cache key.
- *
- * @var string
*/
- private $apcCacheKeyPattern;
+ private ?string $apcCacheKeyPattern = null;
/**
* Mustache View Engine.
@@ -83,6 +79,7 @@ class ClearCacheTemplate extends AdminTemplate
*
* @return \Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -97,10 +94,11 @@ public function title()
*
* @return \Charcoal\Admin\Widget\SecondaryMenuWidgetInterface|null
*/
+ #[\Override]
public function secondaryMenu()
{
if ($this->secondaryMenu === null) {
- $this->secondaryMenu = $this->createSecondaryMenu('system');
+ $this->secondaryMenu = $this->createSecondaryMenu();
}
return $this->secondaryMenu;
@@ -108,14 +106,13 @@ public function secondaryMenu()
/**
* @param boolean $force Whether to reload cache information.
- * @return array
*/
- public function cacheInfo($force = false)
+ public function cacheInfo($force = false): array
{
if ($this->cacheInfo === null || $force === true) {
$flip = array_flip($this->availableCacheDrivers);
- $driver = get_class($this->cache->getDriver());
- $cacheType = isset($flip['\\' . $driver]) ? $flip['\\' . $driver] : $driver;
+ $driver = $this->cache->getDriver()::class;
+ $cacheType = ($flip['\\' . $driver] ?? $driver);
$globalItems = $this->globalCacheItems();
$this->cacheInfo = [
@@ -137,7 +134,7 @@ public function cacheInfo($force = false)
/**
* @return string
*/
- private function getCacheNamespace()
+ private function getCacheNamespace(): bool|string
{
return $this->cache->getNamespace();
}
@@ -150,18 +147,12 @@ private function getApcNamespace()
return $this->cacheConfig['prefix'];
}
- /**
- * @return string
- */
- private function getGlobalCacheKey()
+ private function getGlobalCacheKey(): string
{
return '/::' . $this->getCacheNamespace() . '::/';
}
- /**
- * @return array
- */
- private function globalCacheInfo()
+ private function globalCacheInfo(): array
{
if ($this->isApc()) {
$cacheKey = $this->getGlobalCacheKey();
@@ -190,10 +181,7 @@ private function globalCacheItems()
}
}
- /**
- * @return string
- */
- private function getPagesCacheKey()
+ private function getPagesCacheKey(): string
{
return '/::' . $this->getCacheNamespace() . '::request::|::' . $this->getCacheNamespace() . '::template::/';
}
@@ -224,10 +212,7 @@ public function getTwigEngine(): ?TwigEngine
return null;
}
- /**
- * @return array
- */
- private function pagesCacheInfo()
+ private function pagesCacheInfo(): array
{
if ($this->isApc()) {
$cacheKey = $this->getPagesCacheKey();
@@ -243,31 +228,12 @@ private function pagesCacheInfo()
}
}
- /**
- * @return array
- */
- private function pagesCacheItems()
- {
- if ($this->isApc()) {
- $cacheKey = $this->getPagesCacheKey();
- return $this->apcCacheItems($cacheKey);
- } else {
- return [];
- }
- }
-
- /**
- * @return string
- */
- private function getObjectsCacheKey()
+ private function getObjectsCacheKey(): string
{
return '/::' . $this->getCacheNamespace() . '::object::|::' . $this->getCacheNamespace() . '::metadata::/';
}
- /**
- * @return array
- */
- private function objectsCacheInfo()
+ private function objectsCacheInfo(): array
{
if ($this->isApc()) {
$cacheKey = $this->getObjectsCacheKey();
@@ -289,7 +255,7 @@ private function objectsCacheInfo()
private function twigCacheInfo(): array
{
$engine = $this->getTwigEngine();
- if (!$engine) {
+ if (!$engine instanceof \Charcoal\View\Twig\TwigEngine) {
return [
'num_entries' => 0,
'total_size' => 0,
@@ -298,9 +264,7 @@ private function twigCacheInfo(): array
}
$defaultCachePath = realpath($engine->cache());
- $cachePath = $defaultCachePath
- ? $defaultCachePath
- : realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
+ $cachePath = $defaultCachePath ?: realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
if (!is_dir($cachePath)) {
return [
@@ -323,7 +287,7 @@ private function twigCacheInfo(): array
private function mustacheCacheInfo(): array
{
$engine = $this->getMustacheEngine();
- if (!$engine) {
+ if (!$engine instanceof \Charcoal\View\Mustache\MustacheEngine) {
return [
'num_entries' => 0,
'total_size' => 0,
@@ -332,9 +296,7 @@ private function mustacheCacheInfo(): array
}
$defaultCachePath = realpath($engine->cache());
- $cachePath = $defaultCachePath
- ? $defaultCachePath
- : realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
+ $cachePath = $defaultCachePath ?: realpath($this->appConfig['publicPath'] . DIRECTORY_SEPARATOR . $engine->cache());
if (!is_dir($cachePath)) {
return [
'no_cache_folder' => true,
@@ -362,24 +324,10 @@ private function dirSize(string $directory): int
return $size;
}
- /**
- * @return array
- */
- private function objectsCacheItems()
- {
- if ($this->isApc()) {
- $cacheKey = $this->getObjectsCacheKey();
- return $this->apcCacheItems($cacheKey);
- } else {
- return [];
- }
- }
-
/**
* @param string $key The cache key to look at.
- * @return array
*/
- private function apcCacheInfo($key)
+ private function apcCacheInfo(string $key): array
{
$iter = $this->createApcIterator($key);
@@ -393,8 +341,8 @@ private function apcCacheInfo($key)
$hitsTotal += $item['num_hits'];
$ttlTotal += $item['ttl'];
}
- $sizeAvg = $numEntries ? ($sizeTotal / $numEntries) : 0;
- $hitsAvg = $numEntries ? ($hitsTotal / $numEntries) : 0;
+ $sizeAvg = $numEntries !== 0 ? ($sizeTotal / $numEntries) : 0;
+ $hitsAvg = $numEntries !== 0 ? ($hitsTotal / $numEntries) : 0;
return [
'num_entries' => $numEntries,
'total_size' => $this->formatBytes($sizeTotal),
@@ -408,7 +356,7 @@ private function apcCacheInfo($key)
* @param string $key The cache key to look at.
* @return array|\Generator
*/
- private function apcCacheItems($key)
+ private function apcCacheItems(string $key)
{
$iter = $this->createApcIterator($key);
@@ -431,9 +379,8 @@ private function apcCacheItems($key)
/**
* @param string $key The cache item key to load.
* @throws RuntimeException If the APC Iterator class is missing.
- * @return \APCIterator|\APCUIterator|null
*/
- private function createApcIterator($key)
+ private function createApcIterator(string $key): \APCUIterator|\APCIterator
{
if (class_exists('\\APCUIterator', false)) {
return new \APCUIterator($key);
@@ -446,48 +393,40 @@ private function createApcIterator($key)
/**
* Determine if Charcoal has cache statistics.
- *
- * @return boolean
*/
- public function hasStats()
+ public function hasStats(): bool
{
return $this->isApc();
}
/**
* Determine if Charcoal is using the APC driver.
- *
- * @return boolean
*/
- public function isApc()
+ public function isApc(): bool
{
- return is_a($this->cache->getDriver(), Apc::class);
+ return $this->cache->getDriver() instanceof \Stash\Driver\Apc;
}
/**
* Determine if Charcoal is using the Memcache driver.
- *
- * @return boolean
*/
- public function isMemcache()
+ public function isMemcache(): bool
{
- return is_a($this->cache->getDriver(), Memcache::class);
+ return $this->cache->getDriver() instanceof \Stash\Driver\Memcache;
}
/**
* Determine if Charcoal is using the Ephemeral driver.
- *
- * @return boolean
*/
- public function isMemory()
+ public function isMemory(): bool
{
- return is_a($this->cache->getDriver(), Ephemeral::class);
+ return $this->cache->getDriver() instanceof \Stash\Driver\Ephemeral;
}
public function hasTwigCache(): bool
{
$engine = $this->getTwigEngine();
- if ($engine) {
+ if ($engine instanceof \Charcoal\View\Twig\TwigEngine) {
return (bool)$engine->config()['useCache'];
}
@@ -513,10 +452,8 @@ public function hasViewCache(): bool
* - `stashNS`: Stash Segment
* - `poolNS`: Optional. Application Key
* - `appKey`: Data Segment
- *
- * @return string
*/
- private function getApcCacheKeyPattern()
+ private function getApcCacheKeyPattern(): string
{
if ($this->apcCacheKeyPattern === null) {
$pattern = '/^(?[a-f0-9]{32})::(?:(?';
@@ -556,7 +493,7 @@ private function formatApcCacheKey($key)
* @param integer $bytes The number of bytes to format.
* @return string
*/
- private function formatBytes($bytes)
+ private function formatBytes($bytes): int|string
{
if ($bytes === 0) {
return 0;
@@ -566,7 +503,7 @@ private function formatBytes($bytes)
$base = log($bytes, 1024);
$floor = floor($base);
$unit = $units[$floor];
- $size = round(pow(1024, ($base - $floor)), 2);
+ $size = round((1024 ** ($base - $floor)), 2);
$locale = localeconv();
$size = number_format($size, 2, $locale['decimal_point'], $locale['thousands_sep']);
@@ -585,9 +522,9 @@ private function formatBytes($bytes)
* @param DateTimeInterface|null $date2 The datetime to compare against.
* @return string
*/
- private function formatTimeDiff(DateTimeInterface $date1, DateTimeInterface $date2 = null)
+ private function formatTimeDiff(DateTimeInterface $date1, ?DateTimeInterface $date2 = null)
{
- $isNow = $date2 === null;
+ $isNow = !$date2 instanceof \DateTimeInterface;
if ($isNow) {
$date2 = new DateTime('now', $date1->getTimezone());
}
@@ -626,15 +563,14 @@ private function formatTimeDiff(DateTimeInterface $date1, DateTimeInterface $dat
break;
}
- $time = $translator->transChoice($unit, $count, [ '{{ count }}' => $count ]);
-
- return $time;
+ return $translator->transChoice($unit, $count, [ '{{ count }}' => $count ]);
}
/**
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -644,14 +580,14 @@ protected function setDependencies(Container $container)
$this->cacheConfig = $container['cache/config'];
$this->mustacheEngine = function () use ($container) {
- if (class_exists('\Mustache_Engine')) {
+ if (class_exists('\Mustache\Engine')) {
return $container['view/engine/mustache'];
}
return null;
};
$this->twigEngine = function () use ($container) {
- if (class_exists('\Twig\Environment')) {
+ if (class_exists(\Twig\Environment::class)) {
return $container['view/engine/twig'];
}
diff --git a/packages/admin/src/Charcoal/Admin/Template/System/Object/InfoTemplate.php b/packages/admin/src/Charcoal/Admin/Template/System/Object/InfoTemplate.php
index a4a0f9988..334d10bcf 100644
--- a/packages/admin/src/Charcoal/Admin/Template/System/Object/InfoTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/System/Object/InfoTemplate.php
@@ -26,23 +26,21 @@ class InfoTemplate extends AdminTemplate implements
use DashboardContainerTrait;
use ObjectContainerTrait;
- /**
- * @var array
- */
- private $metadataFiles;
+ public $metadataLoader;
+ public $collectionLoader;
+
+ private ?array $metadataFiles = null;
/**
* @return \Charcoal\Admin\Translation|\Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function title()
{
return $this->objType();
}
- /**
- * @return array
- */
- public function objProperties()
+ public function objProperties(): array
{
$ret = [];
$properties = $this->obj()->metadata()->properties();
@@ -72,10 +70,10 @@ public function objProperties()
$ret[] = $property;
}
- usort($ret, function ($a, $b) {
- $ret = strcmp($a['metadataSource'], $b['metadataSource']);
+ usort($ret, function (array $a, array $b): int {
+ $ret = strcmp((string)$a['metadataSource'], (string)$b['metadataSource']);
if ($ret === 0) {
- return strcmp($a['ident'], $b['ident']);
+ return strcmp((string)$a['ident'], (string)$b['ident']);
} else {
return $ret;
}
@@ -83,29 +81,19 @@ public function objProperties()
return $ret;
}
- /**
- * @return string
- */
- public function className()
+ public function className(): string
{
- return get_class($this->obj());
+ return $this->obj()::class;
}
- /**
- * @return array
- */
- public function classHierarchy()
+ public function classHierarchy(): array
{
$ret = [];
$ret = array_merge($ret, array_keys(class_parents($this->obj())));
- $ret = array_reverse($ret);
- return $ret;
+ return array_reverse($ret);
}
- /**
- * @return array
- */
- public function classTraits()
+ public function classTraits(): array
{
$traits = [];
$hierarchy = $this->classHierarchy();
@@ -117,31 +105,23 @@ public function classTraits()
return $traits;
}
- /**
- * @return array
- */
- public function classInterfaces()
+ public function classInterfaces(): array
{
- $reflection = new ReflectionClass(get_class($this->obj()));
+ $reflection = new ReflectionClass($this->obj()::class);
$interfaces = array_keys($reflection->getInterfaces());
sort($interfaces);
return $interfaces;
}
- /**
- * @return array
- */
- public function metadataFiles()
+ public function metadataFiles(): array
{
if ($this->metadataFiles === null) {
$files = [];
$reflector = new ReflectionObject($this->metadataLoader);
$method = $reflector->getMethod('hierarchy');
- $method->setAccessible(true);
$hierarchy = $method->invoke($this->metadataLoader, $this->objType());
$method2 = $reflector->getMethod('loadMetadataFromSource');
- $method2->setAccessible(true);
foreach ($hierarchy as $source) {
$ret = $method2->invoke($this->metadataLoader, $source);
if (!empty($ret)) {
@@ -177,7 +157,7 @@ public function sourceTable()
*/
public function sourceEntries()
{
- $this->collectionLoader->setModel(get_class($this->obj()));
+ $this->collectionLoader->setModel($this->obj()::class);
return $this->collectionLoader->loadCount();
}
@@ -186,7 +166,8 @@ public function sourceEntries()
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type', 'obj_id'
@@ -197,6 +178,7 @@ protected function validDataFromRequest()
* @param Container $container DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -210,10 +192,7 @@ protected function setDependencies(Container $container)
$this->collectionLoader = $container['model/collection/loader'];
}
- /**
- * @return array
- */
- protected function createDashboardConfig()
+ protected function createDashboardConfig(): array
{
return [];
}
@@ -234,9 +213,8 @@ private function getFirstFile($propertyIdent)
/**
* @param string $propertyIdent The property ident to retrieve.
- * @return array
*/
- private function getAllFiles($propertyIdent)
+ private function getAllFiles($propertyIdent): array
{
$ret = [];
$files = $this->metadataFiles();
diff --git a/packages/admin/src/Charcoal/Admin/Template/System/StaticWebsiteTemplate.php b/packages/admin/src/Charcoal/Admin/Template/System/StaticWebsiteTemplate.php
index 9dadc2108..fb60a3459 100644
--- a/packages/admin/src/Charcoal/Admin/Template/System/StaticWebsiteTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/System/StaticWebsiteTemplate.php
@@ -21,6 +21,7 @@ class StaticWebsiteTemplate extends AdminTemplate
*
* @return \Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function title()
{
if ($this->title === null) {
@@ -35,19 +36,17 @@ public function title()
*
* @return \Charcoal\Admin\Widget\SecondaryMenuWidgetInterface|null
*/
+ #[\Override]
public function secondaryMenu()
{
if ($this->secondaryMenu === null) {
- $this->secondaryMenu = $this->createSecondaryMenu('system');
+ $this->secondaryMenu = $this->createSecondaryMenu();
}
return $this->secondaryMenu;
}
- /**
- * @return boolean
- */
- public function isStaticWebsiteEnabled()
+ public function isStaticWebsiteEnabled(): bool
{
return file_exists($this->basePath . DIRECTORY_SEPARATOR . '/www/static');
}
@@ -65,7 +64,7 @@ public function staticWebsiteFiles()
'size' => $this->formatBytes(filesize($file)),
'mtime' => date(DATE_ATOM, filemtime($file)),
'generated' => date('Y-m-d H:i:s', filemtime($file)),
- 'type' => pathinfo($file, PATHINFO_EXTENSION)
+ 'type' => pathinfo((string)$file, PATHINFO_EXTENSION)
];
}
}
@@ -74,6 +73,7 @@ public function staticWebsiteFiles()
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -84,9 +84,8 @@ protected function setDependencies(Container $container)
* Human-readable bytes format.
*
* @param integer $size The number of bytes to format.
- * @return boolean
*/
- private function formatBytes($size)
+ private function formatBytes(int|bool $size): int|string
{
if ($size === 0) {
return 0;
@@ -95,7 +94,7 @@ private function formatBytes($size)
$suffixes = [ 'bytes', 'k', 'M', 'G', 'T' ];
$floor = floor($base);
- return round(pow(1024, ($base - $floor)), 2) . ' ' . $suffixes[$floor];
+ return round((1024 ** ($base - $floor)), 2) . ' ' . $suffixes[$floor];
}
/**
@@ -104,7 +103,7 @@ private function formatBytes($size)
* @param integer $flags Glob flags.
* @return array
*/
- private function globRecursive($dir, $pattern, $flags = 0)
+ private function globRecursive(string $dir, string $pattern, $flags = 0): array|false
{
$files = glob($dir . '/' . $pattern, $flags);
foreach (glob($dir . '/*', (GLOB_ONLYDIR | GLOB_NOSORT)) as $dir) {
diff --git a/packages/admin/src/Charcoal/Admin/Template/System/UserPermissionsTemplate.php b/packages/admin/src/Charcoal/Admin/Template/System/UserPermissionsTemplate.php
index 633ae4243..745d61a8c 100644
--- a/packages/admin/src/Charcoal/Admin/Template/System/UserPermissionsTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/System/UserPermissionsTemplate.php
@@ -26,9 +26,9 @@ class UserPermissionsTemplate extends AdminTemplate implements
/**
* @param RequestInterface $request PSR-7 request.
- * @return boolean
*/
- public function init(RequestInterface $request)
+ #[\Override]
+ public function init(RequestInterface $request): bool
{
parent::init($request);
@@ -42,17 +42,15 @@ public function init(RequestInterface $request)
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type'
], parent::validDataFromRequest());
}
- /**
- * @return void
- */
- private function createObjTable()
+ private function createObjTable(): void
{
$obj = $this->modelFactory()->create('charcoal/admin/user/permission');
if ($obj->source()->tableExists() === false) {
@@ -70,15 +68,13 @@ private function createObjTable()
/**
* @return \Charcoal\Translator\Translation
*/
- public function title()
+ #[\Override]
+ public function title(): ?\Charcoal\Translator\Translation
{
return $this->translator()->translation('Administrator Permissions');
}
- /**
- * @return mixed
- */
- public function createDashboardConfig()
+ public function createDashboardConfig(): array
{
return [
'layout' => [
@@ -99,6 +95,7 @@ public function createDashboardConfig()
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Template/System/UserRolesTemplate.php b/packages/admin/src/Charcoal/Admin/Template/System/UserRolesTemplate.php
index cf457c235..adadb1a71 100644
--- a/packages/admin/src/Charcoal/Admin/Template/System/UserRolesTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/System/UserRolesTemplate.php
@@ -25,7 +25,8 @@ class UserRolesTemplate extends AdminTemplate implements
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type'
@@ -35,15 +36,13 @@ protected function validDataFromRequest()
/**
* @return \Charcoal\Translator\Translation
*/
- public function title()
+ #[\Override]
+ public function title(): ?\Charcoal\Translator\Translation
{
return $this->translator()->translation('Administrator Roles');
}
- /**
- * @return mixed
- */
- public function createDashboardConfig()
+ public function createDashboardConfig(): array
{
return [
'layout' => [
@@ -64,6 +63,7 @@ public function createDashboardConfig()
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Template/System/UsersTemplate.php b/packages/admin/src/Charcoal/Admin/Template/System/UsersTemplate.php
index 5e83f09d1..6395fd450 100644
--- a/packages/admin/src/Charcoal/Admin/Template/System/UsersTemplate.php
+++ b/packages/admin/src/Charcoal/Admin/Template/System/UsersTemplate.php
@@ -27,7 +27,8 @@ class UsersTemplate extends AdminTemplate implements
*
* @return string[]
*/
- protected function validDataFromRequest()
+ #[\Override]
+ protected function validDataFromRequest(): array
{
return array_merge([
'obj_type'
@@ -39,15 +40,13 @@ protected function validDataFromRequest()
*
* @return \Charcoal\Translator\Translation|string|null
*/
- public function title()
+ #[\Override]
+ public function title(): ?\Charcoal\Translator\Translation
{
return $this->translator()->translation('Administrators');
}
- /**
- * @return mixed
- */
- public function createDashboardConfig()
+ public function createDashboardConfig(): array
{
return [
'layout' => [
@@ -68,6 +67,7 @@ public function createDashboardConfig()
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Ui/ActionContainerTrait.php b/packages/admin/src/Charcoal/Admin/Ui/ActionContainerTrait.php
index b0fa09721..e3016c63e 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/ActionContainerTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/ActionContainerTrait.php
@@ -38,7 +38,7 @@ trait ActionContainerTrait
* to determine if any renderables should be processed.
* @return array Returns a collection of parsed actions.
*/
- protected function parseActions(array $actions, $renderer = false)
+ protected function parseActions(array $actions, $renderer = false): array
{
$this->actionsPriority = $this->defaultActionPriority();
@@ -63,7 +63,7 @@ protected function parseActions(array $actions, $renderer = false)
}
}
- usort($parsedActions, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ usort($parsedActions, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
while (($first = reset($parsedActions)) && $first['isSeparator']) {
array_shift($parsedActions);
@@ -82,7 +82,7 @@ protected function parseActions(array $actions, $renderer = false)
* @param array ...$params Variable list of actions to merge.
* @return array Returns a collection of merged actions.
*/
- protected function mergeActions(array ...$params)
+ protected function mergeActions(array ...$params): array
{
$unique = [];
foreach ($params as $actions) {
@@ -96,15 +96,11 @@ protected function mergeActions(array ...$params)
$action['ident'] = $ident;
$hasActions = (isset($action['actions']) && is_array($action['actions']));
- if ($hasActions) {
- $action['actions'] = $this->mergeActions($action['actions']);
- } else {
- $action['actions'] = [];
- }
+ $action['actions'] = $hasActions ? $this->mergeActions($action['actions']) : [];
if (isset($unique[$ident])) {
if (static::compareActions($action, $unique[$ident])) {
- if ($hasActions && !!$unique[$ident]['actions']) {
+ if ($hasActions && (bool)$unique[$ident]['actions']) {
$action['actions'] = $this->mergeActions(
$unique[$ident]['actions'],
$action['actions']
@@ -113,7 +109,7 @@ protected function mergeActions(array ...$params)
}
$unique[$ident] = array_replace($unique[$ident], $action);
} else {
- if ($hasActions && !!$unique[$ident]['actions']) {
+ if ($hasActions && (bool)$unique[$ident]['actions']) {
$unique[$ident]['actions'] = $this->mergeActions(
$unique[$ident]['actions'],
$action['actions']
@@ -138,13 +134,9 @@ protected function mergeActions(array ...$params)
* @param mixed $action The action structure.
* @return string Resolved action identifier.
*/
- protected function parseActionIdent($ident, $action)
+ protected function parseActionIdent($ident, array $action)
{
- if (isset($action['ident'])) {
- return $action['ident'];
- }
-
- return $ident;
+ return ($action['ident'] ?? $ident);
}
/**
@@ -176,11 +168,9 @@ protected function parseActionItem($action, $ident, $renderer = false)
$action['ident'] = $ident;
}
- if (isset($action['buttonType'])) {
- if (!in_array($action['buttonType'], $buttonTypes)) {
- $action['actionType'] = $action['buttonType'];
- $action['buttonType'] = 'button';
- }
+ if (isset($action['buttonType']) && !in_array($action['buttonType'], $buttonTypes)) {
+ $action['actionType'] = $action['buttonType'];
+ $action['buttonType'] = 'button';
}
if (!isset($action['actionType'])) {
@@ -232,21 +222,17 @@ protected function parseActionItem($action, $ident, $renderer = false)
}
if (isset($action['dataAttributes']) && is_array($action['dataAttributes'])) {
- $action['dataAttributes'] = array_filter($action['dataAttributes'], function ($attribute) {
- return !empty($attribute['key']) &&
- is_string($attribute['key']) &&
- !empty($attribute['value']) &&
- is_string($attribute['value']);
- });
+ $action['dataAttributes'] = array_filter($action['dataAttributes'], fn(array $attribute): bool => !empty($attribute['key']) &&
+ is_string($attribute['key']) &&
+ !empty($attribute['value']) &&
+ is_string($attribute['value']));
} else {
$action['dataAttributes'] = [];
}
if (isset($action['actions']) && is_array($action['actions'])) {
$action['actions'] = $this->parseActions($action['actions']);
- $action['hasActions'] = !!array_filter($action['actions'], function ($action) {
- return $action['active'];
- });
+ $action['hasActions'] = (bool)array_filter($action['actions'], fn(array $action): mixed => $action['active']);
} else {
$action['actions'] = [];
$action['hasActions'] = false;
@@ -267,41 +253,25 @@ protected function parseActionItem($action, $ident, $renderer = false)
* Resolve the action's type.
*
* @param mixed $action The action structure.
- * @return string
*/
- protected function resolveActionType($action)
+ protected function resolveActionType(array $action): string
{
- switch ($action['ident']) {
- case 'create':
- case 'save':
- case 'submit':
- case 'update':
- case 'edit':
- return 'primary';
-
- case 'reset':
- return 'warning';
-
- case 'delete':
- return 'danger';
-
- default:
- return 'dark';
- }
+ return match ($action['ident']) {
+ 'create', 'save', 'submit', 'update', 'edit' => 'primary',
+ 'reset' => 'warning',
+ 'delete' => 'danger',
+ default => 'dark',
+ };
}
/**
* Fetch a viewable instance to process an action's renderables.
- *
- * @return ViewableInterface|null
*/
- protected function getActionRenderer()
+ protected function getActionRenderer(): ?\Charcoal\View\ViewableInterface
{
$obj = null;
- if ($this instanceof FormSidebarInterface) {
- if ($this->form()) {
- $obj = $this->form()->obj();
- }
+ if ($this instanceof FormSidebarInterface && $this->form()) {
+ $obj = $this->form()->obj();
}
if ($this instanceof ObjectContainerInterface) {
@@ -309,7 +279,7 @@ protected function getActionRenderer()
}
if ($this instanceof CollectionContainerInterface) {
- $obj = isset($this->currentObj) ? $this->currentObj : $this->proto();
+ $obj = ($this->currentObj ?? $this->proto());
}
if (($obj instanceof ViewableInterface) && ($obj->view() instanceof ViewInterface)) {
@@ -328,7 +298,7 @@ protected function getActionRenderer()
* @throws RuntimeException If a renderer is unavailable.
* @return array Resolved action structure.
*/
- protected function parseActionRenderables($action, $renderer)
+ protected function parseActionRenderables(array $action, $renderer): array
{
if ($renderer === false) {
return $action;
@@ -379,13 +349,13 @@ protected function parseActionCondition($condition, $action = null, $renderer =
$result = null;
if ($renderer && is_callable([ $renderer, $condition ])) {
- $result = !!$renderer->{$condition}();
+ $result = (bool)$renderer->{$condition}();
} elseif (is_callable([ $this, $condition ])) {
- $result = !!$this->{$condition}();
+ $result = (bool)$this->{$condition}();
} elseif (is_callable($condition)) {
- $result = !!$condition();
+ $result = (bool)$condition();
} elseif ($renderer) {
- $result = !!$renderer->renderTemplate($condition);
+ $result = (bool)$renderer->renderTemplate($condition);
}
if ($result !== null) {
@@ -418,24 +388,24 @@ protected function parseActionUrl($url, $action = null, $renderer = null)
$url = trim($url);
- if (empty($url) && !is_numeric($url)) {
+ if (($url === '' || $url === '0') && !is_numeric($url)) {
return '#';
}
if ($renderer === null) {
/** @todo Shame! Force `{{ id }}` to use "obj_id" GET parameter… */
- $objId = filter_input(INPUT_GET, 'obj_id', FILTER_SANITIZE_STRING);
+ $objId = htmlspecialchars(trim(($_GET['obj_id'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($objId) {
$url = preg_replace('~\{\{\s*(obj_)?id\s*\}\}~', $objId, $url);
}
/** @todo Shame! Force `{{ type }}` to use "obj_type" GET parameter… */
- $objType = filter_input(INPUT_GET, 'obj_type', FILTER_SANITIZE_STRING);
+ $objType = htmlspecialchars(trim(($_GET['obj_type'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($objType) {
- $url = preg_replace('~\{\{\s*(obj_)?type\s*\}\}~', $objType, $url);
+ $url = preg_replace('~\{\{\s*(obj_)?type\s*\}\}~', $objType, (string)$url);
}
- if ($url && strpos($url, ':') === false && !in_array($url[0], [ '/', '#', '?' ])) {
+ if ($url && !str_contains($url, ':') && !in_array($url[0], [ '/', '#', '?' ])) {
$url = $this->adminUrl() . $url;
}
@@ -443,7 +413,7 @@ protected function parseActionUrl($url, $action = null, $renderer = null)
} elseif ($renderer instanceof ViewableInterface) {
$url = $renderer->renderTemplate($url);
- if ($url && strpos($url, ':') === false && !in_array($url[0], [ '/', '#', '?' ])) {
+ if ($url && !str_contains($url, ':') && !in_array($url[0], [ '/', '#', '?' ])) {
$url = $this->adminUrl() . $url;
}
}
@@ -479,10 +449,8 @@ protected function parseActionCssClasses($classes, $action = null, $renderer = n
/**
* Retrieve the default action structure.
- *
- * @return array
*/
- protected function defaultActionStruct()
+ protected function defaultActionStruct(): array
{
return [
'ident' => null,
@@ -533,10 +501,10 @@ protected function defaultActionPriority()
* @param array $b Second action object to sort.
* @return boolean Returns TRUE if $a has priority. Otherwise, FALSE for $b.
*/
- protected function compareActions(array $a, array $b)
+ protected function compareActions(array $a, array $b): bool
{
- $a = isset($a['priority']) ? $a['priority'] : 0;
- $b = isset($b['priority']) ? $b['priority'] : 0;
+ $a = ($a['priority'] ?? 0);
+ $b = ($b['priority'] ?? 0);
$c = isset($action['isSubmittable']) && $action['isSubmittable'];
return ($c || ($a === 0) || ($a >= $b));
diff --git a/packages/admin/src/Charcoal/Admin/Ui/CollectionContainerInterface.php b/packages/admin/src/Charcoal/Admin/Ui/CollectionContainerInterface.php
index b5a47967f..c6a4ad298 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/CollectionContainerInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/CollectionContainerInterface.php
@@ -1,5 +1,7 @@
modelFactory === null) {
throw new Exception(sprintf(
'Model Factory is not defined for "%s"',
- get_class($this)
+ $this::class
));
}
@@ -198,9 +197,8 @@ protected function modelFactory()
/**
* @param FactoryInterface $factory The property display factory.
- * @return CollectionContainerInterface Chainable
*/
- private function setPropertyDisplayFactory(FactoryInterface $factory)
+ private function setPropertyDisplayFactory(FactoryInterface $factory): CollectionContainerInterface
{
$this->propertyDisplayFactory = $factory;
@@ -209,14 +207,13 @@ private function setPropertyDisplayFactory(FactoryInterface $factory)
/**
* @throws Exception If the property display factory was not previously injected / set.
- * @return FactoryInterface
*/
- private function propertyDisplayFactory()
+ private function propertyDisplayFactory(): FactoryInterface
{
if ($this->propertyDisplayFactory === null) {
throw new Exception(sprintf(
'Property display factory is not defined for "%s"',
- get_class($this)
+ $this::class
));
}
@@ -225,9 +222,8 @@ private function propertyDisplayFactory()
/**
* @param CollectionLoader $loader The collection loader.
- * @return CollectionContainerInterface Chainable
*/
- public function setCollectionLoader(CollectionLoader $loader)
+ public function setCollectionLoader(CollectionLoader $loader): CollectionContainerInterface
{
$this->collectionLoader = $loader;
@@ -237,10 +233,8 @@ public function setCollectionLoader(CollectionLoader $loader)
/**
* Safe Collection Loader getter.
* Create the loader if it was not set / injected.
- *
- * @return CollectionLoader
*/
- protected function collectionLoader()
+ protected function collectionLoader(): CollectionLoader
{
if ($this->collectionLoader === null) {
$this->collectionLoader = $this->createCollectionLoader();
@@ -251,10 +245,8 @@ protected function collectionLoader()
/**
* Create a collection loader.
- *
- * @return CollectionLoader
*/
- protected function createCollectionLoader()
+ protected function createCollectionLoader(): \Charcoal\Loader\CollectionLoader
{
return new CollectionLoader([
'logger' => $this->logger,
@@ -269,16 +261,15 @@ protected function createCollectionLoader()
*
* @param CollectionLoader $loader The collection loader to prepare.
* @param array|null $data Optional collection data.
- * @return void
*/
- protected function configureCollectionLoader(CollectionLoader $loader, array $data = null)
+ protected function configureCollectionLoader(CollectionLoader $loader, ?array $data = null): void
{
- $objType = $this->getObjTypeOrFail();
+ $this->getObjTypeOrFail();
$loader->setModel($this->proto());
$config = $this->collectionConfig();
- if (is_array($config) && !empty($config)) {
+ if (is_array($config) && $config !== []) {
unset($config['properties']);
$loader->setData($config);
}
@@ -293,9 +284,8 @@ protected function configureCollectionLoader(CollectionLoader $loader, array $da
/**
* @param string $objType The collection's object type.
* @throws InvalidArgumentException If provided argument is not of type 'string'.
- * @return CollectionContainerInterface Chainable
*/
- public function setObjType($objType)
+ public function setObjType($objType): CollectionContainerInterface
{
if (!is_string($objType)) {
throw new InvalidArgumentException(
@@ -307,10 +297,7 @@ public function setObjType($objType)
return $this;
}
- /**
- * @return string
- */
- public function objType()
+ public function objType(): string
{
return $this->objType;
}
@@ -319,16 +306,15 @@ public function objType()
* Retrieve the current object type or throw an exception.
*
* @throws UnexpectedValueException If the collection object type is invalid or missing.
- * @return string
*/
- public function getObjTypeOrFail()
+ public function getObjTypeOrFail(): string
{
$objType = $this->objType();
if (!$objType) {
throw new UnexpectedValueException(sprintf(
'%1$s cannot create collection. Object type is not defined.',
- get_class($this)
+ $this::class
));
}
@@ -340,9 +326,8 @@ public function getObjTypeOrFail()
*
* @param string $collectionIdent The collection identifier.
* @throws InvalidArgumentException If the identifier argument is not a string.
- * @return CollectionContainerInterface Chainable
*/
- public function setCollectionIdent($collectionIdent)
+ public function setCollectionIdent($collectionIdent): CollectionContainerInterface
{
if (!is_string($collectionIdent)) {
throw new InvalidArgumentException(
@@ -358,10 +343,8 @@ public function setCollectionIdent($collectionIdent)
* Retrieve a key for the collection structure to use.
*
* If the collection key is undefined, resolve a fallback.
- *
- * @return string
*/
- public function collectionIdentFallback()
+ public function collectionIdentFallback(): string
{
$metadata = $this->proto()->metadata();
@@ -376,20 +359,16 @@ public function collectionIdentFallback()
/**
* Retrieve the key for the collection structure to use.
- *
- * @return string|null
*/
- public function collectionIdent()
+ public function collectionIdent(): ?string
{
return $this->collectionIdent;
}
/**
* Return the current collection metadata.
- *
- * @return array
*/
- public function collectionMetadata()
+ public function collectionMetadata(): array
{
$proto = $this->proto();
$collectionIdent = $this->collectionIdent();
@@ -417,10 +396,8 @@ public function collectionMetadata()
/**
* Retrieve the collection configset.
- *
- * @return array|null
*/
- public function collectionConfig()
+ public function collectionConfig(): ?array
{
if ($this->collectionConfig === null) {
$this->collectionConfig = $this->createCollectionConfig();
@@ -433,9 +410,8 @@ public function collectionConfig()
* Replace the collection's configset with the given parameters.
*
* @param mixed $config New collection config values.
- * @return CollectionContainerInterface Chainable
*/
- public function setCollectionConfig($config)
+ public function setCollectionConfig($config): CollectionContainerInterface
{
if (empty($config) || !is_array($config)) {
$config = [];
@@ -453,9 +429,8 @@ public function setCollectionConfig($config)
* Merge given parameters into the collection's configset.
*
* @param array $config New collection config values.
- * @return self
*/
- public function mergeCollectionConfig(array $config)
+ public function mergeCollectionConfig(array $config): static
{
if ($this->collectionConfig === null) {
$this->setCollectionConfig($config);
@@ -475,23 +450,18 @@ public function mergeCollectionConfig(array $config)
* Stub: Parse given parameters into the collection's config set.
*
* @param array $config New collection config values.
- * @return array
*/
- protected function parseCollectionConfig(array $config)
+ protected function parseCollectionConfig(array $config): array
{
- return array_filter($config, function ($val) {
- return !empty($val) || is_numeric($val);
- });
+ return array_filter($config, fn($val): bool => !empty($val) || is_numeric($val));
}
/**
* Retrieve the default collection configuration.
*
* The default configset is determined by the collection ident and object type, if assigned.
- *
- * @return array|null
*/
- protected function defaultCollectionConfig()
+ protected function defaultCollectionConfig(): ?array
{
if ($this->defaultCollectionConfig === null) {
$this->defaultCollectionConfig = $this->collectionMetadata();
@@ -502,28 +472,20 @@ protected function defaultCollectionConfig()
/**
* Stub: reimplement in classes using this trait.
- *
- * @return mixed
*/
- protected function createCollectionConfig()
+ protected function createCollectionConfig(): mixed
{
return $this->collectionMetadata();
}
- /**
- * @return boolean
- */
- public function hasPagination()
+ public function hasPagination(): bool
{
return ($this->pagination() instanceof Pagination);
}
- /**
- * @return PaginationInterface
- */
- public function pagination()
+ public function pagination(): PaginationInterface
{
- if ($this->pagination === null || !($this->pagination instanceof PaginationInterface)) {
+ if (!($this->pagination instanceof PaginationInterface)) {
$this->pagination = $this->createPagination();
$collectionConfig = $this->collectionConfig();
if (isset($collectionConfig['pagination'])) {
@@ -538,43 +500,32 @@ public function pagination()
* Prevents the mutation of pagination.
*
* @param mixed $pagination Unused parameter.
- * @return self
*/
- public function setPagination($pagination)
+ public function setPagination($pagination): static
{
unset($pagination);
return $this;
}
- /**
- * @return PaginationInterface
- */
- protected function createPagination()
+ protected function createPagination(): PaginationInterface
{
- $pagination = new Pagination();
- return $pagination;
+ return new Pagination();
}
- /**
- * @return integer
- */
- public function page()
+ public function page(): int
{
return $this->pagination()->page();
}
- /**
- * @return integer
- */
- public function numPerPage()
+ public function numPerPage(): int
{
return $this->pagination()->numPerPage();
}
/**
- * @return integer
+ * @throws Exception
*/
- public function numPages()
+ public function numPages(): int|float
{
if ($this->numPerPage() === 0) {
return 0;
@@ -583,10 +534,7 @@ public function numPages()
return ceil($this->numTotal() / $this->numPerPage());
}
- /**
- * @return boolean
- */
- public function hasFilters()
+ public function hasFilters(): bool
{
return count($this->filters()) > 0;
}
@@ -594,7 +542,7 @@ public function hasFilters()
/**
* @return FilterInterface[]
*/
- public function filters()
+ public function filters(): array
{
if ($this->filters === null) {
$this->filters = [];
@@ -619,27 +567,19 @@ public function filters()
* Prevents the mutation of filters.
*
* @param mixed $filters Unused parameter.
- * @return self
*/
- public function setFilters($filters)
+ public function setFilters($filters): static
{
unset($filters);
return $this;
}
- /**
- * @return FilterInterface
- */
- protected function createFilter()
+ protected function createFilter(): FilterInterface
{
- $filter = new Filter();
- return $filter;
+ return new Filter();
}
- /**
- * @return boolean
- */
- public function hasOrders()
+ public function hasOrders(): bool
{
return count($this->orders()) > 0;
}
@@ -647,7 +587,7 @@ public function hasOrders()
/**
* @return OrderInterface[]
*/
- public function orders()
+ public function orders(): array
{
if ($this->orders === null) {
$this->orders = [];
@@ -672,37 +612,28 @@ public function orders()
* Prevents the mutation of orders.
*
* @param mixed $orders Unused parameter.
- * @return self
*/
- public function setOrders($orders)
+ public function setOrders($orders): static
{
unset($orders);
return $this;
}
- /**
- * @return OrderInterface
- */
- protected function createOrder()
+ protected function createOrder(): OrderInterface
{
- $order = new Order();
- return $order;
+ return new Order();
}
/**
* @param mixed $collection The collection.
- * @return CollectionContainerInterface Chainable
*/
- public function setCollection($collection)
+ public function setCollection($collection): CollectionContainerInterface
{
$this->collection = $collection;
return $this;
}
- /**
- * @return Collection
- */
- public function collection()
+ public function collection(): Collection
{
if ($this->collection === null) {
$this->collection = $this->createCollection();
@@ -712,26 +643,20 @@ public function collection()
}
/**
+ * @param array|null $data Optional collection data.
+ * @return \ArrayAccess|array|ModelInterface[]
* @todo Integrate $data; merge with $collectionConfig
- * @param array $data Optional collection data.
- * @throws Exception If the object type of the colletion has not been set.
- * @return ModelInterface[]
*/
- public function createCollection(array $data = null)
+ public function createCollection(?array $data = null): \ArrayAccess|array
{
- $objType = $this->getObjTypeOrFail();
+ $this->getObjTypeOrFail();
$loader = $this->collectionLoader();
$this->configureCollectionLoader($loader, $data);
-
- $collection = $loader->load();
- return $collection;
+ return $loader->load();
}
- /**
- * @return array
- */
- public function objects()
+ public function objects(): array
{
return $this->collection()->values();
}
@@ -740,10 +665,8 @@ public function objects()
* Sort the objects before they are displayed as rows.
*
* This method is useful for classes using this trait.
- *
- * @return array
*/
- public function sortObjects()
+ public function sortObjects(): array
{
return $this->objects();
}
@@ -752,9 +675,8 @@ public function sortObjects()
* Prevents the mutation of properties.
*
* @param mixed $properties Unused parameter.
- * @return self
*/
- public function setProperties($properties)
+ public function setProperties($properties): static
{
unset($properties);
return $this;
@@ -764,10 +686,8 @@ public function setProperties($properties)
* Prepares and returns the properties.
*
* This method should be overriden in the class implementing this trait.
- *
- * @return array
*/
- public function properties()
+ public function properties(): array
{
return [];
}
@@ -776,10 +696,8 @@ public function properties()
* Sort the properties before they are displayed as columns.
*
* This method is useful for classes using this trait.
- *
- * @return array
*/
- public function sortProperties()
+ public function sortProperties(): array
{
return $this->properties();
}
@@ -788,19 +706,16 @@ public function sortProperties()
* Retrieve the property customizations for the collection.
*
* This method should be overriden in the class implementing this trait.
- *
- * @return array
*/
- public function propertiesOptions()
+ public function propertiesOptions(): array
{
return [];
}
/**
* Supplies properties for objects in table template specific to object configuration.
- * @return \Generator
*/
- public function objectRows()
+ public function objectRows(): \Generator
{
// Get properties as defined in object's list metadata
$properties = $this->sortProperties();
@@ -811,10 +726,8 @@ public function objectRows()
// Go through each object to generate an array of properties listed in object's list metadata
foreach ($objects as $object) {
- if (isset($object['requiredAclPermissions']) && !empty($object['requiredAclPermissions'])) {
- if ($this->hasPermissions($object['requiredAclPermissions']) === false) {
- continue;
- }
+ if (isset($object['requiredAclPermissions']) && !empty($object['requiredAclPermissions']) && $this->hasPermissions($object['requiredAclPermissions']) === false) {
+ continue;
}
$objectProperties = [];
@@ -855,9 +768,8 @@ public function objectRows()
*
* @param ModelInterface $object The current row's object.
* @param PropertyInterface $property The current property.
- * @return void
*/
- protected function setupDisplayPropertyValue(ModelInterface $object, PropertyInterface $property)
+ protected function setupDisplayPropertyValue(ModelInterface $object, PropertyInterface $property): void
{
$displayType = $property['displayType'];
@@ -891,13 +803,12 @@ protected function setupDisplayPropertyValue(ModelInterface $object, PropertyInt
* @param ModelInterface $object The current row's object.
* @param PropertyInterface $property The current property.
* @param string $propertyValue The property $key's display value.
- * @return array
*/
protected function parsePropertyCell(
ModelInterface $object,
PropertyInterface $property,
- $propertyValue
- ) {
+ string $propertyValue
+ ): array {
unset($object);
return [
@@ -913,9 +824,8 @@ protected function parsePropertyCell(
*
* @param ModelInterface $object The current row's object.
* @param array $objectProperties The $object's display properties.
- * @return array
*/
- protected function parseObjectRow(ModelInterface $object, array $objectProperties)
+ protected function parseObjectRow(ModelInterface $object, array $objectProperties): array
{
return [
'object' => $object,
@@ -925,27 +835,20 @@ protected function parseObjectRow(ModelInterface $object, array $objectPropertie
];
}
- /**
- * @return boolean
- */
- public function hasObjects()
+ public function hasObjects(): bool
{
return ($this->numObjects() > 0);
}
- /**
- * @return integer
- */
- public function numObjects()
+ public function numObjects(): int
{
return count($this->objects());
}
/**
* @throws Exception If obj type was not set.
- * @return integer
*/
- public function numTotal()
+ public function numTotal(): int
{
if ($this->numTotal === null) {
$objType = $this->getObjTypeOrFail();
@@ -967,10 +870,8 @@ public function numTotal()
/**
* Retrieve the object's labels.
- *
- * @return array|null
*/
- public function objLabels()
+ public function objLabels(): ?array
{
if ($this->objLabels === null) {
$objLabels = [];
@@ -978,7 +879,7 @@ public function objLabels()
$objMetadata = $proto->metadata();
if (isset($objMetadata['labels']) && !empty($objMetadata['labels'])) {
$objLabels = $objMetadata['labels'];
- array_walk($objLabels, function (&$value) {
+ array_walk($objLabels, function (&$value): void {
$value = $this->translator()->translation($value);
});
$this->objLabels = $objLabels;
@@ -990,17 +891,16 @@ public function objLabels()
/**
* @param boolean $reload If true, reload will be forced.
- * @throws InvalidArgumentException If the object type is not defined / can not create prototype.
- * @return ModelInterface
+ * @throws InvalidArgumentException|Exception If the object type is not defined / can not create prototype.
*/
- public function proto($reload = false)
+ public function proto($reload = false): ModelInterface
{
if ($this->proto === null || $reload) {
$objType = $this->objType();
if ($objType === null) {
throw new InvalidArgumentException(sprintf(
'%s Can not create an object prototype: object type is null.',
- get_class($this)
+ $this::class
));
}
$this->proto = $this->modelFactory()->create($objType);
@@ -1011,10 +911,9 @@ public function proto($reload = false)
/**
* Retrieve the current object in a collection or its prototype.
- *
- * @return ModelInterface
+ * @throws Exception
*/
- protected function getCurrentObjOrProto()
+ protected function getCurrentObjOrProto(): ModelInterface
{
return $this->currentObj ?: $this->proto();
}
@@ -1022,13 +921,12 @@ protected function getCurrentObjOrProto()
/**
* Determine if the model implements {@see \Charcoal\View\ViewableInterface}.
*
- * @see \Charcoal\Admin\Ui\ObjectContainerTrait::isObjRenderable()
- *
* @param string|object $obj Object type or instance to test.
* @param boolean $toString Whether to test for `__toString()`.
- * @return boolean
+ * @throws Exception
+ * @see \Charcoal\Admin\Ui\ObjectContainerTrait::isObjRenderable()
*/
- protected function isObjRenderable($obj, $toString = false)
+ protected function isObjRenderable($obj, $toString = false): bool
{
if (is_string($obj)) {
if (!method_exists($this, 'modelFactory')) {
@@ -1042,7 +940,7 @@ protected function isObjRenderable($obj, $toString = false)
return false;
}
- $key = get_class($obj);
+ $key = $obj::class;
if (isset(static::$objRenderableCache[$key])) {
return static::$objRenderableCache[$key];
diff --git a/packages/admin/src/Charcoal/Admin/Ui/DashboardContainerInterface.php b/packages/admin/src/Charcoal/Admin/Ui/DashboardContainerInterface.php
index eb5353d44..143e4f6f4 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/DashboardContainerInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/DashboardContainerInterface.php
@@ -1,5 +1,7 @@
defaultDashboardType();
}
- $dashboard = $this->dashboardBuilder->build($dashboardConfig);
-
- return $dashboard;
+ return $this->dashboardBuilder->build($dashboardConfig);
}
/**
* Retrieve the default dashboard type class name.
- *
- * @return string
*/
- public function defaultDashboardType()
+ public function defaultDashboardType(): string
{
return DashboardWidget::class;
}
diff --git a/packages/admin/src/Charcoal/Admin/Ui/FeedbackContainerTrait.php b/packages/admin/src/Charcoal/Admin/Ui/FeedbackContainerTrait.php
index 8eec4f6ae..469c928a6 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/FeedbackContainerTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/FeedbackContainerTrait.php
@@ -33,20 +33,16 @@ public function clearFeedback()
/**
* Determine if there's feedback.
- *
- * @return boolean
*/
- public function hasFeedbacks()
+ public function hasFeedbacks(): bool
{
return ($this->numFeedbacks() > 0);
}
/**
* Count feedback.
- *
- * @return integer
*/
- public function numFeedbacks()
+ public function numFeedbacks(): int
{
return count($this->feedbacks());
}
@@ -95,7 +91,7 @@ public function addFeedback($level, $message = null)
$entry = $level;
} elseif (is_string($level) && is_array($message)) {
$entry = $message;
- $entry['level'] = (string)$level;
+ $entry['level'] = $level;
} else {
$entry = [
'level' => (string)$level,
@@ -184,7 +180,7 @@ public function addFeedbackFromValidatorResult(ValidatorResult $result)
*
* @return string[]
*/
- public function getSupportedValidatorLevelsForFeedback()
+ public function getSupportedValidatorLevelsForFeedback(): array
{
return [
ValidatorInterface::ERROR,
@@ -229,7 +225,7 @@ final protected function parseFeedback(array $entry)
* @throws InvalidArgumentException If the feedback entry is invalid.
* @return array A parsed feedback entry.
*/
- protected function parseFeedbackEntry(array $entry)
+ protected function parseFeedbackEntry(array $entry): array
{
$entry['message'] = (string)$entry['message'];
@@ -247,7 +243,7 @@ protected function parseFeedbackEntry(array $entry)
*
* @return string A unique feedback entry ID.
*/
- protected function generateFeedbackEntryId()
+ protected function generateFeedbackEntryId(): string
{
return uniqid();
}
@@ -258,7 +254,7 @@ protected function generateFeedbackEntryId()
* @param string $level The feedback level.
* @return boolean Whether the level is dismissable (TRUE) or not (FALSE).
*/
- protected function isFeedbackDismissable($level)
+ protected function isFeedbackDismissable($level): bool
{
return in_array($level, [ 'log', 'debug', 'info', 'notice' ]);
}
@@ -271,25 +267,13 @@ protected function isFeedbackDismissable($level)
*/
protected function resolveFeedbackType($level)
{
- switch ($level) {
- case 'emergency':
- case 'alert':
- case 'critical':
- case 'error':
- return 'danger';
-
- case 'debug':
- return 'warning';
-
- case 'notice':
- case 'log':
- return 'info';
-
- case 'done':
- return 'success';
- }
-
- return $level;
+ return match ($level) {
+ 'emergency', 'alert', 'critical', 'error' => 'danger',
+ 'debug' => 'warning',
+ 'notice', 'log' => 'info',
+ 'done' => 'success',
+ default => $level,
+ };
}
/**
@@ -300,24 +284,12 @@ protected function resolveFeedbackType($level)
*/
protected function resolveFeedbackLevel($level)
{
- switch ($level) {
- case 'emergency':
- case 'alert':
- case 'critical':
- case 'danger':
- return 'error';
-
- case 'debug':
- return 'warning';
-
- case 'notice':
- case 'log':
- return 'info';
-
- case 'done':
- return 'success';
- }
-
- return $level;
+ return match ($level) {
+ 'emergency', 'alert', 'critical', 'danger' => 'error',
+ 'debug' => 'warning',
+ 'notice', 'log' => 'info',
+ 'done' => 'success',
+ default => $level,
+ };
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Ui/FormGroupInterface.php b/packages/admin/src/Charcoal/Admin/Ui/FormGroupInterface.php
index 0b917e79a..d7a424a3f 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/FormGroupInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/FormGroupInterface.php
@@ -1,5 +1,7 @@
translator()->getLocale();
$locales = $this->translator()->locales();
$languages = [];
- uasort($locales, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ uasort($locales, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
foreach ($locales as $locale => $localeStruct) {
/**
@@ -48,11 +47,7 @@ public function languages()
$label = $this->translator()->translation($localeStruct['name']);
} else {
$trans = 'locale.' . $locale;
- if ($trans === $this->translator()->trans($trans)) {
- $label = strtoupper($locale);
- } else {
- $label = $this->translator()->translation($trans);
- }
+ $label = $trans === $this->translator()->trans($trans) ? strtoupper((string)$locale) : $this->translator()->translation($trans);
}
$isCurrent = ($locale === $currentLocale);
diff --git a/packages/admin/src/Charcoal/Admin/Ui/ImageAttributesTrait.php b/packages/admin/src/Charcoal/Admin/Ui/ImageAttributesTrait.php
index e70410ff5..362acf3ee 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/ImageAttributesTrait.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/ImageAttributesTrait.php
@@ -90,7 +90,7 @@ public function styleAttr()
*
* @return string
*/
- protected function defaultStyleAttr()
+ protected function defaultStyleAttr(): array
{
return [
'height' => $this->height(),
@@ -104,12 +104,11 @@ protected function defaultStyleAttr()
* Parse the CSS styling declarations from the property's display features.
*
* @param string[] $styles An associative array of CSS styles.
- * @return string
*/
- protected function parseStyleAttr(array $styles)
+ protected function parseStyleAttr(array $styles): string
{
$inline = array_map(
- function ($val, $key) {
+ function (int|string $val, int|string $key) {
if (is_bool($val)) {
return ($val) ? $key : '';
} elseif (isset($val)) {
@@ -278,10 +277,9 @@ public function maxHeight()
* Determine if the value is a {@see @see http://en.wikipedia.org/wiki/Data_URI_scheme Data URI}.
*
* @param string $val A path or URI to analyze.
- * @return boolean
*/
- protected function isDataUri($val)
+ protected function isDataUri($val): bool
{
- return (0 === strpos($val, 'data:'));
+ return (str_starts_with($val, 'data:'));
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Ui/LanguageSwitcherAwareInterface.php b/packages/admin/src/Charcoal/Admin/Ui/LanguageSwitcherAwareInterface.php
index 17878deb2..7d6989268 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/LanguageSwitcherAwareInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/LanguageSwitcherAwareInterface.php
@@ -1,5 +1,7 @@
getWidget();
$this->setDynamicTemplate('widget_template', $widget->template());
@@ -183,12 +183,10 @@ public function widgetData($key = null, $default = null)
if ($key) {
if (isset($this->widgetData[$key])) {
return $this->widgetData[$key];
+ } elseif (!is_string($default) && is_callable($default)) {
+ return $default();
} else {
- if (!is_string($default) && is_callable($default)) {
- return $default();
- } else {
- return $default;
- }
+ return $default;
}
}
@@ -197,10 +195,8 @@ public function widgetData($key = null, $default = null)
/**
* Retrieve the default nested widget options.
- *
- * @return array
*/
- public function defaultWidgetData()
+ public function defaultWidgetData(): array
{
return [];
}
@@ -246,7 +242,7 @@ public function setRenderableData(array $data)
* @throws RuntimeException If the form doesn't have a model.
* @return array|Traversable The rendered data.
*/
- protected function renderDataRecursive($data)
+ protected function renderDataRecursive($data): \Traversable|array
{
if (!is_array($data) && !($data instanceof Traversable)) {
throw new InvalidArgumentException('The renderable data must be iterable.');
@@ -262,7 +258,7 @@ protected function renderDataRecursive($data)
foreach ($data as $key => $val) {
if (is_string($val)) {
$data[$key] = $this->renderData($val);
- } elseif (is_array($val) || ($val instanceof Traversable)) {
+ } elseif (is_iterable($val)) {
$data[$key] = $this->renderDataRecursive($val);
} else {
continue;
@@ -278,7 +274,7 @@ protected function renderDataRecursive($data)
* @param string $data The data to render.
* @return string The rendered data.
*/
- protected function renderData($data)
+ protected function renderData($data): string|array|null
{
$obj = $this->form()->obj();
@@ -300,14 +296,14 @@ protected function renderData($data)
* @throws InvalidArgumentException If a route token is not a string.
* @return string
*/
- private function parseDataToken($token)
+ private function parseDataToken($token): string|float|int
{
// Processes matches from a regular expression operation
if (is_array($token) && isset($token[1])) {
$token = $token[1];
}
- $token = trim($token);
+ $token = trim((string)$token);
$method = [ $this, $token ];
if (is_callable($method)) {
@@ -324,8 +320,8 @@ private function parseDataToken($token)
throw new InvalidArgumentException(sprintf(
'Data token "%1$s" must be a string with %2$s; received %3$s',
$token,
- get_called_class(),
- (is_object($value) ? get_class($value) : gettype($value))
+ static::class,
+ (get_debug_type($value))
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Ui/ObjectContainerInterface.php b/packages/admin/src/Charcoal/Admin/Ui/ObjectContainerInterface.php
index 184e2ecf4..220a0dc09 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/ObjectContainerInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/ObjectContainerInterface.php
@@ -1,5 +1,7 @@
modelFactory === null) {
throw new Exception(sprintf(
'Model factory not set for %s',
- get_class($this)
+ $this::class
));
}
return $this->modelFactory;
@@ -94,7 +93,7 @@ public function setObjType($objType)
if (!is_string($objType)) {
throw new InvalidArgumentException(sprintf(
'Object type must be a string, received %s.',
- (is_object($objType) ? get_class($objType) : gettype($objType))
+ (get_debug_type($objType))
));
}
@@ -125,7 +124,7 @@ public function setObjId($objId)
if (!is_scalar($objId)) {
throw new InvalidArgumentException(sprintf(
'Object ID must be a string or numerical value, received %s.',
- (is_object($objId) ? get_class($objId) : gettype($objId))
+ (get_debug_type($objId))
));
}
@@ -151,7 +150,7 @@ public function objId()
*
* @return string Escaped ID.
*/
- public function objIdWithSlashes()
+ public function objIdWithSlashes(): string
{
return addslashes($this->objId());
}
@@ -198,10 +197,8 @@ public function proto()
/**
* Determine if the class has a concrete object.
- *
- * @return boolean
*/
- public function hasObj()
+ public function hasObj(): bool
{
return ($this->obj() && $this->obj()->id());
}
@@ -216,11 +213,7 @@ public function obj()
if ($this->obj === null) {
$this->obj = $this->createOrLoadObj();
- if ($this->obj instanceof ModelInterface) {
- $this->objId = $this->obj->id();
- } else {
- $this->objId = null;
- }
+ $this->objId = $this->obj instanceof ModelInterface ? $this->obj->id() : null;
}
return $this->obj;
@@ -255,7 +248,7 @@ protected function cloneObj()
if (empty($cloneId)) {
throw new Exception(sprintf(
'%1$s cannot clone object. Clone ID missing from request.',
- get_class($this)
+ $this::class
));
}
@@ -285,7 +278,7 @@ protected function createObjFromBluePrint()
if (empty($bpId)) {
throw new Exception(sprintf(
'%1$s cannot create object from blueprint. Blueprint ID missing from request.',
- get_class($this)
+ $this::class
));
}
@@ -320,30 +313,28 @@ protected function createObj()
if ($objBaseClass) {
$message = sprintf(
'[%1$s] can not create object: Object type [%2$s] does not match [%3$s]',
- get_class($this),
+ $this::class,
$objType,
$objBaseClass
);
} else {
$message = sprintf(
'[%1$s] can not create object: Invalid object type [%2$s]',
- get_class($this),
+ $this::class,
$objType
);
}
} else {
$message = sprintf(
'[%1$s] can not create object: Missing object type',
- get_class($this)
+ $this::class
);
}
throw new Exception($message);
}
- $obj = $this->modelFactory()->create($objType);
-
- return $obj;
+ return $this->modelFactory()->create($objType);
}
/**
@@ -377,16 +368,15 @@ protected function validateObjType()
}
return $this->validateObjBaseClass($this->proto());
- } catch (Exception $e) {
+ } catch (Exception) {
return false;
}
}
/**
* @param mixed $obj Object to validate.
- * @return boolean
*/
- protected function validateObjBaseClass($obj)
+ protected function validateObjBaseClass($obj): bool
{
$objBaseClass = $this->objBaseClass();
if (!$objBaseClass) {
@@ -396,7 +386,7 @@ protected function validateObjBaseClass($obj)
try {
return ($obj instanceof $objBaseClass);
- } catch (Exception $e) {
+ } catch (Exception) {
return false;
}
}
@@ -409,7 +399,7 @@ protected function validateObjBaseClass($obj)
*/
protected function getSingularLabelFromObj(ModelInterface $obj)
{
- $key = get_class($obj);
+ $key = $obj::class;
if (isset(static::$labelCache[$key])) {
return static::$labelCache[$key];
@@ -425,11 +415,7 @@ protected function getSingularLabelFromObj(ModelInterface $obj)
$label = null;
}
- if (is_array($label)) {
- $label = reset($label);
- } else {
- $label = (new ReflectionClass($obj))->getShortName();
- }
+ $label = is_array($label) ? reset($label) : (new ReflectionClass($obj))->getShortName();
static::$labelCache[$key] = $label;
@@ -453,7 +439,7 @@ protected function isObjRenderable($obj, $toString = false)
return false;
}
- $key = get_class($obj);
+ $key = $obj::class;
if (isset(static::$objRenderableCache[$key])) {
return static::$objRenderableCache[$key];
diff --git a/packages/admin/src/Charcoal/Admin/Ui/ObjectRevisionsInterface.php b/packages/admin/src/Charcoal/Admin/Ui/ObjectRevisionsInterface.php
index 846efab13..25c7c1c1e 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/ObjectRevisionsInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/ObjectRevisionsInterface.php
@@ -1,5 +1,7 @@
latestRevision();
$propLabel = '%2$s';
- $callback = function (ObjectRevisionInterface &$revision) use ($lastRevision, $obj, $propLabel) {
+ $callback = function (ObjectRevisionInterface &$revision) use ($lastRevision, $obj, $propLabel): void {
$dataDiff = $revision['dataDiff'];
$revision->revTsDisplay = $revision['revTs']->format('Y-m-d H:i:s');
$revision->revUserDisplay = $revision->p('revUser')->displayVal($revision['revUser']);
diff --git a/packages/admin/src/Charcoal/Admin/Ui/SecondaryMenu/GenericSecondaryMenuGroup.php b/packages/admin/src/Charcoal/Admin/Ui/SecondaryMenu/GenericSecondaryMenuGroup.php
index 9768c560e..c79df642c 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/SecondaryMenu/GenericSecondaryMenuGroup.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/SecondaryMenu/GenericSecondaryMenuGroup.php
@@ -1,5 +1,7 @@
hasPermissions($link['permissions']) === false) {
- continue;
- }
+ if (isset($link['permissions']) && $this->hasPermissions($link['permissions']) === false) {
+ continue;
}
yield $link;
@@ -282,26 +280,22 @@ public function links()
/**
* Determine if the secondary menu has any links.
- *
- * @return boolean
*/
- public function hasLinks()
+ public function hasLinks(): bool
{
- return !!$this->numLinks();
+ return (bool)$this->numLinks();
}
/**
* Count the number of secondary menu links.
- *
- * @return integer
*/
- public function numLinks()
+ public function numLinks(): int
{
if (!is_array($this->links) && !($this->links instanceof \Traversable)) {
return 0;
}
- $links = array_filter($this->links, function ($link) {
+ $links = array_filter($this->links, function (array $link): bool {
if (isset($link['active']) && !$link['active']) {
return false;
}
@@ -310,14 +304,7 @@ public function numLinks()
$link['permissions'] = $link['required_acl_permissions'];
unset($link['required_acl_permissions']);
}
-
- if (isset($link['permissions'])) {
- if ($this->hasPermissions($link['permissions']) === false) {
- return false;
- }
- }
-
- return true;
+ return !(isset($link['permissions']) && $this->hasPermissions($link['permissions']) === false);
});
return count($links);
@@ -332,7 +319,7 @@ public function numLinks()
public function isSelected($flag = null)
{
if ($flag !== null) {
- $this->isSelected = !!$flag;
+ $this->isSelected = (bool)$flag;
$this->setCollapsed(!$flag);
}
@@ -342,20 +329,16 @@ public function isSelected($flag = null)
/**
* Determine if the secondary groups should be displayed as panels.
- *
- * @return boolean
*/
- public function displayAsPanel()
+ public function displayAsPanel(): bool
{
return in_array($this->displayType(), [ 'panel', 'collapsible' ]);
}
/**
* Determine if the group is collapsible.
- *
- * @return boolean
*/
- public function collapsible()
+ public function collapsible(): bool
{
return ($this->displayType() === 'collapsible');
}
@@ -368,7 +351,7 @@ public function collapsible()
*/
public function setCollapsed($flag)
{
- $this->collapsed = !!$flag;
+ $this->collapsed = (bool)$flag;
return $this;
}
@@ -401,7 +384,7 @@ public function collapsed()
*/
public function setParented($flag)
{
- $this->parented = !!$flag;
+ $this->parented = (bool)$flag;
return $this;
}
@@ -447,7 +430,7 @@ public function ident()
*/
public function setActive($active)
{
- $this->active = !!$active;
+ $this->active = (bool)$active;
return $this;
}
diff --git a/packages/admin/src/Charcoal/Admin/Ui/StructureContainerInterface.php b/packages/admin/src/Charcoal/Admin/Ui/StructureContainerInterface.php
index 184421c44..e068046ab 100644
--- a/packages/admin/src/Charcoal/Admin/Ui/StructureContainerInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Ui/StructureContainerInterface.php
@@ -1,5 +1,7 @@
supportedDisplayLayouts();
$displays = [];
@@ -93,10 +91,8 @@ public function displays()
/**
* Retrieve the supported display layouts.
- *
- * @return array
*/
- protected function supportedDisplayLayouts()
+ protected function supportedDisplayLayouts(): array
{
return [
self::GROUP_STRUCT_DISPLAY,
@@ -123,7 +119,7 @@ protected function defaultDisplay()
*/
public function setShowEmpty($show)
{
- $this->showEmpty = !!$show;
+ $this->showEmpty = (bool)$show;
return $this;
}
diff --git a/packages/admin/src/Charcoal/Admin/User.php b/packages/admin/src/Charcoal/Admin/User.php
index 4e518a153..f5a20c453 100644
--- a/packages/admin/src/Charcoal/Admin/User.php
+++ b/packages/admin/src/Charcoal/Admin/User.php
@@ -1,5 +1,7 @@
'charcoal_admin_login',
]);
- return $defaults;
}
}
diff --git a/packages/admin/src/Charcoal/Admin/User/LostPasswordToken.php b/packages/admin/src/Charcoal/Admin/User/LostPasswordToken.php
index a2cc68e79..2b65109ab 100644
--- a/packages/admin/src/Charcoal/Admin/User/LostPasswordToken.php
+++ b/packages/admin/src/Charcoal/Admin/User/LostPasswordToken.php
@@ -1,5 +1,7 @@
token = $token;
return $this;
@@ -63,9 +59,8 @@ public function token()
/**
* @param string $user The user.
- * @return self
*/
- public function setUser($user)
+ public function setUser($user): static
{
$this->user = $user;
return $this;
@@ -82,9 +77,8 @@ public function user()
/**
* @param DateTimeInterface|string|null $expiry The date/time at object's creation.
* @throws InvalidArgumentException If the date/time is invalid.
- * @return self
*/
- public function setExpiry($expiry)
+ public function setExpiry($expiry): static
{
if ($expiry === null) {
$this->expiry = null;
@@ -95,7 +89,7 @@ public function setExpiry($expiry)
try {
$expiry = new DateTime($expiry);
} catch (Exception $e) {
- throw new InvalidArgumentException($e->getMessage());
+ throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
@@ -110,10 +104,7 @@ public function setExpiry($expiry)
return $this;
}
- /**
- * @return DateTimeInterface|null
- */
- public function expiry()
+ public function expiry(): ?\DateTimeInterface
{
return $this->expiry;
}
@@ -122,6 +113,7 @@ public function expiry()
* @param Container $container Pimple DI Container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -132,9 +124,10 @@ protected function setDependencies(Container $container)
* @see \Charcoal\Source\StorableTrait::preSave() For the "create" Event.
* @return boolean
*/
+ #[\Override]
protected function preSave()
{
- if ($this->expiry === null) {
+ if (!$this->expiry instanceof \DateTimeInterface) {
$this->setExpiry('now +' . $this->defaultExpiry);
}
diff --git a/packages/admin/src/Charcoal/Admin/User/Permission.php b/packages/admin/src/Charcoal/Admin/User/Permission.php
index 665cac388..ae5c28817 100644
--- a/packages/admin/src/Charcoal/Admin/User/Permission.php
+++ b/packages/admin/src/Charcoal/Admin/User/Permission.php
@@ -1,5 +1,7 @@
numColumns = $numColumns;
return $this;
}
- /**
- * @return float|integer
- */
- public function bsColRatio()
+ public function bsColRatio(): float|int
{
return abs(12 / ($this->numColumns() ?: 12));
}
@@ -67,9 +63,8 @@ public function cardTemplate()
/**
* @param string $cardTemplate CardTemplate for CardCollectionWidget.
- * @return self
*/
- public function setCardTemplate($cardTemplate)
+ public function setCardTemplate($cardTemplate): static
{
$this->cardTemplate = $cardTemplate;
@@ -94,13 +89,13 @@ public function objectCardRow()
*
* @param ModelInterface $object The current row's object.
* @param array $objectProperties The $object's display properties.
- * @return array
*/
- protected function parseObjectRow(ModelInterface $object, array $objectProperties)
+ #[\Override]
+ protected function parseObjectRow(ModelInterface $object, array $objectProperties): array
{
$row = $this->parseCollectionObjectRow($object, $objectProperties);
$objProps = $row['objectProperties'];
- array_walk($objProps, function ($value) use (&$row) {
+ array_walk($objProps, function (array $value) use (&$row): void {
$row['objectProperties'][$value['ident']] = $value['val'];
if (!method_exists($row['object'], 'isChipSuccess')) {
@@ -113,20 +108,17 @@ protected function parseObjectRow(ModelInterface $object, array $objectPropertie
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
- $data = array_merge_recursive(
+ return array_merge_recursive(
parent::widgetDataForJs(),
[
'card_template' => $this->cardTemplate(),
'num_columns' => $this->numColumns()
]
);
-
- return $data;
}
/**
@@ -161,9 +153,8 @@ public function showFooterChip()
/**
* @param boolean $showFooterChip ShowFooterChip for CardCollectionWidget.
- * @return self
*/
- public function setShowFooterChip($showFooterChip)
+ public function setShowFooterChip($showFooterChip): static
{
$this->showFooterChip = $showFooterChip;
@@ -182,19 +173,15 @@ public function chipTitle()
return $this->chipTitle;
}
- /**
- * @return string
- */
- private function defaultChipTitle()
+ private function defaultChipTitle(): string
{
return $this->translator()->translate('Active');
}
/**
* @param Translation|string $chipTitle ChipTitle for CardCollectionWidget.
- * @return self
*/
- public function setChipTitle($chipTitle)
+ public function setChipTitle($chipTitle): static
{
$this->chipTitle = $this->translator()->translation($chipTitle);
diff --git a/packages/admin/src/Charcoal/Admin/Widget/CollectionMapWidget.php b/packages/admin/src/Charcoal/Admin/Widget/CollectionMapWidget.php
index a8232e52f..750fc873a 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/CollectionMapWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/CollectionMapWidget.php
@@ -66,7 +66,8 @@ class CollectionMapWidget extends AdminWidget implements CollectionContainerInte
* @param array $data The widget data.
* @return TableWidget Chainable
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -82,9 +83,8 @@ public function setData(array $data)
* Sets the API key for the mapping service.
*
* @param string $key An API key.
- * @return self
*/
- public function setApiKey($key)
+ public function setApiKey($key): static
{
$this->apiKey = $key;
@@ -105,7 +105,7 @@ public function apiKey()
* @param string $p The latitude property ident.
* @return MapWidget Chainable
*/
- public function setLatProperty($p)
+ public function setLatProperty($p): static
{
$this->latProperty = $p;
return $this;
@@ -123,7 +123,7 @@ public function latProperty()
* @param string $p The longitude property ident.
* @return MapWidget Chainable
*/
- public function setLonProperty($p)
+ public function setLonProperty($p): static
{
$this->lonProperty = $p;
return $this;
@@ -141,7 +141,7 @@ public function lonProperty()
* @param string $p The polygon property ident.
* @return MapWidget Chainable
*/
- public function setPolygonProperty($p)
+ public function setPolygonProperty($p): static
{
$this->polygonProperty = $p;
return $this;
@@ -159,7 +159,7 @@ public function polygonProperty()
* @param string $p The path property ident.
* @return MapWidget Chainable
*/
- public function setPathProperty($p)
+ public function setPathProperty($p): static
{
$this->pathProperty = $p;
return $this;
@@ -177,7 +177,7 @@ public function pathProperty()
* @param string $template The infobox template ident.
* @return CollectionMapWidget Chainable
*/
- public function setInfoboxTemplate($template)
+ public function setInfoboxTemplate($template): static
{
$this->infoboxTemplate = $template;
return $this;
@@ -204,7 +204,7 @@ public function mapObjects()
if (!$objType) {
throw new UnexpectedValueException(sprintf(
'%1$s cannot create collection map. Object type is not defined.',
- get_class($this)
+ static::class
));
}
@@ -212,12 +212,12 @@ public function mapObjects()
$loader->setModel($this->proto());
$collectionConfig = $this->collectionConfig();
- if (is_array($collectionConfig) && !empty($collectionConfig)) {
+ if (is_array($collectionConfig) && $collectionConfig !== []) {
unset($collectionConfig['properties']);
$loader->setData($collectionConfig);
}
- $callback = function (&$obj) {
+ $callback = function (&$obj): void {
$obj->mapInfoboxTemplate = $this->infoboxTemplate();
if ($this->latProperty() && $this->latProperty()) {
@@ -273,10 +273,7 @@ public function mapObjects()
}
}
- /**
- * @return boolean
- */
- public function showInfobox()
+ public function showInfobox(): bool
{
return ($this->infoboxTemplate != '');
}
@@ -294,10 +291,8 @@ public function dataFromRequest()
/**
* Retrieve the accepted metadata from the current request.
- *
- * @return array
*/
- public function acceptedRequestData()
+ public function acceptedRequestData(): array
{
return [
'obj_type',
@@ -315,7 +310,7 @@ public function dataFromObject()
{
$proto = $this->proto();
$objMetadata = $proto->metadata();
- $adminMetadata = (isset($objMetadata['admin']) ? $objMetadata['admin'] : null);
+ $adminMetadata = ($objMetadata['admin'] ?? null);
if (empty($adminMetadata['lists'])) {
return [];
@@ -334,11 +329,7 @@ public function dataFromObject()
return [];
}
- if (isset($adminMetadata['lists'][$collectionIdent])) {
- $objListData = $adminMetadata['lists'][$collectionIdent];
- } else {
- $objListData = [];
- }
+ $objListData = ($adminMetadata['lists'][$collectionIdent] ?? []);
$collectionConfig = [];
@@ -368,7 +359,7 @@ public function dataFromObject()
}
}
- if ($collectionConfig) {
+ if ($collectionConfig !== []) {
$this->mergeCollectionConfig($collectionConfig);
}
@@ -381,6 +372,7 @@ public function dataFromObject()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -420,11 +412,7 @@ protected function getPropertyValue(ModelInterface $obj, $key)
$data = $obj;
foreach (explode('.', $key) as $segment) {
$accessible = is_array($data) || $data instanceof ArrayAccess;
- if ($data instanceof ArrayAccess) {
- $exists = $data->offsetExists($segment);
- } else {
- $exists = array_key_exists($segment, $data);
- }
+ $exists = $data instanceof ArrayAccess ? $data->offsetExists($segment) : array_key_exists($segment, $data);
if ($accessible && $exists) {
$data = $data[$segment];
@@ -446,6 +434,7 @@ protected function getPropertyValue(ModelInterface $obj, $key)
* @param mixed $toResolve A callable used when merging data.
* @return callable|null
*/
+ #[\Override]
protected function resolveDataSourceFilter($toResolve)
{
if (is_string($toResolve)) {
diff --git a/packages/admin/src/Charcoal/Admin/Widget/DashboardWidget.php b/packages/admin/src/Charcoal/Admin/Widget/DashboardWidget.php
index 0313fdb65..811b7efab 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/DashboardWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/DashboardWidget.php
@@ -28,6 +28,7 @@ class DashboardWidget extends AdminWidget implements
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Widget/Dialog/ImportlistWidget.php b/packages/admin/src/Charcoal/Admin/Widget/Dialog/ImportlistWidget.php
index b1c594c08..d0409a1b3 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/Dialog/ImportlistWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/Dialog/ImportlistWidget.php
@@ -1,5 +1,7 @@
objId()) {
return $this->translator()->translation('Update');
@@ -106,7 +105,8 @@ public function defaultBackToObjectLabel()
* @param array $data The widget data.
* @return ObjectForm Chainable
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -121,6 +121,7 @@ public function setData(array $data)
/**
* @return FormSidebarInterface[]|\Generator
*/
+ #[\Override]
public function sidebars()
{
$objId = $this->obj()->id();
@@ -134,7 +135,7 @@ public function sidebars()
$metadata = $this->obj()->metadata();
$objType = (isset($metadata['labels']['singular_name'])
? $translator->translate($metadata['labels']['singular_name'])
- : (new ReflectionClass($obj))->getShortName());
+ : (new ReflectionClass($this->obj()))->getShortName());
$label = $translator->translate('Back to {{name}} id: {{id}}');
$label = strtr($label, [
@@ -169,9 +170,8 @@ public function sidebars()
*
* @param string $formIdent The form identifier.
* @throws InvalidArgumentException If the identifier is not a string.
- * @return self
*/
- public function setFormIdent($formIdent)
+ public function setFormIdent($formIdent): static
{
if (!is_string($formIdent)) {
throw new InvalidArgumentException(
@@ -209,7 +209,7 @@ public function formIdentFallback()
*
* @return array
*/
- public function displayOptions()
+ public function displayOptions(): ?array
{
if (!$this->displayOptions) {
$this->setDisplayOptions([]);
@@ -223,9 +223,8 @@ public function displayOptions()
*
* @param array $options Display configuration.
* @throws \RuntimeException If the display options are not an associative array.
- * @return self
*/
- public function setDisplayOptions(array $options)
+ public function setDisplayOptions(array $options): static
{
if (!is_array($options)) {
throw new \RuntimeException('The display options must be an associative array.');
@@ -238,10 +237,8 @@ public function setDisplayOptions(array $options)
/**
* Retrieve the default display options for the widget.
- *
- * @return array
*/
- public function defaultDisplayOptions()
+ public function defaultDisplayOptions(): array
{
return [
'parented' => false,
@@ -265,7 +262,7 @@ public function formIdent()
* @throws InvalidArgumentException If argument is not a string.
* @return ActionInterface Chainable
*/
- public function setNextUrl($url)
+ public function setNextUrl($url): static
{
if (!is_string($url)) {
throw new InvalidArgumentException(
@@ -287,6 +284,7 @@ public function setNextUrl($url)
*
* @return string Relative URL
*/
+ #[\Override]
public function action()
{
$action = parent::action();
@@ -311,14 +309,15 @@ public function action()
* @throws UnexpectedValueException If a property data is invalid.
* @return DocFormPropertyWidget[]|Generator
*/
- public function formProperties(array $group = null)
+ #[\Override]
+ public function formProperties(?array $group = null)
{
$obj = $this->obj();
$props = $obj->metadata()->properties();
// We need to sort form properties by form group property order if a group exists
- if (!empty($group)) {
- $group = array_map([ $this, 'camelize' ], $group);
+ if ($group !== null && $group !== []) {
+ $group = array_map($this->camelize(...), $group);
$group = array_flip($group);
$props = array_intersect_key($props, $group);
$props = array_merge($group, $props);
@@ -344,7 +343,7 @@ public function formProperties(array $group = null)
throw new UnexpectedValueException(sprintf(
'Invalid property data for "%1$s", received %2$s',
$propertyIdent,
- (is_object($propertyMetadata) ? get_class($propertyMetadata) : gettype($propertyMetadata))
+ (get_debug_type($propertyMetadata))
));
}
@@ -386,7 +385,7 @@ public function formProperty($propertyIdent)
throw new UnexpectedValueException(sprintf(
'Invalid property data for "%1$s", received %2$s',
$propertyIdent,
- (is_object($propertyMetadata) ? get_class($propertyMetadata) : gettype($propertyMetadata))
+ (get_debug_type($propertyMetadata))
));
}
@@ -407,19 +406,14 @@ public function formProperty($propertyIdent)
* @param array $data Data.
* @return ObjectFormWidget Chainable.
*/
- public function setFormData(array $data)
+ #[\Override]
+ public function setFormData(array $data): static
{
$objData = $this->objData();
$merged = array_replace_recursive($objData, $data);
// Remove null values
- $merged = array_filter($merged, function ($val) {
- if ($val === null) {
- return false;
- }
-
- return true;
- });
+ $merged = array_filter($merged, fn($val): bool => $val !== null);
$this->formData = $merged;
$this->obj()->setData($merged);
@@ -432,6 +426,7 @@ public function setFormData(array $data)
*
* @return array
*/
+ #[\Override]
public function formData()
{
if (!$this->formData) {
@@ -460,9 +455,8 @@ public function showHeader()
/**
* @param boolean $showHeader Is the Header to be shown.
- * @return self
*/
- public function setShowHeader($showHeader)
+ public function setShowHeader($showHeader): static
{
$this->showHeader = $showHeader;
@@ -479,19 +473,16 @@ public function showTitle()
/**
* @param boolean $showTitle Is the title to be shown.
- * @return self
*/
- public function setShowTitle($showTitle)
+ public function setShowTitle($showTitle): static
{
$this->showTitle = $showTitle;
return $this;
}
- /**
- * @return string
- */
- public function defaultGroupType()
+ #[\Override]
+ public function defaultGroupType(): string
{
return 'charcoal/admin/docs/widget/form-group/doc';
}
@@ -501,17 +492,17 @@ public function defaultGroupType()
*
* @return string[]
*/
- protected function defaultDataSources()
+ #[\Override]
+ protected function defaultDataSources(): array
{
return [ static::DATA_SOURCE_REQUEST, static::DATA_SOURCE_OBJECT ];
}
/**
* Retrieve the default data source filters (when setting data on an entity).
- *
- * @return array
*/
- protected function defaultDataSourceFilters()
+ #[\Override]
+ protected function defaultDataSourceFilters(): array
{
return [
'request' => null,
@@ -528,6 +519,7 @@ protected function defaultDataSourceFilters()
* @param mixed $toResolve A callable used when merging data.
* @return callable|null
*/
+ #[\Override]
protected function resolveDataSourceFilter($toResolve)
{
if (is_string($toResolve)) {
@@ -554,10 +546,9 @@ protected function resolveDataSourceFilter($toResolve)
/**
* Retrieve the accepted metadata from the current request.
- *
- * @return array
*/
- protected function acceptedRequestData()
+ #[\Override]
+ protected function acceptedRequestData(): array
{
return array_merge(
[ 'obj_type', 'obj_id', 'template' ],
@@ -574,7 +565,7 @@ protected function dataFromObject()
{
$obj = $this->obj();
$objMetadata = $obj->metadata();
- $adminMetadata = (isset($objMetadata['admin']) ? $objMetadata['admin'] : null);
+ $adminMetadata = ($objMetadata['admin'] ?? null);
$formIdent = $this->formIdent();
if (!$formIdent) {
@@ -585,11 +576,7 @@ protected function dataFromObject()
$formIdent = $obj->render($formIdent);
}
- if (isset($adminMetadata['forms'][$formIdent])) {
- $objFormData = $adminMetadata['forms'][$formIdent];
- } else {
- $objFormData = [];
- }
+ $objFormData = ($adminMetadata['forms'][$formIdent] ?? []);
if (isset($objFormData['groups']) && isset($adminMetadata['form_groups'])) {
$extraFormGroups = array_intersect(
@@ -627,7 +614,8 @@ protected function dataFromObject()
* @param array|null $data Optional. The form group data to set.
* @return FormGroupInterface
*/
- protected function createFormGroup(array $data = null)
+ #[\Override]
+ protected function createFormGroup(?array $data = null)
{
$type = $this->defaultGroupType();
@@ -665,13 +653,13 @@ protected function createFormGroup(array $data = null)
* @param FormGroupInterface $group The form group to update.
* @param array|null $groupData Optional. The new group data to apply.
* @param string|null $groupIdent Optional. The new group identifier.
- * @return FormGroupInterface
*/
+ #[\Override]
protected function updateFormGroup(
FormGroupInterface $group,
- array $groupData = null,
+ ?array $groupData = null,
$groupIdent = null
- ) {
+ ): FormGroupInterface {
$group->setForm($this);
if ($groupIdent !== null) {
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/AclPermissions.php b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/AclPermissions.php
index d0789e22a..7247c6d42 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/AclPermissions.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/AclPermissions.php
@@ -30,20 +30,11 @@ class AclPermissions extends AdminWidget implements
{
use FormGroupTrait;
- /**
- * @var Acl $roleAcl
- */
- private $roleAcl;
+ private ?\Laminas\Permissions\Acl\Acl $roleAcl = null;
- /**
- * @var array
- */
- private $roleAllowed;
+ private ?array $roleAllowed = null;
- /**
- * @var array
- */
- private $roleDenied;
+ private ?array $roleDenied = null;
/**
* Store the collection loader for the current class.
@@ -71,15 +62,12 @@ class AclPermissions extends AdminWidget implements
*
* @return string
*/
- public function objId()
+ public function objId(): string|false|null
{
- return filter_input(INPUT_GET, 'obj_id', FILTER_SANITIZE_STRING);
+ return htmlspecialchars(trim(($_GET['obj_id'] ?? '')), ENT_QUOTES, 'UTF-8');
}
- /**
- * @return array
- */
- public function permissionCategories()
+ public function permissionCategories(): array
{
$loader = $this->collectionLoader();
$loader->setModel(PermissionCategory::class);
@@ -103,6 +91,7 @@ public function permissionCategories()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -120,10 +109,10 @@ protected function setDependencies(Container $container)
*/
protected function db()
{
- if (!isset($this->database)) {
+ if ($this->database === null) {
throw new RuntimeException(sprintf(
'Database Connection is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -138,10 +127,10 @@ protected function db()
*/
protected function adminAcl()
{
- if (!isset($this->aclManager)) {
+ if ($this->aclManager === null) {
throw new RuntimeException(sprintf(
'ACL Manager is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -156,10 +145,10 @@ protected function adminAcl()
*/
protected function collectionLoader()
{
- if (!isset($this->collectionLoader)) {
+ if ($this->collectionLoader === null) {
throw new RuntimeException(sprintf(
'Collection Loader is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -168,12 +157,9 @@ protected function collectionLoader()
- /**
- * @return Acl
- */
- protected function roleAcl()
+ protected function roleAcl(): \Laminas\Permissions\Acl\Acl
{
- if (!$this->roleAcl) {
+ if (!$this->roleAcl instanceof \Laminas\Permissions\Acl\Acl) {
$id = $this->objId();
$this->roleAcl = new Acl();
@@ -195,8 +181,8 @@ protected function roleAcl()
$sth->execute();
$permissions = $sth->fetch(PDO::FETCH_ASSOC);
- $this->roleAllowed = explode(',', trim($permissions['allowed']));
- $this->roleDenied = explode(',', trim($permissions['denied']));
+ $this->roleAllowed = explode(',', trim((string)$permissions['allowed']));
+ $this->roleDenied = explode(',', trim((string)$permissions['denied']));
foreach ($this->roleAllowed as $allowed) {
$this->roleAcl->allow($id, 'admin', $allowed);
@@ -211,12 +197,11 @@ protected function roleAcl()
/**
* @param string $category The category ident to load permissions from.
- * @return array
*/
- private function loadCategoryPermissions($category)
+ private function loadCategoryPermissions($category): array
{
$adminAcl = $this->adminAcl();
- $roleAcl = $this->roleAcl();
+ $this->roleAcl();
$loader = $this->collectionLoader();
$loader->setModel(Permission::class);
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/GenericFormGroup.php b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/GenericFormGroup.php
index e1a20645f..2b175b894 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/GenericFormGroup.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/GenericFormGroup.php
@@ -1,5 +1,7 @@
widgetId = $widgetId;
@@ -116,7 +109,8 @@ public function setWidgetId($widgetId)
/**
* @return Translation|string|null
*/
- public function description()
+ #[\Override]
+ public function description(): string
{
return $this->renderTemplate((string)parent::description());
}
@@ -124,7 +118,8 @@ public function description()
/**
* @return Translation|string|null
*/
- public function notes()
+ #[\Override]
+ public function notes(): string
{
return $this->renderTemplate((string)parent::notes());
}
@@ -135,6 +130,7 @@ public function notes()
* @param boolean|string $show Whether to show or hide notes.
* @return FormGroupWidget Chainable
*/
+ #[\Override]
public function setShowNotes($show)
{
$this->showNotesAbove = ($show === 'above');
@@ -142,10 +138,7 @@ public function setShowNotes($show)
return parent::setShowNotes($show);
}
- /**
- * @return boolean
- */
- public function showNotesAbove()
+ public function showNotesAbove(): bool
{
return $this->showNotesAbove && $this->showNotes();
}
@@ -154,6 +147,7 @@ public function showNotesAbove()
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -168,9 +162,8 @@ protected function setDependencies(Container $container)
* Set the widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return self
*/
- protected function setWidgetFactory(FactoryInterface $factory)
+ protected function setWidgetFactory(FactoryInterface $factory): static
{
$this->widgetFactory = $factory;
@@ -181,14 +174,13 @@ protected function setWidgetFactory(FactoryInterface $factory)
* Retrieve the widget factory.
*
* @throws RuntimeException If the widget factory was not previously set.
- * @return FactoryInterface
*/
- protected function widgetFactory()
+ protected function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->widgetFactory === null) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Widget Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/ObjectRevisionsFormGroup.php b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/ObjectRevisionsFormGroup.php
index ac241fa3a..a9f81723b 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/ObjectRevisionsFormGroup.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/ObjectRevisionsFormGroup.php
@@ -40,9 +40,8 @@ class ObjectRevisionsFormGroup extends AbstractFormGroup implements
/**
* @param string $widgetId The widget identifier.
- * @return self
*/
- public function setWidgetId($widgetId)
+ public function setWidgetId($widgetId): static
{
$this->widgetId = $widgetId;
@@ -61,10 +60,8 @@ public function widgetId()
return $this->widgetId;
}
- /**
- * @return boolean
- */
- public function active()
+ #[\Override]
+ public function active(): bool
{
return parent::active() && $this->objType() && $this->objId();
}
@@ -105,6 +102,7 @@ public function objId()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/StructureFormGroup.php b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/StructureFormGroup.php
index f92b5ff71..b1757bfab 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/StructureFormGroup.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/StructureFormGroup.php
@@ -109,10 +109,8 @@ class StructureFormGroup extends FormGroupWidget implements
/**
* The form group the input belongs to.
- *
- * @var FormGroupInterface|null
*/
- private $formGroup;
+ private ?\Charcoal\Ui\FormGroup\FormGroupInterface $formGroup = null;
/**
* Whether the form is ready.
@@ -136,19 +134,16 @@ class StructureFormGroup extends FormGroupWidget implements
*/
protected $rawData;
- /**
- * @return string
- */
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'charcoal/admin/widget/form-group/structure';
}
/**
* @param string $structId The structure entry identifier.
- * @return self
*/
- public function setStructId($structId)
+ public function setStructId($structId): static
{
$this->structId = $structId;
return $this;
@@ -168,9 +163,9 @@ public function structId()
/**
* @param array $data Widget data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
if ($this->rawData === null) {
$this->rawData = $data;
@@ -186,6 +181,7 @@ public function setData(array $data)
*
* @return boolean If TRUE or unset, check if there is a title.
*/
+ #[\Override]
public function showHeader()
{
if ($this->display() === self::SEAMLESS_STRUCT_DISPLAY) {
@@ -200,6 +196,7 @@ public function showHeader()
*
* @return boolean If TRUE or unset, check if there are notes.
*/
+ #[\Override]
public function showFooter()
{
if ($this->display() === self::SEAMLESS_STRUCT_DISPLAY) {
@@ -216,7 +213,8 @@ public function showFooter()
*
* @return string If unset, returns the UI item type.
*/
- public function template()
+ #[\Override]
+ public function template(): ?string
{
$this->setDynamicTemplate('structure_template', $this->displayTemplate());
@@ -225,10 +223,8 @@ public function template()
/**
* Retrieve the property's display layout template.
- *
- * @return string|null
*/
- public function displayTemplate()
+ public function displayTemplate(): string
{
$display = $this->display();
@@ -272,9 +268,8 @@ public function obj()
* Set the form input's parent group.
*
* @param FormGroupInterface $formGroup The parent form group object.
- * @return self
*/
- public function setFormGroup(FormGroupInterface $formGroup)
+ public function setFormGroup(FormGroupInterface $formGroup): static
{
$this->formGroup = $formGroup;
@@ -283,20 +278,16 @@ public function setFormGroup(FormGroupInterface $formGroup)
/**
* Retrieve the input's parent group.
- *
- * @return FormGroupInterface|null
*/
- public function formGroup()
+ public function formGroup(): ?\Charcoal\Ui\FormGroup\FormGroupInterface
{
return $this->formGroup;
}
/**
* Clear the group's parent group.
- *
- * @return self
*/
- public function clearFormGroup()
+ public function clearFormGroup(): static
{
$this->formGroup = null;
@@ -312,9 +303,8 @@ public function clearFormGroup()
* @param string|ModelStructureProperty $propertyIdent The property identifier—or instance—of a storage property.
* @throws InvalidArgumentException If the property identifier is not a string.
* @throws UnexpectedValueException If a property is invalid.
- * @return self
*/
- public function setStorageProperty($propertyIdent)
+ public function setStorageProperty($propertyIdent): static
{
$property = null;
if ($propertyIdent instanceof PropertyInterface) {
@@ -331,11 +321,11 @@ public function setStorageProperty($propertyIdent)
throw new UnexpectedValueException(sprintf(
'The "%1$s" property is not defined on [%2$s]',
$propertyIdent,
- get_class($obj)
+ $obj::class
));
}
- if ($property === null) {
+ if (!$property instanceof \Charcoal\Property\PropertyInterface) {
$property = $obj->property($propertyIdent);
}
@@ -349,8 +339,8 @@ public function setStorageProperty($propertyIdent)
throw new UnexpectedValueException(sprintf(
'"%s" [%s] is not a model structure property on [%s].',
$propertyIdent,
- (is_object($property) ? get_class($property) : gettype($property)),
- (is_object($obj) ? get_class($obj) : gettype($obj))
+ (get_debug_type($property)),
+ (get_debug_type($obj))
));
}
@@ -368,7 +358,7 @@ public function storageProperty()
if ($this->storageProperty === null) {
throw new RuntimeException(sprintf(
'Storage property owner is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -406,11 +396,7 @@ protected function autoFormGroup()
$property = $this->storageProperty();
$struct = $property->getStructureMetadata();
- if (isset($struct['admin']['auto_form_group'])) {
- $this->autoFormGroup = $struct['admin']['auto_form_group'];
- } else {
- $this->autoFormGroup = true;
- }
+ $this->autoFormGroup = ($struct['admin']['auto_form_group'] ?? true);
}
return $this->autoFormGroup;
@@ -445,8 +431,6 @@ protected function finalizeStructure($reload = false)
protected function findStructureFormGroup(): ?array
{
$struct = $this->storageProperty()->getStructureMetadata();
-
- $formGroup = null;
if (isset($struct['admin']['form_group'])) {
if (\is_string($struct['admin']['form_group'])) {
$groupName = $struct['admin']['form_group'];
@@ -476,6 +460,7 @@ protected function findStructureFormGroup(): ?array
*
* @return array
*/
+ #[\Override]
protected function parsedFormProperties()
{
if ($this->parsedFormProperties === null) {
@@ -485,30 +470,28 @@ protected function parsedFormProperties()
$availableProperties = $this->structProperties();
$structProperties = [];
- if (!empty($groupProperties)) {
- foreach ($groupProperties as $propertyIdent => $propertyMetadata) {
- if (is_string($propertyMetadata)) {
- $propertyIdent = $propertyMetadata;
- $propertyMetadata = null;
- }
-
- $propertyIdent = $this->camelize($propertyIdent);
-
- if (!isset($availableProperties[$propertyIdent])) {
- continue;
- }
-
- if (is_array($propertyMetadata)) {
- $propertyMetadata = array_merge($propertyMetadata, $availableProperties[$propertyIdent]);
- } else {
- $propertyMetadata = $availableProperties[$propertyIdent];
- }
-
- $structProperties[$propertyIdent] = $propertyMetadata;
+ foreach ($groupProperties as $propertyIdent => $propertyMetadata) {
+ if (is_string($propertyMetadata)) {
+ $propertyIdent = $propertyMetadata;
+ $propertyMetadata = null;
}
+
+ $propertyIdent = $this->camelize($propertyIdent);
+
+ if (!isset($availableProperties[$propertyIdent])) {
+ continue;
+ }
+
+ if (is_array($propertyMetadata)) {
+ $propertyMetadata = array_merge($propertyMetadata, $availableProperties[$propertyIdent]);
+ } else {
+ $propertyMetadata = $availableProperties[$propertyIdent];
+ }
+
+ $structProperties[$propertyIdent] = $propertyMetadata;
}
- if (empty($structProperties) && $this->autoFormGroup() === true) {
+ if ($structProperties === [] && $this->autoFormGroup() === true) {
$structProperties = $availableProperties;
}
@@ -526,12 +509,11 @@ protected function parsedFormProperties()
* @throws UnexpectedValueException If a property data is invalid.
* @return \Charcoal\Admin\Widget\FormPropertyWidget[]|\Generator
*/
+ #[\Override]
public function formProperties()
{
- if ($this instanceof ConditionalizableInterface) {
- if ($this->condition() !== null && !$this->resolvedCondition()) {
- return [];
- }
+ if ($this->condition() !== null && !$this->resolvedCondition()) {
+ return [];
}
$this->finalizeStructure();
@@ -592,7 +574,7 @@ public function formProperties()
throw new UnexpectedValueException(sprintf(
'Invalid property data for "%1$s", received %2$s',
$propertyIdent,
- (is_object($propertyMetadata) ? get_class($propertyMetadata) : gettype($propertyMetadata))
+ (get_debug_type($propertyMetadata))
));
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/TemplateOptionsFormGroup.php b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/TemplateOptionsFormGroup.php
index a8584dddd..a4d254b33 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormGroup/TemplateOptionsFormGroup.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormGroup/TemplateOptionsFormGroup.php
@@ -80,14 +80,12 @@ class TemplateOptionsFormGroup extends StructureFormGroup
*
* @var TemplateableInterface|string|null
*/
- private $controllerIdent;
+ private ?string $controllerIdent = null;
/**
* Store the metadata loader instance.
- *
- * @var MetadataLoader
*/
- private $metadataLoader;
+ private ?\Charcoal\Model\Service\MetadataLoader $metadataLoader = null;
/**
* Set the form object's template controller identifier.
@@ -95,7 +93,7 @@ class TemplateOptionsFormGroup extends StructureFormGroup
* @param mixed $ident The template controller identifier.
* @return TemplateableInterface Chainable
*/
- public function setControllerIdent($ident)
+ public function setControllerIdent(string $ident): static
{
if (class_exists($ident)) {
$this->controllerIdent = $ident;
@@ -103,7 +101,7 @@ public function setControllerIdent($ident)
return $this;
}
- if (substr($ident, -9) !== '-template') {
+ if (!str_ends_with($ident, '-template')) {
$ident .= '-template';
}
@@ -114,10 +112,8 @@ public function setControllerIdent($ident)
/**
* Retrieve the form object's template controller identifier.
- *
- * @return mixed
*/
- public function controllerIdent()
+ public function controllerIdent(): ?string
{
return $this->controllerIdent;
}
@@ -132,7 +128,7 @@ public function controllerIdent()
* @throws UnexpectedValueException If a property data is invalid.
* @return StructureFormGroup
*/
- public function setTemplateProperty($propertyIdent)
+ public function setTemplateProperty($propertyIdent): static
{
if ($propertyIdent === null) {
$this->templateProperty = null;
@@ -155,11 +151,11 @@ public function setTemplateProperty($propertyIdent)
throw new UnexpectedValueException(sprintf(
'The "%1$s" property is not defined on [%2$s]',
$propertyIdent,
- get_class($this->obj())
+ $this->obj()::class
));
}
- if ($property === null) {
+ if (!$property instanceof \Charcoal\Property\PropertyInterface) {
$property = $obj->property($propertyIdent);
}
@@ -183,7 +179,7 @@ public function templateProperty()
} else {
throw new RuntimeException(sprintf(
'Storage property owner is not defined for "%s"',
- get_class($this)
+ static::class
));
}
}
@@ -197,6 +193,7 @@ public function templateProperty()
* @throws RuntimeException If the storage property was not previously set.
* @return PropertyInterface
*/
+ #[\Override]
public function storageProperty()
{
if ($this->storageProperty === null) {
@@ -206,7 +203,7 @@ public function storageProperty()
} else {
throw new RuntimeException(sprintf(
'Storage property owner is not defined for "%s"',
- get_class($this)
+ static::class
));
}
}
@@ -220,6 +217,7 @@ public function storageProperty()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -231,9 +229,8 @@ protected function setDependencies(Container $container)
* Set a metadata loader.
*
* @param MetadataLoader $loader The loader instance, used to load metadata.
- * @return self
*/
- protected function setMetadataLoader(MetadataLoader $loader)
+ protected function setMetadataLoader(MetadataLoader $loader): static
{
$this->metadataLoader = $loader;
@@ -244,14 +241,13 @@ protected function setMetadataLoader(MetadataLoader $loader)
* Retrieve the metadata loader.
*
* @throws RuntimeException If the metadata loader was not previously set.
- * @return MetadataLoader
*/
- protected function metadataLoader()
+ protected function metadataLoader(): \Charcoal\Model\Service\MetadataLoader
{
- if ($this->metadataLoader === null) {
+ if (!$this->metadataLoader instanceof \Charcoal\Model\Service\MetadataLoader) {
throw new RuntimeException(sprintf(
'Metadata Loader is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -266,8 +262,7 @@ protected function metadataLoader()
*/
protected function loadMetadata($metadataIdent)
{
- $metadata = $this->metadataLoader()->load($metadataIdent, $this->metadataClass());
- return $metadata;
+ return $this->metadataLoader()->load($metadataIdent, $this->metadataClass());
}
/**
@@ -283,10 +278,8 @@ protected function createMetadata()
/**
* Retrieve the class name of the metadata object.
- *
- * @return string
*/
- protected function metadataClass()
+ protected function metadataClass(): string
{
return StructureMetadata::class;
}
@@ -297,6 +290,7 @@ protected function metadataClass()
* @param boolean $reload Rebuild the form group's structure.
* @return void
*/
+ #[\Override]
protected function finalizeStructure($reload = false)
{
if ($reload || !$this->isStructureFinalized) {
@@ -311,7 +305,7 @@ protected function finalizeStructure($reload = false)
}
$controllerInterfaces = (array)$this->controllerIdent();
- if (!empty($controllerInterfaces)) {
+ if ($controllerInterfaces !== []) {
$metadataLoader = $this->metadataLoader();
$controllerStructKey = $controllerInterfaces;
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormGroupWidget.php b/packages/admin/src/Charcoal/Admin/Widget/FormGroupWidget.php
index b4768d05e..3fdebeb2c 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormGroupWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormGroupWidget.php
@@ -34,30 +34,22 @@ class FormGroupWidget extends AbstractUiItem implements
/**
* Whether notes shoudl be display before or after the form fields.
- *
- * @var boolean
*/
- private $showNotesAbove = false;
+ private bool $showNotesAbove = false;
/**
* @var array|null $parsedFormProperties
*/
protected $parsedFormProperties;
- /**
- * @var array $groupProperties
- */
- private $groupProperties = [];
+ private array $groupProperties = [];
- /**
- * @var array $propertiesOptions
- */
- private $propertiesOptions = [];
+ private array $propertiesOptions = [];
/**
* @param array|\ArrayAccess $data Dependencies.
*/
- public function __construct($data)
+ public function __construct(?array $data)
{
parent::__construct($data);
@@ -70,7 +62,8 @@ public function __construct($data)
* @param array $data Widget data.
* @return FormGroupWidget Chainable
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
if (!empty($data['properties'])) {
$this->setGroupProperties($data['properties']);
@@ -92,10 +85,8 @@ public function setData(array $data)
return $this;
}
- /**
- * @return string
- */
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'charcoal/admin/widget/form-group-widget';
}
@@ -104,7 +95,7 @@ public function type()
* @param string $widgetId The widget identifier.
* @return AdminWidget Chainable
*/
- public function setWidgetId($widgetId)
+ public function setWidgetId($widgetId): static
{
$this->widgetId = $widgetId;
@@ -127,7 +118,7 @@ public function widgetId()
* @param array $properties The group properties.
* @return FormGroupWidget Chainable
*/
- public function setGroupProperties(array $properties)
+ public function setGroupProperties(array $properties): static
{
$this->groupProperties = $properties;
$this->parsedFormProperties = null;
@@ -135,10 +126,7 @@ public function setGroupProperties(array $properties)
return $this;
}
- /**
- * @return array
- */
- public function groupProperties()
+ public function groupProperties(): array
{
return $this->groupProperties;
}
@@ -147,29 +135,24 @@ public function groupProperties()
* @param array $properties The options to customize the group properties.
* @return FormGroupWidget Chainable
*/
- public function setPropertiesOptions(array $properties)
+ public function setPropertiesOptions(array $properties): static
{
$this->propertiesOptions = $properties;
return $this;
}
- /**
- * @return array
- */
- public function propertiesOptions()
+ public function propertiesOptions(): array
{
return $this->propertiesOptions;
}
/**
* Determine if the form group has properties.
- *
- * @return boolean
*/
- public function hasFormProperties()
+ public function hasFormProperties(): bool
{
- return !!count($this->parsedFormProperties());
+ return (bool)count($this->parsedFormProperties());
}
/**
@@ -182,7 +165,7 @@ public function formProperties()
$form = $this->form();
$obj = ($form instanceof ObjectContainerInterface) ? $form->obj() : null;
- $groupProperties = array_map([ $this, 'camelize' ], $this->groupProperties());
+ $groupProperties = array_map($this->camelize(...), $this->groupProperties());
$formProperties = $this->parsedFormProperties();
$propOptions = $this->propertiesOptions();
@@ -233,9 +216,8 @@ public function formProperties()
* Retrieve the available languages, formatted for the sidebar language-switcher.
*
* @see FormSidebarWidget::languages()
- * @return array
*/
- public function languages()
+ public function languages(): array
{
$currentLocale = $this->translator()->getLocale();
$languages = [];
@@ -249,7 +231,7 @@ public function languages()
} else {
$trans = 'locale.' . $locale;
if ($trans === $this->translator()->translate($trans)) {
- $label = strtoupper($locale);
+ $label = strtoupper((string)$locale);
} else {
$label = $this->translator()->translation($trans);
}
@@ -267,10 +249,8 @@ public function languages()
/**
* Retrieve the current language.
- *
- * @return string
*/
- public function lang()
+ public function lang(): string
{
return $this->translator()->getLocale();
}
@@ -300,7 +280,8 @@ public function locale()
/**
* @return Translation|string|null
*/
- public function description()
+ #[\Override]
+ public function description(): string
{
return $this->renderTemplate((string)parent::description());
}
@@ -308,7 +289,8 @@ public function description()
/**
* @return Translation|string|null
*/
- public function notes()
+ #[\Override]
+ public function notes(): string
{
return $this->renderTemplate((string)parent::notes());
}
@@ -319,6 +301,7 @@ public function notes()
* @param boolean|string $show Whether to show or hide notes.
* @return FormGroupWidget Chainable
*/
+ #[\Override]
public function setShowNotes($show)
{
$this->showNotesAbove = ($show === 'above');
@@ -326,10 +309,7 @@ public function setShowNotes($show)
return parent::setShowNotes($show);
}
- /**
- * @return boolean
- */
- public function showNotesAbove()
+ public function showNotesAbove(): bool
{
return $this->showNotesAbove && $this->showNotes();
}
@@ -338,6 +318,7 @@ public function showNotesAbove()
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormPropertyWidget.php b/packages/admin/src/Charcoal/Admin/Widget/FormPropertyWidget.php
index e690ff3f1..64cdd7b78 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormPropertyWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormPropertyWidget.php
@@ -80,10 +80,8 @@ class FormPropertyWidget extends AdminWidget implements
/**
* The model property's metadata.
- *
- * @var array
*/
- private $propertyData = [];
+ private array $propertyData = [];
/**
* Store the property control instance.
@@ -164,31 +162,23 @@ class FormPropertyWidget extends AdminWidget implements
/**
* Store the model property factory.
- *
- * @var FactoryInterface
*/
- private $propertyFactory;
+ private ?\Charcoal\Factory\FactoryInterface $propertyFactory = null;
/**
* Store the property form control factory.
- *
- * @var FactoryInterface
*/
- private $propertyInputFactory;
+ private ?\Charcoal\Factory\FactoryInterface $propertyInputFactory = null;
/**
* Store the property display factory.
- *
- * @var FactoryInterface
*/
- private $propertyDisplayFactory;
+ private ?\Charcoal\Factory\FactoryInterface $propertyDisplayFactory = null;
/**
* Track the state of data merging.
- *
- * @var boolean
*/
- private $isMergingWidgetData = false;
+ private bool $isMergingWidgetData = false;
/**
* The UI item's icon.
@@ -204,11 +194,10 @@ class FormPropertyWidget extends AdminWidget implements
* Retrieve the property factory.
*
* @throws RuntimeException If the property factory is missing.
- * @return FactoryInterface
*/
- public function propertyFactory()
+ public function propertyFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->propertyFactory === null) {
+ if (!$this->propertyFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
'Missing Property Factory'
);
@@ -221,11 +210,10 @@ public function propertyFactory()
* Retrieve the property control factory.
*
* @throws RuntimeException If the property control factory is missing.
- * @return FactoryInterface
*/
- public function propertyInputFactory()
+ public function propertyInputFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->propertyInputFactory === null) {
+ if (!$this->propertyInputFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
'Missing Property Input Factory'
);
@@ -238,11 +226,10 @@ public function propertyInputFactory()
* Retrieve the property display factory.
*
* @throws RuntimeException If the property display factory is missing.
- * @return FactoryInterface
*/
- public function propertyDisplayFactory()
+ public function propertyDisplayFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->propertyDisplayFactory === null) {
+ if (!$this->propertyDisplayFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
'Missing Property Display Factory'
);
@@ -256,6 +243,7 @@ public function propertyDisplayFactory()
*
* @return string
*/
+ #[\Override]
public function widgetId()
{
$type = $this->outputType();
@@ -281,7 +269,8 @@ public function widgetId()
* @throws InvalidArgumentException If the argument is not a string.
* @return FormPropertyWidget Chainable
*/
- public function setType($type)
+ #[\Override]
+ public function setType($type): static
{
if (empty($type)) {
$this->type = null;
@@ -313,7 +302,7 @@ public function setType($type)
* @throws InvalidArgumentException If the argument is not a string.
* @return FormPropertyWidget Chainable
*/
- public function setOutputType($type)
+ public function setOutputType($type): static
{
if (empty($type)) {
$this->outputType = static::DEFAULT_OUTPUT;
@@ -368,10 +357,8 @@ public function outputType()
/**
* Retrieve the supported property output types.
- *
- * @return array
*/
- public function supportedOutputTypes()
+ public function supportedOutputTypes(): array
{
return [ static::PROPERTY_CONTROL, static::PROPERTY_DISPLAY ];
}
@@ -382,7 +369,7 @@ public function supportedOutputTypes()
* @param FormGroupInterface $formGroup The parent form group object.
* @return FormPropertyWidget Chainable
*/
- public function setFormGroup(FormGroupInterface $formGroup)
+ public function setFormGroup(FormGroupInterface $formGroup): static
{
$this->formGroup = $formGroup;
@@ -404,7 +391,7 @@ public function formGroup()
*
* @return FormPropertyWidget Chainable
*/
- public function clearFormGroup()
+ public function clearFormGroup(): static
{
$this->formGroup = null;
@@ -417,7 +404,8 @@ public function clearFormGroup()
* @param array|ArrayAccess $data Widget and property data.
* @return FormPropertyWidget Chainable
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
$this->isMergingWidgetData = true;
@@ -439,7 +427,7 @@ public function setData(array $data)
* @param array $data Widget and property data.
* @return FormPropertyWidget Chainable
*/
- public function merge(array $data)
+ public function merge(array $data): static
{
$this->isMergingWidgetData = true;
@@ -459,7 +447,7 @@ public function merge(array $data)
* @throws InvalidArgumentException If the argument is not a string.
* @return FormPropertyWidget Chainable
*/
- public function setPropertyType($type)
+ public function setPropertyType($type): static
{
if (empty($type)) {
$this->propertyType = null;
@@ -494,7 +482,7 @@ public function propertyType()
* @throws InvalidArgumentException If the property ident is not a string.
* @return FormPropertyWidget Chainable
*/
- public function setPropertyIdent($propertyIdent)
+ public function setPropertyIdent($propertyIdent): static
{
if (!is_string($propertyIdent)) {
throw new InvalidArgumentException(
@@ -523,7 +511,7 @@ public function propertyIdent()
* @param array $data The property configset.
* @return FormPropertyWidget Chainable
*/
- public function setPropertyData(array $data)
+ public function setPropertyData(array $data): static
{
$this->propertyData = $data;
@@ -544,7 +532,7 @@ public function setPropertyData(array $data)
* @param array $data The property configset.
* @return FormPropertyWidget Chainable
*/
- public function mergePropertyData(array $data)
+ public function mergePropertyData(array $data): static
{
$this->propertyData = array_replace($this->propertyData, $data);
@@ -561,10 +549,8 @@ public function mergePropertyData(array $data)
/**
* Retrieve the property metadata.
- *
- * @return array
*/
- public function propertyData()
+ public function propertyData(): array
{
return $this->propertyData;
}
@@ -575,7 +561,7 @@ public function propertyData()
* @param mixed $propertyVal The property value.
* @return FormPropertyWidget Chainable
*/
- public function setPropertyVal($propertyVal)
+ public function setPropertyVal($propertyVal): static
{
$this->propertyVal = $propertyVal;
@@ -598,9 +584,10 @@ public function propertyVal()
* @param boolean $show Show (TRUE) or hide (FALSE) the label.
* @return FormPropertyWidget Chainable
*/
- public function setShowLabel($show)
+ #[\Override]
+ public function setShowLabel($show): static
{
- $this->showLabel = !!$show;
+ $this->showLabel = (bool)$show;
return $this;
}
@@ -610,20 +597,17 @@ public function setShowLabel($show)
*
* @return boolean If TRUE or unset, check if there is a label.
*/
+ #[\Override]
public function showLabel()
{
if ($this->showLabel === null) {
$prop = $this->property();
$show = $prop['show_label'];
- if ($show !== null) {
- $this->showLabel = $show;
- } else {
- $this->showLabel = true;
- }
+ $this->showLabel = ($show ?? true);
}
if ($this->showLabel !== false) {
- return !!strval($this->property()['label']);
+ return (bool)strval($this->property()['label']);
} else {
return false;
}
@@ -635,9 +619,9 @@ public function showLabel()
* @param boolean $show Show (TRUE) or hide (FALSE) the description.
* @return FormPropertyWidget Chainable
*/
- public function setShowDescription($show)
+ public function setShowDescription($show): static
{
- $this->showDescription = !!$show;
+ $this->showDescription = (bool)$show;
return $this;
}
@@ -652,15 +636,11 @@ public function showDescription()
if ($this->showDescription === null) {
$prop = $this->property();
$show = $prop['show_description'];
- if ($show !== null) {
- $this->showDescription = $show;
- } else {
- $this->showDescription = true;
- }
+ $this->showDescription = ($show ?? true);
}
if ($this->showDescription !== false) {
- return !!strval($this->property()['description']);
+ return (bool)strval($this->property()['description']);
} else {
return false;
}
@@ -672,9 +652,9 @@ public function showDescription()
* @param boolean|string $show Show (TRUE) or hide (FALSE) the notes.
* @return FormPropertyWidget Chainable
*/
- public function setShowNotes($show)
+ public function setShowNotes($show): static
{
- $this->showNotes = ($show === 'above' ? $show : !!$show);
+ $this->showNotes = ($show === 'above' ? $show : (bool)$show);
return $this;
}
@@ -689,15 +669,11 @@ public function showNotes()
if ($this->showNotes === null) {
$prop = $this->property();
$show = $prop['show_notes'];
- if ($show !== null) {
- $this->showNotes = $show;
- } else {
- $this->showNotes = true;
- }
+ $this->showNotes = ($show ?? true);
}
if ($this->showNotes !== false) {
- return !!strval($this->property()['notes']);
+ return (bool)strval($this->property()['notes']);
} else {
return false;
}
@@ -720,13 +696,13 @@ public function showNotesAbove()
$notes = $this->property()['notes'];
- return !!$notes;
+ return (bool)$notes;
}
/**
* @return Translation|string|null
*/
- public function description()
+ public function description(): string
{
return $this->renderTemplate((string)$this->property()['description']);
}
@@ -734,23 +710,17 @@ public function description()
/**
* @return Translation|string|null
*/
- public function notes()
+ public function notes(): string
{
return $this->renderTemplate((string)$this->property()['notes']);
}
- /**
- * @return boolean
- */
- public function hidden()
+ public function hidden(): bool
{
return ($this->inputType() === static::HIDDEN_FORM_CONTROL || $this->property()['hidden']);
}
- /**
- * @return boolean
- */
- public function editable()
+ public function editable(): bool
{
return ($this->inputType() !== static::READONLY_FORM_CONTROL && $this->outputType() === static::PROPERTY_CONTROL);
}
@@ -765,34 +735,22 @@ public function required()
return $this->property()['required'];
}
- /**
- * @return string
- */
- public function inputId()
+ public function inputId(): string
{
return 'input_id';
}
- /**
- * @return string
- */
- public function inputName()
+ public function inputName(): string
{
return 'input_name';
}
- /**
- * @return string
- */
- public function displayId()
+ public function displayId(): string
{
return 'display_id';
}
- /**
- * @return string
- */
- public function displayName()
+ public function displayName(): string
{
return 'display_name';
}
@@ -804,7 +762,7 @@ public function displayName()
* @throws InvalidArgumentException If the argument is not a string.
* @return FormPropertyWidget Chainable
*/
- public function setInputType($type)
+ public function setInputType($type): static
{
if (empty($type)) {
$this->inputType = null;
@@ -843,7 +801,7 @@ public function inputType()
* @throws InvalidArgumentException If the argument is not a string.
* @return FormPropertyWidget Chainable
*/
- public function setDisplayType($type)
+ public function setDisplayType($type): static
{
if (empty($type)) {
$this->displayType = null;
@@ -881,7 +839,7 @@ public function displayType()
* @param PropertyInterface $property The property.
* @return FormPropertyWidget Chainable
*/
- public function setProperty(PropertyInterface $property)
+ public function setProperty(PropertyInterface $property): static
{
$this->property = $property;
$this->propertyType = $property->type();
@@ -926,10 +884,8 @@ public function prop()
/**
* Determine if the form control's active language should be displayed.
- *
- * @return boolean
*/
- public function showActiveLanguage()
+ public function showActiveLanguage(): bool
{
$property = $this->property();
$locales = count($this->translator()->availableLocales());
@@ -945,18 +901,16 @@ public function showActiveLanguage()
public function inputNameAsCssClass()
{
$name = str_replace([ ']', '[' ], [ '', '-' ], $this->propertyIdent());
- $name = $this->camelize($name);
- return $name;
+ return $this->camelize($name);
}
/**
* Set the CSS class name(s) for the `.form-field`.
*
* @param mixed $cssClass One or more CSS class names.
- * @return self
*/
- public function setFormFieldCssClass($cssClass)
+ public function setFormFieldCssClass($cssClass): static
{
$cssClass = array_merge($this->defaultFormFieldCssClasses(), $this->parseCssClasses($cssClass));
$this->formFieldCssClass = array_unique($cssClass);
@@ -967,11 +921,10 @@ public function setFormFieldCssClass($cssClass)
* Add CSS class name(s) for the `.form-field`.
*
* @param mixed $cssClass One or more CSS class names.
- * @return self
*/
- public function addFormFieldCssClass($cssClass)
+ public function addFormFieldCssClass($cssClass): static
{
- if (empty($this->formFieldCssClass)) {
+ if ($this->formFieldCssClass === []) {
$this->formFieldCssClass = $this->defaultFormFieldCssClasses();
}
@@ -982,12 +935,10 @@ public function addFormFieldCssClass($cssClass)
/**
* Retrieve the CSS class name(s) for the `.form-field`.
- *
- * @return string
*/
- public function formFieldCssClass()
+ public function formFieldCssClass(): string
{
- if (empty($this->formFieldCssClass)) {
+ if ($this->formFieldCssClass === []) {
$this->formFieldCssClass = $this->defaultFormFieldCssClasses();
}
@@ -998,9 +949,8 @@ public function formFieldCssClass()
* Set the CSS class name(s) for the `.form-group`.
*
* @param mixed $cssClass One or more CSS class names.
- * @return self
*/
- public function setFormGroupCssClass($cssClass)
+ public function setFormGroupCssClass($cssClass): static
{
$cssClass = array_merge($this->defaultFormGroupCssClasses(), $this->parseCssClasses($cssClass));
$this->formGroupCssClass = array_unique($cssClass);
@@ -1011,11 +961,10 @@ public function setFormGroupCssClass($cssClass)
* Add CSS class name(s) for the `.form-group`.
*
* @param mixed $cssClass One or more CSS class names.
- * @return self
*/
- public function addFormGroupCssClass($cssClass)
+ public function addFormGroupCssClass($cssClass): static
{
- if (empty($this->formGroupCssClass)) {
+ if ($this->formGroupCssClass === []) {
$this->formGroupCssClass = $this->defaultFormGroupCssClasses();
}
@@ -1026,12 +975,10 @@ public function addFormGroupCssClass($cssClass)
/**
* Retrieve the CSS class name(s) for the `.form-group`.
- *
- * @return string
*/
- public function formGroupCssClass()
+ public function formGroupCssClass(): string
{
- if (empty($this->formGroupCssClass)) {
+ if ($this->formGroupCssClass === []) {
$this->formGroupCssClass = $this->defaultFormGroupCssClasses();
}
@@ -1044,7 +991,7 @@ public function formGroupCssClass()
* @param string $mode The L10N display mode.
* @return FormPropertyWidget Chainable
*/
- public function setL10nMode($mode)
+ public function setL10nMode($mode): static
{
$this->l10nMode = $mode;
return $this;
@@ -1062,10 +1009,8 @@ public function l10nMode()
/**
* Determine if the property should output for each language.
- *
- * @return boolean
*/
- public function loopL10n()
+ public function loopL10n(): bool
{
return ($this->l10nMode() === 'loop_inputs');
}
@@ -1159,6 +1104,7 @@ public function output()
* @param Container $container Service container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -1175,7 +1121,7 @@ protected function setDependencies(Container $container)
* @param FactoryInterface $factory The factory to create property values.
* @return FormPropertyWidget Chainable
*/
- protected function setPropertyFactory(FactoryInterface $factory)
+ protected function setPropertyFactory(FactoryInterface $factory): static
{
$this->propertyFactory = $factory;
@@ -1188,7 +1134,7 @@ protected function setPropertyFactory(FactoryInterface $factory)
* @param FactoryInterface $factory The factory to create form controls for property values.
* @return FormPropertyWidget Chainable
*/
- protected function setPropertyInputFactory(FactoryInterface $factory)
+ protected function setPropertyInputFactory(FactoryInterface $factory): static
{
$this->propertyInputFactory = $factory;
@@ -1201,7 +1147,7 @@ protected function setPropertyInputFactory(FactoryInterface $factory)
* @param FactoryInterface $factory The factory to create displayable property values.
* @return FormPropertyWidget Chainable
*/
- protected function setPropertyDisplayFactory(FactoryInterface $factory)
+ protected function setPropertyDisplayFactory(FactoryInterface $factory): static
{
$this->propertyDisplayFactory = $factory;
@@ -1229,7 +1175,7 @@ protected function resolveOutputType($type)
} else {
throw new InvalidArgumentException(sprintf(
'Invalid form property output type, received %s',
- is_object($type) ? get_class($type) : gettype($type)
+ get_debug_type($type)
));
}
}
@@ -1255,7 +1201,7 @@ public function resolvedOutputType()
*
* @return string[]
*/
- protected function defaultFormFieldCssClasses()
+ protected function defaultFormFieldCssClasses(): array
{
$classes = [ 'form-field', 'form-field-' . $this->widgetId() ];
@@ -1287,7 +1233,7 @@ protected function defaultFormFieldCssClasses()
*
* @return string[]
*/
- protected function defaultFormGroupCssClasses()
+ protected function defaultFormGroupCssClasses(): array
{
return [ 'form-group' ];
}
@@ -1299,7 +1245,7 @@ protected function defaultFormGroupCssClasses()
* @throws InvalidArgumentException If a class name is not a string.
* @return string[]
*/
- protected function parseCssClasses($classes)
+ protected function parseCssClasses($classes): array
{
if (is_string($classes)) {
$classes = explode(' ', $classes);
@@ -1309,7 +1255,7 @@ protected function parseCssClasses($classes)
throw new InvalidArgumentException('CSS Class(es) must be a space-delimited string or an array');
}
- return array_filter($classes, 'strlen');
+ return array_filter($classes, strlen(...));
}
/**
@@ -1318,7 +1264,7 @@ protected function parseCssClasses($classes)
* @param array $data The widget and property data.
* @return array Returns the remaining dataset.
*/
- private function setCoreData(array $data)
+ private function setCoreData(array $data): array
{
if (isset($data['ident'])) {
$this->setPropertyIdent($data['ident']);
@@ -1370,7 +1316,7 @@ private function resolveInputType()
/** Attempt input type resolution without instantiating the property, at first. */
$metadata = $this->propertyData();
- if ($metadata) {
+ if ($metadata !== []) {
if (isset($metadata['hidden']) && $metadata['hidden']) {
$type = static::HIDDEN_FORM_CONTROL;
}
@@ -1415,10 +1361,8 @@ private function resolveDisplayType()
/** Attempt display type resolution without instantiating the property, at first. */
$metadata = $this->propertyData();
- if ($metadata) {
- if (isset($metadata['display_type'])) {
- $type = $metadata['display_type'];
- }
+ if ($metadata && isset($metadata['display_type'])) {
+ $type = $metadata['display_type'];
}
if ($this->propertyType || $this->property) {
@@ -1443,7 +1387,7 @@ private function createProperty()
if ($ident && is_string($ident)) {
$message = sprintf('Missing property type for property "%s"', $ident);
} else {
- $message = sprintf('Missing property type');
+ $message = 'Missing property type';
}
throw new UnexpectedValueException($message);
}
@@ -1534,7 +1478,7 @@ private function createDisplayProperty()
* @param array $data The widget and property data.
* @return array Returns the remaining dataset.
*/
- protected function filterInputPropertyData(array $data)
+ protected function filterInputPropertyData(array $data): array
{
unset(
$data['formFieldCssClass'],
@@ -1552,7 +1496,7 @@ protected function filterInputPropertyData(array $data)
* @param array $data The widget and property data.
* @return array Returns the remaining dataset.
*/
- protected function filterDisplayPropertyData(array $data)
+ protected function filterDisplayPropertyData(array $data): array
{
return $data;
}
@@ -1571,9 +1515,8 @@ public function icon()
* Set the path to the item's icon associated with the object.
*
* @param string $icon A path to an image.
- * @return self
*/
- public function setIcon($icon)
+ public function setIcon($icon): static
{
$this->icon = $icon;
@@ -1582,15 +1525,13 @@ public function setIcon($icon)
/**
* Check for icon(s)
- *
- * @return boolean
*/
- public function hasIcon()
+ public function hasIcon(): bool
{
if (is_array($this->icon())) {
- return !!count($this->icon());
+ return (bool)count($this->icon());
}
- return !!$this->icon();
+ return (bool)$this->icon();
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormSidebarWidget.php b/packages/admin/src/Charcoal/Admin/Widget/FormSidebarWidget.php
index d2189706b..996130f4d 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormSidebarWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormSidebarWidget.php
@@ -39,10 +39,8 @@ class FormSidebarWidget extends AdminWidget implements
/**
* Store a reference to the parent form widget.
- *
- * @var FormInterface
*/
- private $form;
+ private ?\Charcoal\Ui\Form\FormInterface $form = null;
/**
* Store the sidebar actions.
@@ -74,17 +72,13 @@ class FormSidebarWidget extends AdminWidget implements
/**
* Customize the shown properties.
- *
- * @var array
*/
- private $propertiesOptions = [];
+ private array $propertiesOptions = [];
/**
* The title is displayed by default.
- *
- * @var boolean
*/
- private $showTitle = true;
+ private bool $showTitle = true;
/**
* The sidebar's title.
@@ -95,10 +89,8 @@ class FormSidebarWidget extends AdminWidget implements
/**
* The subtitle is displayed by default.
- *
- * @var boolean
*/
- private $showSubtitle = true;
+ private bool $showSubtitle = true;
/**
* The sidebar's subtitle.
@@ -151,23 +143,22 @@ class FormSidebarWidget extends AdminWidget implements
/**
* Whether the object is revisionable.
- *
- * @var boolean
*/
- private $isObjRevisionable;
+ private ?bool $isObjRevisionable = null;
/**
* The required Acl permissions for the whole sidebar.
*
* @var string[]
*/
- private $requiredGlobalAclPermissions = [];
+ private array $requiredGlobalAclPermissions = [];
/**
* @param array|ArrayInterface $data Class data.
* @return FormSidebarWidget Chainable
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -199,7 +190,7 @@ public function setData(array $data)
* @param FormInterface $form The related form widget.
* @return FormSidebarWidget Chainable
*/
- public function setForm(FormInterface $form)
+ public function setForm(FormInterface $form): static
{
$this->form = $form;
@@ -211,7 +202,7 @@ public function setForm(FormInterface $form)
*
* @return FormInterface
*/
- public function form()
+ public function form(): ?\Charcoal\Ui\Form\FormInterface
{
return $this->form;
}
@@ -222,7 +213,7 @@ public function form()
* @param array $properties The form's object properties.
* @return FormSidebarWidget Chainable
*/
- public function setSidebarProperties(array $properties)
+ public function setSidebarProperties(array $properties): static
{
$this->sidebarProperties = $properties;
@@ -241,20 +232,16 @@ public function sidebarProperties()
/**
* Determine if the sidebar has any object properties.
- *
- * @return boolean
*/
- public function hasSidebarProperties()
+ public function hasSidebarProperties(): bool
{
return ($this->numSidebarProperties() > 0);
}
/**
* Count the number of object properties in the sidebar.
- *
- * @return integer
*/
- public function numSidebarProperties()
+ public function numSidebarProperties(): int
{
return count($this->sidebarProperties());
}
@@ -265,7 +252,7 @@ public function numSidebarProperties()
* @param array $properties The options to customize the group properties.
* @return FormSidebarWidget Chainable
*/
- public function setPropertiesOptions(array $properties)
+ public function setPropertiesOptions(array $properties): static
{
$this->propertiesOptions = $properties;
@@ -274,10 +261,8 @@ public function setPropertiesOptions(array $properties)
/**
* Retrieve the map of object property customizations.
- *
- * @return array
*/
- public function propertiesOptions()
+ public function propertiesOptions(): array
{
return $this->propertiesOptions;
}
@@ -292,7 +277,7 @@ public function formProperties()
$form = $this->form();
$obj = $form->obj();
- $availableProperties = $obj->properties();
+ $obj->properties();
$sidebarProperties = $this->sidebarProperties();
$propertiesOptions = $this->propertiesOptions();
@@ -345,9 +330,7 @@ public function showSidebarActions()
return false;
}
- $actions = array_filter($actions, function ($action) {
- return $action['active'] === true;
- });
+ $actions = array_filter($actions, fn(array $action): bool => $action['active'] === true);
$this->showSidebarActions = (count($actions) > 0);
}
@@ -380,7 +363,7 @@ public function sidebarActions()
* @param array $actions One or more actions.
* @return FormSidebarWidget Chainable.
*/
- protected function setSidebarActions(array $actions)
+ protected function setSidebarActions(array $actions): static
{
$this->parsedSidebarActions = false;
@@ -399,22 +382,19 @@ protected function setSidebarActions(array $actions)
* @param array $actions Actions to resolve.
* @return array Sidebar actions.
*/
- protected function createSidebarActions(array $actions)
+ protected function createSidebarActions(array $actions): array
{
$this->actionsPriority = $this->defaultActionPriority();
- $sidebarActions = $this->parseAsSidebarActions($actions);
-
- return $sidebarActions;
+ return $this->parseAsSidebarActions($actions);
}
/**
* Parse the given actions as object actions.
*
* @param array $actions Actions to resolve.
- * @return array
*/
- protected function parseAsSidebarActions(array $actions)
+ protected function parseAsSidebarActions(array $actions): array
{
$sidebarActions = [];
foreach ($actions as $ident => $action) {
@@ -441,9 +421,7 @@ protected function parseAsSidebarActions(array $actions)
if ($action['actions']) {
$action['actions'] = $this->parseAsSidebarActions($action['actions']);
- $action['hasActions'] = !!array_filter($action['actions'], function ($action) {
- return $action['active'];
- });
+ $action['hasActions'] = (bool)array_filter($action['actions'], fn(array $action): mixed => $action['active']);
}
if (isset($sidebarActions[$ident])) {
@@ -458,7 +436,7 @@ protected function parseAsSidebarActions(array $actions)
}
}
- usort($sidebarActions, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ usort($sidebarActions, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
while (($first = reset($sidebarActions)) && $first['isSeparator']) {
array_shift($sidebarActions);
@@ -481,7 +459,7 @@ protected function defaultSidebarActions()
if ($this->defaultSidebarActions === null) {
$this->defaultSidebarActions = [];
- if ($this->form()) {
+ if ($this->form() instanceof \Charcoal\Ui\Form\FormInterface) {
$save = [
'label' => $this->form()->submitLabel(),
'ident' => 'save',
@@ -495,10 +473,7 @@ protected function defaultSidebarActions()
return $this->defaultSidebarActions;
}
- /**
- * @return string
- */
- public function jsActionPrefix()
+ public function jsActionPrefix(): string
{
return 'js-sidebar';
}
@@ -519,7 +494,7 @@ public function isObjDeletable()
$this->isObjDeletable = false;
} else {
$obj = $this->form()->obj();
- $this->isObjDeletable = !!$obj->id();
+ $this->isObjDeletable = (bool)$obj->id();
$method = [ $obj, 'isDeletable' ];
if (is_callable($method)) {
@@ -539,7 +514,7 @@ public function isObjDeletable()
*
* @return boolean
*/
- public function isObjRevisionable()
+ public function isObjRevisionable(): ?bool
{
if ($this->isObjRevisionable === null) {
// Overridden by permissions
@@ -553,7 +528,7 @@ public function isObjRevisionable()
}
if ($obj instanceof RevisionableInterface && $obj['revisionEnabled']) {
- $this->isObjRevisionable = !!count($obj->allRevisions());
+ $this->isObjRevisionable = (bool)count($obj->allRevisions());
}
}
}
@@ -634,7 +609,7 @@ public function isObjViewable()
$this->isObjViewable = false;
} else {
$obj = $this->form()->obj();
- $this->isObjViewable = !!$obj->id();
+ $this->isObjViewable = (bool)$obj->id();
$method = [ $obj, 'isViewable' ];
if (is_callable($method)) {
@@ -652,9 +627,9 @@ public function isObjViewable()
* @param boolean $show Show (TRUE) or hide (FALSE) the title.
* @return UiItemInterface Chainable
*/
- public function setShowTitle($show)
+ public function setShowTitle($show): static
{
- $this->showTitle = !!$show;
+ $this->showTitle = (bool)$show;
return $this;
}
@@ -669,7 +644,7 @@ public function showTitle()
if ($this->showTitle === false) {
return false;
} else {
- return !!$this->title();
+ return (bool)$this->title();
}
}
@@ -677,7 +652,7 @@ public function showTitle()
* @param mixed $title The sidebar title.
* @return FormSidebarWidget Chainable
*/
- public function setTitle($title)
+ public function setTitle($title): static
{
$this->title = $this->translator()->translation($title);
@@ -700,9 +675,9 @@ public function title()
* @param boolean $show The show subtitle flag.
* @return FormSidebarWidget Chainable
*/
- public function setShowSubtitle($show)
+ public function setShowSubtitle($show): static
{
- $this->showSubtitle = !!$show;
+ $this->showSubtitle = (bool)$show;
return $this;
}
@@ -714,7 +689,7 @@ public function showSubtitle()
if ($this->showSubtitle === false) {
return false;
} else {
- return !!$this->subtitle();
+ return (bool)$this->subtitle();
}
}
@@ -722,7 +697,7 @@ public function showSubtitle()
* @param mixed $subtitle The sidebar widget subtitle.
* @return FormSidebarWidget Chainable
*/
- public function setSubtitle($subtitle)
+ public function setSubtitle($subtitle): static
{
$this->subtitle = $this->translator()->translation($subtitle);
@@ -761,31 +736,26 @@ public function showFooter()
* Enable / Disable the sidebar's footer.
*
* @param mixed $show The show footer flag.
- * @return FormSidebarWidget
*/
- public function setShowFooter($show)
+ public function setShowFooter($show): static
{
- $this->showFooter = !!$show;
+ $this->showFooter = (bool)$show;
return $this;
}
/**
* Determine if wrapper containing the subtitle and properties should be displayed.
- *
- * @return boolean
*/
- public function showPropertiesWrapper()
+ public function showPropertiesWrapper(): bool
{
return $this->showSubtitle() || $this->hasSidebarProperties();
}
/**
* Determine if wrapper containing the language switcher and actions should be displayed.
- *
- * @return boolean
*/
- public function showActionsWrapper()
+ public function showActionsWrapper(): bool
{
return $this->showLanguageSwitch() || $this->showSidebarActions();
}
@@ -797,10 +767,8 @@ public function showActionsWrapper()
protected function resolveShowLanguageSwitch()
{
$form = $this->form();
- if ($form) {
- if ($form instanceof LanguageSwitcherAwareInterface) {
- return $form->supportsLanguageSwitch();
- }
+ if ($form && $form instanceof LanguageSwitcherAwareInterface) {
+ return $form->supportsLanguageSwitch();
}
return false;
@@ -811,24 +779,24 @@ protected function resolveShowLanguageSwitch()
*
* @see AdminWidget::resolveConditionalLogic()
* @param callable|string $condition The callable or renderable condition.
- * @return boolean
*/
- protected function resolveConditionalLogic($condition)
+ #[\Override]
+ protected function resolveConditionalLogic($condition): bool
{
$renderer = $this->getActionRenderer();
if ($renderer && is_callable([ $renderer, $condition ])) {
- return !!$renderer->{$condition}();
+ return (bool)$renderer->{$condition}();
} elseif (is_callable([ $this, $condition ])) {
- return !!$this->{$condition}();
+ return (bool)$this->{$condition}();
} elseif (is_callable($condition)) {
- return !!$condition();
- } elseif ($renderer) {
- return !!$renderer->renderTemplate($condition);
- } elseif ($this->view()) {
- return !!$this->renderTemplate($condition);
+ return (bool)$condition();
+ } elseif ($renderer instanceof \Charcoal\View\ViewableInterface) {
+ return (bool)$renderer->renderTemplate($condition);
+ } elseif ($this->view() instanceof \Charcoal\View\ViewInterface) {
+ return (bool)$this->renderTemplate($condition);
}
- return !!$condition;
+ return (bool)$condition;
}
// ACL Permissions
@@ -851,26 +819,21 @@ protected function checkPermission($permissionName)
}
$authUser = $this->authenticator()->user();
- if (!$authUser || !$this->authorizer()->userAllowed($authUser, $permissions)) {
- return false;
- }
-
- return true;
+ return $authUser && $this->authorizer()->userAllowed($authUser, $permissions);
}
/**
* @return string[]
*/
- public function requiredGlobalAclPermissions()
+ public function requiredGlobalAclPermissions(): array
{
return $this->requiredGlobalAclPermissions;
}
/**
* @param array $permissions The GlobalAcl permissions required pby the form group.
- * @return self
*/
- public function setRequiredGlobalAclPermissions(array $permissions)
+ public function setRequiredGlobalAclPermissions(array $permissions): static
{
$this->requiredGlobalAclPermissions = $permissions;
@@ -892,6 +855,6 @@ protected function isAssoc(array $array)
return false;
}
- return !!array_filter($array, 'is_string', ARRAY_FILTER_USE_KEY);
+ return (bool)array_filter($array, is_string(...), ARRAY_FILTER_USE_KEY);
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/FormWidget.php b/packages/admin/src/Charcoal/Admin/Widget/FormWidget.php
index 233531116..1a8cc18e6 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/FormWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/FormWidget.php
@@ -99,16 +99,15 @@ class FormWidget extends AdminWidget implements
/**
* Store the factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $widgetFactory;
+ private ?\Charcoal\Factory\FactoryInterface $widgetFactory = null;
/**
* @param array $data The widget data.
* @return FormWidget Chainable
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
$this->setDefaultFormGroupsTemplate();
$this->setDefaultFormTabsTemplate();
@@ -122,7 +121,7 @@ public function setData(array $data)
* @param array $data Optional. The form property data to set.
* @return FormPropertyWidget
*/
- public function createFormProperty(array $data = null)
+ public function createFormProperty(?array $data = null)
{
$p = $this->widgetFactory()->create($this->formPropertyClass());
if ($data !== null) {
@@ -139,7 +138,7 @@ public function createFormProperty(array $data = null)
* @throws InvalidArgumentException If the class name is not a string.
* @return FormWidget Chainable
*/
- protected function setFormPropertyClass($className)
+ protected function setFormPropertyClass($className): static
{
if (!is_string($className)) {
throw new InvalidArgumentException(
@@ -167,7 +166,7 @@ public function formPropertyClass()
* @throws InvalidArgumentException If the property is already registered.
* @return \Charcoal\Admin\Widget\FormPropertyWidget|mixed
*/
- public function getOrCreateFormProperty($ident, array $data = null)
+ public function getOrCreateFormProperty($ident, ?array $data = null)
{
if ($this->updateFormProperty($ident, $data)) {
return $this->formProperties[$ident];
@@ -203,7 +202,7 @@ public function getOrCreateFormProperty($ident, array $data = null)
* @throws InvalidArgumentException If the property is already registered.
* @return \Charcoal\Admin\Widget\FormPropertyWidget|mixed
*/
- public function getOrCreateHiddenProperty($ident, array $data = null)
+ public function getOrCreateHiddenProperty($ident, ?array $data = null)
{
if ($this->updateHiddenProperty($ident, $data)) {
return $this->hiddenProperties[$ident];
@@ -233,7 +232,7 @@ public function getOrCreateHiddenProperty($ident, array $data = null)
* @param array $data Property metadata.
* @return \Charcoal\Admin\Widget\FormPropertyWidget|mixed
*/
- protected function buildFormProperty($ident, array $data = null)
+ protected function buildFormProperty($ident, ?array $data = null)
{
$formProperty = $this->createFormProperty();
$formProperty->setPropertyIdent($ident);
@@ -264,7 +263,7 @@ protected function buildFormProperty($ident, array $data = null)
* @param array $data Property metadata.
* @return \Charcoal\Admin\Widget\FormPropertyWidget|null
*/
- protected function updateFormProperty($ident, array $data = null)
+ protected function updateFormProperty($ident, ?array $data = null)
{
if ($ident && isset($this->formProperties[$ident])) {
$formProperty = $this->formProperties[$ident];
@@ -286,7 +285,7 @@ protected function updateFormProperty($ident, array $data = null)
* @param array $data Property metadata.
* @return \Charcoal\Admin\Widget\FormPropertyWidget|null
*/
- protected function updateHiddenProperty($ident, array $data = null)
+ protected function updateHiddenProperty($ident, ?array $data = null)
{
if ($ident && isset($this->hiddenProperties[$ident])) {
$formProperty = $this->hiddenProperties[$ident];
@@ -306,27 +305,24 @@ protected function updateHiddenProperty($ident, array $data = null)
/**
* @param string $ident Property ident.
- * @return boolean
*/
- protected function hasFormProperty($ident)
+ protected function hasFormProperty($ident): bool
{
return ($ident && isset($this->formProperties[$ident]));
}
/**
* @param string $ident Property ident.
- * @return boolean
*/
- protected function hasHiddenProperty($ident)
+ protected function hasHiddenProperty($ident): bool
{
return ($ident && isset($this->hiddenProperties[$ident]));
}
/**
* @param array $sidebars The form sidebars.
- * @return self
*/
- public function setSidebars(array $sidebars)
+ public function setSidebars(array $sidebars): static
{
$this->sidebars = [];
foreach ($sidebars as $sidebarIdent => $sidebar) {
@@ -340,9 +336,8 @@ public function setSidebars(array $sidebars)
* @param string $sidebarIdent The sidebar identifier.
* @param array|FormSidebarInterface $sidebar The sidebar data or object.
* @throws InvalidArgumentException If the ident is not a string or the sidebar is not valid.
- * @return self
*/
- public function addSidebar($sidebarIdent, $sidebar)
+ public function addSidebar($sidebarIdent, $sidebar): static
{
if (!is_string($sidebarIdent)) {
throw new InvalidArgumentException(
@@ -381,10 +376,8 @@ public function addSidebar($sidebarIdent, $sidebar)
/**
* Determines if any sidebars are defined.
- *
- * @return boolean
*/
- public function hasSidebars()
+ public function hasSidebars(): bool
{
return (bool)$this->sidebars;
}
@@ -397,17 +390,13 @@ public function hasSidebars()
public function sidebars()
{
$sidebars = $this->sidebars;
- uasort($sidebars, [ $this, 'sortSidebarsByPriority' ]);
+ uasort($sidebars, $this->sortSidebarsByPriority(...));
foreach ($sidebars as $sidebarIdent => $sidebar) {
if (!$sidebar->active()) {
continue;
}
- if ($sidebar->template()) {
- $template = $sidebar->template();
- } else {
- $template = 'charcoal/admin/widget/form.sidebar';
- }
+ $template = $sidebar->template() ?: 'charcoal/admin/widget/form.sidebar';
$this->setDynamicTemplate('widget_template', $template);
yield $sidebarIdent => $sidebar;
@@ -418,9 +407,8 @@ public function sidebars()
* Replace property controls to the form.
*
* @param array $properties The form properties.
- * @return self
*/
- public function setFormProperties(array $properties)
+ public function setFormProperties(array $properties): static
{
$this->formProperties = [];
@@ -433,9 +421,8 @@ public function setFormProperties(array $properties)
* Add property controls to the form.
*
* @param array $properties The form properties.
- * @return self
*/
- public function addFormProperties(array $properties)
+ public function addFormProperties(array $properties): static
{
foreach ($properties as $propertyIdent => $property) {
$this->addFormProperty($propertyIdent, $property);
@@ -455,7 +442,7 @@ public function addFormProperties(array $properties)
* @throws InvalidArgumentException If the identifier or the property is invalid.
* @return FormInterface Chainable
*/
- public function addFormProperty($propertyIdent, $formProperty)
+ public function addFormProperty($propertyIdent, $formProperty): static
{
if (!is_string($propertyIdent)) {
throw new InvalidArgumentException(
@@ -480,7 +467,7 @@ public function addFormProperty($propertyIdent, $formProperty)
throw new InvalidArgumentException(sprintf(
'Property must be an array or an instance of FormPropertyWidget, received %s',
- is_object($formProperty) ? get_class($formProperty) : gettype($formProperty)
+ get_debug_type($formProperty)
));
}
@@ -510,7 +497,7 @@ public function formProperties()
*
* @return FormPropertyWidget[]
*/
- public function getFormProperties()
+ public function getFormProperties(): array
{
$formProperties = [];
foreach ($this->formProperties as $formProperty) {
@@ -530,7 +517,7 @@ public function getFormProperties()
* @param array $properties The hidden form properties.
* @return FormInterface Chainable
*/
- public function setHiddenProperties(array $properties)
+ public function setHiddenProperties(array $properties): static
{
$this->hiddenProperties = [];
@@ -545,7 +532,7 @@ public function setHiddenProperties(array $properties)
* @param array $properties The hidden form properties.
* @return FormInterface Chainable
*/
- public function addHiddenProperties(array $properties)
+ public function addHiddenProperties(array $properties): static
{
foreach ($properties as $propertyIdent => $property) {
$this->addHiddenProperty($propertyIdent, $property);
@@ -562,7 +549,7 @@ public function addHiddenProperties(array $properties)
* @throws InvalidArgumentException If the identifier or the property is invalid.
* @return FormInterface Chainable
*/
- public function addHiddenProperty($propertyIdent, $formProperty)
+ public function addHiddenProperty($propertyIdent, $formProperty): static
{
if (!is_string($propertyIdent)) {
throw new InvalidArgumentException(
@@ -588,7 +575,7 @@ public function addHiddenProperty($propertyIdent, $formProperty)
throw new InvalidArgumentException(sprintf(
'Form property must be an array or an instance of FormPropertyWidget, received %s',
- is_object($formProperty) ? get_class($formProperty) : gettype($formProperty)
+ get_debug_type($formProperty)
));
}
@@ -610,8 +597,6 @@ public function hiddenProperties()
/**
* Whether a language switcher could be displayed.
- *
- * @return bool
*/
public function supportsLanguageSwitch(): bool
{
@@ -620,10 +605,8 @@ public function supportsLanguageSwitch(): bool
/**
* Determine if the form has any multilingual properties.
- *
- * @return boolean
*/
- public function hasL10nFormProperties()
+ public function hasL10nFormProperties(): bool
{
$locales = count($this->translator()->availableLocales());
if ($locales > 1) {
@@ -653,9 +636,8 @@ public function submitLabel()
/**
* @param string|Translation $label The submit label for the form.
- * @return self
*/
- public function setSubmitLabel($label)
+ public function setSubmitLabel($label): static
{
$this->submitLabel = $this->translator()->translate($label);
@@ -664,18 +646,13 @@ public function setSubmitLabel($label)
/**
* Retrieve the default label for the form submission button.
- *
- * @return \Charcoal\Translator\Translation|null
*/
- public function defaultSubmitLabel()
+ public function defaultSubmitLabel(): ?\Charcoal\Translator\Translation
{
return $this->translator()->translation('Save');
}
- /**
- * @return string
- */
- public function defaultGroupType()
+ public function defaultGroupType(): string
{
return 'charcoal/admin/widget/form-group/generic';
}
@@ -686,7 +663,7 @@ public function defaultGroupType()
* @param string $partial The partial template to render the form groups within.
* @return FormWidget Chainable
*/
- public function setGroupsTemplate($partial)
+ public function setGroupsTemplate(?string $partial): static
{
$this->setDynamicTemplate('form_groups_template', $partial);
$this->groupsTemplate = $partial;
@@ -707,18 +684,12 @@ public function groupsTemplate()
return $this->groupsTemplate;
}
- /**
- * @return void
- */
- public function setDefaultFormGroupsTemplate()
+ public function setDefaultFormGroupsTemplate(): void
{
$this->setGroupsTemplate($this->defaultFormGroupsTemplate());
}
- /**
- * @return string
- */
- public function defaultFormGroupsTemplate()
+ public function defaultFormGroupsTemplate(): string
{
return 'charcoal/admin/template/form/groups-wrapper';
}
@@ -729,7 +700,7 @@ public function defaultFormGroupsTemplate()
* @param string $partial The partial template to render the form tabs within.
* @return FormWidget Chainable
*/
- public function setTabsTemplate($partial)
+ public function setTabsTemplate(?string $partial): static
{
$this->setDynamicTemplate('form_tabs_template', $partial);
$this->tabsTemplate = $partial;
@@ -750,18 +721,12 @@ public function tabsTemplate()
return $this->tabsTemplate;
}
- /**
- * @return void
- */
- public function setDefaultFormTabsTemplate()
+ public function setDefaultFormTabsTemplate(): void
{
$this->setTabsTemplate($this->defaultFormTabsTemplate());
}
- /**
- * @return string
- */
- public function defaultFormTabsTemplate()
+ public function defaultFormTabsTemplate(): string
{
return 'charcoal/admin/template/form/nav-tabs';
}
@@ -770,6 +735,7 @@ public function defaultFormTabsTemplate()
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -790,14 +756,13 @@ protected function setDependencies(Container $container)
* Retrieve the widget factory.
*
* @throws RuntimeException If the widget factory was not previously set.
- * @return FactoryInterface
*/
- protected function widgetFactory()
+ protected function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->widgetFactory === null) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Widget Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -827,10 +792,8 @@ protected function dataFromRequest()
/**
* Retrieve the accepted metadata from the current request.
- *
- * @return array
*/
- protected function acceptedRequestData()
+ protected function acceptedRequestData(): array
{
return [
'form_ident',
@@ -852,15 +815,10 @@ protected function acceptedRequestData()
protected function sortItemsByPriority(
PrioritizableInterface $a,
PrioritizableInterface $b
- ) {
+ ): int {
$priorityA = $a->priority();
$priorityB = $b->priority();
-
- if ($priorityA === $priorityB) {
- return 0;
- }
-
- return ($priorityA < $priorityB) ? (-1) : 1;
+ return ($priorityA <=> $priorityB);
}
/**
@@ -873,14 +831,9 @@ protected function sortItemsByPriority(
protected function sortSidebarsByPriority(
FormSidebarInterface $a,
FormSidebarInterface $b
- ) {
+ ): int {
$a = $a->priority();
$b = $b->priority();
-
- if ($a === $b) {
- return 0;
- }
-
- return ($a < $b) ? (-1) : 1;
+ return ($a <=> $b);
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractGraphWidget.php b/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractGraphWidget.php
index faacc7cea..9b7b02416 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractGraphWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractGraphWidget.php
@@ -164,10 +164,9 @@ public function categoriesJson()
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
return [
'list_actions' => $this->graphActions(),
@@ -278,9 +277,7 @@ protected function createGraphActions(array $actions)
{
$this->actionsPriority = $this->defaultActionPriority();
- $graphActions = $this->parseAsGraphActions($actions);
-
- return $graphActions;
+ return $this->parseAsGraphActions($actions);
}
/**
@@ -300,13 +297,11 @@ protected function parseAsGraphActions(array $actions)
$action['priority'] = $this->actionsPriority++;
}
- $action['empty'] = (isset($action['empty']) ? boolval($action['empty']) : false);
+ $action['empty'] = (isset($action['empty']) && boolval($action['empty']));
if (is_array($action['actions'])) {
$action['actions'] = $this->parseAsGraphActions($action['actions']);
- $action['hasActions'] = !!array_filter($action['actions'], function ($action) {
- return $action['active'];
- });
+ $action['hasActions'] = (bool)array_filter($action['actions'], fn(array $action): mixed => $action['active']);
}
if (isset($graphActions[$ident])) {
@@ -321,7 +316,7 @@ protected function parseAsGraphActions(array $actions)
}
}
- usort($graphActions, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ usort($graphActions, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
while (($first = reset($graphActions)) && $first['isSeparator']) {
array_shift($graphActions);
diff --git a/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractTimeGraphWidget.php b/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractTimeGraphWidget.php
index 6693057f3..26c86bad7 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractTimeGraphWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/Graph/AbstractTimeGraphWidget.php
@@ -27,30 +27,16 @@ abstract class AbstractTimeGraphWidget extends AbstractGraphWidget implements Ti
/**
* The date grouping type can be "hour", "day" or "month".
- *
- * @var string $groupingType
*/
- private $groupingType;
+ private ?string $groupingType = null;
- /**
- * @var string $dateFirnat
- */
- private $dateFormat;
+ private ?string $dateFormat = null;
- /**
- * @var string $sqlDateFormat
- */
- private $sqlDateFormat;
+ private ?string $sqlDateFormat = null;
- /**
- * @var DateTimeInterface $startDate
- */
- private $startDate;
+ private ?\DateTimeInterface $startDate = null;
- /**
- * @var DateTimeInterface $endDate
- */
- private $endDate;
+ private ?\DateTimeInterface $endDate = null;
/**
* @var DateInterval $dateInterval
@@ -150,7 +136,7 @@ public function setStartDate($ts)
throw new InvalidArgumentException(sprintf(
'Invalid start date: %s',
$e->getMessage()
- ), $e);
+ ), $e, $e);
}
}
if (!($ts instanceof DateTimeInterface)) {
@@ -184,7 +170,7 @@ public function setEndDate($ts)
throw new InvalidArgumentException(sprintf(
'Invalid end date: %s',
$e->getMessage()
- ), $e);
+ ), $e, $e);
}
}
if (!($ts instanceof DateTimeInterface)) {
diff --git a/packages/admin/src/Charcoal/Admin/Widget/Graph/GraphWidgetInterface.php b/packages/admin/src/Charcoal/Admin/Widget/Graph/GraphWidgetInterface.php
index 143d3935f..7b96d5de1 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/Graph/GraphWidgetInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/Graph/GraphWidgetInterface.php
@@ -1,5 +1,7 @@
showAsCard = !!$show;
+ $this->showAsCard = (bool)$show;
return $this;
}
@@ -71,9 +71,8 @@ public function getShowAsCard()
* Set the input options.
*
* @param array $options Optional property input settings.
- * @return self
*/
- public function setGraphOptions(array $options)
+ public function setGraphOptions(array $options): static
{
$this->graphOptions = array_merge($this->getDefaultGraphOptions(), $options);
@@ -91,11 +90,7 @@ public function getGraphOption($key, $default = null)
{
$options = $this->getGraphOptions();
- if (isset($options[$key])) {
- return $options[$key];
- }
-
- return $default;
+ return ($options[$key] ?? $default);
}
/**
@@ -114,20 +109,17 @@ public function getGraphOptions()
/**
* Retrieve the default display options.
- *
- * @return array
*/
- public function getDefaultGraphOptions()
+ public function getDefaultGraphOptions(): array
{
return [];
}
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
return [
'graph_options' => $this->getGraphOptions(),
diff --git a/packages/admin/src/Charcoal/Admin/Widget/GridStackDashboardWidget.php b/packages/admin/src/Charcoal/Admin/Widget/GridStackDashboardWidget.php
index 76ad80e89..cf0fb78ed 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/GridStackDashboardWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/GridStackDashboardWidget.php
@@ -41,6 +41,7 @@ class GridStackDashboardWidget extends AdminWidget implements
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -55,49 +56,46 @@ protected function setDependencies(Container $container)
* @param callable $widgetCallback A callback applied to each widget.
* @return UiItemInterface[]|\Generator
*/
- public function widgets(callable $widgetCallback = null)
+ public function widgets(?callable $widgetCallback = null)
{
$widgets = $this->widgets;
$gridStack = $this->gridStack() ?: [];
$parsedGridStack = [];
- array_walk($gridStack, function ($item) use (&$parsedGridStack) {
+ array_walk($gridStack, function (array $item) use (&$parsedGridStack): void {
$parsedGridStack[$item['id']] = $item;
});
// Load gridStack from user preferences
$user = $this->adminUser();
- $userGridStack = json_decode($user->preferences(), true)['grid_stack'] ?: [];
+ $userGridStack = json_decode((string)$user->preferences(), true)['grid_stack'] ?: [];
$parsedUserGridStack = [];
- array_walk($userGridStack, function ($item) use (&$parsedUserGridStack) {
+ array_walk($userGridStack, function (array $item) use (&$parsedUserGridStack): void {
$parsedUserGridStack[$item['id']] = $item;
});
- $widgetCallback = isset($widgetCallback) ? $widgetCallback : $this->widgetCallback;
+ $widgetCallback ??= $this->widgetCallback;
foreach ($widgets as $widget) {
if (isset($widget['permissions']) && $this instanceof AuthAwareInterface) {
$widget->setActive($this->hasPermissions($widget['permissions']));
}
- if (!!count($parsedUserGridStack)) {
+ if ((bool)count($parsedUserGridStack)) {
if (isset($parsedUserGridStack[$widget->ident()])) {
$widget->setData([
'grid_stack' => $parsedUserGridStack[$widget->ident()]
]);
}
- } else {
- if (isset($parsedGridStack[$widget->ident()])) {
- $gridStack = array_replace_recursive(
- $parsedGridStack[$widget->ident()],
- $widget['grid_stack'] ?: []
- );
-
- $widget->setData([
- 'grid_stack' => $gridStack
- ]);
- }
+ } elseif (isset($parsedGridStack[$widget->ident()])) {
+ $gridStack = array_replace_recursive(
+ $parsedGridStack[$widget->ident()],
+ $widget['grid_stack'] ?: []
+ );
+ $widget->setData([
+ 'grid_stack' => $gridStack
+ ]);
}
$gridStackDeco = new GridStackWidgetDecorator($widget);
@@ -126,9 +124,8 @@ public function gridStack()
/**
* @param mixed $gridStack GridStack for AdvancedDashboardWidget.
- * @return self
*/
- public function setGridStack($gridStack)
+ public function setGridStack($gridStack): static
{
$this->gridStack = $gridStack;
@@ -157,7 +154,7 @@ public function adminUser()
* @param LayoutBuilder $builder The layout builder, to create customized layout object(s).
* @return \Charcoal\Ui\Layout\DashboardInterface Chainable
*/
- public function setLayoutBuilder(LayoutBuilder $builder)
+ public function setLayoutBuilder(LayoutBuilder $builder): null
{
return null;
}
@@ -166,7 +163,7 @@ public function setLayoutBuilder(LayoutBuilder $builder)
* @param LayoutInterface|array $layout The layout object or structure.
* @return \Charcoal\Ui\Layout\DashboardInterface Chainable
*/
- public function setLayout($layout)
+ public function setLayout($layout): null
{
return null;
}
@@ -174,7 +171,7 @@ public function setLayout($layout)
/**
* @return LayoutInterface
*/
- public function layout()
+ public function layout(): null
{
return null;
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/HierarchicalTableWidget.php b/packages/admin/src/Charcoal/Admin/Widget/HierarchicalTableWidget.php
index f8e6ba872..c5d0933c0 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/HierarchicalTableWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/HierarchicalTableWidget.php
@@ -19,10 +19,9 @@ class HierarchicalTableWidget extends TableWidget
{
/**
* Provide a template to fullfill UIItem interface.
- *
- * @return string
*/
- public function template()
+ #[\Override]
+ public function template(): string
{
return 'charcoal/admin/widget/table';
}
@@ -36,10 +35,11 @@ public function template()
* @param PropertyInterface $property The current property.
* @return void
*/
+ #[\Override]
protected function setupDisplayPropertyValue(
ModelInterface $object,
PropertyInterface $property
- ) {
+ ): void {
parent::setupDisplayPropertyValue($object, $property);
if ($this->display instanceof HierarchicalDisplay) {
@@ -51,9 +51,9 @@ protected function setupDisplayPropertyValue(
* Sort the objects before they are displayed as rows.
*
* @see \Charcoal\Admin\Ui\CollectionContainerTrait::sortObjects()
- * @return array
*/
- public function sortObjects()
+ #[\Override]
+ public function sortObjects(): array
{
$collection = new HierarchicalCollection($this->objects(), false);
$collection
diff --git a/packages/admin/src/Charcoal/Admin/Widget/LayoutWidget.php b/packages/admin/src/Charcoal/Admin/Widget/LayoutWidget.php
index ad496119b..198bda638 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/LayoutWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/LayoutWidget.php
@@ -1,5 +1,7 @@
null,
@@ -89,9 +77,8 @@ public function widgetDataForJs()
*
* @param string|null $key The latitude property ident.
* @throws InvalidArgumentException If the property key is not a string.
- * @return self
*/
- public function setLatProperty($key)
+ public function setLatProperty($key): static
{
if ($key === null) {
$this->latProperty = $key;
@@ -110,10 +97,8 @@ public function setLatProperty($key)
/**
* Retrieve the $obj property key for the latitude.
- *
- * @return string|null
*/
- public function latProperty()
+ public function latProperty(): ?string
{
return $this->latProperty;
}
@@ -123,9 +108,8 @@ public function latProperty()
*
* @param string|null $key The longitude property key.
* @throws InvalidArgumentException If the property key is not a string.
- * @return self
*/
- public function setLngProperty($key)
+ public function setLngProperty($key): static
{
if ($key === null) {
$this->lngProperty = $key;
@@ -145,11 +129,10 @@ public function setLngProperty($key)
/**
* Set the $obj property key for the longitude.
*
- * @deprecated In favour of {@see self::setLngProperty()}.
* @param string $key The longitude property key.
- * @return self
*/
- public function setLonProperty($key)
+ #[\Deprecated(message: 'In favour of {@see self::setLngProperty()}.')]
+ public function setLonProperty($key): static
{
$this->logger->warning(
'MapWidget "lon_property" is deprecated. Use "lng_property".',
@@ -161,10 +144,8 @@ public function setLonProperty($key)
/**
* Retrieve the $obj property key for the longitude.
- *
- * @return string|null
*/
- public function lngProperty()
+ public function lngProperty(): ?string
{
return $this->lngProperty;
}
@@ -174,9 +155,8 @@ public function lngProperty()
*
* @param float $coord The latitude of a location.
* @throws InvalidArgumentException If the longitude is not a number.
- * @return self
*/
- public function setLat($coord)
+ public function setLat($coord): static
{
if ($coord === null) {
$this->lat = $coord;
@@ -217,9 +197,8 @@ public function lat()
*
* @param float $coord The longitude of a location.
* @throws InvalidArgumentException If the longitude is not a number.
- * @return self
*/
- public function setLng($coord)
+ public function setLng($coord): static
{
if ($coord === null) {
$this->lng = $coord;
@@ -258,9 +237,9 @@ public function lng()
/**
* Set the $obj property key for the longitude.
*
- * @deprecated In favour of {@see self::lng()}.
* @return self
*/
+ #[\Deprecated(message: 'In favour of {@see self::lng()}.')]
public function lon()
{
$this->logger->warning(
@@ -275,7 +254,7 @@ public function lon()
*
* @return float[]|null
*/
- public function latLng()
+ public function latLng(): ?array
{
$lat = $this->lat();
$lng = $this->lng();
@@ -292,7 +271,7 @@ public function latLng()
*
* @return float[]|null
*/
- public function coords()
+ public function coords(): ?array
{
$lat = $this->lat();
$lng = $this->lng();
@@ -314,7 +293,7 @@ public function hasObj()
if ($this->obj === null) {
try {
$this->obj();
- } catch (InvalidArgumentException $e) {
+ } catch (InvalidArgumentException) {
return false;
}
}
@@ -331,8 +310,8 @@ public function hasObj()
public function obj()
{
if ($this->obj === null) {
- $objId = filter_input(INPUT_GET, 'obj_id', FILTER_SANITIZE_STRING);
- $objType = filter_input(INPUT_GET, 'obj_type', FILTER_SANITIZE_STRING);
+ $objId = htmlspecialchars(trim(($_GET['obj_id'] ?? '')), ENT_QUOTES, 'UTF-8');
+ $objType = htmlspecialchars(trim(($_GET['obj_type'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($objId && $objType) {
$obj = $this->modelFactory()->create($objType);
$obj->load($objId);
diff --git a/packages/admin/src/Charcoal/Admin/Widget/ObjectFormWidget.php b/packages/admin/src/Charcoal/Admin/Widget/ObjectFormWidget.php
index a76dd8068..9ae33675a 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/ObjectFormWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/ObjectFormWidget.php
@@ -29,6 +29,11 @@ class ObjectFormWidget extends FormWidget implements
{
use ObjectContainerTrait;
+ /**
+ * @var mixed
+ */
+ public $nextUrl;
+
/**
* @var string
*/
@@ -54,10 +59,7 @@ class ObjectFormWidget extends FormWidget implements
*/
protected $forcePageReload = false;
- /**
- * @return string
- */
- public function widgetType()
+ public function widgetType(): string
{
return 'charcoal/admin/widget/object-form';
}
@@ -67,7 +69,8 @@ public function widgetType()
*
* @return Translation|string|null
*/
- public function defaultSubmitLabel()
+ #[\Override]
+ public function defaultSubmitLabel(): ?\Charcoal\Translator\Translation
{
if ($this->objId()) {
return $this->translator()->translation('Update');
@@ -80,7 +83,8 @@ public function defaultSubmitLabel()
* @param array $data The widget data.
* @return ObjectFormWidget Chainable
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -99,7 +103,7 @@ public function setData(array $data)
* @throws InvalidArgumentException If the identifier is not a string.
* @return ObjectForm Chainable
*/
- public function setFormIdent($formIdent)
+ public function setFormIdent($formIdent): static
{
if (!is_string($formIdent)) {
throw new InvalidArgumentException(
@@ -147,7 +151,7 @@ public function formIdent()
* @throws InvalidArgumentException If argument is not a string.
* @return ActionInterface Chainable
*/
- public function setNextUrl($url)
+ public function setNextUrl($url): static
{
if (!is_string($url)) {
throw new InvalidArgumentException(
@@ -174,9 +178,8 @@ public function allowReload()
/**
* @param boolean $allowReload AllowReload for ObjectFormWidget.
- * @return self
*/
- public function setAllowReload($allowReload)
+ public function setAllowReload($allowReload): static
{
$this->allowReload = $allowReload;
@@ -193,9 +196,8 @@ public function forcePageReload()
/**
* @param boolean $forcePageReload ForcePageReload for ObjectFormWidget.
- * @return self
*/
- public function setForcePageReload($forcePageReload)
+ public function setForcePageReload($forcePageReload): static
{
$this->forcePageReload = $forcePageReload;
@@ -207,6 +209,7 @@ public function setForcePageReload($forcePageReload)
*
* @return string Relative URL
*/
+ #[\Override]
public function action()
{
$action = parent::action();
@@ -230,14 +233,15 @@ public function action()
* @throws UnexpectedValueException If a property data is invalid.
* @return FormPropertyWidget[]|\Generator
*/
- public function formProperties(array $group = null)
+ #[\Override]
+ public function formProperties(?array $group = null)
{
$obj = $this->obj();
$props = $obj->metadata()->properties();
// We need to sort form properties by form group property order if a group exists
- if (!empty($group)) {
- $group = array_map([ $this, 'camelize' ], $group);
+ if ($group !== null && $group !== []) {
+ $group = array_map($this->camelize(...), $group);
$group = array_flip($group);
$props = array_intersect_key($props, $group);
$props = array_merge($group, $props);
@@ -253,7 +257,7 @@ public function formProperties(array $group = null)
throw new UnexpectedValueException(sprintf(
'Invalid property data for "%1$s", received %2$s',
$propertyIdent,
- (is_object($propertyMetadata) ? get_class($propertyMetadata) : gettype($propertyMetadata))
+ (get_debug_type($propertyMetadata))
));
}
@@ -293,13 +297,11 @@ public function formProperty($propertyIdent)
throw new UnexpectedValueException(sprintf(
'Invalid property data for "%1$s", received %2$s',
$propertyIdent,
- (is_object($propertyMetadata) ? get_class($propertyMetadata) : gettype($propertyMetadata))
+ (get_debug_type($propertyMetadata))
));
}
- $p = $this->getOrCreateFormProperty($propertyIdent, $propertyMetadata);
-
- return $p;
+ return $this->getOrCreateFormProperty($propertyIdent, $propertyMetadata);
}
/**
@@ -311,19 +313,14 @@ public function formProperty($propertyIdent)
* @param array $data Data.
* @return ObjectFormWidget Chainable.
*/
- public function setFormData(array $data)
+ #[\Override]
+ public function setFormData(array $data): static
{
$objData = $this->objData();
$merged = array_replace_recursive($objData, $data);
// Remove null values
- $merged = array_filter($merged, function ($val) {
- if ($val === null) {
- return false;
- }
-
- return true;
- });
+ $merged = array_filter($merged, fn($val): bool => $val !== null);
$this->formData = $merged;
$this->obj()->setData($merged);
@@ -336,6 +333,7 @@ public function setFormData(array $data)
*
* @return array
*/
+ #[\Override]
public function formData()
{
if (!$this->formData) {
@@ -356,10 +354,9 @@ public function objData()
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
return [
'obj_id' => $this->objId(),
@@ -378,9 +375,8 @@ public function widgetDataForJs()
* Self recursive when a groups is an instance of FormInterface.
*
* @param array|null $groups Form groups to parse.
- * @return array
*/
- protected function groupsConditionalLogic(array $groups = null)
+ protected function groupsConditionalLogic(?array $groups = null): array
{
if (!$groups) {
$groups = iterator_to_array($this->groups());
@@ -391,7 +387,7 @@ protected function groupsConditionalLogic(array $groups = null)
foreach ($groups as $group) {
if ($group instanceof FormInterface) {
$groupGroups = iterator_to_array($group->groups());
- if (!empty($groupGroups)) {
+ if ($groupGroups !== []) {
$conditions = array_merge(
$conditions,
$this->groupsConditionalLogic($groupGroups)
@@ -411,6 +407,7 @@ protected function groupsConditionalLogic(array $groups = null)
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -424,17 +421,17 @@ protected function setDependencies(Container $container)
*
* @return string[]
*/
- protected function defaultDataSources()
+ #[\Override]
+ protected function defaultDataSources(): array
{
return [static::DATA_SOURCE_REQUEST, static::DATA_SOURCE_OBJECT];
}
/**
* Retrieve the default data source filters (when setting data on an entity).
- *
- * @return array
*/
- protected function defaultDataSourceFilters()
+ #[\Override]
+ protected function defaultDataSourceFilters(): array
{
return [
'request' => null,
@@ -451,6 +448,7 @@ protected function defaultDataSourceFilters()
* @param mixed $toResolve A callable used when merging data.
* @return callable|null
*/
+ #[\Override]
protected function resolveDataSourceFilter($toResolve)
{
if (is_string($toResolve)) {
@@ -477,10 +475,9 @@ protected function resolveDataSourceFilter($toResolve)
/**
* Retrieve the accepted metadata from the current request.
- *
- * @return array
*/
- protected function acceptedRequestData()
+ #[\Override]
+ protected function acceptedRequestData(): array
{
return array_merge([
'obj_type',
@@ -498,7 +495,7 @@ protected function dataFromObject()
{
$obj = $this->obj();
$objMetadata = $obj->metadata();
- $adminMetadata = (isset($objMetadata['admin']) ? $objMetadata['admin'] : null);
+ $adminMetadata = ($objMetadata['admin'] ?? null);
$formIdent = $this->formIdent();
if (!$formIdent) {
@@ -509,11 +506,7 @@ protected function dataFromObject()
$formIdent = $obj->render($formIdent);
}
- if (isset($adminMetadata['forms'][$formIdent])) {
- $objFormData = $adminMetadata['forms'][$formIdent];
- } else {
- $objFormData = [];
- }
+ $objFormData = ($adminMetadata['forms'][$formIdent] ?? []);
$formGroups = [];
@@ -525,7 +518,7 @@ protected function dataFromObject()
$formGroups = array_merge($formGroups, $adminMetadata['formGroups']);
}
- if (isset($objFormData['groups']) && !empty($formGroups)) {
+ if (isset($objFormData['groups']) && $formGroups !== []) {
$extraFormGroups = array_intersect(
array_keys($formGroups),
array_keys($objFormData['groups'])
@@ -548,7 +541,7 @@ protected function dataFromObject()
$formSidebars = array_merge($formSidebars, $adminMetadata['formSidebars']);
}
- if (isset($objFormData['sidebars']) && !empty($formSidebars)) {
+ if (isset($objFormData['sidebars']) && $formSidebars !== []) {
$extraFormSidebars = array_intersect(
array_keys($formSidebars),
array_keys($objFormData['sidebars'])
@@ -566,9 +559,8 @@ protected function dataFromObject()
/**
* Whether a language switcher could be displayed.
- *
- * @return bool
*/
+ #[\Override]
public function supportsLanguageSwitch(): bool
{
if ($this->validateObjType()) {
@@ -593,10 +585,9 @@ public function supportsLanguageSwitch(): bool
/**
* Determine if the form has any multilingual properties.
- *
- * @return boolean
*/
- public function hasL10nFormProperties()
+ #[\Override]
+ public function hasL10nFormProperties(): bool
{
if ($this->validateObjType()) {
$locales = count($this->translator()->availableLocales());
@@ -616,11 +607,8 @@ public function hasL10nFormProperties()
/**
* Determine if the group has any multilingual properties.
- *
- * @param FormGroupInterface $group
- * @return bool
*/
- protected function hasL10nGroupProperties(FormGroupInterface $group)
+ protected function hasL10nGroupProperties(FormGroupInterface $group): bool
{
if ($group instanceof AdminFormGroupInterface) {
foreach ($group->groupProperties() as $prop) {
@@ -635,10 +623,6 @@ protected function hasL10nGroupProperties(FormGroupInterface $group)
/**
* Determine if the model property is multilingual.
- *
- * @param ModelInterface $model
- * @param string $propertyIdent
- * @return ?bool
*/
protected function isL10nModelProperty(ModelInterface $model, string $propertyIdent): ?bool
{
@@ -667,6 +651,7 @@ protected function isL10nModelProperty(ModelInterface $model, string $propertyId
* @throws InvalidArgumentException If the identifier is not a string or the group is invalid.
* @return FormGroupInterface
*/
+ #[\Override]
protected function parseFormGroup($groupIdent, $group)
{
$group = parent::parseFormGroup($groupIdent, $group);
@@ -680,10 +665,8 @@ protected function parseFormGroup($groupIdent, $group)
/**
* Yield the form's property controls.
- *
- * @return array
*/
- public function parseFormProperties()
+ public function parseFormProperties(): array
{
$props = [];
foreach ($this->formProperties as $k => $v) {
@@ -699,13 +682,10 @@ public function parseFormProperties()
* @param array|null $data Optional. The form group data to set.
* @return FormGroupInterface
*/
- protected function createFormGroup(array $data = null)
+ #[\Override]
+ protected function createFormGroup(?array $data = null)
{
- if (isset($data['type'])) {
- $type = $data['type'];
- } else {
- $type = $this->defaultGroupType();
- }
+ $type = ($data['type'] ?? $this->defaultGroupType());
$group = $this->formGroupFactory()->create($type);
$group->setForm($this->formWidget());
@@ -734,13 +714,13 @@ protected function createFormGroup(array $data = null)
* @param FormGroupInterface $group The form group to update.
* @param array|null $groupData Optional. The new group data to apply.
* @param string|null $groupIdent Optional. The new group identifier.
- * @return FormGroupInterface
*/
+ #[\Override]
protected function updateFormGroup(
FormGroupInterface $group,
- array $groupData = null,
+ ?array $groupData = null,
$groupIdent = null
- ) {
+ ): FormGroupInterface {
$group->setForm($this);
if ($groupIdent !== null) {
diff --git a/packages/admin/src/Charcoal/Admin/Widget/ObjectRevisionsWidget.php b/packages/admin/src/Charcoal/Admin/Widget/ObjectRevisionsWidget.php
index cb482ded4..d5239e223 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/ObjectRevisionsWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/ObjectRevisionsWidget.php
@@ -1,5 +1,7 @@
objType() && $this->objId();
}
@@ -45,9 +45,8 @@ public function objType()
/**
* @param string $objType ObjType for ObjectRevisionsWidget.
- * @return self
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
@@ -64,9 +63,8 @@ public function objId()
/**
* @param string|integer $objId ObjId for ObjectRevisionsWidget.
- * @return self
*/
- public function setObjId($objId)
+ public function setObjId($objId): static
{
$this->objId = $objId;
@@ -78,7 +76,8 @@ public function setObjId($objId)
*
* @return string[]
*/
- protected function defaultDataSources()
+ #[\Override]
+ protected function defaultDataSources(): array
{
return [
static::DATA_SOURCE_REQUEST,
@@ -88,15 +87,9 @@ protected function defaultDataSources()
/**
* Retrieve the accepted metadata from the current request.
- *
- * @return array
*/
- protected function acceptedRequestData()
+ protected function acceptedRequestData(): array
{
- return array_merge([
- 'obj_type',
- 'obj_id',
- 'template',
- ]);
+ return ['obj_type', 'obj_id', 'template'];
}
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/PaginationWidget.php b/packages/admin/src/Charcoal/Admin/Widget/PaginationWidget.php
index b72ce6473..bb08a46a7 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/PaginationWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/PaginationWidget.php
@@ -21,17 +21,13 @@ class PaginationWidget extends AdminWidget
/**
* The pager object.
- *
- * @var PaginationInterface
*/
- private $pager;
+ private ?\Charcoal\Source\Pagination $pager = null;
/**
* The total number of items.
- *
- * @var integer
*/
- private $numTotal;
+ private ?int $numTotal = null;
/**
* @var integer
@@ -43,9 +39,9 @@ class PaginationWidget extends AdminWidget
*
* @return PaginationInterface
*/
- protected function pager()
+ protected function pager(): \Charcoal\Source\Pagination
{
- if ($this->pager === null) {
+ if (!$this->pager instanceof \Charcoal\Source\Pagination) {
$this->pager = $this->createPagination();
}
@@ -57,19 +53,17 @@ protected function pager()
*
* @return PaginationInterface
*/
- protected function createPagination()
+ protected function createPagination(): \Charcoal\Source\Pagination
{
- $pagination = new Pagination();
- return $pagination;
+ return new Pagination();
}
/**
* Set the page number.
*
* @param integer $page The current page. Pages should start at 1.
- * @return self
*/
- public function setPage($page)
+ public function setPage($page): static
{
$this->pager()->setPage($page);
@@ -88,20 +82,16 @@ public function page()
/**
* Retrieve the previous page number.
- *
- * @return integer
*/
- public function pagePrev()
+ public function pagePrev(): int
{
return max(1, ($this->page() - 1));
}
/**
* Retrieve the next page number.
- *
- * @return integer
*/
- public function pageNext()
+ public function pageNext(): int
{
return min($this->numPages(), ($this->page() + 1));
}
@@ -111,9 +101,8 @@ public function pageNext()
*
* @param integer $count The number of results to return, per page.
* Use 0 to request all results.
- * @return self
*/
- public function setNumPerPage($count)
+ public function setNumPerPage($count): static
{
$this->pager()->setNumPerPage($count);
@@ -135,7 +124,7 @@ public function numPerPage()
*
* @return integer
*/
- public function numTotal()
+ public function numTotal(): ?int
{
return $this->numTotal;
}
@@ -145,9 +134,8 @@ public function numTotal()
*
* @param integer $total The total number of items.
* @throws InvalidArgumentException If the argument is not a number or lower than 0.
- * @return self
*/
- public function setNumTotal($total)
+ public function setNumTotal($total): static
{
if (!is_numeric($total)) {
throw new InvalidArgumentException(
@@ -167,10 +155,7 @@ public function setNumTotal($total)
return $this;
}
- /**
- * @return array
- */
- public function pages()
+ public function pages(): array
{
if ($this->quickJumpEnabled()) {
return $this->buildQuickJumpForm();
@@ -189,12 +174,8 @@ public function pages()
return $out;
}
- /**
- * @return array
- */
- private function buildQuickJumpForm()
+ private function buildQuickJumpForm(): array
{
- $out = [];
$i = 1;
$numPages = $this->numPages();
$maxPageCount = $this->maxPageCount();
@@ -253,16 +234,13 @@ private function buildQuickJumpForm()
}
}
- $out = array_merge($left, $middle, $right);
-
- return $out;
+ return array_merge($left, $middle, $right);
}
/**
* @param integer $page The page index.
- * @return array
*/
- private function formatPage($page)
+ private function formatPage($page): array
{
return [
'separator' => false,
@@ -276,7 +254,7 @@ private function formatPage($page)
*
* @return integer
*/
- public function numPages()
+ public function numPages(): int|float
{
if ($this->numPerPage() == 0) {
return 1;
@@ -295,9 +273,8 @@ public function maxPageCount()
/**
* @param integer $maxPageCount The maximum number of page to display in pager at the same time.
- * @return PaginationWidget
*/
- public function setMaxPageCount($maxPageCount)
+ public function setMaxPageCount($maxPageCount): static
{
$this->maxPageCount = $maxPageCount;
@@ -307,40 +284,32 @@ public function setMaxPageCount($maxPageCount)
/**
* Determine if pagination can be displayed.
- *
- * @return boolean
*/
- public function showPagination()
+ public function showPagination(): bool
{
return ($this->numPages() > 1);
}
/**
* Determine if the "previous page" link can be displayed.
- *
- * @return boolean
*/
- public function previousEnabled()
+ public function previousEnabled(): bool
{
return ($this->page() > 1);
}
/**
* Determine if the "next page" link can be displayed.
- *
- * @return boolean
*/
- public function nextEnabled()
+ public function nextEnabled(): bool
{
return ($this->page() < $this->numPages());
}
/**
* His the quick jump input allowed?
- *
- * @return boolean
*/
- public function quickJumpEnabled()
+ public function quickJumpEnabled(): bool
{
return ($this->numPages() > $this->maxPageCount());
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/QuickFormWidget.php b/packages/admin/src/Charcoal/Admin/Widget/QuickFormWidget.php
index 8db61685b..c6cfaa9ed 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/QuickFormWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/QuickFormWidget.php
@@ -1,5 +1,7 @@
obj()->metadata();
@@ -60,7 +63,7 @@ public function formIdentFallback()
if (isset($this->formData()['form_ident'])) {
$ident = $this->formData()['form_ident'];
- if (is_string($ident) && !empty($ident)) {
+ if (is_string($ident) && ($ident !== '' && $ident !== '0')) {
return $ident;
}
}
@@ -70,10 +73,9 @@ public function formIdentFallback()
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
return array_merge_recursive(
parent::widgetDataForJs(),
@@ -89,6 +91,7 @@ public function widgetDataForJs()
*
* @return \Charcoal\Translator\Translation|string|null
*/
+ #[\Override]
public function submitLabel()
{
if (isset($this->formData()['submit_label'])) {
@@ -101,37 +104,30 @@ public function submitLabel()
/**
* @see HasLanguageSwitcherTrait::showLanguageSwitch()
- * @return boolean
*/
- protected function resolveShowLanguageSwitch()
+ protected function resolveShowLanguageSwitch(): bool
{
return $this->supportsLanguageSwitch();
}
/**
* Determine if content groups are to be displayed as languages tabbable panes.
- *
- * @return boolean
*/
- public function isDisplayModeLang()
+ public function isDisplayModeLang(): bool
{
return ($this->groupDisplayMode() === self::DISPLAY_MODE_LANG);
}
/**
* Determine if content groups are to be displayed as tabbable panes.
- *
- * @return boolean
*/
- public function isTabbable()
+ #[\Override]
+ public function isTabbable(): bool
{
return in_array($this->groupDisplayMode(), $this->getTabbableDisplayModes());
}
- /**
- * @return array
- */
- public function getTabbableDisplayModes()
+ public function getTabbableDisplayModes(): array
{
return [
self::DISPLAY_MODE_TAB,
@@ -147,16 +143,14 @@ public function availableLanguagesAsJson()
$options = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($this->debug()) {
- $options = ($options | JSON_PRETTY_PRINT);
+ $options |= JSON_PRETTY_PRINT;
}
return json_encode($this->languages(), $options);
}
- /**
- * @return string
- */
- public function defaultFormTabsTemplate()
+ #[\Override]
+ public function defaultFormTabsTemplate(): string
{
return 'charcoal/admin/template/form/nav-tabs';
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/SearchWidget.php b/packages/admin/src/Charcoal/Admin/Widget/SearchWidget.php
index dacdb82bc..d8b495792 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/SearchWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/SearchWidget.php
@@ -26,9 +26,9 @@ class SearchWidget extends AdminWidget implements CollectionContainerInterface
/**
* @param array $data The search widget data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
if (isset($data['obj_type'])) {
$this->setObjType($data['obj_type']);
@@ -51,10 +51,10 @@ public function dataFromObject()
{
$obj = $this->proto();
$metadata = $obj->metadata();
- $adminMetadata = isset($metadata['admin']) ? $metadata['admin'] : null;
+ $adminMetadata = ($metadata['admin'] ?? null);
$collectionIdent = $this->collectionIdent();
if (!$collectionIdent) {
- $collectionIdent = isset($adminMetadata['default_list']) ? $adminMetadata['default_list'] : '';
+ $collectionIdent = ($adminMetadata['default_list'] ?? '');
}
if (isset($adminMetadata['lists'][$collectionIdent])) {
@@ -80,7 +80,7 @@ public function properties()
$collectionIdent = $this->collectionIdent();
if ($collectionIdent) {
$metadata = $model->metadata();
- $adminMetadata = isset($metadata['admin']) ? $metadata['admin'] : null;
+ $adminMetadata = ($metadata['admin'] ?? null);
if (isset($adminMetadata['lists'][$collectionIdent]['properties'])) {
// Flipping to have property ident as key
@@ -119,10 +119,9 @@ public function propertiesIdents()
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
return [
'obj_type' => $this->objType(),
diff --git a/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidget.php b/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidget.php
index 96dc4bc25..3364d4576 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidget.php
@@ -27,6 +27,8 @@ class SecondaryMenuWidget extends AdminWidget implements
use ActionContainerTrait;
use HttpAwareTrait;
+ public $isCurrent;
+
/**
* Default sorting priority for an action.
*
@@ -71,31 +73,23 @@ class SecondaryMenuWidget extends AdminWidget implements
/**
* Whether the group is collapsed or not.
- *
- * @var boolean
*/
- private $collapsed = false;
+ private bool $collapsed = false;
/**
* Whether the group has siblings or not.
- *
- * @var boolean
*/
- private $parented = false;
+ private bool $parented = false;
/**
* The title is displayed by default.
- *
- * @var boolean
*/
- private $showTitle = true;
+ private bool $showTitle = true;
/**
* The description is displayed by default.
- *
- * @var boolean
*/
- private $showDescription = true;
+ private bool $showDescription = true;
/**
* The currently highlighted item.
@@ -148,9 +142,9 @@ class SecondaryMenuWidget extends AdminWidget implements
/**
* @param array $data Class data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
if (isset($data['actions'])) {
@@ -242,9 +236,8 @@ public function adminRoute()
/**
* @param string $ident The ident for the current item to highlight.
- * @return self
*/
- public function setCurrentItem($ident)
+ public function setCurrentItem($ident): static
{
$this->currentItem = $ident;
return $this;
@@ -262,9 +255,8 @@ public function currentItem()
* Computes the intersection of values to determine if the link is the current item.
*
* @param mixed $linkIdent The link's value(s) to check.
- * @return boolean
*/
- public function isCurrentItem($linkIdent)
+ public function isCurrentItem($linkIdent): bool
{
$context = array_filter([
$this->currentItem(),
@@ -274,7 +266,7 @@ public function isCurrentItem($linkIdent)
$matches = array_intersect((array)$linkIdent, $context);
- return !!$matches;
+ return (bool)$matches;
}
/**
@@ -291,11 +283,10 @@ public function objType()
* Show/hide the widget's title.
*
* @param boolean $show Show (TRUE) or hide (FALSE) the title.
- * @return self
*/
- public function setShowTitle($show)
+ public function setShowTitle($show): static
{
- $this->showTitle = !!$show;
+ $this->showTitle = (bool)$show;
return $this;
}
@@ -310,7 +301,7 @@ public function showTitle()
if ($this->showTitle === false) {
return false;
} else {
- return !!$this->title();
+ return (bool)$this->title();
}
}
@@ -318,9 +309,8 @@ public function showTitle()
* Set the title of the secondary menu.
*
* @param mixed $title A title for the secondary menu.
- * @return self
*/
- public function setTitle($title)
+ public function setTitle($title): static
{
$this->title = $this->translator()->translation($title);
@@ -352,9 +342,8 @@ public function title()
* Set the secondary menu links.
*
* @param array $links A collection of link objects.
- * @return self
*/
- public function setLinks(array $links)
+ public function setLinks(array $links): static
{
$this->links = new ArrayIterator();
@@ -371,9 +360,8 @@ public function setLinks(array $links)
* @param string $linkIdent The link identifier.
* @param array|object $link The link object or structure.
* @throws InvalidArgumentException If the link is invalid.
- * @return self
*/
- public function addLink($linkIdent, $link)
+ public function addLink($linkIdent, $link): static
{
if (!is_string($linkIdent) && !is_numeric($linkIdent)) {
throw new InvalidArgumentException(
@@ -394,7 +382,7 @@ public function addLink($linkIdent, $link)
}
if (isset($link['active'])) {
- $active = !!$link['active'];
+ $active = (bool)$link['active'];
}
if (isset($link['name'])) {
@@ -423,7 +411,7 @@ public function addLink($linkIdent, $link)
} else {
throw new InvalidArgumentException(sprintf(
'Link must be an associative array, received %s',
- (is_object($link) ? get_class($link) : gettype($link))
+ (get_debug_type($link))
));
}
@@ -463,10 +451,8 @@ public function links()
unset($link['required_acl_permissions']);
}
- if (isset($link['permissions'])) {
- if ($this->hasPermissions($link['permissions']) === false) {
- continue;
- }
+ if (isset($link['permissions']) && $this->hasPermissions($link['permissions']) === false) {
+ continue;
}
$out[] = $link;
@@ -481,9 +467,8 @@ public function links()
*
* @param mixed $type The display type.
* @throws InvalidArgumentException If the display type is invalid.
- * @return self
*/
- public function setDisplayType($type)
+ public function setDisplayType($type): static
{
if (!is_string($type)) {
throw new InvalidArgumentException('The display type must be a string.');
@@ -517,20 +502,16 @@ public function displayType()
/**
* Determine if the secondary menu groups should be displayed as panels.
- *
- * @return boolean
*/
- public function displayAsPanel()
+ public function displayAsPanel(): bool
{
return in_array($this->displayType(), [ 'panel', 'collapsible' ]);
}
/**
* Determine if the display type is "collapsible".
- *
- * @return boolean
*/
- public function collapsible()
+ public function collapsible(): bool
{
return ($this->displayType() === 'collapsible');
}
@@ -540,9 +521,8 @@ public function collapsible()
*
* @param array $options Display configuration.
* @throws InvalidArgumentException If the display options are not an associative array.
- * @return self
*/
- public function setDisplayOptions(array $options)
+ public function setDisplayOptions(array $options): static
{
$this->displayOptions = array_replace($this->defaultDisplayOptions(), $options);
@@ -579,10 +559,8 @@ public function displayOptions()
/**
* Retrieve the default display options for the secondary menu.
- *
- * @return array
*/
- public function defaultDisplayOptions()
+ public function defaultDisplayOptions(): array
{
return [
'parented' => false,
@@ -618,9 +596,8 @@ public function collapsed()
* Set the secondary menu's groups.
*
* @param array $groups A collection of group structures.
- * @return self
*/
- public function setGroups(array $groups)
+ public function setGroups(array $groups): static
{
$this->groups = [];
@@ -628,12 +605,10 @@ public function setGroups(array $groups)
$this->addGroup($groupIdent, $group);
}
- uasort($this->groups, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ uasort($this->groups, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
// Remove items that are not active and reset keys.
- $this->groups = array_values(array_filter($this->groups, function ($item) {
- return ($item->active());
- }));
+ $this->groups = array_values(array_filter($this->groups, fn($item) => $item->active()));
return $this;
}
@@ -644,9 +619,8 @@ public function setGroups(array $groups)
* @param string $groupIdent The group identifier.
* @param array|SecondaryMenuGroupInterface $group The group object or structure.
* @throws InvalidArgumentException If the identifier is not a string or the group is invalid.
- * @return self
*/
- public function addGroup($groupIdent, $group)
+ public function addGroup($groupIdent, $group): static
{
if (!is_string($groupIdent)) {
throw new InvalidArgumentException(
@@ -695,7 +669,7 @@ public function addGroup($groupIdent, $group)
throw new InvalidArgumentException(sprintf(
'Group must be an instance of %s or an array of form group options, received %s',
'SecondaryMenuGroupInterface',
- (is_object($group) ? get_class($group) : gettype($group))
+ (get_debug_type($group))
));
}
@@ -734,36 +708,30 @@ public function groups()
/**
* Retrieve the default secondary menu group class name.
- *
- * @return string
*/
- public function defaultGroupType()
+ public function defaultGroupType(): string
{
return 'charcoal/ui/secondary-menu/generic';
}
/**
* Determine if the secondary menu has any links.
- *
- * @return boolean
*/
- public function hasLinks()
+ public function hasLinks(): bool
{
- return !!$this->numLinks();
+ return (bool)$this->numLinks();
}
/**
* Count the number of secondary menu links.
- *
- * @return integer
*/
- public function numLinks()
+ public function numLinks(): int
{
if (!is_array($this->links()) && !($this->links() instanceof \Traversable)) {
return 0;
}
- $links = array_filter($this->links, function ($link) {
+ $links = array_filter($this->links, function (array $link): bool {
if (isset($link['active']) && !$link['active']) {
return false;
}
@@ -772,14 +740,7 @@ public function numLinks()
$link['permissions'] = $link['required_acl_permissions'];
unset($link['required_acl_permissions']);
}
-
- if (isset($link['permissions'])) {
- if ($this->hasPermissions($link['permissions']) === false) {
- return false;
- }
- }
-
- return true;
+ return !(isset($link['permissions']) && $this->hasPermissions($link['permissions']) === false);
});
return count($links);
@@ -787,40 +748,32 @@ public function numLinks()
/**
* Determine if the secondary menu has any groups of links.
- *
- * @return boolean
*/
- public function hasGroups()
+ public function hasGroups(): bool
{
- return !!$this->numGroups();
+ return (bool)$this->numGroups();
}
/**
* Count the number of secondary menu groups.
- *
- * @return integer
*/
- public function numGroups()
+ public function numGroups(): int
{
return count($this->groups());
}
/**
* Alias for {@see self::showSecondaryMenuActions()}
- *
- * @return boolean
*/
- public function hasActions()
+ public function hasActions(): int
{
return $this->showSecondaryMenuActions();
}
/**
* Determine if the secondary menu's actions should be shown.
- *
- * @return boolean
*/
- public function showSecondaryMenuActions()
+ public function showSecondaryMenuActions(): int
{
$actions = $this->secondaryMenuActions();
@@ -837,11 +790,7 @@ public function secondaryMenuActions()
if ($this->secondaryMenuActions === null) {
$ident = $this->ident();
$metadata = $this->adminSecondaryMenu();
- if (isset($metadata[$ident]['actions'])) {
- $actions = $metadata[$ident]['actions'];
- } else {
- $actions = [];
- }
+ $actions = ($metadata[$ident]['actions'] ?? []);
$this->setSecondaryMenuActions($actions);
}
@@ -857,9 +806,8 @@ public function secondaryMenuActions()
* Set the description of the secondary menu.
*
* @param mixed $description A description for the secondary menu.
- * @return self
*/
- public function setDescription($description)
+ public function setDescription($description): static
{
$this->description = $this->translator()->translation($description);
@@ -891,11 +839,10 @@ public function description()
* Determine if the description is to be displayed.
*
* @param boolean $show Show (TRUE) or hide (FALSE) the description.
- * @return self
*/
- public function setShowDescription($show)
+ public function setShowDescription($show): static
{
- $this->showDescription = !!$show;
+ $this->showDescription = (bool)$show;
return $this;
}
@@ -909,14 +856,11 @@ public function showDescription()
if ($this->showDescription === false) {
return false;
} else {
- return !!$this->description();
+ return (bool)$this->description();
}
}
- /**
- * @return string
- */
- public function jsActionPrefix()
+ public function jsActionPrefix(): string
{
return 'js-secondary-menu';
}
@@ -927,6 +871,7 @@ public function jsActionPrefix()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -951,9 +896,8 @@ public function isCurrent()
* Set the widget's display state.
*
* @param boolean $flag A truthy state.
- * @return self
*/
- protected function setIsCurrent($flag)
+ protected function setIsCurrent($flag): static
{
$this->isCurrent = boolval($flag);
@@ -968,10 +912,10 @@ protected function setIsCurrent($flag)
*/
protected function secondaryMenu()
{
- if (!isset($this->secondaryMenu)) {
+ if ($this->secondaryMenu === null) {
throw new RuntimeException(sprintf(
'Secondary Menu Group Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -982,9 +926,8 @@ protected function secondaryMenu()
* Set the secondary menu's actions.
*
* @param array $actions One or more actions.
- * @return self
*/
- protected function setSecondaryMenuActions(array $actions)
+ protected function setSecondaryMenuActions(array $actions): static
{
$this->parsedSecondaryMenuActions = false;
@@ -1003,11 +946,9 @@ protected function setSecondaryMenuActions(array $actions)
* @param array $actions Actions to resolve.
* @return array Secondary menu actions.
*/
- protected function createSecondaryMenuActions(array $actions)
+ protected function createSecondaryMenuActions(array $actions): array
{
- $secondaryMenuActions = $this->parseActions($actions);
-
- return $secondaryMenuActions;
+ return $this->parseActions($actions);
}
/**
@@ -1028,9 +969,8 @@ protected function defaultSecondaryMenuActions()
* Set a secondary menu group factory.
*
* @param FactoryInterface $factory The group factory, to create objects.
- * @return void
*/
- private function setSecondaryMenuGroupFactory(FactoryInterface $factory)
+ private function setSecondaryMenuGroupFactory(FactoryInterface $factory): void
{
$this->secondaryMenu = $factory;
}
diff --git a/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidgetInterface.php b/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidgetInterface.php
index cc915305e..8ffa0fe1a 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidgetInterface.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/SecondaryMenuWidgetInterface.php
@@ -1,5 +1,7 @@
proto();
$objMetadata = $proto->metadata();
- $adminMetadata = (isset($objMetadata['admin']) ? $objMetadata['admin'] : null);
+ $adminMetadata = ($objMetadata['admin'] ?? null);
if (empty($adminMetadata['lists'])) {
return [];
@@ -260,11 +250,7 @@ public function dataFromObject()
return [];
}
- if (isset($adminMetadata['lists'][$collectionIdent])) {
- $objListData = $adminMetadata['lists'][$collectionIdent];
- } else {
- $objListData = [];
- }
+ $objListData = ($adminMetadata['lists'][$collectionIdent] ?? []);
$collectionConfig = [];
@@ -320,7 +306,7 @@ public function dataFromObject()
}
}
- if ($collectionConfig) {
+ if ($collectionConfig !== []) {
$this->mergeCollectionConfig($collectionConfig);
}
@@ -329,10 +315,9 @@ public function dataFromObject()
/**
* Retrieve the widget's data options for JavaScript components.
- *
- * @return array
*/
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
return [
'obj_type' => $this->objType(),
@@ -376,7 +361,7 @@ public function properties()
if ($listProperties) {
$props = [];
foreach ($listProperties as $k => $v) {
- $k = lcfirst(implode('', array_map('ucfirst', explode('_', $k))));
+ $k = lcfirst(implode('', array_map(ucfirst(...), explode('_', (string)$k))));
$props[$k] = $v;
}
// Replacing values of listProperties from index to actual property values
@@ -398,11 +383,8 @@ public function properties()
public function propertiesIdents()
{
$collectionConfig = $this->collectionConfig();
- if (isset($collectionConfig['properties'])) {
- return $collectionConfig['properties'];
- }
- return [];
+ return ($collectionConfig['properties'] ?? []);
}
/**
@@ -472,11 +454,7 @@ public function collectionProperties()
$options = $this->viewOptions($propertyIdent);
$classes = $this->parsePropertyCellClasses($p);
- if (isset($options['label'])) {
- $label = $this->translator()->translate($options['label']);
- } else {
- $label = strval($p['label']);
- }
+ $label = isset($options['label']) ? $this->translator()->translate($options['label']) : strval($p['label']);
$column = [
'label' => trim($label)
@@ -489,24 +467,20 @@ public function collectionProperties()
if (isset($options['attr'])) {
$column['attr'] = array_merge($column['attr'], $options['attr']);
}
+ if (isset($column['attr']['class'])) {
+ if (is_string($classes)) {
+ $classes = explode(' ', $column['attr']['class']);
+ }
- if (isset($classes)) {
- if (isset($column['attr']['class'])) {
- if (is_string($classes)) {
- $classes = explode(' ', $column['attr']['class']);
- }
-
- if (is_string($column['attr']['class'])) {
- $column['attr']['class'] = explode(' ', $column['attr']['class']);
- }
-
- $column['attr']['class'] = array_unique(array_merge($column['attr']['class'], $classes));
- } else {
- $column['attr']['class'] = $classes;
+ if (is_string($column['attr']['class'])) {
+ $column['attr']['class'] = explode(' ', $column['attr']['class']);
}
- unset($classes);
+ $column['attr']['class'] = array_unique(array_merge($column['attr']['class'], $classes));
+ } else {
+ $column['attr']['class'] = $classes;
}
+ unset($classes);
$column['attr'] = html_build_attributes($column['attr']);
@@ -520,19 +494,17 @@ public function collectionProperties()
* @param boolean $show Show (TRUE) or hide (FALSE) the actions.
* @return TableWidget Chainable
*/
- public function setShowObjectActions($show)
+ public function setShowObjectActions($show): static
{
- $this->showObjectActions = !!$show;
+ $this->showObjectActions = (bool)$show;
return $this;
}
/**
* Determine if the table's object actions should be shown.
- *
- * @return boolean
*/
- public function showObjectActions()
+ public function showObjectActions(): false|int
{
if ($this->showObjectActions === false) {
return false;
@@ -543,10 +515,8 @@ public function showObjectActions()
/**
* Retrieve the table's object actions.
- *
- * @return array
*/
- public function objectActions()
+ public function objectActions(): array
{
$this->rawObjectActions();
@@ -571,11 +541,7 @@ public function rawObjectActions()
$parsed = $this->parsedObjectActions;
$collectionConfig = $this->collectionConfig();
- if (isset($collectionConfig['object_actions'])) {
- $actions = $collectionConfig['object_actions'];
- } else {
- $actions = [];
- }
+ $actions = ($collectionConfig['object_actions'] ?? []);
$this->setObjectActions($actions);
@@ -596,7 +562,7 @@ public function rawObjectActions()
* @param array $actions One or more actions.
* @return TableWidget Chainable.
*/
- public function setObjectActions(array $actions)
+ public function setObjectActions(array $actions): static
{
$this->parsedObjectActions = false;
@@ -619,7 +585,7 @@ public function setObjectActions(array $actions)
* @param array $actions Actions to resolve.
* @return array Object actions.
*/
- public function createObjectActions(array $actions)
+ public function createObjectActions(array $actions): array
{
$this->parsingObjectActions = true;
$objectActions = $this->parseActions($actions);
@@ -632,9 +598,8 @@ public function createObjectActions(array $actions)
* Parse the given actions as (row) object actions.
*
* @param array $actions Actions to resolve.
- * @return array
*/
- protected function parseAsObjectActions(array $actions)
+ protected function parseAsObjectActions(array $actions): array
{
$objectActions = [];
foreach ($actions as $action) {
@@ -654,9 +619,7 @@ protected function parseAsObjectActions(array $actions)
if ($action['actions']) {
$action['actions'] = $this->parseAsObjectActions($action['actions']);
- $action['hasActions'] = !!array_filter($action['actions'], function ($action) {
- return $action['active'];
- });
+ $action['hasActions'] = (bool)array_filter($action['actions'], fn(array $action): mixed => $action['active']);
}
$objectActions[] = $action;
@@ -667,10 +630,8 @@ protected function parseAsObjectActions(array $actions)
/**
* Determine if the table's empty collection actions should be shown.
- *
- * @return boolean
*/
- public function showEmptyListActions()
+ public function showEmptyListActions(): int
{
$actions = $this->emptyListActions();
@@ -679,16 +640,12 @@ public function showEmptyListActions()
/**
* Retrieve the table's empty collection actions.
- *
- * @return array
*/
- public function emptyListActions()
+ public function emptyListActions(): array
{
$actions = $this->listActions();
- $filteredArray = array_filter($actions, function ($action) {
- return $action['empty'] && $action['active'];
- });
+ $filteredArray = array_filter($actions, fn(array $action): bool => $action['empty'] && $action['active']);
return array_values($filteredArray);
}
@@ -699,19 +656,17 @@ public function emptyListActions()
* @param boolean $show Show (TRUE) or hide (FALSE) the actions.
* @return TableWidget Chainable
*/
- public function setShowListActions($show)
+ public function setShowListActions($show): static
{
- $this->showListActions = !!$show;
+ $this->showListActions = (bool)$show;
return $this;
}
/**
* Determine if the table's collection actions should be shown.
- *
- * @return boolean
*/
- public function showListActions()
+ public function showListActions(): false|int
{
if ($this->showListActions === false) {
return false;
@@ -729,11 +684,7 @@ public function listActions()
{
if ($this->listActions === null) {
$collectionConfig = $this->collectionConfig();
- if (isset($collectionConfig['list_actions'])) {
- $actions = $collectionConfig['list_actions'];
- } else {
- $actions = [];
- }
+ $actions = ($collectionConfig['list_actions'] ?? []);
$this->setListActions($actions);
}
@@ -765,9 +716,9 @@ public function paginationWidget()
* @param boolean $show The show flag.
* @return TableWidget Chainable
*/
- public function setShowTableHeader($show)
+ public function setShowTableHeader($show): static
{
- $this->showTableHeader = !!$show;
+ $this->showTableHeader = (bool)$show;
return $this;
}
@@ -784,9 +735,9 @@ public function showTableHeader()
* @param boolean $show The show flag.
* @return TableWidget Chainable
*/
- public function setShowTableHead($show)
+ public function setShowTableHead($show): static
{
- $this->showTableHead = !!$show;
+ $this->showTableHead = (bool)$show;
return $this;
}
@@ -803,9 +754,9 @@ public function showTableHead()
* @param boolean $show The show flag.
* @return TableWidget Chainable
*/
- public function setShowTableFoot($show)
+ public function setShowTableFoot($show): static
{
- $this->showTableFoot = !!$show;
+ $this->showTableFoot = (bool)$show;
return $this;
}
@@ -822,9 +773,9 @@ public function showTableFoot()
* @param boolean $sortable The sortable flag.
* @return TableWidget Chainable
*/
- public function setSortable($sortable)
+ public function setSortable($sortable): static
{
- $this->sortable = !!$sortable;
+ $this->sortable = (bool)$sortable;
return $this;
}
@@ -842,30 +793,21 @@ public function sortable()
*
* @param mixed $action The action structure.
* @param boolean $row Whether to resolve action type for a row.
- * @return string
*/
- protected function resolveActionType($action, $row = false)
+ protected function resolveActionType(array $action, $row = false): string
{
if ($row || $this->parsingObjectActions) {
- switch ($action['ident']) {
- case 'reset':
- return 'warning';
-
- case 'delete':
- return 'danger';
-
- default:
- return 'seamless';
- }
+ return match ($action['ident']) {
+ 'reset' => 'warning',
+ 'delete' => 'danger',
+ default => 'seamless',
+ };
}
return $this->resolveDefaultActionType($action);
}
- /**
- * @return string
- */
- public function jsActionPrefix()
+ public function jsActionPrefix(): string
{
return ($this->currentObj) ? 'js-obj' : 'js-list';
}
@@ -880,9 +822,9 @@ public function objectEditUrl()
$url = 'object/edit?main_menu={{ main_menu }}&obj_type=' . $this->objType();
if ($this->isObjRenderable($model)) {
- $url = $model->render((string)$url);
+ $url = $model->render($url);
} else {
- $url = preg_replace('~{{\s*id\s*}}~', $this->currentObjId, $url);
+ $url = preg_replace('~{{\s*id\s*}}~', (string)$this->currentObjId, $url);
}
return $url;
@@ -897,17 +839,14 @@ public function objectCreateUrl()
$actions = $this->listActions();
if ($actions) {
foreach ($actions as $action) {
- if (isset($action['ident']) && $action['ident'] === 'create') {
- if (isset($action['url'])) {
- $model = $this->proto();
- if ($this->isObjRenderable($model)) {
- $action['url'] = $model->render((string)$action['url']);
- } else {
- $action['url'] = preg_replace('~{{\s*id\s*}}~', $this->currentObjId, $action['url']);
- }
-
- return $action['url'];
+ if (isset($action['ident']) && $action['ident'] === 'create' && isset($action['url'])) {
+ $model = $this->proto();
+ if ($this->isObjRenderable($model)) {
+ $action['url'] = $model->render((string)$action['url']);
+ } else {
+ $action['url'] = preg_replace('~{{\s*id\s*}}~', (string)$this->currentObjId, $action['url']);
}
+ return $action['url'];
}
}
}
@@ -921,9 +860,9 @@ public function objectCreateUrl()
* @param ModelInterface|null $object The object to test.
* @return boolean
*/
- public function isObjActive(ModelInterface $object = null)
+ public function isObjActive(?ModelInterface $object = null)
{
- if ($object === null) {
+ if (!$object instanceof \Charcoal\Model\ModelInterface) {
$object = $this->getCurrentObjOrProto();
}
@@ -948,9 +887,9 @@ public function isObjActive(ModelInterface $object = null)
* @param ModelInterface|null $object The object to test.
* @return boolean
*/
- public function isObjCreatable(ModelInterface $object = null)
+ public function isObjCreatable(?ModelInterface $object = null)
{
- if ($object === null) {
+ if (!$object instanceof \Charcoal\Model\ModelInterface) {
$object = $this->proto();
}
@@ -971,9 +910,9 @@ public function isObjCreatable(ModelInterface $object = null)
* @param ModelInterface|null $object The object to test.
* @return boolean
*/
- public function isObjEditable(ModelInterface $object = null)
+ public function isObjEditable(?ModelInterface $object = null)
{
- if ($object === null) {
+ if (!$object instanceof \Charcoal\Model\ModelInterface) {
$object = $this->getCurrentObjOrProto();
}
@@ -994,9 +933,9 @@ public function isObjEditable(ModelInterface $object = null)
* @param ModelInterface|null $object The object to test.
* @return boolean
*/
- public function isObjDeletable(ModelInterface $object = null)
+ public function isObjDeletable(?ModelInterface $object = null)
{
- if ($object === null) {
+ if (!$object instanceof \Charcoal\Model\ModelInterface) {
$object = $this->getCurrentObjOrProto();
}
@@ -1017,9 +956,9 @@ public function isObjDeletable(ModelInterface $object = null)
* @param ModelInterface|null $object The object to test.
* @return boolean
*/
- public function isObjViewable(ModelInterface $object = null)
+ public function isObjViewable(?ModelInterface $object = null)
{
- if ($object === null) {
+ if (!$object instanceof \Charcoal\Model\ModelInterface) {
$object = $this->getCurrentObjOrProto();
}
@@ -1039,6 +978,7 @@ public function isObjViewable(ModelInterface $object = null)
* @param Container $container Pimple DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -1063,27 +1003,23 @@ protected function setDependencies(Container $container)
* @param array|null $data Optional collection data.
* @return void
*/
- protected function configureCollectionLoader(CollectionLoader $loader, array $data = null)
+ protected function configureCollectionLoader(CollectionLoader $loader, ?array $data = null)
{
$this->configureCollectionLoaderFromTrait($loader, $data);
- if (!isset($loader->hasMainMenuCallback)) {
- $mainMenu = filter_input(INPUT_GET, 'main_menu', FILTER_SANITIZE_STRING);
+ if (!property_exists($loader, 'hasMainMenuCallback') || $loader->hasMainMenuCallback === null) {
+ $mainMenu = htmlspecialchars(trim(($_GET['main_menu'] ?? '')), ENT_QUOTES, 'UTF-8');
if ($mainMenu) {
- $fn = function (&$obj) use ($mainMenu) {
+ $fn = function (array &$obj) use ($mainMenu): void {
if (!$obj['main_menu']) {
$obj['main_menu'] = $mainMenu;
}
};
$callback = $loader->callback();
- if ($callback === null) {
- $callback = $fn;
- } else {
- $callback = function (&$obj) use ($fn) {
- $fn($obj);
- };
- }
+ $callback = $callback === null ? $fn : function (&$obj) use ($fn): void {
+ $fn($obj);
+ };
$loader->setCallback($callback);
$loader->hasMainMenuCallback = true;
@@ -1095,13 +1031,12 @@ protected function configureCollectionLoader(CollectionLoader $loader, array $da
* Retrieve the widget factory.
*
* @throws RuntimeException If the widget factory was not previously set.
- * @return FactoryInterface
*/
- protected function widgetFactory()
+ protected function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->widgetFactory === null) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
- sprintf('Widget Factory is not defined for "%s"', get_class($this))
+ sprintf('Widget Factory is not defined for "%s"', static::class)
);
}
@@ -1110,11 +1045,10 @@ protected function widgetFactory()
/**
* @throws RuntimeException If the property factory was not previously set / injected.
- * @return FactoryInterface
*/
- protected function propertyFactory()
+ protected function propertyFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->propertyFactory === null) {
+ if (!$this->propertyFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
'Property factory is not set for table widget'
);
@@ -1132,6 +1066,7 @@ protected function propertyFactory()
* @param mixed $toResolve A callable used when merging data.
* @return callable|null
*/
+ #[\Override]
protected function resolveDataSourceFilter($toResolve)
{
if (is_string($toResolve)) {
@@ -1162,7 +1097,7 @@ protected function resolveDataSourceFilter($toResolve)
* @param array $actions One or more actions.
* @return TableWidget Chainable.
*/
- protected function setListActions(array $actions)
+ protected function setListActions(array $actions): static
{
$this->parsedListActions = false;
@@ -1183,7 +1118,7 @@ protected function setListActions(array $actions)
* @param array $actions Actions to resolve.
* @return array List actions.
*/
- protected function createListActions(array $actions)
+ protected function createListActions(array $actions): array
{
$this->actionsPriority = $this->defaultActionPriority();
@@ -1198,9 +1133,8 @@ protected function createListActions(array $actions)
* Parse the given actions as collection actions.
*
* @param array $actions Actions to resolve.
- * @return array
*/
- protected function parseAsListActions(array $actions)
+ protected function parseAsListActions(array $actions): array
{
$listActions = [];
foreach ($actions as $ident => $action) {
@@ -1218,14 +1152,12 @@ protected function parseAsListActions(array $actions)
$action['active'] = false;
}
} else {
- $action['empty'] = (isset($action['empty']) ? boolval($action['empty']) : false);
+ $action['empty'] = (isset($action['empty']) && boolval($action['empty']));
}
if (is_array($action['actions'])) {
$action['actions'] = $this->parseAsListActions($action['actions']);
- $action['hasActions'] = !!array_filter($action['actions'], function ($action) {
- return $action['active'];
- });
+ $action['hasActions'] = (bool)array_filter($action['actions'], fn(array $action): mixed => $action['active']);
}
if (isset($listActions[$ident])) {
@@ -1240,7 +1172,7 @@ protected function parseAsListActions(array $actions)
}
}
- usort($listActions, [ 'Charcoal\Admin\Support\Sorter', 'sortByPriority' ]);
+ usort($listActions, \Charcoal\Admin\Support\Sorter::sortByPriority(...));
while (($first = reset($listActions)) && $first['isSeparator']) {
array_shift($listActions);
@@ -1313,19 +1245,18 @@ protected function defaultPropertiesOptions()
* @param ModelInterface $object The current row's object.
* @param PropertyInterface $property The current property.
* @param string $propertyValue The property $key's display value.
- * @return array
*/
protected function parsePropertyCell(
ModelInterface $object,
PropertyInterface $property,
- $propertyValue
- ) {
+ string $propertyValue
+ ): array {
$cell = $this->parseCollectionPropertyCell($object, $property, $propertyValue);
$ident = $property->ident();
$options = $this->viewOptions($ident);
$classes = $this->parsePropertyCellClasses($property, $object);
- $cell['truncate'] = (isset($options['truncate']) ? boolval($options['truncate']) : false);
+ $cell['truncate'] = (isset($options['truncate']) && boolval($options['truncate']));
if (!isset($cell['attr'])) {
$cell['attr'] = [];
@@ -1335,24 +1266,20 @@ protected function parsePropertyCell(
unset($options['attr']['width']);
$cell['attr'] = array_merge($cell['attr'], $options['attr']);
}
+ if (isset($cell['attr']['class'])) {
+ if (is_string($classes)) {
+ $classes = explode(' ', $cell['attr']['class']);
+ }
- if (isset($classes)) {
- if (isset($cell['attr']['class'])) {
- if (is_string($classes)) {
- $classes = explode(' ', $cell['attr']['class']);
- }
-
- if (is_string($cell['attr']['class'])) {
- $cell['attr']['class'] = explode(' ', $cell['attr']['class']);
- }
-
- $cell['attr']['class'] = array_unique(array_merge($cell['attr']['class'], $classes));
- } else {
- $cell['attr']['class'] = $classes;
+ if (is_string($cell['attr']['class'])) {
+ $cell['attr']['class'] = explode(' ', $cell['attr']['class']);
}
- unset($classes);
+ $cell['attr']['class'] = array_unique(array_merge($cell['attr']['class'], $classes));
+ } else {
+ $cell['attr']['class'] = $classes;
}
+ unset($classes);
$cell['attr'] = html_build_attributes($cell['attr']);
@@ -1367,12 +1294,11 @@ protected function parsePropertyCell(
*
* @param PropertyInterface $property The current property.
* @param ModelInterface|null $object Optional. The current row's object.
- * @return array
*/
protected function parsePropertyCellClasses(
PropertyInterface $property,
- ModelInterface $object = null
- ) {
+ ?ModelInterface $object = null
+ ): array {
unset($object);
$ident = $property->ident();
@@ -1397,13 +1323,12 @@ protected function parsePropertyCellClasses(
*
* @param ModelInterface $object The current row's object.
* @param array $objectProperties The $object's display properties.
- * @return array
*/
- protected function parseObjectRow(ModelInterface $object, array $objectProperties)
+ protected function parseObjectRow(ModelInterface $object, array $objectProperties): array
{
$row = $this->parseCollectionObjectRow($object, $objectProperties);
$row['objectActions'] = $this->objectActions();
- $row['showObjectActions'] = ($this->showObjectActions() === false) ? false : !!$row['objectActions'];
+ $row['showObjectActions'] = ($this->showObjectActions() === false) ? false : (bool)$row['objectActions'];
$row['attr'] = [
'class' => []
@@ -1424,9 +1349,8 @@ protected function parseObjectRow(ModelInterface $object, array $objectPropertie
* Set an widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return void
*/
- private function setWidgetFactory(FactoryInterface $factory)
+ private function setWidgetFactory(FactoryInterface $factory): void
{
$this->widgetFactory = $factory;
}
@@ -1435,7 +1359,7 @@ private function setWidgetFactory(FactoryInterface $factory)
* @param FactoryInterface $factory The property factory, to create properties.
* @return TableWidget Chainable
*/
- private function setPropertyFactory(FactoryInterface $factory)
+ private function setPropertyFactory(FactoryInterface $factory): static
{
$this->propertyFactory = $factory;
diff --git a/packages/admin/src/Charcoal/Admin/Widget/TextWidget.php b/packages/admin/src/Charcoal/Admin/Widget/TextWidget.php
index d667bc7fd..4cd93ba66 100644
--- a/packages/admin/src/Charcoal/Admin/Widget/TextWidget.php
+++ b/packages/admin/src/Charcoal/Admin/Widget/TextWidget.php
@@ -1,5 +1,7 @@
showTitle = !!$show;
+ $this->showTitle = (bool)$show;
return $this;
}
@@ -68,17 +57,16 @@ public function showTitle()
if ($this->showTitle === false) {
return false;
} else {
- return !!$this->title();
+ return (bool)$this->title();
}
}
/**
* @param boolean $show The show subtitle flag.
- * @return self
*/
- public function setShowSubtitle($show)
+ public function setShowSubtitle($show): static
{
- $this->showSubtitle = !!$show;
+ $this->showSubtitle = (bool)$show;
return $this;
}
@@ -90,17 +78,16 @@ public function showSubtitle()
if ($this->showSubtitle === false) {
return false;
} else {
- return !!$this->subtitle();
+ return (bool)$this->subtitle();
}
}
/**
* @param boolean $show The show description flag.
- * @return self
*/
- public function setShowDescription($show)
+ public function setShowDescription($show): static
{
- $this->showDescription = !!$show;
+ $this->showDescription = (bool)$show;
return $this;
}
@@ -112,17 +99,16 @@ public function showDescription()
if ($this->showDescription === false) {
return false;
} else {
- return !!$this->description();
+ return (bool)$this->description();
}
}
/**
* @param boolean $show The "show notes" flag.
- * @return self
*/
- public function setShowNotes($show)
+ public function setShowNotes($show): static
{
- $this->showNotes = !!$show;
+ $this->showNotes = (bool)$show;
return $this;
}
@@ -134,15 +120,14 @@ public function showNotes()
if ($this->showNotes === false) {
return false;
} else {
- return !!$this->notes();
+ return (bool)$this->notes();
}
}
/**
* @param mixed $title The text widget title.
- * @return self
*/
- public function setTitle($title)
+ public function setTitle($title): static
{
$this->title = $this->translator()->translation($title);
@@ -159,9 +144,8 @@ public function title()
/**
* @param mixed $subtitle The text widget subtitle.
- * @return self
*/
- public function setSubtitle($subtitle)
+ public function setSubtitle($subtitle): static
{
$this->subtitle = $this->translator()->translation($subtitle);
@@ -178,9 +162,8 @@ public function subtitle()
/**
* @param mixed $description The text widget description (main content).
- * @return self
*/
- public function setDescription($description)
+ public function setDescription($description): static
{
$this->description = $this->translator()->translation($description);
@@ -197,9 +180,8 @@ public function description()
/**
* @param mixed $notes The text widget notes.
- * @return self
*/
- public function setNotes($notes)
+ public function setNotes($notes): static
{
$this->notes = $this->translator()->translation($notes);
diff --git a/packages/admin/tests/Charcoal/AbstractTestCase.php b/packages/admin/tests/Charcoal/AbstractTestCase.php
index 59ba12ea0..80f1772c4 100644
--- a/packages/admin/tests/Charcoal/AbstractTestCase.php
+++ b/packages/admin/tests/Charcoal/AbstractTestCase.php
@@ -1,5 +1,7 @@
callMethod($this->obj, 'authRequired');
$this->assertFalse($res);
}
- /**
- * @return void
- */
- public function testRunWithoutEmailReturns400()
+ public function testRunWithoutEmailReturns400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -84,10 +72,7 @@ public function testRunWithoutEmailReturns400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithoutRecaptchaReturns400()
+ public function testRunWithoutRecaptchaReturns400(): void
{
$mock = m::mock($this->obj);
$mock->shouldAllowMockingProtectedMethods()
@@ -107,10 +92,7 @@ public function testRunWithoutRecaptchaReturns400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithInvalidRecaptchaReturns400()
+ public function testRunWithInvalidRecaptchaReturns400(): void
{
$mock = m::mock($this->obj);
$mock->shouldAllowMockingProtectedMethods()
@@ -132,12 +114,10 @@ public function testRunWithInvalidRecaptchaReturns400()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerAdminServices($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/Account/ResetPasswordActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/Account/ResetPasswordActionTest.php
index 72255bd13..443760af0 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/Account/ResetPasswordActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/Account/ResetPasswordActionTest.php
@@ -38,15 +38,11 @@ class ResetPasswordActionTest extends AbstractTestCase
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -60,19 +56,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsFalse()
+ public function testAuthRequiredIsFalse(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertFalse($res);
}
- /**
- * @return void
- */
- public function testRunWithoutTokenReturns400()
+ public function testRunWithoutTokenReturns400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -84,10 +74,7 @@ public function testRunWithoutTokenReturns400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithoutEmailReturns400()
+ public function testRunWithoutEmailReturns400(): void
{
$request = Request::createFromEnvironment(Environment::mock([
'QUERY_STRING' => 'token=foobar'
@@ -101,10 +88,7 @@ public function testRunWithoutEmailReturns400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithoutPasswordReturns400()
+ public function testRunWithoutPasswordReturns400(): void
{
$request = Request::createFromEnvironment(Environment::mock([
'QUERY_STRING' => 'token=foobar&email=foobar@foo.bar'
@@ -118,10 +102,7 @@ public function testRunWithoutPasswordReturns400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithoutMatchingPasswordsReturns400()
+ public function testRunWithoutMatchingPasswordsReturns400(): void
{
$request = Request::createFromEnvironment(Environment::mock([
'QUERY_STRING' => 'token=foobar&email=foobar@foo.bar&password1=foo&password2=bar'
@@ -135,10 +116,7 @@ public function testRunWithoutMatchingPasswordsReturns400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithoutRecaptchaReturns400()
+ public function testRunWithoutRecaptchaReturns400(): void
{
$mock = m::mock($this->obj);
$mock->shouldAllowMockingProtectedMethods()
@@ -158,10 +136,7 @@ public function testRunWithoutRecaptchaReturns400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithInvalidRecaptchaReturns400()
+ public function testRunWithInvalidRecaptchaReturns400(): void
{
$mock = m::mock($this->obj);
$mock->shouldAllowMockingProtectedMethods()
@@ -183,12 +158,10 @@ public function testRunWithInvalidRecaptchaReturns400()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerAdminServices($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/LoginActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/LoginActionTest.php
index 8c814c806..4d7f90b32 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/LoginActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/LoginActionTest.php
@@ -30,22 +30,16 @@ class LoginActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var LoginAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\LoginAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -61,19 +55,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsFalse()
+ public function testAuthRequiredIsFalse(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertFalse($res);
}
- /**
- * @return void
- */
- public function testRunWithoutParamsIs400()
+ public function testRunWithoutParamsIs400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,10 +70,7 @@ public function testRunWithoutParamsIs400()
$this->assertEquals(400, $response->getStatusCode());
}
- /**
- * @return void
- */
- public function testRunWithInvalidCredentials()
+ public function testRunWithInvalidCredentials(): void
{
$this->createUser('foo@bar.com');
@@ -108,28 +93,25 @@ public function testRunWithInvalidCredentials()
public function testRunWithValidCredentials()
{
$this->createUser('foo@bar.com');
-
+
$request = Request::createFromEnvironment(Environment::mock([
'QUERY_STRING' => 'password=qwerty'
]));
$response = new Response();
-
+
$response = $this->obj->run($request, $response);
$this->assertEquals(200, $response->getStatusCode());
-
+
$results = $this->obj->results();
$this->assertTrue($results['success']);
}
*/
-
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/LogoutActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/LogoutActionTest.php
index ccaf20f5f..493b4ac4b 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/LogoutActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/LogoutActionTest.php
@@ -29,22 +29,16 @@ class LogoutActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var LogoutAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\LogoutAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -59,19 +53,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRunWithUnauthenticatedUser()
+ public function testRunWithUnauthenticatedUser(): void
{
$this->createUser('foo@bar.com');
@@ -85,10 +73,7 @@ public function testRunWithUnauthenticatedUser()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithAuthenticatedUser()
+ public function testRunWithAuthenticatedUser(): void
{
$user = $this->createUser('foo@bar.com');
$this->getAuthenticator()->setUser($user);
@@ -105,12 +90,10 @@ public function testRunWithAuthenticatedUser()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/Object/DeleteActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/Object/DeleteActionTest.php
index ea41c1900..5e0b62206 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/Object/DeleteActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/Object/DeleteActionTest.php
@@ -29,22 +29,16 @@ class DeleteActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var DeleteAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\Object\DeleteAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRunWithoutObjTypeIs400()
+ public function testRunWithoutObjTypeIs400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -80,10 +68,7 @@ public function testRunWithoutObjTypeIs400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithoutObjIdIs400()
+ public function testRunWithoutObjIdIs400(): void
{
$request = Request::createFromEnvironment(Environment::mock([
'QUERY_STRING' => 'obj_type=charcoal/admin/user'
@@ -97,13 +82,10 @@ public function testRunWithoutObjIdIs400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRunWithInvalidObject()
+ public function testRunWithInvalidObject(): void
{
$email = 'foobar@foo.bar';
- $user = $this->createUser($email);
+ $this->createUser($email);
$this->assertTrue($this->userExists($email));
$request = Request::createFromEnvironment(Environment::mock([
@@ -120,10 +102,7 @@ public function testRunWithInvalidObject()
$this->assertTrue($this->userExists($email));
}
- /**
- * @return void
- */
- public function testRunWithObjectDelete()
+ public function testRunWithObjectDelete(): void
{
$email = 'foobar@foo.bar';
$user = $this->createUser($email);
@@ -145,12 +124,10 @@ public function testRunWithObjectDelete()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/Object/ExportActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/Object/ExportActionTest.php
index 6fc3c0a81..12789dbcc 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/Object/ExportActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/Object/ExportActionTest.php
@@ -28,22 +28,16 @@ class ExportActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var ExportAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\Object\ExportAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -57,19 +51,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRunWithoutObjTypeIs400()
+ public function testRunWithoutObjTypeIs400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -83,12 +71,10 @@ public function testRunWithoutObjTypeIs400()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerAdminServices($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/Object/LoadActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/Object/LoadActionTest.php
index e43192b2b..ff137c54d 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/Object/LoadActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/Object/LoadActionTest.php
@@ -29,22 +29,16 @@ class LoadActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var LoadAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\Object\LoadAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRunWithoutObjTypeIs400()
+ public function testRunWithoutObjTypeIs400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -80,10 +68,7 @@ public function testRunWithoutObjTypeIs400()
$this->assertFalse($results['success']);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$user = $this->createUser('foo@bar.com');
@@ -103,12 +88,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/Object/ReorderActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/Object/ReorderActionTest.php
index 03e60d274..eaf87608c 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/Object/ReorderActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/Object/ReorderActionTest.php
@@ -32,36 +32,26 @@ class ReorderActionTest extends AbstractTestCase
/**
* The primary model to test with.
- *
- * @var string
*/
- private $model = Model::class;
+ private string $model = Model::class;
/**
* Store the tested instance.
- *
- * @var ReorderAction
*/
- private $action;
+ private \Charcoal\Admin\Action\Object\ReorderAction $action;
/**
* Store the object collection loader.
- *
- * @var CollectionLoader
*/
- private $collectionLoader;
+ private ?\Charcoal\Loader\CollectionLoader $collectionLoader = null;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -78,7 +68,7 @@ public function setUp(): void
/**
* @return array
*/
- public function setUpObjects()
+ public function setUpObjects(): \ArrayAccess|array
{
$container = $this->container();
@@ -110,9 +100,9 @@ public function setUpObjects()
/**
* @return Collection
*/
- public function getObjects()
+ public function getObjects(): \ArrayAccess|array
{
- if ($this->collectionLoader === null) {
+ if (!$this->collectionLoader instanceof \Charcoal\Loader\CollectionLoader) {
$container = $this->container();
$loader = new CollectionLoader([
@@ -129,24 +119,20 @@ public function getObjects()
return $this->collectionLoader->load();
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->action, 'authRequired');
$this->assertTrue($res);
}
/**
- * @dataProvider runRequestProvider
*
* @param integer $status An HTTP status code.
* @param string $success Whether the action was successful.
* @param array $mock The request parameters to test.
- * @return void
*/
- public function testRun($status, $success, array $mock)
+ #[\PHPUnit\Framework\Attributes\DataProvider('runRequestProvider')]
+ public function testRun(int $status, bool $success, array $mock): void
{
if ($status === 200) {
$this->setUpObjects();
@@ -167,29 +153,25 @@ public function testRun($status, $success, array $mock)
}
}
- /**
- * @return array
- */
- public function runRequestProvider()
+ public static function runRequestProvider(): array
{
+ $model = Model::class;
return [
[ 400, false, [] ],
- [ 400, false, [ 'QUERY_STRING' => 'obj_type='.$this->model ] ],
- [ 400, false, [ 'QUERY_STRING' => 'obj_type='.$this->model.'&order_property=5' ] ],
- [ 400, false, [ 'QUERY_STRING' => 'obj_type='.$this->model.'&order_property=foobar' ] ],
- [ 500, false, [ 'QUERY_STRING' => 'obj_type='.$this->model.'&obj_orders[]=xyzzy&obj_orders[]=qwerty' ] ],
- [ 200, true, [ 'QUERY_STRING' => 'obj_type='.$this->model.'&obj_orders[]=baz&obj_orders[]=bar&obj_orders[]=qux&obj_orders[]=foo' ] ],
+ [ 400, false, [ 'QUERY_STRING' => 'obj_type='.$model ] ],
+ [ 400, false, [ 'QUERY_STRING' => 'obj_type='.$model.'&order_property=5' ] ],
+ [ 400, false, [ 'QUERY_STRING' => 'obj_type='.$model.'&order_property=foobar' ] ],
+ [ 500, false, [ 'QUERY_STRING' => 'obj_type='.$model.'&obj_orders[]=xyzzy&obj_orders[]=qwerty' ] ],
+ [ 200, true, [ 'QUERY_STRING' => 'obj_type='.$model.'&obj_orders[]=baz&obj_orders[]=bar&obj_orders[]=qux&obj_orders[]=foo' ] ],
];
}
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerAdminServices($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/Object/SaveActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/Object/SaveActionTest.php
index 7b3ee7c43..17c05fb2a 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/Object/SaveActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/Object/SaveActionTest.php
@@ -28,22 +28,16 @@ class SaveActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var SaveAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\Object\SaveAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -55,19 +49,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRunWithoutObjTypeIs400()
+ public function testRunWithoutObjTypeIs400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -81,12 +69,10 @@ public function testRunWithoutObjTypeIs400()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/Object/UpdateActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/Object/UpdateActionTest.php
index a412fee17..6bc82a358 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/Object/UpdateActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/Object/UpdateActionTest.php
@@ -28,22 +28,16 @@ class UpdateActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var UpdateAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\Object\UpdateAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -55,19 +49,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRunWithoutObjTypeIs400()
+ public function testRunWithoutObjTypeIs400(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -81,12 +69,10 @@ public function testRunWithoutObjTypeIs400()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/ClearCacheActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/ClearCacheActionTest.php
index b818971e9..e7d751412 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/ClearCacheActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/ClearCacheActionTest.php
@@ -29,22 +29,16 @@ class ClearCacheActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var ClearCacheAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\ClearCacheAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/ActivateActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/ActivateActionTest.php
index 82238774e..89f8d7c6b 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/ActivateActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/ActivateActionTest.php
@@ -29,22 +29,16 @@ class ActivateActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var ActivateAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\ActivateAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/AddActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/AddActionTest.php
index f84930ea9..2c7e7fd7a 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/AddActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/AddActionTest.php
@@ -29,22 +29,16 @@ class AddActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var AddAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\AddAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeactivateActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeactivateActionTest.php
index 800c641ec..d7b7b3eef 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeactivateActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeactivateActionTest.php
@@ -29,22 +29,16 @@ class DeactivateActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var DeactivateAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\DeactivateAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteActionTest.php
index 3107cc470..bb2849be6 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteActionTest.php
@@ -29,22 +29,16 @@ class DeleteActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var DeleteAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\DeleteAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllActionTest.php
index dfdaaf235..df1de19ca 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/DeleteAllActionTest.php
@@ -29,22 +29,16 @@ class DeleteAllActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var DeleteAllAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\DeleteAllAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/PreviewActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/PreviewActionTest.php
index bb7506d81..1245fa77d 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/PreviewActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/PreviewActionTest.php
@@ -29,22 +29,16 @@ class PreviewActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var PreviewAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\PreviewAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateActionTest.php
index c121e60d4..92c646a3e 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateActionTest.php
@@ -29,22 +29,16 @@ class UpdateActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var UpdateAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\UpdateAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllActionTest.php b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllActionTest.php
index 6f2a53054..2e86a6fa3 100644
--- a/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Action/System/StaticWebsite/UpdateAllActionTest.php
@@ -29,22 +29,16 @@ class UpdateAllActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var UpdateAllAction
*/
- private $obj;
+ private \Charcoal\Admin\Action\System\StaticWebsite\UpdateAllAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -56,19 +50,13 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testRun()
+ public function testRun(): void
{
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();
@@ -82,12 +70,10 @@ public function testRun()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/AdminActionTest.php b/packages/admin/tests/Charcoal/Admin/AdminActionTest.php
index 9444e06a0..ea4428993 100644
--- a/packages/admin/tests/Charcoal/Admin/AdminActionTest.php
+++ b/packages/admin/tests/Charcoal/Admin/AdminActionTest.php
@@ -2,6 +2,7 @@
namespace Charcoal\Tests\Admin;
+use Psr\Http\Message\ResponseInterface;
use ReflectionClass;
// From PSR-7
@@ -27,31 +28,30 @@ class AdminActionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var AdminAction
*/
- private $obj;
+ private \Charcoal\Admin\AdminAction $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
$container = $this->container();
- $this->obj = $this->getMockForAbstractClass(AdminAction::class, [[
+ $this->obj = new class([
'logger' => $container['logger'],
'container' => $container
- ]]);
+ ]) extends AdminAction {
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
+ {
+ return $response;
+ }
+ };
}
/**
@@ -63,10 +63,8 @@ public function setUp(): void
* - success can be set by ArrayAccess
* - success can be set with get()
* - success can be accessed by ArrayAccess
- *
- * @return void
*/
- public function testSuccess()
+ public function testSuccess(): void
{
$this->assertFalse($this->obj->success());
$ret = $this->obj->setSuccess(true);
@@ -83,10 +81,7 @@ public function testSuccess()
$this->assertFalse($this->obj['success']);
}
- /**
- * @return void
- */
- public function testFeedback()
+ public function testFeedback(): void
{
$this->assertFalse($this->obj->hasFeedbacks());
$this->assertEquals([], $this->obj->feedbacks());
@@ -105,18 +100,12 @@ public function testFeedback()
$this->assertEquals(1, $this->obj->numFeedbacks());
}
- /**
- * @return void
- */
- public function testAdminUrl()
+ public function testAdminUrl(): void
{
$this->assertEquals('/admin/', $this->obj->adminUrl());
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
@@ -124,12 +113,10 @@ public function testAuthRequiredIsTrue()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerActionDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/AdminTemplateTest.php b/packages/admin/tests/Charcoal/Admin/AdminTemplateTest.php
index 555eb2eeb..1dd3ff197 100644
--- a/packages/admin/tests/Charcoal/Admin/AdminTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/AdminTemplateTest.php
@@ -23,22 +23,16 @@ class AdminTemplateTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var AdminTemplate
*/
- private $obj;
+ private \Charcoal\Admin\AdminTemplate $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -50,10 +44,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetIdent()
+ public function testSetIdent(): void
{
$this->assertNull($this->obj->ident());
$ret = $this->obj->setIdent('foobar');
@@ -61,10 +52,7 @@ public function testSetIdent()
$this->assertEquals('foobar', $this->obj->ident());
}
- /**
- * @return void
- */
- public function testSetLabel()
+ public function testSetLabel(): void
{
$this->assertNull($this->obj->label());
$ret = $this->obj->setLabel('foobar');
@@ -72,10 +60,7 @@ public function testSetLabel()
$this->assertEquals('foobar', (string)$this->obj->label());
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
@@ -83,17 +68,15 @@ public function testAuthRequiredIsTrue()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerTemplateDependencies($container);
- $container['widget/factory'] = $this->createMock('\Charcoal\Factory\FactoryInterface');
+ $container['widget/factory'] = $this->createMock(\Charcoal\Factory\FactoryInterface::class);
$this->container = $container;
}
diff --git a/packages/admin/tests/Charcoal/Admin/AdminWidgetTest.php b/packages/admin/tests/Charcoal/Admin/AdminWidgetTest.php
index a534248bf..9617919d0 100644
--- a/packages/admin/tests/Charcoal/Admin/AdminWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/AdminWidgetTest.php
@@ -17,22 +17,16 @@ class AdminWidgetTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var AdminWidget
*/
- private $obj;
+ private \Charcoal\Admin\AdminWidget $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -44,10 +38,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -64,10 +55,7 @@ public function testSetData()
$this->assertNotTrue($obj->showActions());
}
- /**
- * @return void
- */
- public function testSetType()
+ public function testSetType(): void
{
$obj = $this->obj;
$this->assertEquals(null, $obj->type());
@@ -80,12 +68,8 @@ public function testSetType()
$obj->setType(1);
}
- /**
- * @return void
- */
- public function testSetLabel()
+ public function testSetLabel(): void
{
- $obj = $this->obj;
//$this->assertEquals(null, $obj->label());
$obj = $this->obj;
@@ -101,12 +85,10 @@ public function testSetLabel()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerWidgetDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/ConfigTest.php b/packages/admin/tests/Charcoal/Admin/ConfigTest.php
index 3bf16bd6f..9244ba664 100644
--- a/packages/admin/tests/Charcoal/Admin/ConfigTest.php
+++ b/packages/admin/tests/Charcoal/Admin/ConfigTest.php
@@ -11,10 +11,7 @@
*/
class ConfigTest extends AbstractTestCase
{
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = new Config();
$ret = $obj->merge([
@@ -24,10 +21,7 @@ public function testSetData()
$this->assertEquals('foo', $obj->basePath());
}
- /**
- * @return void
- */
- public function testSetBasePath()
+ public function testSetBasePath(): void
{
$obj = new Config();
$this->assertEquals('admin', $obj->basePath());
@@ -40,10 +34,7 @@ public function testSetBasePath()
$obj->setBasePath([]);
}
- /**
- * @return void
- */
- public function testSetBasePathEmptyParamThrowsException()
+ public function testSetBasePathEmptyParamThrowsException(): void
{
$obj = new Config();
diff --git a/packages/admin/tests/Charcoal/Admin/ContainerProvider.php b/packages/admin/tests/Charcoal/Admin/ContainerProvider.php
index fea6cebe0..58400598d 100644
--- a/packages/admin/tests/Charcoal/Admin/ContainerProvider.php
+++ b/packages/admin/tests/Charcoal/Admin/ContainerProvider.php
@@ -74,9 +74,8 @@ class ContainerProvider
* Register the unit tests required services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerDebug(Container $container)
+ public function registerDebug(Container $container): void
{
if (!isset($container['debug'])) {
$container['debug'] = false;
@@ -87,9 +86,8 @@ public function registerDebug(Container $container)
* Register the unit tests required services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseServices(Container $container)
+ public function registerBaseServices(Container $container): void
{
$this->registerDebug($container);
$this->registerConfig($container);
@@ -102,9 +100,8 @@ public function registerBaseServices(Container $container)
* Register the admin services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerAdminServices(Container $container)
+ public function registerAdminServices(Container $container): void
{
$this->registerBaseServices($container);
$this->registerBaseUrl($container);
@@ -115,67 +112,57 @@ public function registerAdminServices(Container $container)
* Setup the application's base URI.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseUrl(Container $container)
+ public function registerBaseUrl(Container $container): void
{
- $container['base-url'] = function () {
- return Uri::createFromString('');
- };
+ $container['base-url'] = (fn() => Uri::createFromString(''));
- $container['admin/base-url'] = function () {
- return Uri::createFromString('admin');
- };
+ $container['admin/base-url'] = (fn() => Uri::createFromString('admin'));
}
/**
* Setup the application configset.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerConfig(Container $container)
+ public function registerConfig(Container $container): void
{
- $container['config'] = function () {
- return new AppConfig([
- 'base_path' => realpath(__DIR__.'/../../..'),
- 'apis' => [
- 'google' => [
- 'recaptcha' => [
- 'public_key' => 'foobar',
- 'private_key' => 'bazqux',
- ],
+ $container['config'] = (fn(): \Charcoal\App\AppConfig => new AppConfig([
+ 'base_path' => realpath(__DIR__.'/../../..'),
+ 'apis' => [
+ 'google' => [
+ 'recaptcha' => [
+ 'public_key' => 'foobar',
+ 'private_key' => 'bazqux',
],
],
- 'locales' => [
- 'en' => [
- 'locale' => 'en-US',
- ],
+ ],
+ 'locales' => [
+ 'en' => [
+ 'locale' => 'en-US',
],
- 'translator' => [
- 'paths' => [],
+ ],
+ 'translator' => [
+ 'paths' => [],
+ ],
+ 'metadata' => [
+ 'paths' => [
+ 'metadata',
+ // Standalone
+ 'vendor/charcoal/object/metadata',
+ 'vendor/charcoal/user/metadata',
+ // Monorepo
+ '/../object/metadata',
+ '/../user/metadata',
],
- 'metadata' => [
- 'paths' => [
- 'metadata',
- // Standalone
- 'vendor/charcoal/object/metadata',
- 'vendor/charcoal/user/metadata',
- // Monorepo
- '/../object/metadata',
- '/../user/metadata',
- ],
- ],
- ]);
- };
+ ],
+ ]));
/**
* List of Charcoal module classes.
*
* Explicitly defined in case of a version mismatch with dependencies. This parameter
* is normally defined by {@see \Charcoal\App\ServiceProvider\AppServiceProvider}.
- *
- * @var array
*/
$container['module/classes'] = [];
}
@@ -184,134 +171,110 @@ public function registerConfig(Container $container)
* Setup the admin module configset.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerAdminConfig(Container $container)
+ public function registerAdminConfig(Container $container): void
{
$this->registerConfig($container);
- $container['admin/config'] = function () {
- return new AdminConfig();
- };
+ $container['admin/config'] = (fn(): \Charcoal\Admin\Config => new AdminConfig());
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerElfinderConfig(Container $container)
+ public function registerElfinderConfig(Container $container): void
{
- $container['elfinder/config'] = function () {
- return [];
- };
+ $container['elfinder/config'] = (fn(): array => []);
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerLayoutFactory(Container $container)
+ public function registerLayoutFactory(Container $container): void
{
- $container['layout/factory'] = function () {
- $layoutFactory = new LayoutFactory();
- return $layoutFactory;
- };
+ $container['layout/factory'] = (fn(): \Charcoal\Ui\Layout\LayoutFactory => new LayoutFactory());
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerLayoutBuilder(Container $container)
+ public function registerLayoutBuilder(Container $container): void
{
$this->registerLayoutFactory($container);
- $container['layout/builder'] = function (Container $container) {
+ $container['layout/builder'] = function (Container $container): \Charcoal\Ui\Layout\LayoutBuilder {
$layoutFactory = $container['layout/factory'];
- $layoutBuilder = new LayoutBuilder($layoutFactory, $container);
- return $layoutBuilder;
+ return new LayoutBuilder($layoutFactory, $container);
};
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerDashboardFactory(Container $container)
+ public function registerDashboardFactory(Container $container): void
{
$this->registerLogger($container);
$this->registerWidgetBuilder($container);
$this->registerLayoutBuilder($container);
- $container['dashboard/factory'] = function (Container $container) {
- return new Factory([
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger'],
- 'widget_builder' => $container['widget/builder'],
- 'layout_builder' => $container['layout/builder']
- ]],
- 'resolver_options' => [
- 'suffix' => 'Dashboard'
- ]
- ]);
- };
+ $container['dashboard/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger'],
+ 'widget_builder' => $container['widget/builder'],
+ 'layout_builder' => $container['layout/builder']
+ ]],
+ 'resolver_options' => [
+ 'suffix' => 'Dashboard'
+ ]
+ ]));
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerDashboardBuilder(Container $container)
+ public function registerDashboardBuilder(Container $container): void
{
$this->registerDashboardFactory($container);
- $container['dashboard/builder'] = function (Container $container) {
+ $container['dashboard/builder'] = function (Container $container): \Charcoal\Ui\Dashboard\DashboardBuilder {
$dashboardFactory = $container['dashboard/factory'];
- $dashboardBuilder = new DashboardBuilder($dashboardFactory, $container);
- return $dashboardBuilder;
+ return new DashboardBuilder($dashboardFactory, $container);
};
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerWidgetFactory(Container $container)
+ public function registerWidgetFactory(Container $container): void
{
$this->registerLogger($container);
- $container['widget/factory'] = function (Container $container) {
- return new Factory([
- 'resolver_options' => [
- 'suffix' => 'Widget'
- ],
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger']
- ]]
- ]);
- };
+ $container['widget/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'resolver_options' => [
+ 'suffix' => 'Widget'
+ ],
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger']
+ ]]
+ ]));
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerWidgetBuilder(Container $container)
+ public function registerWidgetBuilder(Container $container): void
{
$this->registerWidgetFactory($container);
- $container['widget/builder'] = function (Container $container) {
- return new WidgetBuilder($container['widget/factory'], $container);
- };
+ $container['widget/builder'] = (fn(Container $container): \Charcoal\App\Template\WidgetBuilder => new WidgetBuilder($container['widget/factory'], $container));
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerClimate(Container $container)
+ public function registerClimate(Container $container): void
{
$container['climate/system'] = function () {
$system = Mockery::mock(Linux::class);
@@ -338,11 +301,9 @@ public function registerClimate(Container $container)
return $reader;
};
- $container['climate/util'] = function (Container $container) {
- return new UtilFactory($container['climate/system']);
- };
+ $container['climate/util'] = (fn(Container $container): \League\CLImate\Util\UtilFactory => new UtilFactory($container['climate/system']));
- $container['climate'] = function (Container $container) {
+ $container['climate'] = function (Container $container): \League\CLImate\CLImate {
$climate = new CLImate();
$climate->setOutput($container['climate/output']);
@@ -357,35 +318,28 @@ public function registerClimate(Container $container)
* Setup the application's logging interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerLogger(Container $container)
+ public function registerLogger(Container $container): void
{
- $container['logger'] = function () {
- return new NullLogger();
- };
+ $container['logger'] = (fn(): \Psr\Log\NullLogger => new NullLogger());
}
/**
* Setup the application's caching interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerCache(Container $container)
+ public function registerCache(Container $container): void
{
- $container['cache'] = function () {
- return new Pool();
- };
+ $container['cache'] = (fn(): \Stash\Pool => new Pool());
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerDatabase(Container $container)
+ public function registerDatabase(Container $container): void
{
- $container['database'] = function () {
+ $container['database'] = function (): \PDO {
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
@@ -394,9 +348,8 @@ public function registerDatabase(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerModelServiceProvider(Container $container)
+ public function registerModelServiceProvider(Container $container): void
{
static $provider = null;
@@ -409,9 +362,8 @@ public function registerModelServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerTranslatorServiceProvider(Container $container)
+ public function registerTranslatorServiceProvider(Container $container): void
{
static $provider = null;
@@ -424,9 +376,8 @@ public function registerTranslatorServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerViewServiceProvider(Container $container)
+ public function registerViewServiceProvider(Container $container): void
{
static $provider = null;
@@ -439,107 +390,85 @@ public function registerViewServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerAcl(Container $container)
+ public function registerAcl(Container $container): void
{
- $container['admin/acl'] = function () {
- return new Acl();
- };
+ $container['admin/acl'] = (fn(): \Laminas\Permissions\Acl\Acl => new Acl());
- $container['authorizer/acl'] = function ($container) {
- return $container['admin/acl'];
- };
+ $container['authorizer/acl'] = (fn($container) => $container['admin/acl']);
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerAuthenticator(Container $container)
+ public function registerAuthenticator(Container $container): void
{
$this->registerLogger($container);
$this->registerModelServiceProvider($container);
- $container['admin/authenticator'] = function (Container $container) {
- return new Authenticator([
- 'logger' => $container['logger'],
- 'user_type' => AdminUser::class,
- 'user_factory' => $container['model/factory'],
- 'token_type' => AdminAuthToken::class,
- 'token_factory' => $container['model/factory'],
- ]);
- };
+ $container['admin/authenticator'] = (fn(Container $container): \Charcoal\User\Authenticator => new Authenticator([
+ 'logger' => $container['logger'],
+ 'user_type' => AdminUser::class,
+ 'user_factory' => $container['model/factory'],
+ 'token_type' => AdminAuthToken::class,
+ 'token_factory' => $container['model/factory'],
+ ]));
- $container['authenticator'] = function (Container $container) {
- return $container['admin/authenticator'];
- };
+ $container['authenticator'] = (fn(Container $container): mixed => $container['admin/authenticator']);
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerAuthorizer(Container $container)
+ public function registerAuthorizer(Container $container): void
{
$this->registerLogger($container);
$this->registerAcl($container);
- $container['admin/authorizer'] = function (Container $container) {
- return new Authorizer([
- 'logger' => $container['logger'],
- 'acl' => $container['admin/acl'],
- 'resource' => 'admin',
- ]);
- };
+ $container['admin/authorizer'] = (fn(Container $container): \Charcoal\User\Authorizer => new Authorizer([
+ 'logger' => $container['logger'],
+ 'acl' => $container['admin/acl'],
+ 'resource' => 'admin',
+ ]));
- $container['authorizer'] = function (Container $container) {
- return $container['admin/authorizer'];
- };
+ $container['authorizer'] = (fn(Container $container): mixed => $container['admin/authorizer']);
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerPropertyDisplayFactory(Container $container)
+ public function registerPropertyDisplayFactory(Container $container): void
{
$this->registerDatabase($container);
$this->registerLogger($container);
- $container['property/display/factory'] = function (Container $container) {
- return new Factory([
- 'resolver_options' => [
- 'suffix' => 'Display'
- ],
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger']
- ]]
- ]);
- };
+ $container['property/display/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'resolver_options' => [
+ 'suffix' => 'Display'
+ ],
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger']
+ ]]
+ ]));
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerEmailFactory(Container $container)
+ public function registerEmailFactory(Container $container): void
{
- $container['email/factory'] = function () {
- return new Factory([
- 'map' => [
- 'email' => Email::class,
- ],
- ]);
- };
+ $container['email/factory'] = (fn(): \Charcoal\Factory\GenericFactory => new Factory([
+ 'map' => [
+ 'email' => Email::class,
+ ],
+ ]));
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerActionDependencies(Container $container)
+ public function registerActionDependencies(Container $container): void
{
$this->registerDebug($container);
$this->registerLogger($container);
@@ -559,9 +488,8 @@ public function registerActionDependencies(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerTemplateDependencies(Container $container)
+ public function registerTemplateDependencies(Container $container): void
{
$this->registerDebug($container);
$this->registerLogger($container);
@@ -584,9 +512,8 @@ public function registerTemplateDependencies(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerWidgetDependencies(Container $container)
+ public function registerWidgetDependencies(Container $container): void
{
$this->registerDebug($container);
$this->registerLogger($container);
@@ -606,9 +533,8 @@ public function registerWidgetDependencies(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerInputDependencies(Container $container)
+ public function registerInputDependencies(Container $container): void
{
$this->registerDebug($container);
$this->registerLogger($container);
@@ -628,9 +554,8 @@ public function registerInputDependencies(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerScriptDependencies(Container $container)
+ public function registerScriptDependencies(Container $container): void
{
$this->registerDebug($container);
$this->registerLogger($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Mock/AuthToken.php b/packages/admin/tests/Charcoal/Admin/Mock/AuthToken.php
index 88b634a31..19258cbfd 100644
--- a/packages/admin/tests/Charcoal/Admin/Mock/AuthToken.php
+++ b/packages/admin/tests/Charcoal/Admin/Mock/AuthToken.php
@@ -1,5 +1,7 @@
isEnabled()) {
- return false;
- }
-
- return true;
+ return $this->isEnabled();
}
/**
* @return boolean
*/
+ #[\Override]
public function deleteCookie()
{
- if (!$this->isEnabled()) {
- return false;
- }
-
- return true;
+ return $this->isEnabled();
}
}
diff --git a/packages/admin/tests/Charcoal/Admin/Mock/SortableModel.php b/packages/admin/tests/Charcoal/Admin/Mock/SortableModel.php
index 61678f63c..46d140d03 100644
--- a/packages/admin/tests/Charcoal/Admin/Mock/SortableModel.php
+++ b/packages/admin/tests/Charcoal/Admin/Mock/SortableModel.php
@@ -1,5 +1,7 @@
[
diff --git a/packages/admin/tests/Charcoal/Admin/Mock/UserProviderTrait.php b/packages/admin/tests/Charcoal/Admin/Mock/UserProviderTrait.php
index 78997e386..8dcb61b01 100644
--- a/packages/admin/tests/Charcoal/Admin/Mock/UserProviderTrait.php
+++ b/packages/admin/tests/Charcoal/Admin/Mock/UserProviderTrait.php
@@ -56,14 +56,14 @@ protected function createUser(
* @param string $email The email to lookup.
* @return User
*/
- protected function userExists($email)
+ protected function userExists($email): bool
{
$container = $this->container();
$user = $container['model/factory']->create($this->userClass);
$user->loadFrom('email', $email);
- return !!$user->id();
+ return (bool) $user->id();
}
/**
diff --git a/packages/admin/tests/Charcoal/Admin/Property/AbstractInputTest.php b/packages/admin/tests/Charcoal/Admin/Property/AbstractInputTest.php
index 9a231a339..46f27d752 100644
--- a/packages/admin/tests/Charcoal/Admin/Property/AbstractInputTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Property/AbstractInputTest.php
@@ -22,30 +22,25 @@ class AbstractInputTest extends AbstractTestCase
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
- /**
- * @return void
- */
public function setUp(): void
{
$container = $this->container();
- $this->obj = $this->getMockForAbstractClass(AbstractPropertyInput::class, [
- [
- 'logger' => $container['logger'],
- 'metadata_loader' => $container['metadata/loader'],
- ],
- ]);
+ $this->obj = new Class([
+ 'logger' => $container['logger'],
+ 'metadata_loader' => $container['metadata/loader'],
+ ]) extends AbstractPropertyInput {
+ public function type(): string
+ {
+ return 'foo';
+ }
+ };
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -63,12 +58,10 @@ public function testSetData()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerInputDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Property/Input/TextInputTest.php b/packages/admin/tests/Charcoal/Admin/Property/Input/TextInputTest.php
index 78154afe5..876fb56a5 100644
--- a/packages/admin/tests/Charcoal/Admin/Property/Input/TextInputTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Property/Input/TextInputTest.php
@@ -15,14 +15,8 @@
*/
class TextInputTest extends AbstractTestCase
{
- /**
- * @var TextInput
- */
- private $obj;
-
- /**
- * @return void
- */
+ private \Charcoal\Admin\Property\Input\TextInput $obj;
+
public function setUp(): void
{
$container = new Container();
@@ -36,10 +30,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -53,14 +44,11 @@ public function testSetData()
$this->assertEquals(42, $obj->size());
$this->assertEquals(10, $obj->minLength());
$this->assertEquals(100, $obj->maxLength());
- $this->assertEquals('foo', (string)$obj->pattern());
+ $this->assertEquals('foo', $obj->pattern());
$this->assertEquals('bar', (string)$obj->placeholder());
}
- /**
- * @return void
- */
- public function testSetSize()
+ public function testSetSize(): void
{
$obj = $this->obj;
$ret = $obj->setSize(42);
@@ -71,10 +59,7 @@ public function testSetSize()
$obj->setSize(false);
}
- /**
- * @return void
- */
- public function testSetMinLength()
+ public function testSetMinLength(): void
{
$obj = $this->obj;
$ret = $obj->setMinLength(42);
@@ -85,10 +70,7 @@ public function testSetMinLength()
$obj->setMinLength(false);
}
- /**
- * @return void
- */
- public function testSetMaxLength()
+ public function testSetMaxLength(): void
{
$obj = $this->obj;
$ret = $obj->setMaxLength(42);
@@ -99,10 +81,7 @@ public function testSetMaxLength()
$obj->setMaxLength(false);
}
- /**
- * @return void
- */
- public function testSetPattern()
+ public function testSetPattern(): void
{
$obj = $this->obj;
$ret = $obj->setPattern('foo');
@@ -113,10 +92,7 @@ public function testSetPattern()
$obj->setPattern(false);
}
- /**
- * @return void
- */
- public function testSetPlaceholder()
+ public function testSetPlaceholder(): void
{
$obj = $this->obj;
$ret = $obj->setPlaceholder('foo');
diff --git a/packages/admin/tests/Charcoal/Admin/Property/Input/TextareaInputTest.php b/packages/admin/tests/Charcoal/Admin/Property/Input/TextareaInputTest.php
index 12fce74e1..0a27b823e 100644
--- a/packages/admin/tests/Charcoal/Admin/Property/Input/TextareaInputTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Property/Input/TextareaInputTest.php
@@ -17,21 +17,14 @@ class TextareaInputTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var TextareaInput
*/
- private $obj;
+ private \Charcoal\Admin\Property\Input\TextareaInput $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
- /**
- * @return void
- */
public function setUp(): void
{
$container = $this->container();
@@ -42,10 +35,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -57,10 +47,7 @@ public function testSetData()
$this->assertEquals(84, $obj->rows());
}
- /**
- * @return void
- */
- public function testSetCols()
+ public function testSetCols(): void
{
$obj = $this->obj;
$ret = $obj->setCols(42);
@@ -72,10 +59,7 @@ public function testSetCols()
$obj->setCols('foo');
}
- /**
- * @return void
- */
- public function testSetRows()
+ public function testSetRows(): void
{
$obj = $this->obj;
$ret = $obj->setRows(42);
@@ -89,12 +73,10 @@ public function testSetRows()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerInputDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessDailyScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessDailyScriptTest.php
index 5fb93807f..96a5beb6d 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessDailyScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessDailyScriptTest.php
@@ -21,36 +21,25 @@ class ProcessDailyScriptTest extends AbstractTestCase
{
use ReflectionsTrait;
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
* @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\Notification\ProcessDailyScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerScriptDependencies($container);
- $container['email/factory'] = function(Container $container) {
- return $container['model/factory'];
- };
+ $container['email/factory'] = (fn(Container $container): mixed => $container['model/factory']);
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -66,19 +55,13 @@ public function setUp(): void
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
$this->assertArrayHasKey('now', $args);
}
- /**
- * @return void
- */
- public function testFrequency()
+ public function testFrequency(): void
{
$this->assertEquals('daily', $this->callMethod($this->obj, 'frequency'));
}
diff --git a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessHourlyScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessHourlyScriptTest.php
index 398cbdf37..4c4b78a96 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessHourlyScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessHourlyScriptTest.php
@@ -21,36 +21,25 @@ class ProcessHourlyScriptTest extends AbstractTestCase
{
use ReflectionsTrait;
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
* @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\Notification\ProcessHourlyScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerScriptDependencies($container);
- $container['email/factory'] = function(Container $container) {
- return $container['model/factory'];
- };
+ $container['email/factory'] = (fn(Container $container): mixed => $container['model/factory']);
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -66,19 +55,13 @@ public function setUp(): void
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
$this->assertArrayHasKey('now', $args);
}
- /**
- * @return void
- */
- public function testFrequency()
+ public function testFrequency(): void
{
$this->assertEquals('hourly', $this->callMethod($this->obj, 'frequency'));
}
diff --git a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMinuteScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMinuteScriptTest.php
index 9e45bc5ed..216af9ff4 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMinuteScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMinuteScriptTest.php
@@ -21,36 +21,25 @@ class ProcessMinuteScriptTest extends AbstractTestCase
{
use ReflectionsTrait;
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
* @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\Notification\ProcessMinuteScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerScriptDependencies($container);
- $container['email/factory'] = function(Container $container) {
- return $container['model/factory'];
- };
+ $container['email/factory'] = (fn(Container $container): mixed => $container['model/factory']);
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -66,19 +55,13 @@ public function setUp(): void
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
$this->assertArrayHasKey('now', $args);
}
- /**
- * @return void
- */
- public function testFrequency()
+ public function testFrequency(): void
{
$this->assertEquals('minute', $this->callMethod($this->obj, 'frequency'));
}
diff --git a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMonthlyScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMonthlyScriptTest.php
index 4e4e934a5..e9a14f4f8 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMonthlyScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessMonthlyScriptTest.php
@@ -21,36 +21,25 @@ class ProcessMonthlyScriptTest extends AbstractTestCase
{
use ReflectionsTrait;
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
* @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\Notification\ProcessMonthlyScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerScriptDependencies($container);
- $container['email/factory'] = function(Container $container) {
- return $container['model/factory'];
- };
+ $container['email/factory'] = (fn(Container $container): mixed => $container['model/factory']);
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -66,19 +55,13 @@ public function setUp(): void
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
$this->assertArrayHasKey('now', $args);
}
- /**
- * @return void
- */
- public function testFrequency()
+ public function testFrequency(): void
{
$this->assertEquals('monthly', $this->callMethod($this->obj, 'frequency'));
}
diff --git a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessWeeklyScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessWeeklyScriptTest.php
index f53a98581..d43177a70 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessWeeklyScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/Notification/ProcessWeeklyScriptTest.php
@@ -21,36 +21,25 @@ class ProcessWeeklyScriptTest extends AbstractTestCase
{
use ReflectionsTrait;
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
* @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\Notification\ProcessWeeklyScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerScriptDependencies($container);
- $container['email/factory'] = function(Container $container) {
- return $container['model/factory'];
- };
+ $container['email/factory'] = (fn(Container $container): mixed => $container['model/factory']);
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -66,19 +55,13 @@ public function setUp(): void
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
$this->assertArrayHasKey('now', $args);
}
- /**
- * @return void
- */
- public function testFrequency()
+ public function testFrequency(): void
{
$this->assertEquals('weekly', $this->callMethod($this->obj, 'frequency'));
}
diff --git a/packages/admin/tests/Charcoal/Admin/Script/Object/Table/CreateScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/Object/Table/CreateScriptTest.php
index aea0c9675..c9889c991 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/Object/Table/CreateScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/Object/Table/CreateScriptTest.php
@@ -31,21 +31,14 @@
*/
class CreateScriptTest extends AbstractTestCase
{
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
- * @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\Object\Table\CreateScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
@@ -53,9 +46,6 @@ private function getContainer()
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -71,10 +61,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
diff --git a/packages/admin/tests/Charcoal/Admin/Script/User/CreateScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/User/CreateScriptTest.php
index 18e44d639..d93bcc516 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/User/CreateScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/User/CreateScriptTest.php
@@ -31,21 +31,14 @@
*/
class CreateScriptTest extends AbstractTestCase
{
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
- * @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\User\CreateScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
@@ -53,9 +46,6 @@ private function getContainer()
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -68,10 +58,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
@@ -80,10 +67,7 @@ public function testDefaultArguments()
$this->assertArrayHasKey('roles', $args);
}
- /**
- * @return void
- */
- public function testArguments()
+ public function testArguments(): void
{
$args = $this->obj->arguments();
@@ -92,20 +76,6 @@ public function testArguments()
$this->assertArrayHasKey('roles', $args);
}
- /**
- * @return integer
- */
- private function numAdminUsersInSource()
- {
- $source = $this->container['model/factory']->create('charcoal/admin/user')->source();
- $source->createTable();
-
- $table = $source->table();
- $q = 'select count(`email`) as num from `'.$table.'`';
- $req = $this->container['database']->query($q);
- return $req->fetchColumn(0);
- }
-
// public function testInvoke()
// {
// // Ensure that no admin user exists in test database
diff --git a/packages/admin/tests/Charcoal/Admin/Script/User/ResetPasswordScriptTest.php b/packages/admin/tests/Charcoal/Admin/Script/User/ResetPasswordScriptTest.php
index fbf9f9140..0caa45b52 100644
--- a/packages/admin/tests/Charcoal/Admin/Script/User/ResetPasswordScriptTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Script/User/ResetPasswordScriptTest.php
@@ -31,21 +31,15 @@
*/
class ResetPasswordScriptTest extends AbstractTestCase
{
- /**
- * @var Container
- */
- private $container;
+ private \Pimple\Container $container;
/**
* Instance of class under test
* @var CreateScript
*/
- private $obj;
+ private \Charcoal\Admin\Script\User\ResetPasswordScript $obj;
- /**
- * @return Container
- */
- private function getContainer()
+ private function getContainer(): \Pimple\Container
{
$container = new Container();
$containerProvider = new ContainerProvider();
@@ -53,9 +47,6 @@ private function getContainer()
return $container;
}
- /**
- * @return void
- */
public function setUp(): void
{
$this->container = $this->getContainer();
@@ -70,10 +61,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testDefaultArguments()
+ public function testDefaultArguments(): void
{
$args = $this->obj->defaultArguments();
@@ -81,10 +69,7 @@ public function testDefaultArguments()
$this->assertArrayHasKey('password', $args);
}
- /**
- * @return void
- */
- public function testArguments()
+ public function testArguments(): void
{
$args = $this->obj->arguments();
diff --git a/packages/admin/tests/Charcoal/Admin/Service/ExporterTest.php b/packages/admin/tests/Charcoal/Admin/Service/ExporterTest.php
index 49551abe9..b3a7eb8d8 100644
--- a/packages/admin/tests/Charcoal/Admin/Service/ExporterTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Service/ExporterTest.php
@@ -21,51 +21,27 @@
*/
class ExporterTest extends AbstractTestCase
{
- /**
- * @var Exporter
- */
- private $obj;
-
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
- /**
- * @return void
- */
public function setUp(): void
{
- $container = $this->container();
-
- $this->obj = new Exporter([
- 'logger' => $container['logger'],
- 'factory' => $container['model/factory'],
- 'propertyFactory' => $container['property/factory'],
- 'translator' => $container['translator'],
- 'obj_type' => 'charcoal/admin/user',
- 'export_ident' => 'y',
- ]);
+ $this->container();
}
- /**
- * @return void
- */
- public function testExport()
+ public function testExport(): void
{
$this->assertTrue(true);
}
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerBaseServices($container);
@@ -73,7 +49,7 @@ protected function container()
$containerProvider->registerModelServiceProvider($container);
$containerProvider->registerTranslatorServiceProvider($container);
- $container['view'] = $this->createMock('\Charcoal\View\ViewInterface');
+ $container['view'] = $this->createMock(\Charcoal\View\ViewInterface::class);
$this->container = $container;
}
diff --git a/packages/admin/tests/Charcoal/Admin/ServiceProvider/AclServiceProviderTest.php b/packages/admin/tests/Charcoal/Admin/ServiceProvider/AclServiceProviderTest.php
index fd87dc892..b53310ee0 100644
--- a/packages/admin/tests/Charcoal/Admin/ServiceProvider/AclServiceProviderTest.php
+++ b/packages/admin/tests/Charcoal/Admin/ServiceProvider/AclServiceProviderTest.php
@@ -14,10 +14,7 @@
*/
class AclServiceProviderTest extends AbstractTestCase
{
- /**
- * @return void
- */
- public function testProvider()
+ public function testProvider(): void
{
$container = new Container([
'config' => []
diff --git a/packages/admin/tests/Charcoal/Admin/Template/Account/LostPasswordTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/Account/LostPasswordTemplateTest.php
index 6960e7dd1..d48415a92 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/Account/LostPasswordTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/Account/LostPasswordTemplateTest.php
@@ -23,11 +23,8 @@ class LostPasswordTemplateTest extends AbstractTestCase
* Instance of object under test
* @var LoginTemplate
*/
- private $obj;
+ private \Charcoal\Admin\Template\Account\LostPasswordTemplate $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$this->obj = new LostPasswordTemplate([
@@ -35,10 +32,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsFalse()
+ public function testAuthRequiredIsFalse(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertNotTrue($res);
diff --git a/packages/admin/tests/Charcoal/Admin/Template/Account/ResetPasswordTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/Account/ResetPasswordTemplateTest.php
index 23f551637..69cb2eb62 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/Account/ResetPasswordTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/Account/ResetPasswordTemplateTest.php
@@ -23,11 +23,8 @@ class ResetPasswordTemplateTest extends AbstractTestCase
* Instance of object under test
* @var LoginTemplate
*/
- private $obj;
+ private \Charcoal\Admin\Template\Account\ResetPasswordTemplate $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$this->obj = new ResetPasswordTemplate([
@@ -35,10 +32,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsFalse()
+ public function testAuthRequiredIsFalse(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertNotTrue($res);
diff --git a/packages/admin/tests/Charcoal/Admin/Template/ElfinderTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/ElfinderTemplateTest.php
index 750206148..ac56a0043 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/ElfinderTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/ElfinderTemplateTest.php
@@ -19,22 +19,16 @@ class ElfinderTemplateTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var ElfinderTemplate
*/
- private $obj;
+ private \Charcoal\Admin\Template\ElfinderTemplate $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -46,10 +40,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAdminAssertsUrl()
+ public function testAdminAssertsUrl(): void
{
$ret = $this->obj->adminAssetsUrl();
$this->assertEquals('/assets/admin/', $ret);
@@ -57,17 +48,15 @@ public function testAdminAssertsUrl()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerTemplateDependencies($container);
$containerProvider->registerElfinderConfig($container);
- $container['widget/factory'] = $this->createMock('\Charcoal\Factory\FactoryInterface');
+ $container['widget/factory'] = $this->createMock(\Charcoal\Factory\FactoryInterface::class);
$this->container = $container;
}
diff --git a/packages/admin/tests/Charcoal/Admin/Template/LoginTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/LoginTemplateTest.php
index a216acde6..6869de520 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/LoginTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/LoginTemplateTest.php
@@ -21,13 +21,9 @@ class LoginTemplateTest extends AbstractTestCase
/**
* Instance of object under test
- * @var LoginTemplate
*/
- private $obj;
+ private \Charcoal\Admin\Template\LoginTemplate $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$this->obj = new LoginTemplate([
@@ -35,10 +31,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsFalse()
+ public function testAuthRequiredIsFalse(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertNotTrue($res);
diff --git a/packages/admin/tests/Charcoal/Admin/Template/LogoutTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/LogoutTemplateTest.php
index 8dacfb792..5d3731c6f 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/LogoutTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/LogoutTemplateTest.php
@@ -22,9 +22,6 @@ class LogoutTemplateTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$this->obj = new LogoutTemplate([
@@ -32,10 +29,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsFalse()
+ public function testAuthRequiredIsFalse(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertNotTrue($res);
diff --git a/packages/admin/tests/Charcoal/Admin/Template/Object/CollectionTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/Object/CollectionTemplateTest.php
index 2281d714b..f1c44b1f9 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/Object/CollectionTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/Object/CollectionTemplateTest.php
@@ -22,22 +22,16 @@ class CollectionTemplateTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var CollectionTemplate
*/
- private $obj;
+ private \Charcoal\Admin\Template\Object\CollectionTemplate $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -50,28 +44,19 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testInit()
+ public function testInit(): void
{
//$ret = $this->obj->init();
$this->assertTrue(true);
}
- /**
- * @return void
- */
- public function testTitle()
+ public function testTitle(): void
{
$this->obj->setObjType('charcoal/admin/user');
$ret = $this->obj->title();
@@ -82,12 +67,10 @@ public function testTitle()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerTemplateDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Template/Object/CreateTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/Object/CreateTemplateTest.php
index c392c1d3e..4860ebd7c 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/Object/CreateTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/Object/CreateTemplateTest.php
@@ -21,22 +21,16 @@ class CreateTemplateTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var CreateTemplate
*/
- private $obj;
+ private \Charcoal\Admin\Template\Object\CreateTemplate $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -50,19 +44,13 @@ public function setUp(): void
//$this->obj->setDependencies($container);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testTitle()
+ public function testTitle(): void
{
$this->obj->setObjType('charcoal/admin/user');
$ret = $this->obj->title();
@@ -73,12 +61,10 @@ public function testTitle()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerTemplateDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Template/Object/EditTemplateTest.php b/packages/admin/tests/Charcoal/Admin/Template/Object/EditTemplateTest.php
index 0bae749e0..f26fe68b6 100644
--- a/packages/admin/tests/Charcoal/Admin/Template/Object/EditTemplateTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Template/Object/EditTemplateTest.php
@@ -21,22 +21,16 @@ class EditTemplateTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var EditTemplate
*/
- private $obj;
+ private \Charcoal\Admin\Template\Object\EditTemplate $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -50,19 +44,13 @@ public function setUp(): void
//$this->obj->setDependencies($container);
}
- /**
- * @return void
- */
- public function testAuthRequiredIsTrue()
+ public function testAuthRequiredIsTrue(): void
{
$res = $this->callMethod($this->obj, 'authRequired');
$this->assertTrue($res);
}
- /**
- * @return void
- */
- public function testTitle()
+ public function testTitle(): void
{
$this->obj->setObjType('charcoal/admin/user');
$ret = $this->obj->title();
@@ -73,12 +61,10 @@ public function testTitle()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerTemplateDependencies($container);
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/CollectionMapWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/CollectionMapWidgetTest.php
index 55fa2f365..d01e02845 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/CollectionMapWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/CollectionMapWidgetTest.php
@@ -19,9 +19,6 @@ class CollectionMapWidgetTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$logger = new NullLogger();
@@ -30,40 +27,28 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetLatProperty()
+ public function testSetLatProperty(): void
{
$ret = $this->obj->setLatProperty('foo');
$this->assertSame($ret, $this->obj);
$this->assertEquals('foo', $this->obj->latProperty());
}
- /**
- * @return void
- */
- public function testSetLonProperty()
+ public function testSetLonProperty(): void
{
$ret = $this->obj->setLonProperty('foo');
$this->assertSame($ret, $this->obj);
$this->assertEquals('foo', $this->obj->lonProperty());
}
- /**
- * @return void
- */
- public function testSetPolygonProperty()
+ public function testSetPolygonProperty(): void
{
$ret = $this->obj->setPolygonProperty('foo');
$this->assertSame($ret, $this->obj);
$this->assertEquals('foo', $this->obj->polygonProperty());
}
- /**
- * @return void
- */
- public function testSetInfoboxTemplate()
+ public function testSetInfoboxTemplate(): void
{
$ret = $this->obj->setInfoboxTemplate('foo');
$this->assertSame($ret, $this->obj);
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/FormGroupWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/FormGroupWidgetTest.php
index d44421d2a..cce0be26f 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/FormGroupWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/FormGroupWidgetTest.php
@@ -18,9 +18,7 @@
*/
class FormGroupWidgetTest extends AbstractTestCase
{
- /**
- * @return void
- */
+ public $obj;
public function setUp(): void
{
$container = new Container();
@@ -31,7 +29,7 @@ public function setUp(): void
$containerProvider->registerAuthenticator($container);
- $container['form/input/builder'] = $this->createMock(\Charcoal\Ui\FormInput\FormInputBuilder::class, '');
+ $container['form/input/builder'] = $this->createMock(\Charcoal\Ui\FormInput\FormInputBuilder::class);
$container['authorizer'] = $container['admin/authorizer'];
$container['authenticator'] = $container['admin/authenticator'];
@@ -42,10 +40,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(FormGroupWidget::class, $this->obj);
}
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/FormPropertyWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/FormPropertyWidgetTest.php
index 7ed853709..dc4d8aca9 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/FormPropertyWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/FormPropertyWidgetTest.php
@@ -18,9 +18,7 @@
*/
class FormPropertyWidgetTest extends AbstractTestCase
{
- /**
- * @return void
- */
+ public $obj;
public function setUp(): void
{
$container = new Container();
@@ -36,18 +34,12 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(FormPropertyWidget::class, $this->obj);
}
- /**
- * @return void
- */
- public function testSetOutputType()
+ public function testSetOutputType(): void
{
//$this->assertEquals(FormPropertyWidget::DEFAULT_OUTPUT, $this->obj->outputType());
@@ -68,10 +60,7 @@ public function testSetOutputType()
$this->obj->setOutputType('foobar');
}
- /**
- * @return void
- */
- public function testPropertyType()
+ public function testPropertyType(): void
{
$this->assertNull($this->obj->propertyType());
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/FormSidebarWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/FormSidebarWidgetTest.php
index ad78b17d4..7712df3de 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/FormSidebarWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/FormSidebarWidgetTest.php
@@ -18,9 +18,7 @@
*/
class FormSidebarWidgetTest extends AbstractTestCase
{
- /**
- * @return void
- */
+ public $obj;
public function setUp(): void
{
$container = new Container();
@@ -36,10 +34,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(FormSidebarWidget::class, $this->obj);
}
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/FormWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/FormWidgetTest.php
index 1f9665814..422c4274b 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/FormWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/FormWidgetTest.php
@@ -17,13 +17,9 @@ class FormWidgetTest extends AbstractTestCase
{
/**
* Object under test
- * @var FormWidget
*/
- private $obj;
+ private \Charcoal\Admin\Widget\FormWidget $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$logger = new NullLogger();
@@ -32,21 +28,7 @@ public function setUp(): void
]);
}
- /**
- * @return FormSidebarWidget
- */
- private function sidebarWidget()
- {
- $logger = new NullLogger();
- return new FormSidebarWidget([
- 'logger' => $logger,
- ]);
- }
-
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(FormWidget::class, $this->obj);
}
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/GraphWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/GraphWidgetTest.php
index 679ee6017..990251f3b 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/GraphWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/GraphWidgetTest.php
@@ -14,21 +14,26 @@
*/
class GraphWidgetTest extends AbstractTestCase
{
- /**
- * @return void
- */
+ public $obj;
public function setUp(): void
{
$logger = new NullLogger();
- $this->obj = $this->getMockForAbstractClass('\Charcoal\Admin\Widget\Graph\AbstractGraphWidget', [[
- 'logger'=>$logger
- ]]);
+
+ $this->obj = new class ([
+ 'logger' => $logger
+ ]) extends AbstractGraphWidget {
+ public function categories()
+ {
+ return ['foo', 'bar'];
+ }
+ public function series()
+ {
+ return ['foo', 'bar'];
+ }
+ };
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -40,10 +45,7 @@ public function testSetData()
$this->assertEquals(['#ff0000', '#0000ff'], $obj->colors());
}
- /**
- * @return void
- */
- public function testSetHeight()
+ public function testSetHeight(): void
{
$obj = $this->obj;
$this->assertEquals('400px', $obj->height());
@@ -56,10 +58,7 @@ public function testSetHeight()
//$obj->setHeight(false);
}
- /**
- * @return void
- */
- public function testSetColors()
+ public function testSetColors(): void
{
$obj = $this->obj;
$this->assertEquals($obj->defaultColors(), $obj->colors());
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/LayoutWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/LayoutWidgetTest.php
index e336da11b..1071b1390 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/LayoutWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/LayoutWidgetTest.php
@@ -14,9 +14,7 @@
*/
class LayoutWidgetTest extends AbstractTestCase
{
- /**
- * @return void
- */
+ public $obj;
public function setUp(): void
{
$logger = new NullLogger();
@@ -25,27 +23,18 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testDefaultPosition()
+ public function testDefaultPosition(): void
{
$obj = $this->obj;
- $this->assertInstanceOf('\Charcoal\Admin\Widget\LayoutWidget', $obj);
+ $this->assertInstanceOf(\Charcoal\Admin\Widget\LayoutWidget::class, $obj);
$this->assertEquals(0, $obj->position());
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$struct = [[
'columns'=>[1]
]];
- $computed = [
- 'columns'=>[1]
- ];
$obj = $this->obj;
$ret = $obj->setData([
@@ -55,10 +44,7 @@ public function testSetData()
//$this->assertEquals($computed, $obj->structure());
}
- /**
- * @return void
- */
- public function testSetStructure()
+ public function testSetStructure(): void
{
$obj = $this->obj;
$this->assertEquals([], $obj->structure());
@@ -83,10 +69,7 @@ public function testSetStructure()
//$this->assertEquals($struct, $obj->structure());
}
- /**
- * @return void
- */
- public function testNumRows()
+ public function testNumRows(): void
{
$obj = $this->obj;
$this->assertEquals(0, $obj->numRows());
@@ -98,10 +81,7 @@ public function testNumRows()
$this->assertEquals(3, $obj->numRows());
}
- /**
- * @return void
- */
- public function testRowIndex()
+ public function testRowIndex(): void
{
$obj = $this->obj;
$this->assertNull($obj->rowIndex());
@@ -118,10 +98,7 @@ public function testRowIndex()
$this->assertEquals(0, $obj->rowIndex(5));
}
- /**
- * @return void
- */
- public function testRowData()
+ public function testRowData(): void
{
$obj = $this->obj;
$this->assertNull($obj->rowData());
@@ -138,10 +115,7 @@ public function testRowData()
$this->assertNull($obj->rowData(5));
}
- /**
- * @return void
- */
- public function testRowNumColumns()
+ public function testRowNumColumns(): void
{
$obj = $this->obj;
$this->assertNull($obj->rowNumColumns());
@@ -158,10 +132,7 @@ public function testRowNumColumns()
$this->assertNull($obj->rowNumColumns(5));
}
- /**
- * @return void
- */
- public function testRowNumCells()
+ public function testRowNumCells(): void
{
$obj = $this->obj;
$this->assertNull($obj->rowNumCells());
@@ -178,10 +149,7 @@ public function testRowNumCells()
$this->assertNull($obj->rowNumCells(5));
}
- /**
- * @return void
- */
- public function testRowFirstCellIndex()
+ public function testRowFirstCellIndex(): void
{
$obj = $this->obj;
$this->assertNull($obj->rowFirstCellIndex());
@@ -198,10 +166,7 @@ public function testRowFirstCellIndex()
//$this->assertNull($obj->rowFirstCellIndex(5));
}
- /**
- * @return void
- */
- public function testCellRowIndex()
+ public function testCellRowIndex(): void
{
$obj = $this->obj;
//$this->assertNull($obj->cellRowIndex());
@@ -218,10 +183,7 @@ public function testCellRowIndex()
//$this->assertNull($obj->cellRowIndex(5));
}
- /**
- * @return void
- */
- public function testNumCellsTotal()
+ public function testNumCellsTotal(): void
{
$obj = $this->obj;
$this->assertEquals(0, $obj->numCellsTotal());
@@ -233,10 +195,7 @@ public function testNumCellsTotal()
$this->assertEquals(5, $obj->numCellsTotal());
}
- /**
- * @return void
- */
- public function testNumCellSpan()
+ public function testNumCellSpan(): void
{
$obj = $this->obj;
$this->assertNull($obj->cellSpan());
@@ -253,10 +212,7 @@ public function testNumCellSpan()
$this->assertNull($obj->cellSpan(5));
}
- /**
- * @return void
- */
- public function testNumCellSpanBy12()
+ public function testNumCellSpanBy12(): void
{
$obj = $this->obj;
$this->assertNull($obj->cellSpanBy12());
@@ -273,10 +229,7 @@ public function testNumCellSpanBy12()
$this->assertNull($obj->cellSpanBy12(5));
}
- /**
- * @return void
- */
- public function testCellStartsRow()
+ public function testCellStartsRow(): void
{
$obj = $this->obj;
//$this->assertNull($obj->cellStartsRow());
@@ -293,10 +246,7 @@ public function testCellStartsRow()
//$this->assertNull($obj->cellStartsRow(5));
}
- /**
- * @return void
- */
- public function testCellEndsRow()
+ public function testCellEndsRow(): void
{
$obj = $this->obj;
//$this->assertNull($obj->cellStartsRow());
@@ -313,19 +263,13 @@ public function testCellEndsRow()
//$this->assertNull($obj->cellEndsRow(5));
}
- /**
- * @return void
- */
- public function testStart()
+ public function testStart(): void
{
$obj = $this->obj;
$this->assertEquals('', $obj->start());
}
- /**
- * @return void
- */
- public function testEnd()
+ public function testEnd(): void
{
$obj = $this->obj;
$this->assertEquals(0, $obj->position());
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/ObjectFormWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/ObjectFormWidgetTest.php
index 3d9f9a50a..215a6454b 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/ObjectFormWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/ObjectFormWidgetTest.php
@@ -19,9 +19,6 @@ class ObjectFormWidgetTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$logger = new NullLogger();
@@ -30,10 +27,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetFormIdent()
+ public function testSetFormIdent(): void
{
$ret = $this->obj->setFormIdent('foobar');
$this->assertSame($ret, $this->obj);
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/PaginationWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/PaginationWidgetTest.php
index 3f9185543..f9b84d499 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/PaginationWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/PaginationWidgetTest.php
@@ -21,9 +21,6 @@ class PaginationWidgetTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$this->obj = new PaginationWidget([
@@ -31,10 +28,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testPageLogic()
+ public function testPageLogic(): void
{
$this->obj->setData([
'page' => 3,
@@ -67,10 +61,7 @@ public function testPageLogic()
$this->assertEquals(1, $this->obj->pageNext());
}
- /**
- * @return void
- */
- public function testSetNumTotal()
+ public function testSetNumTotal(): void
{
$ret = $this->obj->setNumTotal(42);
$this->assertSame($ret, $this->obj);
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/SearchWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/SearchWidgetTest.php
index f473a6251..9430596dc 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/SearchWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/SearchWidgetTest.php
@@ -14,9 +14,7 @@
*/
class SearchWidgetTest extends AbstractTestCase
{
- /**
- * @return void
- */
+ public $obj;
public function setUp(): void
{
$logger = new NullLogger();
@@ -25,10 +23,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(SearchWidget::class, $this->obj);
}
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/SecondaryMenuWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/SecondaryMenuWidgetTest.php
index 5c2793e4b..208f3a217 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/SecondaryMenuWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/SecondaryMenuWidgetTest.php
@@ -25,9 +25,6 @@ class SecondaryMenuWidgetTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
public function setUp(): void
{
$container = new Container();
@@ -44,10 +41,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(SecondaryMenuWidget::class, $this->obj);
}
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/TableWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/TableWidgetTest.php
index a69847d83..b7cf8895f 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/TableWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/TableWidgetTest.php
@@ -21,22 +21,16 @@ class TableWidgetTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var TableWidget
*/
- private $obj;
+ private \Charcoal\Admin\Widget\TableWidget|array $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
- *
- * @return void
*/
public function setUp(): void
{
@@ -49,10 +43,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetSortable()
+ public function testSetSortable(): void
{
$ret = $this->obj->setSortable(true);
$this->assertSame($ret, $this->obj);
@@ -65,10 +56,7 @@ public function testSetSortable()
$this->assertTrue($this->obj['sortable']);
}
- /**
- * @return void
- */
- public function testShowTableHeader()
+ public function testShowTableHeader(): void
{
$this->assertTrue($this->obj->showTableHeader());
$ret = $this->obj->setShowTableHeader(false);
@@ -82,10 +70,7 @@ public function testShowTableHeader()
$this->assertFalse($this->obj['show_table_header']);
}
- /**
- * @return void
- */
- public function testShowTableHead()
+ public function testShowTableHead(): void
{
$this->assertTrue($this->obj->showTableHead());
$ret = $this->obj->setShowTableHead(false);
@@ -99,10 +84,7 @@ public function testShowTableHead()
$this->assertFalse($this->obj['show_table_head']);
}
- /**
- * @return void
- */
- public function testShowTableFoot()
+ public function testShowTableFoot(): void
{
$this->assertFalse($this->obj->showTableFoot());
$ret = $this->obj->setShowTableFoot(false);
@@ -118,19 +100,17 @@ public function testShowTableFoot()
/**
* Set up the service container.
- *
- * @return Container
*/
- protected function container()
+ protected function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerWidgetDependencies($container);
$containerProvider->registerWidgetFactory($container);
$containerProvider->registerPropertyDisplayFactory($container);
- $container['view'] = $this->createMock('\Charcoal\View\ViewInterface');
+ $container['view'] = $this->createMock(\Charcoal\View\ViewInterface::class);
$this->container = $container;
}
diff --git a/packages/admin/tests/Charcoal/Admin/Widget/TextWidgetTest.php b/packages/admin/tests/Charcoal/Admin/Widget/TextWidgetTest.php
index a9e49a6e0..a77e4d22d 100644
--- a/packages/admin/tests/Charcoal/Admin/Widget/TextWidgetTest.php
+++ b/packages/admin/tests/Charcoal/Admin/Widget/TextWidgetTest.php
@@ -18,9 +18,7 @@
*/
class TextWidgetTest extends AbstractTestCase
{
- /**
- * @return void
- */
+ public $obj;
public function setUp(): void
{
$container = new Container();
@@ -33,10 +31,7 @@ public function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testSetShowTitle()
+ public function testSetShowTitle(): void
{
$this->assertFalse($this->obj->showTitle());
$ret = $this->obj->setShowTitle(false);
@@ -48,10 +43,7 @@ public function testSetShowTitle()
$this->assertTrue($this->obj->showTitle());
}
- /**
- * @return void
- */
- public function testSetShowSubtitle()
+ public function testSetShowSubtitle(): void
{
$this->assertFalse($this->obj->showSubtitle());
$ret = $this->obj->setShowSubtitle(false);
@@ -63,10 +55,7 @@ public function testSetShowSubtitle()
$this->assertTrue($this->obj->showSubtitle());
}
- /**
- * @return void
- */
- public function testSetShowDescription()
+ public function testSetShowDescription(): void
{
$this->assertFalse($this->obj->showDescription());
$ret = $this->obj->setShowDescription(false);
@@ -78,10 +67,7 @@ public function testSetShowDescription()
$this->assertTrue($this->obj->showDescription());
}
- /**
- * @return void
- */
- public function testSetShowNotes()
+ public function testSetShowNotes(): void
{
$this->assertFalse($this->obj->showNotes());
$ret = $this->obj->setShowNotes(false);
@@ -93,40 +79,28 @@ public function testSetShowNotes()
$this->assertTrue($this->obj->showNotes());
}
- /**
- * @return void
- */
- public function testSetTitle()
+ public function testSetTitle(): void
{
$ret = $this->obj->setTitle('Fôö title');
$this->assertSame($ret, $this->obj);
$this->assertEquals('Fôö title', (string)$this->obj->title());
}
- /**
- * @return void
- */
- public function testSetSubtitle()
+ public function testSetSubtitle(): void
{
$ret = $this->obj->setSubtitle('Fôö subtitle');
$this->assertSame($ret, $this->obj);
$this->assertEquals('Fôö subtitle', (string)$this->obj->subtitle());
}
- /**
- * @return void
- */
- public function testSetDescription()
+ public function testSetDescription(): void
{
$ret = $this->obj->setDescription('Fôö description');
$this->assertSame($ret, $this->obj);
$this->assertEquals('Fôö description', (string)$this->obj->description());
}
- /**
- * @return void
- */
- public function testSetNotes()
+ public function testSetNotes(): void
{
$ret = $this->obj->setNotes('Fôö notes');
$this->assertSame($ret, $this->obj);
diff --git a/packages/admin/tests/Charcoal/AssertionsTrait.php b/packages/admin/tests/Charcoal/AssertionsTrait.php
index 21b2a53f6..0670b2627 100644
--- a/packages/admin/tests/Charcoal/AssertionsTrait.php
+++ b/packages/admin/tests/Charcoal/AssertionsTrait.php
@@ -15,9 +15,8 @@ trait AssertionsTrait
* @param array $expected The expected haystack.
* @param array $haystack The actual haystack.
* @param string $message The error to report.
- * @return void
*/
- public function assertArrayEquals(array $expected, array $haystack, $message = '')
+ public function assertArrayEquals(array $expected, array $haystack, $message = ''): void
{
$this->assertCount(count($expected), $haystack, $message);
$this->assertEquals($expected, $haystack, $message);
@@ -29,9 +28,8 @@ public function assertArrayEquals(array $expected, array $haystack, $message = '
* @param array $expected The expected haystack.
* @param array $haystack The actual haystack.
* @param string $message The error to report.
- * @return void
*/
- public function assertArrayContains(array $expected, array $haystack, $message = '')
+ public function assertArrayContains(array $expected, array $haystack, $message = ''): void
{
foreach ($expected as $item) {
$this->assertContains($item, $haystack, $message);
@@ -44,9 +42,8 @@ public function assertArrayContains(array $expected, array $haystack, $message =
* @param array $expected The expected haystack.
* @param array $haystack The actual haystack.
* @param string $message The error to report.
- * @return void
*/
- public function assertArrayHasKeys(array $expected, array $haystack, $message = '')
+ public function assertArrayHasKeys(array $expected, array $haystack, $message = ''): void
{
foreach ($expected as $item) {
$this->assertArrayHasKey($item, $haystack, $message);
@@ -60,14 +57,13 @@ public function assertArrayHasKeys(array $expected, array $haystack, $message =
* @param array $haystack The actual haystack.
* @param boolean $strict Whether to check for object identity.
* @param string $message The error to report.
- * @return void
*/
public function assertArraySubsets(
array $expected,
array $haystack,
$strict = false,
$message = ''
- ) {
+ ): void {
foreach ($expected as $key => $val) {
$this->assertArraySubset([ $key => $val ], $haystack, $strict, $message);
}
@@ -84,17 +80,16 @@ public function assertArraySubsets(
* @param boolean $checkForObjectIdentity Unused.
* @param string $message The error to report.
* @throws InvalidArgumentException
- * @return void
*/
public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = ''): void
{
- if (!(is_array($subset) || $subset instanceof ArrayAccess)) {
+ if (!is_array($subset) && !$subset instanceof ArrayAccess) {
throw InvalidArgumentException::create(
1,
'array or ArrayAccess'
);
}
- if (!(is_array($array) || $array instanceof ArrayAccess)) {
+ if (!is_array($array) && !$array instanceof ArrayAccess) {
throw InvalidArgumentException::create(
2,
'array or ArrayAccess'
diff --git a/packages/admin/tests/Charcoal/ReflectionsTrait.php b/packages/admin/tests/Charcoal/ReflectionsTrait.php
index 3a63ff2b1..047d2c172 100644
--- a/packages/admin/tests/Charcoal/ReflectionsTrait.php
+++ b/packages/admin/tests/Charcoal/ReflectionsTrait.php
@@ -18,13 +18,10 @@ trait ReflectionsTrait
*
* @param mixed $class The class name or object that contains the method.
* @param string $name The method name to reflect.
- * @return ReflectionMethod
*/
- public function getMethod($class, $name)
+ public function getMethod($class, $name): \ReflectionMethod
{
- $reflected = new ReflectionMethod($class, $name);
- $reflected->setAccessible(true);
- return $reflected;
+ return new ReflectionMethod($class, $name);
}
/**
@@ -38,7 +35,7 @@ public function getMethod($class, $name)
public function callMethod($object, $name, array $args = [])
{
$method = $this->getMethod($object, $name);
- if (empty($args)) {
+ if ($args === []) {
return $method->invoke($object);
} else {
return $method->invokeArgs($object, $args);
@@ -65,13 +62,10 @@ public function callMethodWith($object, $name, ...$args)
*
* @param mixed $class The class name or object that contains the property.
* @param string $name The property name to reflect.
- * @return ReflectionProperty
*/
- public function getProperty($class, $name)
+ public function getProperty($class, $name): \ReflectionProperty
{
- $reflected = new ReflectionProperty($class, $name);
- $reflected->setAccessible(true);
- return $reflected;
+ return new ReflectionProperty($class, $name);
}
/**
@@ -92,9 +86,8 @@ public function getPropertyValue($object, $name)
* @param mixed $object The object to access.
* @param string $name The property name to affect.
* @param mixed $value The new value.
- * @return void
*/
- public function setPropertyValue($object, $name, $value)
+ public function setPropertyValue($object, $name, $value): void
{
$this->getProperty($object, $name)->setValue($object, $value);
}
diff --git a/packages/admin/tests/bootstrap.php b/packages/admin/tests/bootstrap.php
new file mode 100644
index 000000000..90929e3b5
--- /dev/null
+++ b/packages/admin/tests/bootstrap.php
@@ -0,0 +1,14 @@
+
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
-
+ ./src/Charcoal
+
+
+
diff --git a/packages/app/src/Charcoal/App/Action/AbstractAction.php b/packages/app/src/Charcoal/App/Action/AbstractAction.php
index 842eb7325..75edf0525 100644
--- a/packages/app/src/Charcoal/App/Action/AbstractAction.php
+++ b/packages/app/src/Charcoal/App/Action/AbstractAction.php
@@ -44,25 +44,13 @@ abstract class AbstractAction extends AbstractEntity implements
public const MODE_EVENT_STREAM = 'event-stream';
public const DEFAULT_MODE = self::MODE_JSON;
- /**
- * @var string $mode
- */
- private $mode = self::DEFAULT_MODE;
+ private string $mode = self::DEFAULT_MODE;
- /**
- * @var boolean $success
- */
- private $success = false;
+ private bool $success = false;
- /**
- * @var string|null $successUrl
- */
- private $successUrl;
+ private ?string $successUrl = null;
- /**
- * @var string|null $failureUrl
- */
- private $failureUrl;
+ private ?string $failureUrl = null;
/**
* @param array|\ArrayAccess $data The dependencies (app and logger).
@@ -116,9 +104,7 @@ final public function __invoke(RequestInterface $request, ResponseInterface $res
break;
case self::MODE_EVENT_STREAM:
- $output = new CallbackStream(function () {
- return $this->results();
- });
+ $output = new CallbackStream(fn(): mixed => $this->results());
$response = $response
->withHeader('Content-Type', 'text/event-stream')
@@ -162,7 +148,7 @@ public function mode()
*/
public function setSuccess($success)
{
- $this->success = !!$success;
+ $this->success = (bool)$success;
return $this;
}
@@ -248,13 +234,7 @@ public function failureUrl()
*/
public function redirectUrl()
{
- if ($this->success() === true) {
- $url = $this->successUrl();
- } else {
- $url = $this->failureUrl();
- }
-
- return $url;
+ return $this->success() === true ? $this->successUrl() : $this->failureUrl();
}
/**
diff --git a/packages/app/src/Charcoal/App/Action/ActionInterface.php b/packages/app/src/Charcoal/App/Action/ActionInterface.php
index ec5251915..909e0ac36 100644
--- a/packages/app/src/Charcoal/App/Action/ActionInterface.php
+++ b/packages/app/src/Charcoal/App/Action/ActionInterface.php
@@ -1,5 +1,7 @@
setup();
@@ -116,10 +117,8 @@ public function run($silent = false)
/**
* Registers the default services and features that Charcoal needs to work.
- *
- * @return void
*/
- private function setup()
+ private function setup(): void
{
$config = $this->config();
date_default_timezone_set($config['timezone']);
@@ -150,9 +149,9 @@ private function setup()
*/
private function routeManager()
{
- if (!isset($this->routeManager)) {
+ if ($this->routeManager === null) {
$config = $this->config();
- $routesConfig = (isset($config['routes']) ? $config['routes'] : [] );
+ $routesConfig = ($config['routes'] ?? [] );
$this->routeManager = new RouteManager([
'config' => $routesConfig,
@@ -163,10 +162,7 @@ private function routeManager()
return $this->routeManager;
}
- /**
- * @return void
- */
- private function setupModules()
+ private function setupModules(): void
{
$container = $this->getContainer();
$modules = $container['config']['modules'];
@@ -180,10 +176,8 @@ private function setupModules()
* Setup the application's "global" routables.
*
* Routables can only be defined globally (app-level) for now.
- *
- * @return void
*/
- private function setupRoutables()
+ private function setupRoutables(): void
{
$app = $this;
@@ -198,7 +192,7 @@ function (
$config = $app->config();
$routables = $config['routables'];
- if (is_array($routables) && !empty($routables)) {
+ if (is_array($routables) && $routables !== []) {
$routeFactory = $this['route/factory'];
foreach ($routables as $routableType => $routableOptions) {
$route = $routeFactory->create($routableType, [
@@ -222,9 +216,8 @@ function (
/**
* @throws RuntimeException If the middleware was not set properly on the container.
- * @return void
*/
- private function setupMiddlewares()
+ private function setupMiddlewares(): void
{
$container = $this->getContainer();
$middlewaresConfig = $container['config']['middlewares'];
@@ -258,29 +251,26 @@ private function setupMiddlewares()
/**
* @throws LogicException If trying to clone an instance of a singleton.
- * @return void
*/
final public function __clone()
{
throw new LogicException(
sprintf(
'Cloning "%s" is not allowed.',
- get_called_class()
+ static::class
)
);
}
/**
* @throws LogicException If trying to unserialize an instance of a singleton.
- * @return void
*/
- final public function __wakeup()
+ final public function __unserialize(array $data): void
{
- throw new LogicException(
- sprintf(
- 'Unserializing "%s" is not allowed.',
- get_called_class()
- )
- );
+ foreach ($data as $property => $value) {
+ if (property_exists($this, $property)) {
+ $this->{$property} = $value;
+ }
+ }
}
}
diff --git a/packages/app/src/Charcoal/App/AppAwareInterface.php b/packages/app/src/Charcoal/App/AppAwareInterface.php
index 17fa8770f..58f89a4ae 100644
--- a/packages/app/src/Charcoal/App/AppAwareInterface.php
+++ b/packages/app/src/Charcoal/App/AppAwareInterface.php
@@ -1,5 +1,7 @@
'',
@@ -188,11 +150,10 @@ public function defaults()
/**
* @param array $values Array of values to resolve.
- * @return array
*/
public function resolveValues(array $values): array
{
- return array_map([$this, 'resolveValue'], $values);
+ return array_map($this->resolveValue(...), $values);
}
/**
@@ -213,7 +174,7 @@ public function resolveValue($value)
];
if (is_string($value)) {
- return preg_replace_callback('/%%|%([^%\s]+)%/', function ($match) use ($tags, $value) {
+ return preg_replace_callback('/%%|%([^%\s]+)%/', function (array $match) use ($tags, $value): string|float|int {
// skip escaped %%
if (!isset($match[1])) {
return '%%';
@@ -224,7 +185,7 @@ public function resolveValue($value)
$resolved = ($tags[$tag] ?? null);
if (!is_string($resolved) && !is_numeric($resolved)) {
- $resolvedType = (is_object($resolved) ? get_class($resolved) : gettype($resolved));
+ $resolvedType = (get_debug_type($resolved));
throw new UnexpectedValueException(sprintf(
'Invalid config parameter "%s" inside string value "%s";' .
@@ -251,6 +212,7 @@ public function resolveValue($value)
* @param string $path The file to load and add.
* @return self
*/
+ #[\Override]
public function addFile($path)
{
$path = $this->resolveValue($path);
@@ -265,9 +227,8 @@ public function addFile($path)
*
* @param string $path The absolute path to the application's root directory.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setBasePath($path)
+ public function setBasePath($path): static
{
if ($path === null) {
throw new InvalidArgumentException(
@@ -290,7 +251,7 @@ public function setBasePath($path)
*
* @return string|null The absolute path to the application's root directory.
*/
- public function basePath()
+ public function basePath(): ?string
{
return $this->basePath;
}
@@ -300,9 +261,8 @@ public function basePath()
*
* @param string $path The path to the application's public directory.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setPublicPath($path)
+ public function setPublicPath($path): static
{
if ($path === null) {
$this->publicPath = null;
@@ -324,7 +284,7 @@ public function setPublicPath($path)
*
* @return string The absolute path to the application's public directory.
*/
- public function publicPath()
+ public function publicPath(): string
{
if ($this->publicPath === null) {
$this->publicPath = $this->basePath() . DIRECTORY_SEPARATOR . 'www';
@@ -338,9 +298,8 @@ public function publicPath()
*
* @param string $path The path to the application's cache directory.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setCachePath($path)
+ public function setCachePath($path): static
{
if ($path === null) {
$this->cachePath = null;
@@ -362,7 +321,7 @@ public function setCachePath($path)
*
* @return string The absolute path to the application's cache directory.
*/
- public function cachePath()
+ public function cachePath(): string
{
if ($this->cachePath === null) {
$this->cachePath = $this->basePath() . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'cache';
@@ -376,9 +335,8 @@ public function cachePath()
*
* @param string $path The path to the application's logs directory.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setLogsPath($path)
+ public function setLogsPath($path): static
{
if ($path === null) {
$this->logsPath = null;
@@ -400,7 +358,7 @@ public function setLogsPath($path)
*
* @return string The absolute path to the application's logs directory.
*/
- public function logsPath()
+ public function logsPath(): string
{
if ($this->logsPath === null) {
$this->logsPath = $this->basePath() . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'logs';
@@ -413,15 +371,10 @@ public function logsPath()
* Set the application's fully qualified base URL to the public web directory.
*
* @param UriInterface|string $uri The base URI to the application's web directory.
- * @return self
*/
- public function setBaseUrl($uri)
+ public function setBaseUrl($uri): static
{
- if (is_string($uri)) {
- $this->baseUrl = Uri::createFromString($uri);
- } else {
- $this->baseUrl = $uri;
- }
+ $this->baseUrl = is_string($uri) ? Uri::createFromString($uri) : $uri;
return $this;
}
@@ -440,9 +393,8 @@ public function baseUrl()
*
* @param string $timezone The timezone string.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setTimezone($timezone)
+ public function setTimezone($timezone): static
{
if (!is_string($timezone)) {
throw new InvalidArgumentException(
@@ -458,12 +410,10 @@ public function setTimezone($timezone)
* Retrieve the application's default timezone.
*
* Will be used by the PHP date and date-time functions.
- *
- * @return string
*/
- public function timezone()
+ public function timezone(): string
{
- if (isset($this->timezone)) {
+ if ($this->timezone !== null) {
return $this->timezone;
} else {
return 'UTC';
@@ -475,9 +425,8 @@ public function timezone()
*
* @param string|null $projectName The project name.
* @throws InvalidArgumentException If the project argument is not a string (or null).
- * @return self
*/
- public function setProjectName($projectName)
+ public function setProjectName($projectName): static
{
if ($projectName === null) {
$this->projectName = null;
@@ -510,20 +459,16 @@ public function projectName()
/**
* @param boolean $devMode The "dev mode" flag.
- * @return self
*/
- public function setDevMode($devMode)
+ public function setDevMode($devMode): static
{
- $this->devMode = !!$devMode;
+ $this->devMode = (bool)$devMode;
return $this;
}
- /**
- * @return boolean
- */
- public function devMode()
+ public function devMode(): bool
{
- return !!$this->devMode;
+ return $this->devMode;
}
/**
@@ -531,9 +476,8 @@ public function devMode()
*
* @param array $view The global configset for the application's view service.
* @throws InvalidArgumentException If the argument is not a configset.
- * @return self
*/
- public function setView(array $view)
+ public function setView(array $view): static
{
$this->view = $view;
return $this;
@@ -553,18 +497,14 @@ public function view()
* Parse the application's API configuration.
*
* @param array $apis The API configuration structure to set.
- * @return self
*/
- public function setApis(array $apis)
+ public function setApis(array $apis): static
{
$this->apis = $apis;
return $this;
}
- /**
- * @return array
- */
- public function apis()
+ public function apis(): array
{
return $this->apis;
}
@@ -574,42 +514,32 @@ public function apis()
*
* @see \Charcoal\Admin\Config::setRoutes() For a similar implementation.
* @param array $routes The route configuration structure to set.
- * @return self
*/
- public function setRoutes(array $routes)
+ public function setRoutes(array $routes): static
{
$this->routes = $routes;
return $this;
}
- /**
- * @return array
- */
- public function routes()
+ public function routes(): array
{
return $this->routes;
}
/**
* @param array|boolean $routables The routable configuration structure to set or FALSE to disable dynamic routing.
- * @return self
*/
- public function setRoutables($routables)
+ public function setRoutables($routables): static
{
- if ($routables !== false) {
- if (!is_array($routables) || empty($routables)) {
- $routables = [];
- }
+ if ($routables !== false && (!is_array($routables) || $routables === [])) {
+ $routables = [];
}
$this->routables = $routables;
return $this;
}
- /**
- * @return array|boolean
- */
- public function routables()
+ public function routables(): bool|array
{
return $this->routables;
}
@@ -618,18 +548,14 @@ public function routables()
* Parse the application's HTTP middleware.
*
* @param array $middlewares The middleware configuration structure to set.
- * @return self
*/
- public function setMiddlewares(array $middlewares)
+ public function setMiddlewares(array $middlewares): static
{
$this->middlewares = $middlewares;
return $this;
}
- /**
- * @return array
- */
- public function middlewares()
+ public function middlewares(): array
{
return $this->middlewares;
}
@@ -645,18 +571,14 @@ public function middlewares()
* - "phpErrorHandler"
*
* @param array $handlers The handlers configuration structure to set.
- * @return self
*/
- public function setHandlers(array $handlers)
+ public function setHandlers(array $handlers): static
{
$this->handlers = $handlers;
return $this;
}
- /**
- * @return array
- */
- public function handlers()
+ public function handlers(): array
{
return $this->handlers;
}
@@ -665,18 +587,14 @@ public function handlers()
* Set the configuration modules.
*
* @param array $modules The module configuration structure to set.
- * @return self
*/
- public function setModules(array $modules)
+ public function setModules(array $modules): static
{
$this->modules = $modules;
return $this;
}
- /**
- * @return array
- */
- public function modules()
+ public function modules(): array
{
return $this->modules;
}
@@ -686,9 +604,8 @@ public function modules()
*
* @param array $cache The global config for the application's cache service.
* @throws InvalidArgumentException If the argument is not a configset.
- * @return self
*/
- public function setCache(array $cache)
+ public function setCache(array $cache): static
{
$this->cache = $cache;
return $this;
@@ -699,7 +616,7 @@ public function setCache(array $cache)
*
* @return array
*/
- public function cache()
+ public function cache(): ?array
{
return $this->cache;
}
@@ -709,9 +626,8 @@ public function cache()
*
* @param array $logger The global config for the application's logger service.
* @throws InvalidArgumentException If the argument is not a configset.
- * @return self
*/
- public function setLogger(array $logger)
+ public function setLogger(array $logger): static
{
$this->logger = $logger;
return $this;
@@ -722,16 +638,15 @@ public function setLogger(array $logger)
*
* @return array
*/
- public function logger()
+ public function logger(): ?array
{
return $this->logger;
}
/**
* @param array $databases The avaiable databases config.
- * @return self
*/
- public function setDatabases(array $databases)
+ public function setDatabases(array $databases): static
{
$this->databases = $databases;
return $this;
@@ -739,9 +654,8 @@ public function setDatabases(array $databases)
/**
* @throws Exception If trying to access this method and no databases were set.
- * @return array
*/
- public function databases()
+ public function databases(): array
{
if ($this->databases === null) {
throw new Exception(
@@ -776,9 +690,8 @@ public function databaseConfig($ident)
/**
* @param string $defaultDatabase The default database ident.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setDefaultDatabase($defaultDatabase)
+ public function setDefaultDatabase($defaultDatabase): static
{
if (!is_string($defaultDatabase)) {
throw new InvalidArgumentException(
@@ -793,9 +706,8 @@ public function setDefaultDatabase($defaultDatabase)
* @param string $ident The database ident.
* @param array $config The database options.
* @throws InvalidArgumentException If the arguments are invalid.
- * @return self
*/
- public function addDatabase($ident, array $config)
+ public function addDatabase($ident, array $config): static
{
if (!is_string($ident)) {
throw new InvalidArgumentException(
@@ -812,9 +724,8 @@ public function addDatabase($ident, array $config)
/**
* @throws Exception If trying to access this method before a setter.
- * @return mixed
*/
- public function defaultDatabase()
+ public function defaultDatabase(): string
{
if ($this->defaultDatabase === null) {
throw new Exception(
@@ -829,9 +740,8 @@ public function defaultDatabase()
*
* @param array $filesystem The global config for the application's file system.
* @throws InvalidArgumentException If the argument is not a configset.
- * @return self
*/
- public function setFilesystem(array $filesystem)
+ public function setFilesystem(array $filesystem): static
{
$this->filesystem = $filesystem;
return $this;
@@ -842,7 +752,7 @@ public function setFilesystem(array $filesystem)
*
* @return array
*/
- public function filesystem()
+ public function filesystem(): ?array
{
return $this->filesystem;
}
diff --git a/packages/app/src/Charcoal/App/AppContainer.php b/packages/app/src/Charcoal/App/AppContainer.php
index 7b5b3d635..fa494869e 100644
--- a/packages/app/src/Charcoal/App/AppContainer.php
+++ b/packages/app/src/Charcoal/App/AppContainer.php
@@ -28,7 +28,7 @@ public function __construct(array $values = [])
parent::__construct($values);
// Ensure "config" is set
- $this['config'] = (isset($values['config']) ? $values['config'] : new AppConfig());
+ $this['config'] = ($values['config'] ?? new AppConfig());
$this->register(new AppServiceProvider());
@@ -36,30 +36,22 @@ public function __construct(array $values = [])
$this->registerConfigProviders();
}
- /**
- * @return void
- */
- private function registerProviderFactory()
+ private function registerProviderFactory(): void
{
/**
* @return Factory
*/
if (!isset($this['provider/factory'])) {
- $this['provider/factory'] = function () {
- return new Factory([
- 'base_class' => ServiceProviderInterface::class,
- 'resolver_options' => [
- 'suffix' => 'ServiceProvider'
- ]
- ]);
- };
+ $this['provider/factory'] = (fn(): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => ServiceProviderInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'ServiceProvider'
+ ]
+ ]));
}
}
- /**
- * @return void
- */
- private function registerConfigProviders()
+ private function registerConfigProviders(): void
{
if (empty($this['config']['service_providers'])) {
return;
diff --git a/packages/app/src/Charcoal/App/CallableResolverAwareTrait.php b/packages/app/src/Charcoal/App/CallableResolverAwareTrait.php
index de76534ca..44fa5b724 100644
--- a/packages/app/src/Charcoal/App/CallableResolverAwareTrait.php
+++ b/packages/app/src/Charcoal/App/CallableResolverAwareTrait.php
@@ -72,7 +72,7 @@ protected function resolveCallable($callable, $context = null)
{
if (!isset($this->callableResolver)) {
throw new RuntimeException(
- sprintf('Callable Resolver is not defined for "%s"', get_class($this))
+ sprintf('Callable Resolver is not defined for "%s"', $this::class)
);
}
diff --git a/packages/app/src/Charcoal/App/Config/DatabaseConfig.php b/packages/app/src/Charcoal/App/Config/DatabaseConfig.php
index c5533aa49..bca2c88f8 100644
--- a/packages/app/src/Charcoal/App/Config/DatabaseConfig.php
+++ b/packages/app/src/Charcoal/App/Config/DatabaseConfig.php
@@ -1,5 +1,7 @@
'mysql',
@@ -61,9 +43,8 @@ public function defaults()
*
* @param string $type The database type.
* @throws InvalidArgumentException If parameter is not a string.
- * @return self
*/
- public function setType($type)
+ public function setType($type): static
{
if (!is_string($type)) {
throw new InvalidArgumentException(
@@ -79,7 +60,7 @@ public function setType($type)
*
* @return string
*/
- public function type()
+ public function type(): ?string
{
return $this->type;
}
@@ -89,9 +70,8 @@ public function type()
*
* @param string $hostname The database server hostname.
* @throws InvalidArgumentException If hostname is not a string.
- * @return self
*/
- public function setHostname($hostname)
+ public function setHostname($hostname): static
{
if (!is_string($hostname)) {
throw new InvalidArgumentException(
@@ -107,7 +87,7 @@ public function setHostname($hostname)
*
* @return string
*/
- public function hostname()
+ public function hostname(): ?string
{
return $this->hostname;
}
@@ -117,9 +97,8 @@ public function hostname()
*
* @param string $username The username.
* @throws InvalidArgumentException If username is not a string.
- * @return self
*/
- public function setUsername($username)
+ public function setUsername($username): static
{
if (!is_string($username)) {
throw new InvalidArgumentException(
@@ -135,7 +114,7 @@ public function setUsername($username)
*
* @return string
*/
- public function username()
+ public function username(): ?string
{
return $this->username;
}
@@ -145,9 +124,8 @@ public function username()
*
* @param string $password The password.
* @throws InvalidArgumentException If password is not a string.
- * @return self
*/
- public function setPassword($password)
+ public function setPassword($password): static
{
if (!is_string($password)) {
throw new InvalidArgumentException(
@@ -163,7 +141,7 @@ public function setPassword($password)
*
* @return string
*/
- public function password()
+ public function password(): ?string
{
return $this->password;
}
@@ -173,9 +151,8 @@ public function password()
*
* @param string $database The database name.
* @throws InvalidArgumentException If database is not a string.
- * @return self
*/
- public function setDatabase($database)
+ public function setDatabase($database): static
{
if (!is_string($database)) {
throw new InvalidArgumentException(
@@ -191,7 +168,7 @@ public function setDatabase($database)
*
* @return string
*/
- public function database()
+ public function database(): ?string
{
return $this->database;
}
@@ -200,11 +177,10 @@ public function database()
* Set whether to disable UTF-8 compatibility or not.
*
* @param boolean $disableUtf8 The disable flag.
- * @return self
*/
- public function setDisableUtf8($disableUtf8)
+ public function setDisableUtf8($disableUtf8): static
{
- $this->disableUtf8 = !!$disableUtf8;
+ $this->disableUtf8 = (bool)$disableUtf8;
return $this;
}
@@ -213,7 +189,7 @@ public function setDisableUtf8($disableUtf8)
*
* @return boolean
*/
- public function disableUtf8()
+ public function disableUtf8(): ?bool
{
return $this->disableUtf8;
}
diff --git a/packages/app/src/Charcoal/App/Config/FilesystemConfig.php b/packages/app/src/Charcoal/App/Config/FilesystemConfig.php
index 57a96f37a..e8eace876 100644
--- a/packages/app/src/Charcoal/App/Config/FilesystemConfig.php
+++ b/packages/app/src/Charcoal/App/Config/FilesystemConfig.php
@@ -20,22 +20,19 @@ class FilesystemConfig extends AbstractConfig
*/
public $defaultConnection;
- /**
- * @return array
- */
- public function defaultConnections()
+ public function defaultConnections(): array
{
return [
'public' => [
'public' => true,
'type' => 'local',
- 'path' => '%app.public_path%',
+ 'path' => './',
'label' => 'Public',
],
'private' => [
'public' => false,
'type' => 'local',
- 'path' => '%app.base_path%',
+ 'path' => '../',
'label' => 'Private',
],
];
@@ -43,10 +40,8 @@ public function defaultConnections()
/**
* Ensure connections always return the default connections.
- *
- * @return array
*/
- public function connections()
+ public function connections(): array
{
return array_merge($this->defaultConnections(), $this->connections);
}
diff --git a/packages/app/src/Charcoal/App/Config/FilesystemConfig.php.rej b/packages/app/src/Charcoal/App/Config/FilesystemConfig.php.rej
new file mode 100644
index 000000000..2cf06ddd5
--- /dev/null
+++ b/packages/app/src/Charcoal/App/Config/FilesystemConfig.php.rej
@@ -0,0 +1,18 @@
+--- packages/app/src/Charcoal/App/Config/FilesystemConfig.php
++++ packages/app/src/Charcoal/App/Config/FilesystemConfig.php
+@@ -29,13 +29,13 @@ class FilesystemConfig extends AbstractConfig
+ 'public' => [
+ 'public' => true,
+ 'type' => 'local',
+- 'path' => '%app.public_path%',
++ 'path' => './',
+ 'label' => 'Public',
+ ],
+ 'private' => [
+ 'public' => false,
+ 'type' => 'local',
+- 'path' => '%app.base_path%',
++ 'path' => '../',
+ 'label' => 'Private',
+ ],
+ ];
diff --git a/packages/app/src/Charcoal/App/Config/LoggerConfig.php b/packages/app/src/Charcoal/App/Config/LoggerConfig.php
index 800314189..d61dc1865 100644
--- a/packages/app/src/Charcoal/App/Config/LoggerConfig.php
+++ b/packages/app/src/Charcoal/App/Config/LoggerConfig.php
@@ -15,42 +15,33 @@ class LoggerConfig extends AbstractConfig
/**
* Whether to enable or disable the logger service.
- *
- * @var boolean
*/
- private $active;
+ private ?bool $active = null;
/**
* Record handler(s) to use.
*
* Whenever you add a record to the logger, it traverses the handler stack.
- *
- * @var array
*/
- private $handlers;
+ private ?array $handlers = null;
/**
* Record processor(s) to use.
*
* For customizing records added to the logger.
- *
- * @var array
*/
- private $processors;
+ private ?array $processors = null;
/**
* Channel name.
- *
- * @var string
*/
- private $channel = self::DEFAULT_CHANNEL;
+ private string $channel = self::DEFAULT_CHANNEL;
/**
* Retrieve the default values.
- *
- * @return array
*/
- public function defaults()
+ #[\Override]
+ public function defaults(): array
{
return [
'active' => true,
@@ -88,9 +79,9 @@ public function defaults()
* TRUE to enable, FALSE to disable.
* @return LoggerConfig Chainable
*/
- public function setActive($active)
+ public function setActive($active): static
{
- $this->active = !!$active;
+ $this->active = (bool)$active;
return $this;
}
@@ -99,7 +90,7 @@ public function setActive($active)
*
* @return boolean TRUE if enabled, FALSE if disabled.
*/
- public function active()
+ public function active(): ?bool
{
return $this->active;
}
@@ -108,9 +99,8 @@ public function active()
* Set the record handler(s) to use.
*
* @param array $handlers One or more (Monolog) record handlers; used as a stack.
- * @return self
*/
- public function setHandlers(array $handlers)
+ public function setHandlers(array $handlers): static
{
$this->handlers = [];
$this->addHandlers($handlers);
@@ -121,9 +111,8 @@ public function setHandlers(array $handlers)
* Add record handler(s) to use.
*
* @param string[] $handlers One or more (Monolog) handlers to stack.
- * @return self
*/
- public function addHandlers(array $handlers)
+ public function addHandlers(array $handlers): static
{
foreach ($handlers as $key => $handler) {
$this->addHandler($handler, $key);
@@ -137,9 +126,8 @@ public function addHandlers(array $handlers)
* @param array $handler The record handler structure.
* @param string|null $key The handler's key.
* @throws InvalidArgumentException If the handler is invalid.
- * @return self
*/
- public function addHandler(array $handler, $key = null)
+ public function addHandler(array $handler, $key = null): static
{
if (!isset($handler['type'])) {
throw new InvalidArgumentException(
@@ -161,7 +149,7 @@ public function addHandler(array $handler, $key = null)
*
* @return array
*/
- public function handlers()
+ public function handlers(): ?array
{
return $this->handlers;
}
@@ -170,9 +158,8 @@ public function handlers()
* Set the record processor(s) to use.
*
* @param array $processors One or more (Monolog) record processors; used as a stack.
- * @return self
*/
- public function setProcessors(array $processors)
+ public function setProcessors(array $processors): static
{
$this->processors = [];
$this->addProcessors($processors);
@@ -183,9 +170,8 @@ public function setProcessors(array $processors)
* Add record processor(s) to use.
*
* @param string[] $processors One or more (Monolog) processors to stack.
- * @return self
*/
- public function addProcessors(array $processors)
+ public function addProcessors(array $processors): static
{
foreach ($processors as $key => $processor) {
$this->addProcessor($processor, $key);
@@ -199,9 +185,8 @@ public function addProcessors(array $processors)
* @param array $processor The record processor structure.
* @param string|null $key The processor's key.
* @throws InvalidArgumentException If the processor is invalid.
- * @return self
*/
- public function addProcessor(array $processor, $key = null)
+ public function addProcessor(array $processor, $key = null): static
{
if (!isset($processor['type'])) {
throw new InvalidArgumentException(
@@ -223,7 +208,7 @@ public function addProcessor(array $processor, $key = null)
*
* @return array
*/
- public function processors()
+ public function processors(): ?array
{
return $this->processors;
}
@@ -233,9 +218,8 @@ public function processors()
*
* @param string $name The channe name (namespace).
* @throws InvalidArgumentException If the channel name is not a string.
- * @return self
*/
- public function setChannel($name)
+ public function setChannel($name): static
{
if (!is_string($name)) {
throw new InvalidArgumentException(
@@ -249,10 +233,8 @@ public function setChannel($name)
/**
* Retrieve the cache namespace.
- *
- * @return string
*/
- public function channel()
+ public function channel(): string
{
return $this->channel;
}
diff --git a/packages/app/src/Charcoal/App/DebugAwareTrait.php b/packages/app/src/Charcoal/App/DebugAwareTrait.php
index 44914d556..15ab462d3 100644
--- a/packages/app/src/Charcoal/App/DebugAwareTrait.php
+++ b/packages/app/src/Charcoal/App/DebugAwareTrait.php
@@ -22,7 +22,7 @@ trait DebugAwareTrait
*/
protected function setDebug($debug)
{
- $this->debug = !!$debug;
+ $this->debug = (bool)$debug;
}
/**
diff --git a/packages/app/src/Charcoal/App/Handler/AbstractError.php b/packages/app/src/Charcoal/App/Handler/AbstractError.php
index 654257bf1..2db73e286 100644
--- a/packages/app/src/Charcoal/App/Handler/AbstractError.php
+++ b/packages/app/src/Charcoal/App/Handler/AbstractError.php
@@ -21,10 +21,8 @@ abstract class AbstractError extends AbstractHandler
{
/**
* Whether to output the error's details.
- *
- * @var boolean $displayErrorDetails
*/
- private $displayErrorDetails;
+ private ?bool $displayErrorDetails = null;
/**
* The caught throwable.
@@ -50,7 +48,7 @@ public function displayErrorDetails()
*/
public function hasThrown()
{
- return !!$this->thrown;
+ return (bool)$this->thrown;
}
/**
@@ -86,6 +84,7 @@ public function renderHtmlErrorDetails()
*
* @return integer
*/
+ #[\Override]
public function getCode()
{
return 500;
@@ -125,6 +124,7 @@ public function getMessage()
* @param Container $container A service locator.
* @return self
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -143,7 +143,7 @@ protected function setDependencies(Container $container)
*/
protected function setDisplayErrorDetails($state)
{
- $this->displayErrorDetails = !!$state;
+ $this->displayErrorDetails = (bool)$state;
return $this;
}
@@ -171,7 +171,7 @@ protected function setThrown($throwable)
*/
protected function renderThrowableAsText($throwable)
{
- $text = sprintf('Type: %s' . PHP_EOL, get_class($throwable));
+ $text = sprintf('Type: %s' . PHP_EOL, $throwable::class);
$code = $throwable->getCode();
if (!empty($code)) {
@@ -285,7 +285,7 @@ protected function renderJsonMessage($throwable)
do {
$json['error'][] = [
- 'type' => get_class($throwable),
+ 'type' => $throwable::class,
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
'file' => $throwable->getFile(),
@@ -310,7 +310,7 @@ protected function renderXmlMessage($throwable)
if ($this->displayErrorDetails()) {
do {
$xml .= " \n";
- $xml .= ' ' . get_class($throwable) . "\n";
+ $xml .= ' ' . $throwable::class . "\n";
$xml .= ' ' . $throwable->getCode() . "\n";
$xml .= ' ' . $this->createCdataSection($throwable->getMessage()) . "\n";
$xml .= ' ' . $throwable->getFile() . "\n";
@@ -319,9 +319,8 @@ protected function renderXmlMessage($throwable)
$xml .= " \n";
} while ($throwable = $throwable->getPrevious());
}
- $xml .= '';
- return $xml;
+ return $xml . '';
}
/**
@@ -349,7 +348,7 @@ protected function renderHtmlError($throwable)
$line = $throwable->getLine();
$trace = $throwable->getTraceAsString();
- $html = sprintf('
Type: %s
', get_class($throwable));
+ $html = sprintf('
Type: %s
', $throwable::class);
if ($code) {
$html .= sprintf('
Code: %s
', $code);
@@ -381,6 +380,7 @@ protected function renderHtmlError($throwable)
* @param array|\ArrayAccess $data Raw template data.
* @return array|\ArrayAccess Expanded and processed template data.
*/
+ #[\Override]
protected function parseTemplateData($data = [])
{
$error = $this->getThrown();
diff --git a/packages/app/src/Charcoal/App/Handler/AbstractHandler.php b/packages/app/src/Charcoal/App/Handler/AbstractHandler.php
index ddc0a31c9..1f7cc831e 100644
--- a/packages/app/src/Charcoal/App/Handler/AbstractHandler.php
+++ b/packages/app/src/Charcoal/App/Handler/AbstractHandler.php
@@ -98,8 +98,6 @@ public function __construct(Container $container, $config = null)
/**
* String representation of the handler.
- *
- * @return string
*/
public function __toString(): string
{
@@ -183,7 +181,7 @@ final protected function templateFactory()
if ($this->templateFactory === null) {
throw new RuntimeException(sprintf(
'Template Factory is not defined for [%s]',
- get_class($this)
+ static::class
));
}
@@ -216,7 +214,7 @@ final protected function httpRequest()
if ($this->httpRequest === null) {
throw new RuntimeException(sprintf(
'HTTP Request is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -276,9 +274,8 @@ protected function respondWith(ResponseInterface $response, $contentType, $outpu
* Set an template factory.
*
* @param FactoryInterface $factory The factory to create templates.
- * @return void
*/
- private function setTemplateFactory(FactoryInterface $factory)
+ private function setTemplateFactory(FactoryInterface $factory): void
{
$this->templateFactory = $factory;
}
@@ -287,9 +284,8 @@ private function setTemplateFactory(FactoryInterface $factory)
* Set container for use with the template controller
*
* @param Container $container A dependencies container instance.
- * @return void
*/
- private function setContainer(Container $container)
+ private function setContainer(Container $container): void
{
$this->container = $container;
}
diff --git a/packages/app/src/Charcoal/App/Handler/Error.php b/packages/app/src/Charcoal/App/Handler/Error.php
index 0f439da48..7bb3df614 100644
--- a/packages/app/src/Charcoal/App/Handler/Error.php
+++ b/packages/app/src/Charcoal/App/Handler/Error.php
@@ -37,30 +37,16 @@ public function __invoke(
$this->setThrown($error);
$contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonOutput();
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlOutput();
- break;
-
- case 'text/html':
- $output = $this->renderHtmlOutput();
- break;
-
- case 'text/plain':
- $output = $this->renderPlainOutput();
- break;
-
- default:
- throw new UnexpectedValueException(sprintf(
- 'Cannot render unknown content type: %s',
- $contentType
- ));
- }
+ $output = match ($contentType) {
+ 'application/json' => $this->renderJsonOutput(),
+ 'text/xml', 'application/xml' => $this->renderXmlOutput(),
+ 'text/html' => $this->renderHtmlOutput(),
+ 'text/plain' => $this->renderPlainOutput(),
+ default => throw new UnexpectedValueException(sprintf(
+ 'Cannot render unknown content type: %s',
+ $contentType
+ )),
+ };
$this->writeToErrorLog($error);
@@ -73,10 +59,8 @@ public function __invoke(
/**
* Render Text Error
- *
- * @return string
*/
- protected function renderPlainOutput()
+ protected function renderPlainOutput(): string
{
$message = $this->renderTextMessage($this->getThrown());
@@ -85,10 +69,8 @@ protected function renderPlainOutput()
/**
* Render JSON Error
- *
- * @return string
*/
- protected function renderJsonOutput()
+ protected function renderJsonOutput(): string
{
$message = $this->renderJsonMessage($this->getThrown());
@@ -97,10 +79,8 @@ protected function renderJsonOutput()
/**
* Render XML Error
- *
- * @return string
*/
- protected function renderXmlOutput()
+ protected function renderXmlOutput(): string
{
$message = $this->renderXmlMessage($this->getThrown());
diff --git a/packages/app/src/Charcoal/App/Handler/HandlerConfig.php b/packages/app/src/Charcoal/App/Handler/HandlerConfig.php
index a4944bceb..f51d631de 100644
--- a/packages/app/src/Charcoal/App/Handler/HandlerConfig.php
+++ b/packages/app/src/Charcoal/App/Handler/HandlerConfig.php
@@ -16,26 +16,20 @@ class HandlerConfig extends AbstractConfig
{
/**
* The view (to load).
- *
- * @var string|null
*/
- private $template;
+ private ?string $template = null;
/**
* The view engine ident to use.
*
* For example: "mustache"
- *
- * @var string|null
*/
- private $engine;
+ private ?string $engine = null;
/**
* The view controller.
- *
- * @var string|null
*/
- private $controller;
+ private ?string $controller = null;
/**
* Dynamic views to register.
@@ -48,31 +42,23 @@ class HandlerConfig extends AbstractConfig
/**
* Additional view data.
- *
- * @var array
*/
- private $templateData = [];
+ private array $templateData = [];
/**
* Enable handler-level caching for the view.
- *
- * @var boolean $cache
*/
- private $cache = false;
+ private bool $cache = false;
/**
* Time-to-live, in seconds, of the cache. (0 = no limit).
- *
- * @var integer
*/
- private $cacheTtl = 0;
+ private int $cacheTtl = 0;
/**
* Retrieve the default handler types.
- *
- * @return array
*/
- public static function defaultHandlerTypes()
+ public static function defaultHandlerTypes(): array
{
return [
'maintenance',
@@ -90,7 +76,7 @@ public static function defaultHandlerTypes()
* @throws InvalidArgumentException If the template view is invalid.
* @return HandlerConfig Chainable
*/
- public function setTemplate($template)
+ public function setTemplate($template): static
{
if (empty($template)) {
$this->template = null;
@@ -109,10 +95,8 @@ public function setTemplate($template)
/**
* Retrieve the template view.
- *
- * @return string
*/
- public function template()
+ public function template(): string
{
if ($this->template === null) {
return 'charcoal/app/handler/layout';
@@ -126,9 +110,8 @@ public function template()
*
* @param string|null $controller Handler controller name.
* @throws InvalidArgumentException If the template controller is invalid.
- * @return self
*/
- public function setController($controller)
+ public function setController($controller): static
{
if (empty($controller)) {
$this->controller = null;
@@ -183,9 +166,8 @@ public function defaultController()
*
* @param string|null $engine The view engine identifier.
* @throws InvalidArgumentException If the engine is invalid.
- * @return self
*/
- public function setEngine($engine)
+ public function setEngine($engine): static
{
if (empty($engine)) {
$this->engine = null;
@@ -235,9 +217,8 @@ public function defaultEngine()
* Set the "handlerMessage" view ident.
*
* @param string $templateIdent A template identifier.
- * @return self
*/
- public function setPartial($templateIdent)
+ public function setPartial($templateIdent): static
{
$this->partials['handlerMessage'] = $templateIdent;
return $this;
@@ -259,7 +240,7 @@ public function partial()
* @param array $partials Dynamic templates.
* @return HandlerConfig Chainable
*/
- public function setPartials(array $partials)
+ public function setPartials(array $partials): static
{
$this->partials = array_replace($this->partials, $partials);
return $this;
@@ -281,7 +262,7 @@ public function partials()
* @param array $data Additional template data.
* @return HandlerConfig Chainable
*/
- public function setTemplateData(array $data)
+ public function setTemplateData(array $data): static
{
$this->templateData = array_merge($this->templateData, $data);
return $this;
@@ -289,10 +270,8 @@ public function setTemplateData(array $data)
/**
* Retrieve the template data for the view.
- *
- * @return array
*/
- public function templateData()
+ public function templateData(): array
{
return $this->templateData;
}
@@ -303,18 +282,16 @@ public function templateData()
* @param boolean $cache The cache flag.
* @return HandlerConfig Chainable
*/
- public function setCache($cache)
+ public function setCache($cache): static
{
- $this->cache = !!$cache;
+ $this->cache = (bool)$cache;
return $this;
}
/**
* Determine if the cache is enabled or disabled.
- *
- * @return boolean
*/
- public function cache()
+ public function cache(): bool
{
return $this->cache;
}
@@ -325,7 +302,7 @@ public function cache()
* @param integer $ttl The time-to-live, in seconds.
* @return HandlerConfig Chainable
*/
- public function setCacheTtl($ttl)
+ public function setCacheTtl($ttl): static
{
$this->cacheTtl = intval($ttl);
return $this;
@@ -333,10 +310,8 @@ public function setCacheTtl($ttl)
/**
* Retrieve the time-to-live for the cached template.
- *
- * @return integer
*/
- public function cacheTtl()
+ public function cacheTtl(): int
{
return $this->cacheTtl;
}
diff --git a/packages/app/src/Charcoal/App/Handler/HandlerInterface.php b/packages/app/src/Charcoal/App/Handler/HandlerInterface.php
index f371301c2..9c6f69d02 100644
--- a/packages/app/src/Charcoal/App/Handler/HandlerInterface.php
+++ b/packages/app/src/Charcoal/App/Handler/HandlerInterface.php
@@ -1,5 +1,7 @@
renderPlainOutput();
} else {
$contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonOutput();
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlOutput();
- break;
-
- case 'text/html':
- $output = $this->renderHtmlOutput();
- break;
-
- case 'text/plain':
- $output = $this->renderPlainOutput();
- break;
-
- default:
- throw new UnexpectedValueException(sprintf(
- 'Cannot render unknown content type: %s',
- $contentType
- ));
- }
+ $output = match ($contentType) {
+ 'application/json' => $this->renderJsonOutput(),
+ 'text/xml', 'application/xml' => $this->renderXmlOutput(),
+ 'text/html' => $this->renderHtmlOutput(),
+ 'text/plain' => $this->renderPlainOutput(),
+ default => throw new UnexpectedValueException(sprintf(
+ 'Cannot render unknown content type: %s',
+ $contentType
+ )),
+ };
}
return $this->respondWith(
@@ -74,10 +60,8 @@ public function __invoke(
/**
* Render Text Error
- *
- * @return string
*/
- protected function renderPlainOutput()
+ protected function renderPlainOutput(): string
{
$message = $this->translator()->translate('Service Unavailable', [], 'charcoal');
@@ -86,10 +70,8 @@ protected function renderPlainOutput()
/**
* Render JSON Error
- *
- * @return string
*/
- protected function renderJsonOutput()
+ protected function renderJsonOutput(): string
{
$message = $this->translator()->translate(
'The server is currently unavailable. We will be right back.',
@@ -103,10 +85,8 @@ protected function renderJsonOutput()
/**
* Render XML Error
- *
- * @return string
*/
- protected function renderXmlOutput()
+ protected function renderXmlOutput(): string
{
$message = $this->translator()->translate(
'The server is currently unavailable. We will be right back.',
@@ -129,30 +109,25 @@ protected function renderHtmlOutput()
/**
* Retrieve the response's HTTP code.
- *
- * @return integer
*/
- public function getCode()
+ #[\Override]
+ public function getCode(): int
{
return 503;
}
/**
* Retrieve the handler's summary.
- *
- * @return string
*/
- public function getSummary()
+ public function getSummary(): string
{
return $this->translator()->translate('Service Unavailable', [], 'charcoal');
}
/**
* Retrieve the handler's message.
- *
- * @return string
*/
- public function getMessage()
+ public function getMessage(): string
{
return $this->translator()->translate(
'The server is currently unavailable. We will be right back.',
diff --git a/packages/app/src/Charcoal/App/Handler/NotAllowed.php b/packages/app/src/Charcoal/App/Handler/NotAllowed.php
index d4a3287c4..bd9aa6be0 100644
--- a/packages/app/src/Charcoal/App/Handler/NotAllowed.php
+++ b/packages/app/src/Charcoal/App/Handler/NotAllowed.php
@@ -49,30 +49,16 @@ public function __invoke(
} else {
$status = 405;
$contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonOutput();
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlOutput();
- break;
-
- case 'text/html':
- $output = $this->renderHtmlOutput();
- break;
-
- case 'text/plain':
- $output = $this->renderPlainOutput();
- break;
-
- default:
- throw new UnexpectedValueException(sprintf(
- 'Cannot render unknown content type: %s',
- $contentType
- ));
- }
+ $output = match ($contentType) {
+ 'application/json' => $this->renderJsonOutput(),
+ 'text/xml', 'application/xml' => $this->renderXmlOutput(),
+ 'text/html' => $this->renderHtmlOutput(),
+ 'text/plain' => $this->renderPlainOutput(),
+ default => throw new UnexpectedValueException(sprintf(
+ 'Cannot render unknown content type: %s',
+ $contentType
+ )),
+ };
}
return $this->respondWith(
@@ -87,9 +73,8 @@ public function __invoke(
* Set the HTTP methods allowed by the current request.
*
* @param array $methods Case-sensitive array of methods.
- * @return self
*/
- protected function setMethods(array $methods)
+ protected function setMethods(array $methods): static
{
$this->methods = implode(', ', $methods);
@@ -108,10 +93,8 @@ public function getMethods()
/**
* Render Text Error
- *
- * @return string
*/
- protected function renderPlainOutput()
+ protected function renderPlainOutput(): string
{
$message = $this->translator()->translate('Allowed methods: {{ methods }}', [
'{{ methods }}' => $this->getMethods()
@@ -122,10 +105,8 @@ protected function renderPlainOutput()
/**
* Render JSON Error
- *
- * @return string
*/
- protected function renderJsonOutput()
+ protected function renderJsonOutput(): string
{
$message = $this->translator()->translate('Method not allowed. Must be one of: {{ methods }}', [
'{{ methods }}' => $this->getMethods()
@@ -137,10 +118,8 @@ protected function renderJsonOutput()
/**
* Render XML Error
- *
- * @return string
*/
- protected function renderXmlOutput()
+ protected function renderXmlOutput(): string
{
$message = $this->translator()->translate('Method not allowed. Must be one of: {{ methods }}', [
'{{ methods }}' => $this->getMethods()
@@ -165,6 +144,7 @@ protected function renderHtmlOutput()
* @param array|\ArrayAccess $data Raw template data.
* @return array|\ArrayAccess Expanded and processed template data.
*/
+ #[\Override]
protected function parseTemplateData($data = [])
{
$data['allowedMethods'] = $this->getMethods();
@@ -174,30 +154,25 @@ protected function parseTemplateData($data = [])
/**
* Retrieve the response's HTTP code.
- *
- * @return integer
*/
- public function getCode()
+ #[\Override]
+ public function getCode(): int
{
return 405;
}
/**
* Retrieve the handler's summary.
- *
- * @return string
*/
- public function getSummary()
+ public function getSummary(): string
{
return $this->translator()->translate('Method not allowed.', [], 'charcoal');
}
/**
* Retrieve the handler's message.
- *
- * @return string
*/
- public function getMessage()
+ public function getMessage(): string
{
return $this->renderPlainOutput();
}
diff --git a/packages/app/src/Charcoal/App/Handler/NotFound.php b/packages/app/src/Charcoal/App/Handler/NotFound.php
index f9d75ec19..aab322f07 100644
--- a/packages/app/src/Charcoal/App/Handler/NotFound.php
+++ b/packages/app/src/Charcoal/App/Handler/NotFound.php
@@ -33,30 +33,16 @@ public function __invoke(
$this->setHttpRequest($request);
$contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonOutput();
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlOutput();
- break;
-
- case 'text/html':
- $output = $this->renderHtmlOutput();
- break;
-
- case 'text/plain':
- $output = $this->renderPlainOutput();
- break;
-
- default:
- throw new UnexpectedValueException(sprintf(
- 'Cannot render unknown content type: %s',
- $contentType
- ));
- }
+ $output = match ($contentType) {
+ 'application/json' => $this->renderJsonOutput(),
+ 'text/xml', 'application/xml' => $this->renderXmlOutput(),
+ 'text/html' => $this->renderHtmlOutput(),
+ 'text/plain' => $this->renderPlainOutput(),
+ default => throw new UnexpectedValueException(sprintf(
+ 'Cannot render unknown content type: %s',
+ $contentType
+ )),
+ };
return $this->respondWith(
$response->withStatus(404),
@@ -67,10 +53,8 @@ public function __invoke(
/**
* Render Text Error
- *
- * @return string
*/
- protected function renderPlainOutput()
+ protected function renderPlainOutput(): string
{
$message = $this->translator()->translate('Not Found', [], 'charcoal');
@@ -79,10 +63,8 @@ protected function renderPlainOutput()
/**
* Render JSON Error
- *
- * @return string
*/
- protected function renderJsonOutput()
+ protected function renderJsonOutput(): string
{
$message = $this->translator()->translate('Not Found', [], 'charcoal');
$message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
@@ -92,10 +74,8 @@ protected function renderJsonOutput()
/**
* Render XML Error
- *
- * @return string
*/
- protected function renderXmlOutput()
+ protected function renderXmlOutput(): string
{
$message = $this->translator()->translate('Not Found', [], 'charcoal');
@@ -114,30 +94,25 @@ protected function renderHtmlOutput()
/**
* Retrieve the response's HTTP code.
- *
- * @return integer
*/
- public function getCode()
+ #[\Override]
+ public function getCode(): int
{
return 404;
}
/**
* Retrieve the handler's summary.
- *
- * @return string
*/
- public function getSummary()
+ public function getSummary(): string
{
return $this->translator()->translate('Page Not Found', [], 'charcoal');
}
/**
* Retrieve the handler's message.
- *
- * @return string
*/
- public function getMessage()
+ public function getMessage(): string
{
return $this->translator()->translate(
'The page you are looking for could not be found.',
diff --git a/packages/app/src/Charcoal/App/Handler/PhpError.php b/packages/app/src/Charcoal/App/Handler/PhpError.php
index f2af5a186..59673cff7 100644
--- a/packages/app/src/Charcoal/App/Handler/PhpError.php
+++ b/packages/app/src/Charcoal/App/Handler/PhpError.php
@@ -37,30 +37,16 @@ public function __invoke(
$this->setThrown($error);
$contentType = $this->determineContentType($request);
- switch ($contentType) {
- case 'application/json':
- $output = $this->renderJsonOutput();
- break;
-
- case 'text/xml':
- case 'application/xml':
- $output = $this->renderXmlOutput();
- break;
-
- case 'text/html':
- $output = $this->renderHtmlOutput();
- break;
-
- case 'text/plain':
- $output = $this->renderPlainOutput();
- break;
-
- default:
- throw new UnexpectedValueException(sprintf(
- 'Cannot render unknown content type: %s',
- $contentType
- ));
- }
+ $output = match ($contentType) {
+ 'application/json' => $this->renderJsonOutput(),
+ 'text/xml', 'application/xml' => $this->renderXmlOutput(),
+ 'text/html' => $this->renderHtmlOutput(),
+ 'text/plain' => $this->renderPlainOutput(),
+ default => throw new UnexpectedValueException(sprintf(
+ 'Cannot render unknown content type: %s',
+ $contentType
+ )),
+ };
$this->writeToErrorLog($error);
@@ -73,10 +59,8 @@ public function __invoke(
/**
* Render Text Error
- *
- * @return string
*/
- protected function renderPlainOutput()
+ protected function renderPlainOutput(): string
{
$message = $this->renderTextMessage($this->getThrown());
@@ -85,10 +69,8 @@ protected function renderPlainOutput()
/**
* Render JSON Error
- *
- * @return string
*/
- protected function renderJsonOutput()
+ protected function renderJsonOutput(): string
{
$message = $this->renderJsonMessage($this->getThrown());
@@ -97,10 +79,8 @@ protected function renderJsonOutput()
/**
* Render XML Error
- *
- * @return string
*/
- protected function renderXmlOutput()
+ protected function renderXmlOutput(): string
{
$message = $this->renderXmlMessage($this->getThrown());
diff --git a/packages/app/src/Charcoal/App/Helper/CallbackStream.php b/packages/app/src/Charcoal/App/Helper/CallbackStream.php
index 384da2e90..d8647e164 100644
--- a/packages/app/src/Charcoal/App/Helper/CallbackStream.php
+++ b/packages/app/src/Charcoal/App/Helper/CallbackStream.php
@@ -19,9 +19,8 @@ class CallbackStream implements StreamInterface
/**
* Whether or not the callback has been previously invoked.
- * @var boolean
*/
- private $called = false;
+ private bool $called = false;
/**
* CallbackStream constructor.
@@ -32,12 +31,9 @@ public function __construct(callable $callback)
$this->callback = $callback;
}
- /**
- * @return string
- */
- public function __toString()
+ public function __toString(): string
{
- return $this->output();
+ return (string)$this->output();
}
/**
@@ -77,7 +73,7 @@ public function detach()
/**
* @return integer|null Returns the size in bytes if known, or null if unknown.
*/
- public function getSize()
+ public function getSize(): null
{
return null;
}
@@ -85,23 +81,17 @@ public function getSize()
/**
* @return integer|boolean Position of the file pointer or false on error.
*/
- public function tell()
+ public function tell(): int
{
return 0;
}
- /**
- * @return boolean
- */
- public function eof()
+ public function eof(): bool
{
return $this->called;
}
- /**
- * @return boolean
- */
- public function isSeekable()
+ public function isSeekable(): bool
{
return false;
}
@@ -116,7 +106,7 @@ public function isSeekable()
* SEEK_END: Set position to end-of-stream plus offset.
* @return boolean Returns TRUE on success or FALSE on failure.
*/
- public function seek($offset, $whence = SEEK_SET)
+ public function seek($offset, $whence = SEEK_SET): bool
{
return false;
}
@@ -126,15 +116,12 @@ public function seek($offset, $whence = SEEK_SET)
* @link http://www.php.net/manual/en/function.fseek.php 1
* @return boolean Returns TRUE on success or FALSE on failure.
*/
- public function rewind()
+ public function rewind(): bool
{
return false;
}
- /**
- * @return boolean
- */
- public function isWritable()
+ public function isWritable(): bool
{
return false;
}
@@ -144,15 +131,12 @@ public function isWritable()
* @return integer|boolean Returns the number of bytes written to the stream on
* success or FALSE on failure.
*/
- public function write($string)
+ public function write($string): bool
{
return false;
}
- /**
- * @return boolean
- */
- public function isReadable()
+ public function isReadable(): bool
{
return true;
}
@@ -185,7 +169,7 @@ public function getContents()
* provided. Returns a specific key value if a key is provided and the
* value is found, or null if the key is not found.
*/
- public function getMetadata($key = null)
+ public function getMetadata($key = null): ?array
{
if ($key === null) {
return [];
diff --git a/packages/app/src/Charcoal/App/Middleware/IpMiddleware.php b/packages/app/src/Charcoal/App/Middleware/IpMiddleware.php
index 3e5678455..633318127 100644
--- a/packages/app/src/Charcoal/App/Middleware/IpMiddleware.php
+++ b/packages/app/src/Charcoal/App/Middleware/IpMiddleware.php
@@ -61,8 +61,6 @@ public function __construct(array $data)
/**
* Default middleware options.
- *
- * @return array
*/
public function defaults(): array
{
@@ -97,7 +95,7 @@ public function defaults(): array
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$ip = $this->getClientIp();
- if (!$ip) {
+ if ($ip === '' || $ip === '0') {
if ((!empty($this->disallowed) || !empty($this->allowed)) && $this->failOnInvalidIp === true) {
if ($this->errorMessage) {
$response->getBody()->write($this->errorMessage);
@@ -109,7 +107,7 @@ public function __invoke(RequestInterface $request, ResponseInterface $response,
}
// Check disallowed.
- if ($this->isIpDisallowed($ip) === true) {
+ if ($this->isIpDisallowed($ip)) {
if ($this->disallowedRedirect !== '') {
return $response
->withStatus(302)
@@ -150,9 +148,8 @@ public function __invoke(RequestInterface $request, ResponseInterface $response,
* Note: this method only performs an exact string match on IP address, no IP masking / range features.
*
* @param string $ip The IP address to check against the disallowed.
- * @return boolean
*/
- private function isIpDisallowed($ip): bool
+ private function isIpDisallowed(string $ip): bool
{
if (empty($this->disallowed)) {
return false;
@@ -168,9 +165,8 @@ private function isIpDisallowed($ip): bool
* Note; This method only performs an exact string match on IP address, no IP masking / range features.
*
* @param string $ip The IP address to check against the allowed.
- * @return boolean
*/
- private function isIpAllowed($ip): bool
+ private function isIpAllowed(string $ip): bool
{
if (empty($this->allowed)) {
return true;
@@ -181,18 +177,17 @@ private function isIpAllowed($ip): bool
/**
* @param string $ip The IP to check.
* @param string[] $cidrs The array of IPs/CIDRs to validate against. "/32" netmask is assumed.
- * @return boolean
*/
private function isIpInRange(string $ip, array $cidrs): bool
{
foreach ($cidrs as $range) {
- if (strpos($range, '/') === false) {
+ if (!str_contains($range, '/')) {
$range .= '/32';
}
// $range is in IP/CIDR format eg 127.0.0.1/24
- list($subnet, $netmask) = explode('/', $range, 2);
- $netmask = ~(pow(2, (32 - (int)$netmask)) - 1);
- if ((ip2long($ip) & $netmask) == (ip2long($subnet) & $netmask)) {
+ [$subnet, $netmask] = explode('/', $range, 2);
+ $netmask = ~(2 ** (32 - (int)$netmask) - 1);
+ if ((ip2long($ip) & $netmask) === (ip2long($subnet) & $netmask)) {
return true;
}
}
@@ -200,9 +195,6 @@ private function isIpInRange(string $ip, array $cidrs): bool
return false;
}
- /**
- * @return string
- */
private function getClientIp(): string
{
if (isset($_SERVER['REMOTE_ADDR'])) {
diff --git a/packages/app/src/Charcoal/App/Module/AbstractModule.php b/packages/app/src/Charcoal/App/Module/AbstractModule.php
index d45da11d3..bfc5e3000 100644
--- a/packages/app/src/Charcoal/App/Module/AbstractModule.php
+++ b/packages/app/src/Charcoal/App/Module/AbstractModule.php
@@ -105,9 +105,9 @@ public function setUp()
*/
public function setupRoutes()
{
- if (!isset($this->routeManager)) {
+ if ($this->routeManager === null) {
$config = $this->config();
- $routes = (isset($config['routes']) ? $config['routes'] : [] );
+ $routes = ($config['routes'] ?? [] );
$this->routeManager = new RouteManager([
'config' => $routes,
diff --git a/packages/app/src/Charcoal/App/Module/ModuleInterface.php b/packages/app/src/Charcoal/App/Module/ModuleInterface.php
index bdd2c30ac..e6683ad96 100644
--- a/packages/app/src/Charcoal/App/Module/ModuleInterface.php
+++ b/packages/app/src/Charcoal/App/Module/ModuleInterface.php
@@ -1,5 +1,7 @@
createConfig()
*
* @param mixed|null $data Optional config data.
- * @return ActionRouteConfig
*/
- public function createConfig($data = null)
+ public function createConfig($data = null): \Charcoal\App\Route\ActionRouteConfig
{
return new ActionRouteConfig($data);
}
diff --git a/packages/app/src/Charcoal/App/Route/ActionRouteConfig.php b/packages/app/src/Charcoal/App/Route/ActionRouteConfig.php
index e4a7f29d6..aa5510850 100644
--- a/packages/app/src/Charcoal/App/Route/ActionRouteConfig.php
+++ b/packages/app/src/Charcoal/App/Route/ActionRouteConfig.php
@@ -1,5 +1,7 @@
actionData = $actionData;
return $this;
@@ -29,10 +28,8 @@ public function setActionData(array $actionData)
/**
* Get the action data.
- *
- * @return array
*/
- public function actionData()
+ public function actionData(): array
{
return $this->actionData;
}
diff --git a/packages/app/src/Charcoal/App/Route/RouteConfig.php b/packages/app/src/Charcoal/App/Route/RouteConfig.php
index 97b287c93..eef7e3481 100644
--- a/packages/app/src/Charcoal/App/Route/RouteConfig.php
+++ b/packages/app/src/Charcoal/App/Route/RouteConfig.php
@@ -13,54 +13,44 @@ class RouteConfig extends AbstractConfig
{
/**
* Route identifier/name
- *
- * @var string
*/
- private $ident;
+ private ?string $ident = null;
/**
* Route pattern
- *
- * @var string
*/
- private $route;
+ private ?string $route = null;
/**
* HTTP methods supported by this route
*
* @var string[]
*/
- private $methods = [ 'GET' ];
+ private array $methods = [ 'GET' ];
/**
* Response controller classname
*
* Should be the class-ident of an action, a script or a template controller.
- *
- * @var string
*/
- private $controller;
+ private ?string $controller = null;
/**
* Parent route groups
*
* @var string[]
*/
- private $groups = [];
+ private array $groups = [];
/**
* Optional headers to set on response.
- *
- * @var array
*/
- private $headers = [];
+ private array $headers = [];
/**
* Retrieve the default route types.
- *
- * @return array
*/
- public static function defaultRouteTypes()
+ public static function defaultRouteTypes(): array
{
return [
'templates',
@@ -74,9 +64,8 @@ public static function defaultRouteTypes()
*
* @param string $ident Route identifier.
* @throws InvalidArgumentException If the identifier is not a string.
- * @return self
*/
- public function setIdent($ident)
+ public function setIdent($ident): static
{
if (!is_string($ident)) {
throw new InvalidArgumentException(
@@ -94,7 +83,7 @@ public function setIdent($ident)
*
* @return string
*/
- public function ident()
+ public function ident(): ?string
{
return $this->ident;
}
@@ -104,9 +93,8 @@ public function ident()
*
* @param string $pattern Route pattern.
* @throws InvalidArgumentException If the pattern argument is not a string.
- * @return self
*/
- public function setRoute($pattern)
+ public function setRoute($pattern): static
{
if (!is_string($pattern)) {
throw new InvalidArgumentException(
@@ -124,7 +112,7 @@ public function setRoute($pattern)
*
* @return string
*/
- public function route()
+ public function route(): ?string
{
return $this->route;
}
@@ -133,9 +121,8 @@ public function route()
* Set parent route groups
*
* @param string[] $groups The parent route groups.
- * @return self
*/
- public function setGroups(array $groups)
+ public function setGroups(array $groups): static
{
$this->groups = [];
@@ -151,9 +138,8 @@ public function setGroups(array $groups)
*
* @param string $group The parent route group.
* @throws InvalidArgumentException If the group is invalid.
- * @return self
*/
- public function addGroup($group)
+ public function addGroup($group): static
{
if (!is_string($group)) {
throw new InvalidArgumentException(
@@ -168,10 +154,8 @@ public function addGroup($group)
/**
* Get parent route groups
- *
- * @return array
*/
- public function groups()
+ public function groups(): array
{
return $this->groups;
}
@@ -180,9 +164,8 @@ public function groups()
* Add custom headers
*
* @param array $headers The custom headers, in key=>val pairs.
- * @return self
*/
- public function setHeaders(array $headers)
+ public function setHeaders(array $headers): static
{
$this->headers = [];
foreach ($headers as $name => $val) {
@@ -197,7 +180,7 @@ public function setHeaders(array $headers)
* @throws InvalidArgumentException If the header name or value is not a string.
* @return $this
*/
- public function addHeader($name, $val)
+ public function addHeader($name, $val): static
{
if (!is_string($name)) {
throw new InvalidArgumentException(
@@ -215,10 +198,8 @@ public function addHeader($name, $val)
/**
* Get custom route headers.
- *
- * @return array
*/
- public function headers()
+ public function headers(): array
{
return $this->headers;
}
@@ -228,9 +209,8 @@ public function headers()
*
* @param string $controller Route controller name.
* @throws InvalidArgumentException If the route view controller is not a string.
- * @return self
*/
- public function setController($controller)
+ public function setController($controller): static
{
if (!is_string($controller)) {
throw new InvalidArgumentException(
@@ -250,9 +230,9 @@ public function setController($controller)
*
* @return string
*/
- public function controller()
+ public function controller(): ?string
{
- if (!isset($this->controller)) {
+ if ($this->controller === null) {
return $this->ident();
}
@@ -263,9 +243,8 @@ public function controller()
* Set route methods
*
* @param string[] $methods The route's supported HTTP methods.
- * @return self
*/
- public function setMethods(array $methods)
+ public function setMethods(array $methods): static
{
$this->methods = [];
@@ -281,15 +260,14 @@ public function setMethods(array $methods)
*
* @param string $method The route's supported HTTP method.
* @throws InvalidArgumentException If the HTTP method is invalid.
- * @return self
*/
- public function addMethod($method)
+ public function addMethod($method): static
{
if (!is_string($method)) {
throw new InvalidArgumentException(
sprintf(
'Unsupported HTTP method; must be a string, received %s',
- (is_object($method) ? get_class($method) : gettype($method))
+ (get_debug_type($method))
)
);
}
@@ -327,7 +305,7 @@ public function addMethod($method)
*
* @return string[]
*/
- public function methods()
+ public function methods(): array
{
return $this->methods;
}
diff --git a/packages/app/src/Charcoal/App/Route/RouteInterface.php b/packages/app/src/Charcoal/App/Route/RouteInterface.php
index 54bd241a8..51d415832 100644
--- a/packages/app/src/Charcoal/App/Route/RouteInterface.php
+++ b/packages/app/src/Charcoal/App/Route/RouteInterface.php
@@ -1,5 +1,7 @@
config();
- if (PHP_SAPI == 'cli') {
- $scripts = ( isset($routes['scripts']) ? $routes['scripts'] : [] );
+ if (PHP_SAPI === 'cli') {
+ $scripts = ( $routes['scripts'] ?? [] );
foreach ($scripts as $scriptIdent => $scriptConfig) {
$this->setupScript($scriptIdent, $scriptConfig);
}
} else {
- $templates = ( isset($routes['templates']) ? $routes['templates'] : [] );
+ $templates = ( $routes['templates'] ?? [] );
foreach ($templates as $routeIdent => $templateConfig) {
$this->setupTemplate($routeIdent, $templateConfig);
}
- $actions = ( isset($routes['actions']) ? $routes['actions'] : [] );
+ $actions = ( $routes['actions'] ?? [] );
foreach ($actions as $actionIdent => $actionConfig) {
$this->setupAction($actionIdent, $actionConfig);
}
@@ -77,15 +75,11 @@ public function setupRoutes()
*/
private function setupTemplate($routeIdent, $templateConfig)
{
- $routePattern = isset($templateConfig['route'])
- ? $templateConfig['route']
- : '/' . ltrim($routeIdent, '/');
+ $routePattern = ($templateConfig['route'] ?? '/' . ltrim($routeIdent, '/'));
$templateConfig['route'] = $routePattern;
- $methods = isset($templateConfig['methods'])
- ? $templateConfig['methods']
- : [ 'GET' ];
+ $methods = ($templateConfig['methods'] ?? [ 'GET' ]);
$routeHandler = $this->app->map(
$methods,
@@ -119,9 +113,7 @@ function (
}
$defaultController = $this['route/controller/template/class'];
- $routeController = isset($templateConfig['route_controller'])
- ? $templateConfig['route_controller']
- : $defaultController;
+ $routeController = ($templateConfig['route_controller'] ?? $defaultController);
$routeFactory = $this['route/factory'];
$routeFactory->setDefaultClass($defaultController);
@@ -153,15 +145,11 @@ function (
*/
private function setupAction($routeIdent, $actionConfig)
{
- $routePattern = isset($actionConfig['route'])
- ? $actionConfig['route']
- : '/' . ltrim($routeIdent, '/');
+ $routePattern = ($actionConfig['route'] ?? '/') . ltrim($routeIdent, '/');
$actionConfig['route'] = $routePattern;
- $methods = isset($actionConfig['methods'])
- ? $actionConfig['methods']
- : [ 'POST' ];
+ $methods = ($actionConfig['methods'] ?? [ 'POST' ]);
$routeHandler = $this->app->map(
$methods,
@@ -195,9 +183,7 @@ function (
}
$defaultController = $this['route/controller/action/class'];
- $routeController = isset($actionConfig['route_controller'])
- ? $actionConfig['route_controller']
- : $defaultController;
+ $routeController = ($actionConfig['route_controller'] ?? $defaultController);
$routeFactory = $this['route/factory'];
$routeFactory->setDefaultClass($defaultController);
@@ -229,15 +215,11 @@ function (
*/
private function setupScript($routeIdent, $scriptConfig)
{
- $routePattern = isset($scriptConfig['route'])
- ? $scriptConfig['route']
- : '/' . ltrim($routeIdent, '/');
+ $routePattern = ($scriptConfig['route'] ?? '/') . ltrim($routeIdent, '/');
$scriptConfig['route'] = $routePattern;
- $methods = isset($scriptConfig['methods'])
- ? $scriptConfig['methods']
- : [ 'GET' ];
+ $methods = ($scriptConfig['methods'] ?? [ 'GET' ]);
$routeHandler = $this->app->map(
$methods,
@@ -271,9 +253,7 @@ function (
}
$defaultController = $this['route/controller/script/class'];
- $routeController = isset($scriptConfig['route_controller'])
- ? $scriptConfig['route_controller']
- : $defaultController;
+ $routeController = ($scriptConfig['route_controller'] ?? $defaultController);
$routeFactory = $this['route/factory'];
$routeFactory->setDefaultClass($defaultController);
diff --git a/packages/app/src/Charcoal/App/Route/ScriptRoute.php b/packages/app/src/Charcoal/App/Route/ScriptRoute.php
index 5af4e1a3d..0baeb1fc7 100644
--- a/packages/app/src/Charcoal/App/Route/ScriptRoute.php
+++ b/packages/app/src/Charcoal/App/Route/ScriptRoute.php
@@ -36,10 +36,9 @@ public function __construct(array $data)
/**
* @param mixed|null $data Optional config data.
- * @return ScriptRouteConfig
* @see ConfigurableTrait::createConfig()
*/
- public function createConfig($data = null)
+ public function createConfig($data = null): \Charcoal\App\Route\ScriptRouteConfig
{
return new ScriptRouteConfig($data);
}
diff --git a/packages/app/src/Charcoal/App/Route/ScriptRouteConfig.php b/packages/app/src/Charcoal/App/Route/ScriptRouteConfig.php
index f34fa141f..cea95818b 100644
--- a/packages/app/src/Charcoal/App/Route/ScriptRouteConfig.php
+++ b/packages/app/src/Charcoal/App/Route/ScriptRouteConfig.php
@@ -1,5 +1,7 @@
createConfig()
*
* @param mixed|null $data Optional config data.
- * @return TemplateRouteConfig
*/
- public function createConfig($data = null)
+ public function createConfig($data = null): \Charcoal\App\Route\TemplateRouteConfig
{
return new TemplateRouteConfig($data);
}
diff --git a/packages/app/src/Charcoal/App/Route/TemplateRouteConfig.php b/packages/app/src/Charcoal/App/Route/TemplateRouteConfig.php
index 845ef94b5..7f95deec6 100644
--- a/packages/app/src/Charcoal/App/Route/TemplateRouteConfig.php
+++ b/packages/app/src/Charcoal/App/Route/TemplateRouteConfig.php
@@ -16,22 +16,19 @@ class TemplateRouteConfig extends RouteConfig
{
/**
* The template ident (to load).
- * @var string|null $template
*/
- private $template;
+ private ?string $template = null;
/**
* The view engine ident to use.
* Ex: "mustache", ""
- * @var string|null $engine
*/
- private $engine;
+ private ?string $engine = null;
/**
* Additional template data.
- * @var array $templateData
*/
- private $templateData = [];
+ private array $templateData = [];
/**
* Redirect URL.
@@ -41,28 +38,25 @@ class TemplateRouteConfig extends RouteConfig
/**
* Redirect Mode (HTTP status code).
- * @var integer $redirectMode
*/
- private $redirectMode = 301;
+ private int $redirectMode = 301;
/**
* Enable route-level caching for this template.
- * @var boolean $cache
*/
- private $cache = false;
+ private bool $cache = false;
/**
* If using cache, the time-to-live, in seconds, of the cache. (0 = no limit).
- * @var integer $cacheTtl
*/
- private $cacheTtl = 0;
+ private int $cacheTtl = 0;
/**
* @param string|null $template The template identifier.
* @throws InvalidArgumentException If the tempalte parameter is not null or not a string.
* @return TemplateRouteConfig Chainable
*/
- public function setTemplate($template)
+ public function setTemplate($template): static
{
if ($template === null) {
$this->template = null;
@@ -80,7 +74,7 @@ public function setTemplate($template)
/**
* @return string
*/
- public function template()
+ public function template(): ?string
{
if ($this->template === null) {
return $this->ident();
@@ -110,7 +104,7 @@ public function defaultController()
* @throws InvalidArgumentException If the engine is not null or not a string.
* @return TemplateRouteConfig Chainable
*/
- public function setEngine($engine)
+ public function setEngine($engine): static
{
if ($engine === null) {
$this->engine = null;
@@ -156,9 +150,9 @@ public function defaultEngine()
* @param array $templateData The route template data.
* @return TemplateRouteConfig Chainable
*/
- public function setTemplateData(array $templateData)
+ public function setTemplateData(array $templateData): static
{
- if (!isset($this->templateData)) {
+ if ($this->templateData === null) {
$this->templateData = [];
}
@@ -169,10 +163,8 @@ public function setTemplateData(array $templateData)
/**
* Get the template data for the view.
- *
- * @return array
*/
- public function templateData()
+ public function templateData(): array
{
return $this->templateData;
}
@@ -181,7 +173,7 @@ public function templateData()
* @param string|string[] $url Points to a route.
* @return TemplateRouteConfig Chainable
*/
- public function setRedirect($url)
+ public function setRedirect($url): static
{
$this->redirect = $url;
@@ -205,7 +197,7 @@ public function redirect()
* @throws InvalidArgumentException If the redirect mode is not 3xx.
* @return TemplateRouteConfig Chainable
*/
- public function setRedirectMode($redirectMode)
+ public function setRedirectMode($redirectMode): static
{
$redirectMode = (int)$redirectMode;
if ($redirectMode < 300 || $redirectMode >= 400) {
@@ -218,10 +210,7 @@ public function setRedirectMode($redirectMode)
return $this;
}
- /**
- * @return integer
- */
- public function redirectMode()
+ public function redirectMode(): int
{
return $this->redirectMode;
}
@@ -230,16 +219,13 @@ public function redirectMode()
* @param boolean $cache The cache enabled flag.
* @return TemplateRouteConfig Chainable
*/
- public function setCache($cache)
+ public function setCache($cache): static
{
- $this->cache = !!$cache;
+ $this->cache = (bool)$cache;
return $this;
}
- /**
- * @return boolean
- */
- public function cache()
+ public function cache(): bool
{
return $this->cache;
}
@@ -248,16 +234,13 @@ public function cache()
* @param integer $ttl The cache Time-To-Live, in seconds.
* @return TemplateRouteConfig Chainable
*/
- public function setCacheTtl($ttl)
+ public function setCacheTtl($ttl): static
{
$this->cacheTtl = intval($ttl);
return $this;
}
- /**
- * @return integer
- */
- public function cacheTtl()
+ public function cacheTtl(): int
{
return $this->cacheTtl;
}
diff --git a/packages/app/src/Charcoal/App/Script/AbstractScript.php b/packages/app/src/Charcoal/App/Script/AbstractScript.php
index 614b39dba..2f8c49415 100644
--- a/packages/app/src/Charcoal/App/Script/AbstractScript.php
+++ b/packages/app/src/Charcoal/App/Script/AbstractScript.php
@@ -30,50 +30,23 @@ abstract class AbstractScript extends AbstractEntity implements
{
use LoggerAwareTrait;
- /**
- * @var string $ident
- */
- private $ident;
+ private ?string $ident = null;
- /**
- * @var string $description
- */
- private $description;
+ private ?string $description = null;
- /**
- * @var array $arguments
- */
- private $arguments;
+ private ?array $arguments = null;
- /**
- * @var CLImate $climate
- */
- private $climate;
+ private \League\CLImate\CLImate $climate;
- /**
- * @var ReaderInterface $cliamteReader
- */
- private $climateReader;
+ private ?\League\CLImate\Util\Reader\ReaderInterface $climateReader = null;
- /**
- * @var boolean $quiet
- */
- private $quiet = false;
+ private bool $quiet = false;
- /**
- * @var boolean $verbose
- */
- private $verbose = false;
+ private bool $verbose = false;
- /**
- * @var boolean $interactive
- */
- private $interactive = false;
+ private bool $interactive = false;
- /**
- * @var boolean $dryRun
- */
- private $dryRun = false;
+ private bool $dryRun = false;
/**
* Return a new CLI script.
@@ -231,7 +204,7 @@ public function description()
*/
public function setQuiet($quiet)
{
- $this->quiet = !!$quiet;
+ $this->quiet = (bool)$quiet;
return $this;
}
@@ -249,7 +222,7 @@ public function quiet()
*/
public function setVerbose($verbose)
{
- $this->verbose = !!$verbose;
+ $this->verbose = (bool)$verbose;
return $this;
}
@@ -267,7 +240,7 @@ public function verbose()
*/
public function setInteractive($interactive)
{
- $this->interactive = !!$interactive;
+ $this->interactive = (bool)$interactive;
return $this;
}
@@ -285,7 +258,7 @@ public function interactive()
*/
public function setDryRun($simulate)
{
- $this->dryRun = !!$simulate;
+ $this->dryRun = (bool)$simulate;
return $this;
}
@@ -434,7 +407,7 @@ protected function argOrInput($argName)
* @throws RuntimeException If a radio or checkbox prompt has no options.
* @return mixed Returns the prompt value.
*/
- protected function input($name)
+ protected function input(string $name)
{
$cli = $this->climate();
$arg = $this->argument($name);
@@ -468,19 +441,15 @@ protected function input($name)
$accept = false;
}
- if (!in_array($type, [ 'confirm', 'checkboxes', 'radio' ])) {
- if (isset($arg['defaultValue'])) {
- $default = $arg['defaultValue'];
-
- if (is_bool($default) || is_null($default)) {
- $default = var_export($default, true);
- }
-
- if ($default && is_string($default) || is_numeric($default)) {
- $pattern = '/[\(\[\<]' . preg_quote($default, '/') . '[\)\]\>]/';
- if (!preg_match($pattern, $prompt)) {
- $prompt .= ' (' . $default . ')';
- }
+ if (!in_array($type, [ 'confirm', 'checkboxes', 'radio' ]) && isset($arg['defaultValue'])) {
+ $default = $arg['defaultValue'];
+ if (is_bool($default) || is_null($default)) {
+ $default = var_export($default, true);
+ }
+ if ($default && is_string($default) || is_numeric($default)) {
+ $pattern = '/[\(\[\<]' . preg_quote($default, '/') . '[\)\]\>]/';
+ if (!preg_match($pattern, (string)$prompt)) {
+ $prompt .= ' (' . $default . ')';
}
}
}
@@ -523,12 +492,8 @@ protected function input($name)
break;
}
- if ($accept) {
- if (isset($arg['acceptValue'])) {
- if (is_array($arg['acceptValue']) || is_callable($arg['acceptValue'])) {
- $input->accept($arg['acceptValue']);
- }
- }
+ if ($accept && isset($arg['acceptValue']) && (is_array($arg['acceptValue']) || is_callable($arg['acceptValue']))) {
+ $input->accept($arg['acceptValue']);
}
if (isset($arg['defaultValue'])) {
@@ -540,18 +505,16 @@ protected function input($name)
/**
* @param CLImate $climate A climate instance.
- * @return void
*/
- private function setClimate(CLImate $climate)
+ private function setClimate(CLImate $climate): void
{
$this->climate = $climate;
}
/**
* @param ReaderInterface $climateReader A climate reader.
- * @return void
*/
- private function setClimateReader(ReaderInterface $climateReader)
+ private function setClimateReader(ReaderInterface $climateReader): void
{
$this->climateReader = $climateReader;
}
diff --git a/packages/app/src/Charcoal/App/Script/ArgScriptTrait.php b/packages/app/src/Charcoal/App/Script/ArgScriptTrait.php
index 8f0dbb00a..c2fe6e98f 100644
--- a/packages/app/src/Charcoal/App/Script/ArgScriptTrait.php
+++ b/packages/app/src/Charcoal/App/Script/ArgScriptTrait.php
@@ -31,7 +31,7 @@ protected function parseAsArray($var, $delimiter = '[\s,]+')
$var = preg_split('#(?useLock = !!$useLock;
+ $this->useLock = (bool)$useLock;
return $this;
}
@@ -40,9 +40,8 @@ public function useLock()
/**
* @throws Exception If the lock file can not be opened or the script is already locked.
- * @return boolean
*/
- public function startLock()
+ public function startLock(): bool
{
$lockFile = $this->getLockFileName();
$this->lockFilePointer = fopen($lockFile, 'w');
@@ -60,10 +59,7 @@ public function startLock()
}
}
- /**
- * @return void
- */
- public function stopLock()
+ public function stopLock(): void
{
if ($this->lockFilePointer) {
flock($this->lockFilePointer, LOCK_UN);
@@ -71,10 +67,7 @@ public function stopLock()
}
}
- /**
- * @return string
- */
- private function getLockFileName()
+ private function getLockFileName(): string
{
$lockName = str_replace('\\', '-', static::class);
$lockName .= md5(__DIR__);
diff --git a/packages/app/src/Charcoal/App/Script/PathScriptTrait.php b/packages/app/src/Charcoal/App/Script/PathScriptTrait.php
index 9b43b7b86..6f267cd1b 100644
--- a/packages/app/src/Charcoal/App/Script/PathScriptTrait.php
+++ b/packages/app/src/Charcoal/App/Script/PathScriptTrait.php
@@ -45,7 +45,7 @@ public function processMultiplePaths($paths)
throw new InvalidArgumentException('Received invalid paths.');
}
- if (empty($paths)) {
+ if ($paths === []) {
throw new InvalidArgumentException('Received empty paths.');
}
@@ -78,13 +78,13 @@ public function pathExists($path)
* @throws InvalidArgumentException If the path is invalid.
* @return string Returns the filtered path.
*/
- public function filterPath($path, $trim = null)
+ public function filterPath($path, $trim = null): string
{
if (!is_string($path)) {
throw new InvalidArgumentException('The path must be a string.');
}
- if ($trim === null && defined(get_called_class() . '::DIRECTORY_SEPARATORS')) {
+ if ($trim === null && defined(static::class . '::DIRECTORY_SEPARATORS')) {
$trim = static::DIRECTORY_SEPARATORS;
}
@@ -111,7 +111,7 @@ public function filterPath($path, $trim = null)
*/
public function filterWritablePath($path, $name = null)
{
- if ($name === null && defined(get_called_class() . '::DEFAULT_BASENAME')) {
+ if ($name === null && defined(static::class . '::DEFAULT_BASENAME')) {
$name = static::DEFAULT_BASENAME;
}
@@ -135,7 +135,7 @@ public function filterWritablePath($path, $name = null)
throw new InvalidArgumentException('The target file is not writeable.');
}
} else {
- $info = pathinfo($path);
+ $info = pathinfo((string)$path);
$path = $this->filterWritablePath($info['dirname'], $info['basename']);
}
@@ -169,7 +169,7 @@ public function globRecursive($pattern, $flags = 0)
}
}
- static::$globCache[$pattern][$depthKey] = array_filter($files, 'is_file');
+ static::$globCache[$pattern][$depthKey] = array_filter($files, is_file(...));
return $files;
}
diff --git a/packages/app/src/Charcoal/App/Script/ScriptInterface.php b/packages/app/src/Charcoal/App/Script/ScriptInterface.php
index 9a9b66ee2..0c6a1873b 100644
--- a/packages/app/src/Charcoal/App/Script/ScriptInterface.php
+++ b/packages/app/src/Charcoal/App/Script/ScriptInterface.php
@@ -1,5 +1,7 @@
register(new CacheServiceProvider());
$container->register(new DatabaseServiceProvider());
@@ -104,13 +103,13 @@ protected function registerKernelServices(Container $container)
* @param Container $container A service container.
* @return boolean
*/
- $container['debug'] = function (Container $container) {
+ $container['debug'] = function (Container $container): bool {
if (isset($container['config']['debug'])) {
- return !!$container['config']['debug'];
+ return (bool)$container['config']['debug'];
}
if (isset($container['config']['dev_mode'])) {
- return !!$container['config']['dev_mode'];
+ return (bool)$container['config']['dev_mode'];
}
return false;
@@ -273,19 +272,17 @@ protected function registerRouteServices(Container $container)
* @param Container $container A service container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['route/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => RouteInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Route',
- ],
- 'arguments' => [
- [
- 'logger' => $container['logger'],
- ],
+ $container['route/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => RouteInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Route',
+ ],
+ 'arguments' => [
+ [
+ 'logger' => $container['logger'],
],
- ]);
- };
+ ],
+ ]));
}
/**
@@ -298,7 +295,7 @@ protected function registerMiddlewareServices(Container $container)
* @param Container $container A service container.
* @return IpMiddleware
*/
- $container['middlewares/charcoal/app/middleware/ip'] = function (container $container) {
+ $container['middlewares/charcoal/app/middleware/ip'] = function (container $container): \Charcoal\App\Middleware\IpMiddleware {
$wareConfig = $container['config']['middlewares']['charcoal/app/middleware/ip'];
return new IpMiddleware($wareConfig);
};
@@ -319,20 +316,18 @@ protected function registerRequestControllerServices(Container $container)
* @param Container $container A service container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['action/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => ActionInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Action',
+ $container['action/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => ActionInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Action',
+ ],
+ 'arguments' => [
+ [
+ 'container' => $container,
+ 'logger' => $container['logger'],
],
- 'arguments' => [
- [
- 'container' => $container,
- 'logger' => $container['logger'],
- ],
- ],
- ]);
- };
+ ],
+ ]));
/**
* The Template Factory service is used to instanciate new templates.
@@ -343,20 +338,18 @@ protected function registerRequestControllerServices(Container $container)
* @param Container $container A service container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['template/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => TemplateInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Template',
- ],
- 'arguments' => [
- [
- 'container' => $container,
- 'logger' => $container['logger'],
- ],
+ $container['template/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => TemplateInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Template',
+ ],
+ 'arguments' => [
+ [
+ 'container' => $container,
+ 'logger' => $container['logger'],
],
- ]);
- };
+ ],
+ ]));
/**
* The Widget Factory service is used to instanciate new widgets.
@@ -367,28 +360,24 @@ protected function registerRequestControllerServices(Container $container)
* @param Container $container A service container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['widget/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => WidgetInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Widget',
+ $container['widget/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => WidgetInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Widget',
+ ],
+ 'arguments' => [
+ [
+ 'container' => $container,
+ 'logger' => $container['logger'],
],
- 'arguments' => [
- [
- 'container' => $container,
- 'logger' => $container['logger'],
- ],
- ],
- ]);
- };
+ ],
+ ]));
/**
* @param Container $container A service container.
* @return WidgetBuilder
*/
- $container['widget/builder'] = function (Container $container) {
- return new WidgetBuilder($container['widget/factory'], $container);
- };
+ $container['widget/builder'] = (fn(Container $container): \Charcoal\App\Template\WidgetBuilder => new WidgetBuilder($container['widget/factory'], $container));
}
/**
@@ -405,19 +394,17 @@ protected function registerModuleServices(Container $container)
* @param Container $container A service container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['module/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => ModuleInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Module',
- ],
- 'arguments' => [
- [
- 'logger' => $container['logger'],
- ],
+ $container['module/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => ModuleInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Module',
+ ],
+ 'arguments' => [
+ [
+ 'logger' => $container['logger'],
],
- ]);
- };
+ ],
+ ]));
/**
* The modules as PHP classes.
@@ -425,7 +412,7 @@ protected function registerModuleServices(Container $container)
* @param Container $container A service container.
* @return array
*/
- $container['module/classes'] = function (Container $container) {
+ $container['module/classes'] = function (Container $container): array {
$appConfig = $container['config'];
$modules = $appConfig['modules'];
@@ -435,13 +422,9 @@ protected function registerModuleServices(Container $container)
'suffix' => 'Module',
]);
- $modules = array_map(function ($module) use ($moduleResolver) {
- return $moduleResolver->resolve($module);
- }, $modules);
+ $modules = array_map($moduleResolver->resolve(...), $modules);
- array_filter($modules, function ($class) {
- return class_exists($class);
- });
+ array_filter($modules, class_exists(...));
return $modules;
};
@@ -462,14 +445,11 @@ protected function registerViewServices(Container $container)
/**
* @param Container $container The DI container.
- * @return void
*/
protected function registerMustacheHelpersServices(Container $container): void
{
if (!isset($container['view/mustache/helpers'])) {
- $container['view/mustache/helpers'] = function () {
- return [];
- };
+ $container['view/mustache/helpers'] = (fn(): array => []);
}
/**
@@ -477,7 +457,7 @@ protected function registerMustacheHelpersServices(Container $container): void
*
* @return array
*/
- $container->extend('view/mustache/helpers', function (array $helpers, Container $container) {
+ $container->extend('view/mustache/helpers', function (array $helpers, Container $container): array {
$baseUrl = $container['base-url'];
$urls = [
/**
@@ -504,34 +484,28 @@ protected function registerMustacheHelpersServices(Container $container): void
* @param string $uri A URI path to wrap.
* @return UriInterface|null
*/
- 'withBaseUrl' => function ($uri, LambdaHelper $helper = null) use ($baseUrl) {
- if ($helper) {
+ 'withBaseUrl' => function ($uri, ?LambdaHelper $helper = null) use ($baseUrl) {
+ if ($helper instanceof LambdaHelper) {
$uri = $helper->render($uri);
}
-
$uri = strval($uri);
if ($uri === '') {
$uri = $baseUrl->withPath('');
} else {
$parts = parse_url($uri);
- if (!isset($parts['scheme'])) {
- if (!in_array($uri[0], [ '/', '#', '?' ])) {
- $path = isset($parts['path']) ? $parts['path'] : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
-
- $uri = $baseUrl->withPath($path)
- ->withQuery($query)
- ->withFragment($hash);
- }
+ if (!isset($parts['scheme']) && !in_array($uri[0], [ '/', '#', '?' ])) {
+ $path = ($parts['path'] ?? '');
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
+ $uri = $baseUrl->withPath($path)
+ ->withQuery($query)
+ ->withFragment($hash);
}
}
- return $uri;
- },
- 'renderContext' => function ($text, LambdaHelper $helper = null) {
- return $helper->render('{{>' . $helper->render($text) . '}}');
+ return (string)$uri;
},
+ 'renderContext' => fn($text, ?LambdaHelper $helper = null) => $helper->render('{{>' . $helper->render($text) . '}}'),
];
return array_merge($helpers, $urls);
@@ -540,14 +514,11 @@ protected function registerMustacheHelpersServices(Container $container): void
/**
* @param Container $container The DI container.
- * @return void
*/
protected function registerTwigHelpersServices(Container $container): void
{
if (!isset($container['view/twig/helpers'])) {
- $container['view/twig/helpers'] = function () {
- return [];
- };
+ $container['view/twig/helpers'] = (fn(): array => []);
}
/**
@@ -555,22 +526,18 @@ protected function registerTwigHelpersServices(Container $container): void
*
* @return TwigUrlHelpers
*/
- $container['view/twig/helpers/url'] = function (Container $container): TwigHelpersInterface {
- return new TwigUrlHelpers([
- 'baseUrl' => $container['base-url'],
- ]);
- };
+ $container['view/twig/helpers/url'] = (fn(Container $container): TwigHelpersInterface => new TwigUrlHelpers([
+ 'baseUrl' => $container['base-url'],
+ ]));
/**
* Debug helpers for Twig.
*
* @return TwigDebugHelpers
*/
- $container['view/twig/helpers/debug'] = function (Container $container): TwigHelpersInterface {
- return new TwigDebugHelpers([
- 'debug' => $container['debug'],
- ]);
- };
+ $container['view/twig/helpers/debug'] = (fn(Container $container): TwigHelpersInterface => new TwigDebugHelpers([
+ 'debug' => $container['debug'],
+ ]));
/**
* Extend global helpers for the Twig Engine.
@@ -579,12 +546,10 @@ protected function registerTwigHelpersServices(Container $container): void
* @param Container $container A container instance.
* @return array
*/
- $container->extend('view/twig/helpers', function (array $helpers, Container $container): array {
- return array_merge(
- $helpers,
- $container['view/twig/helpers/url']->toArray(),
- $container['view/twig/helpers/debug']->toArray(),
- );
- });
+ $container->extend('view/twig/helpers', fn(array $helpers, Container $container): array => array_merge(
+ $helpers,
+ $container['view/twig/helpers/url']->toArray(),
+ $container['view/twig/helpers/debug']->toArray(),
+ ));
}
}
diff --git a/packages/app/src/Charcoal/App/ServiceProvider/DatabaseServiceProvider.php b/packages/app/src/Charcoal/App/ServiceProvider/DatabaseServiceProvider.php
index fb1f6c3ab..ab723b96b 100644
--- a/packages/app/src/Charcoal/App/ServiceProvider/DatabaseServiceProvider.php
+++ b/packages/app/src/Charcoal/App/ServiceProvider/DatabaseServiceProvider.php
@@ -32,15 +32,14 @@ class DatabaseServiceProvider implements ServiceProviderInterface
* It should not get services.
*
* @param Container $container A service container.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
/**
* @param Container $container A service container.
* @return Container A map of database configsets.
*/
- $container['databases/config'] = function (Container $container) {
+ $container['databases/config'] = function (Container $container): \Pimple\Container {
$databases = ($container['config']['databases'] ?? []);
$configs = new Container();
@@ -48,9 +47,7 @@ public function register(Container $container)
/**
* @return DatabaseConfig
*/
- $configs[$dbIdent] = function () use ($dbOptions) {
- return new DatabaseConfig($dbOptions);
- };
+ $configs[$dbIdent] = (fn(): \Charcoal\App\Config\DatabaseConfig => new DatabaseConfig($dbOptions));
}
return $configs;
@@ -60,7 +57,7 @@ public function register(Container $container)
* @param Container $container A service container.
* @return Container A map of database handlers.
*/
- $container['databases'] = function (Container $container) {
+ $container['databases'] = function (Container $container): \Pimple\Container {
$databases = ($container['config']['databases'] ?? []);
$dbs = new Container();
@@ -68,7 +65,7 @@ public function register(Container $container)
/**
* @return PDO
*/
- $dbs[$dbIdent] = function () use ($dbIdent, $container) {
+ $dbs[$dbIdent] = function () use ($dbIdent, $container): \PDO {
$dbConfig = $container['databases/config'][$dbIdent];
$type = $dbConfig['type'];
@@ -80,23 +77,19 @@ public function register(Container $container)
// Set UTf-8 compatibility by default. Disable it if it is set as such in config
$extraOptions = null;
- if (!isset($dbConfig['disable_utf8']) || !$dbConfig['disable_utf8']) {
+ if ($type !== 'sqlite' && (!isset($dbConfig['disable_utf8']) || !$dbConfig['disable_utf8'])) {
$extraOptions = [
- PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
+ \Pdo\Mysql::ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
];
}
- if ($type === 'sqlite') {
- $dsn = $type . ':' . $database;
- } else {
- $dsn = $type . ':host=' . $host . ';dbname=' . $database;
- }
+ $dsn = $type === 'sqlite' ? $type . ':' . $database : $type . ':host=' . $host . ';dbname=' . $database;
$db = new PDO($dsn, $username, $password, $extraOptions);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($type === 'mysql') {
- $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
+ $db->setAttribute(\Pdo\Mysql::ATTR_USE_BUFFERED_QUERY, true);
}
return $db;
diff --git a/packages/app/src/Charcoal/App/ServiceProvider/FilesystemServiceProvider.php b/packages/app/src/Charcoal/App/ServiceProvider/FilesystemServiceProvider.php
index 48b93ae39..2b050c6ba 100644
--- a/packages/app/src/Charcoal/App/ServiceProvider/FilesystemServiceProvider.php
+++ b/packages/app/src/Charcoal/App/ServiceProvider/FilesystemServiceProvider.php
@@ -33,15 +33,14 @@ class FilesystemServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container A service container.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
/**
* @param Container $container A service container.
* @return FilesystemConfig
*/
- $container['filesystem/config'] = function (Container $container) {
+ $container['filesystem/config'] = function (Container $container): \Charcoal\App\Config\FilesystemConfig {
$fsConfig = ($container['config']['filesystem'] ?? null);
return new FilesystemConfig($fsConfig);
};
@@ -50,15 +49,13 @@ public function register(Container $container)
* @param Container $container A service container.
* @return MountManager
*/
- $container['filesystem/manager'] = function () {
- return new MountManager();
- };
+ $container['filesystem/manager'] = (fn(): \League\Flysystem\MountManager => new MountManager());
/**
* @param Container $container A service container.
* @return array
*/
- $container['filesystems'] = function (Container $container) {
+ $container['filesystems'] = function (Container $container): \Pimple\Container {
$filesystemConfig = $container['filesystem/config'];
$filesystems = new Container();
@@ -77,9 +74,8 @@ public function register(Container $container)
* @param Container $container A service container.
* @throws Exception If the filesystem type is not defined in config.
* @throws UnexpectedValueException If the filesystem type is invalid / unsupported.
- * @return Filesystem
*/
- private function createConnection(array $config, Container $container)
+ private function createConnection(array $config, Container $container): \League\Flysystem\Filesystem
{
if (!isset($config['type'])) {
throw new Exception(
@@ -89,36 +85,17 @@ private function createConnection(array $config, Container $container)
$type = $config['type'];
- switch ($type) {
- case 'local':
- $adapter = $this->createLocalAdapter($config, $container);
- break;
-
- case 's3':
- $adapter = $this->createS3Adapter($config);
- break;
-
- case 'ftp':
- $adapter = $this->createFtpAdapter($config);
- break;
-
- case 'sftp':
- $adapter = $this->createSftpAdapter($config);
- break;
-
- case 'memory':
- $adapter = $this->createMemoryAdapter();
- break;
-
- case 'noop':
- $adapter = $this->createNullAdapter();
- break;
-
- default:
- throw new UnexpectedValueException(
- sprintf('Invalid filesystem type "%s"', $type)
- );
- }
+ $adapter = match ($type) {
+ 'local' => $this->createLocalAdapter($config, $container),
+ 's3' => $this->createS3Adapter($config),
+ 'ftp' => $this->createFtpAdapter($config),
+ 'sftp' => $this->createSftpAdapter($config),
+ 'memory' => $this->createMemoryAdapter(),
+ 'noop' => $this->createNullAdapter(),
+ default => throw new UnexpectedValueException(
+ sprintf('Invalid filesystem type "%s"', $type)
+ ),
+ };
return new Filesystem($adapter);
}
@@ -127,9 +104,8 @@ private function createConnection(array $config, Container $container)
* @param array $config The driver (adapter) configuration.
* @param Container $container A service container.
* @throws InvalidArgumentException If the path is not defined.
- * @return LocalAdapter
*/
- private function createLocalAdapter(array $config, Container $container)
+ private function createLocalAdapter(array $config, Container $container): \League\Flysystem\Adapter\Local
{
if (empty($config['path'])) {
throw new InvalidArgumentException(
@@ -138,10 +114,8 @@ private function createLocalAdapter(array $config, Container $container)
}
$path = $config['path'];
- if (is_string($path)) {
- if (isset($container['config']) && ($container['config'] instanceof AppConfig)) {
- $path = $container['config']->resolveValue($path);
- }
+ if (is_string($path) && (isset($container['config']) && $container['config'] instanceof AppConfig)) {
+ $path = $container['config']->resolveValue($path);
}
$defaults = [
@@ -157,9 +131,8 @@ private function createLocalAdapter(array $config, Container $container)
/**
* @param array $config The driver (adapter) configuration.
* @throws InvalidArgumentException If the key, secret or bucket is not defined in config.
- * @return AwsS3Adapter
*/
- private function createS3Adapter(array $config)
+ private function createS3Adapter(array $config): \League\Flysystem\AwsS3v3\AwsS3Adapter
{
if (!isset($config['key']) || !$config['key']) {
throw new InvalidArgumentException(
@@ -195,13 +168,9 @@ private function createS3Adapter(array $config)
'version' => $config['version'],
]);
- if (isset($config['public']) && !$config['public']) {
- $permissions = null;
- } else {
- $permissions = [
- 'ACL' => 'public-read',
- ];
- }
+ $permissions = isset($config['public']) && !$config['public'] ? null : [
+ 'ACL' => 'public-read',
+ ];
return new AwsS3Adapter($client, $config['bucket'], $config['prefix'], $permissions);
}
@@ -209,9 +178,8 @@ private function createS3Adapter(array $config)
/**
* @param array $config The driver (adapter) configuration.
* @throws InvalidArgumentException If the host, username or password is not defined in config.
- * @return FtpAdapter
*/
- private function createFtpAdapter(array $config)
+ private function createFtpAdapter(array $config): \League\Flysystem\Adapter\Ftp
{
if (!$config['host']) {
throw new InvalidArgumentException(
@@ -246,9 +214,8 @@ private function createFtpAdapter(array $config)
/**
* @param array $config The driver (adapter) configuration.
* @throws InvalidArgumentException If the host, username or password is not defined in config.
- * @return SftpAdapter
*/
- private function createSftpAdapter(array $config)
+ private function createSftpAdapter(array $config): \League\Flysystem\Sftp\SftpAdapter
{
if (!$config['host']) {
throw new InvalidArgumentException(
@@ -279,18 +246,12 @@ private function createSftpAdapter(array $config)
return new SftpAdapter($config);
}
- /**
- * @return MemoryAdapter
- */
- private function createMemoryAdapter()
+ private function createMemoryAdapter(): \League\Flysystem\Memory\MemoryAdapter
{
return new MemoryAdapter();
}
- /**
- * @return NullAdapter
- */
- private function createNullAdapter()
+ private function createNullAdapter(): \League\Flysystem\Adapter\NullAdapter
{
return new NullAdapter();
}
diff --git a/packages/app/src/Charcoal/App/ServiceProvider/LoggerServiceProvider.php b/packages/app/src/Charcoal/App/ServiceProvider/LoggerServiceProvider.php
index ee36758b3..3f4113899 100644
--- a/packages/app/src/Charcoal/App/ServiceProvider/LoggerServiceProvider.php
+++ b/packages/app/src/Charcoal/App/ServiceProvider/LoggerServiceProvider.php
@@ -44,15 +44,14 @@ class LoggerServiceProvider implements ServiceProviderInterface
* It should not get services.
*
* @param Container $container A service container.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
/**
* @param Container $container A service container.
* @return LoggerConfig
*/
- $container['logger/config'] = function (Container $container) {
+ $container['logger/config'] = function (Container $container): \Charcoal\App\Config\LoggerConfig {
$loggerConfig = ($container['config']['logger'] ?? null);
return new LoggerConfig($loggerConfig);
};
@@ -62,7 +61,7 @@ public function register(Container $container)
* @throws InvalidArgumentException If the path is not defined or invalid.
* @return StreamHandler|null
*/
- $container['logger/handler/stream'] = function (Container $container) {
+ $container['logger/handler/stream'] = function (Container $container): ?\Monolog\Handler\StreamHandler {
$loggerConfig = $container['logger/config'];
$handlerConfig = $loggerConfig['handlers.stream'];
@@ -77,10 +76,8 @@ public function register(Container $container)
}
$stream = $handlerConfig['stream'];
- if (is_string($stream)) {
- if (isset($container['config']) && ($container['config'] instanceof AppConfig)) {
- $stream = $container['config']->resolveValue($stream);
- }
+ if (is_string($stream) && (isset($container['config']) && $container['config'] instanceof AppConfig)) {
+ $stream = $container['config']->resolveValue($stream);
}
$level = $handlerConfig['level'] ?: $loggerConfig['level'];
@@ -91,7 +88,7 @@ public function register(Container $container)
* @param Container $container A service container.
* @return BrowserConsoleHandler|null
*/
- $container['logger/handler/browser-console'] = function (Container $container) {
+ $container['logger/handler/browser-console'] = function (Container $container): ?\Monolog\Handler\BrowserConsoleHandler {
$loggerConfig = $container['logger/config'];
$handlerConfig = $loggerConfig['handlers.console'];
@@ -109,7 +106,7 @@ public function register(Container $container)
* @param Container $container A service container.
* @return LoggerInterface
*/
- $container['logger'] = function (Container $container) {
+ $container['logger'] = function (Container $container): \Psr\Log\NullLogger|\Monolog\Logger {
$loggerConfig = $container['logger/config'];
if ($loggerConfig['active'] !== true) {
diff --git a/packages/app/src/Charcoal/App/ServiceProvider/ScriptServiceProvider.php b/packages/app/src/Charcoal/App/ServiceProvider/ScriptServiceProvider.php
index a7c0ec6f2..73dda4365 100644
--- a/packages/app/src/Charcoal/App/ServiceProvider/ScriptServiceProvider.php
+++ b/packages/app/src/Charcoal/App/ServiceProvider/ScriptServiceProvider.php
@@ -1,5 +1,7 @@
ScriptInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Script',
- ],
- 'arguments' => [
- [
- 'container' => $container,
- 'logger' => $container['logger'],
- 'climate' => $container['script/climate'],
- 'climate_reader' => $container['script/climate/reader'],
- ],
+ $container['script/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => ScriptInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Script',
+ ],
+ 'arguments' => [
+ [
+ 'container' => $container,
+ 'logger' => $container['logger'],
+ 'climate' => $container['script/climate'],
+ 'climate_reader' => $container['script/climate/reader'],
],
- ]);
- };
+ ],
+ ]));
}
/**
* @param Container $container A service container.
- * @return void
*/
- private function registerClimate(Container $container)
+ private function registerClimate(Container $container): void
{
/**
* @param Container $container A service container.
* @return \League\CLImate\Util\Reader\ReaderInterface|null
*/
- $container['script/climate/reader'] = function () {
- return null;
- };
+ $container['script/climate/reader'] = (fn(): null => null);
/**
* @param Container $container A service container.
* @return CLImate
*/
- $container['script/climate'] = function () {
- $climate = new CLImate();
- return $climate;
- };
+ $container['script/climate'] = (fn(): \League\CLImate\CLImate => new CLImate());
}
}
diff --git a/packages/app/src/Charcoal/App/Template/AbstractTemplate.php b/packages/app/src/Charcoal/App/Template/AbstractTemplate.php
index 1d156e67e..09a4bb19b 100644
--- a/packages/app/src/Charcoal/App/Template/AbstractTemplate.php
+++ b/packages/app/src/Charcoal/App/Template/AbstractTemplate.php
@@ -49,14 +49,14 @@ public function __construct($data = null)
*/
public function templateName()
{
- $key = substr(strrchr('\\' . get_class($this), '\\'), 1);
+ $key = substr(strrchr('\\' . static::class, '\\'), 1);
if (!isset(static::$templateNameCache[$key])) {
$value = $key;
if (!ctype_lower($value)) {
$value = preg_replace('/\s+/u', '', $value);
- $value = mb_strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1-', $value), 'UTF-8');
+ $value = mb_strtolower((string)preg_replace('/(.)(?=[A-Z])/u', '$1-', (string)$value), 'UTF-8');
}
$value = str_replace(
diff --git a/packages/app/src/Charcoal/App/Template/AbstractWidget.php b/packages/app/src/Charcoal/App/Template/AbstractWidget.php
index 2721ee557..a63fa545e 100644
--- a/packages/app/src/Charcoal/App/Template/AbstractWidget.php
+++ b/packages/app/src/Charcoal/App/Template/AbstractWidget.php
@@ -26,10 +26,7 @@ abstract class AbstractWidget extends AbstractEntity implements
use LoggerAwareTrait;
use ViewableTrait;
- /**
- * @var boolean $active
- */
- private $active = true;
+ private bool $active = true;
/**
* @param array|\ArrayAccess $data Optional dependencies.
@@ -49,7 +46,7 @@ public function __construct($data = null)
*/
public function setActive($active)
{
- $this->active = !!$active;
+ $this->active = (bool)$active;
return $this;
}
diff --git a/packages/app/src/Charcoal/App/Template/GenericTemplate.php b/packages/app/src/Charcoal/App/Template/GenericTemplate.php
index 3a9d77ba5..cf5c7d1bc 100644
--- a/packages/app/src/Charcoal/App/Template/GenericTemplate.php
+++ b/packages/app/src/Charcoal/App/Template/GenericTemplate.php
@@ -1,5 +1,7 @@
factory = $factory;
- $this->container = $container;
}
/**
diff --git a/packages/app/src/Charcoal/App/Template/WidgetInterface.php b/packages/app/src/Charcoal/App/Template/WidgetInterface.php
index 23afe7e5b..3ec065347 100644
--- a/packages/app/src/Charcoal/App/Template/WidgetInterface.php
+++ b/packages/app/src/Charcoal/App/Template/WidgetInterface.php
@@ -1,5 +1,7 @@
container();
- $this->obj = $this->getMockForAbstractClass(AbstractAction::class, [[
+ $this->obj = new class ([
'logger' => $container['logger'],
'container' => $container
- ]]);
+ ]) extends AbstractAction {
+ public function results()
+ {
+ return ''; // Works for both JSON and XML
+ }
+
+ public function run(RequestInterface $request, ResponseInterface $response)
+ {
+ return $response;
+ }
+ };
}
- public function testSetData()
+ public function testSetData(): void
{
$ret = $this->obj->setData([
'mode' => 'redirect',
@@ -63,7 +70,7 @@ public function testSetData()
$this->assertEquals('fail', $this->obj->failureUrl());
}
- public function testSetMode()
+ public function testSetMode(): void
{
$this->assertEquals('json', $this->obj->mode());
$ret = $this->obj->setMode('redirect');
@@ -74,7 +81,7 @@ public function testSetMode()
$this->obj->setMode(false);
}
- public function testSetSuccess()
+ public function testSetSuccess(): void
{
$ret = $this->obj->setSuccess(false);
$this->assertSame($ret, $this->obj);
@@ -86,7 +93,7 @@ public function testSetSuccess()
$this->assertTrue($this->obj->success());
}
- public function testSuccessUrl()
+ public function testSuccessUrl(): void
{
$this->assertEquals('', $this->obj->successUrl());
$ret = $this->obj->setSuccessUrl('foo');
@@ -99,7 +106,7 @@ public function testSuccessUrl()
$this->obj->setSuccessUrl([]);
}
- public function testSetFailureUrl()
+ public function testSetFailureUrl(): void
{
$this->assertEquals('', $this->obj->failureUrl());
$ret = $this->obj->setFailureUrl('foo');
@@ -112,7 +119,7 @@ public function testSetFailureUrl()
$this->obj->setFailureUrl([]);
}
- public function testRedirectUrlSuccess()
+ public function testRedirectUrlSuccess(): void
{
$this->obj->setData([
'failure_url' => 'fail',
@@ -130,30 +137,22 @@ public function testRedirectUrlSuccess()
*
* For this, the `run` method must be added as public in the mock object.
*/
- public function testInvokable()
+ public function testInvokable(): void
{
- $request = $this->createMock(RequestInterface::class);
+ $request = $this->createStub(RequestInterface::class);
$response = new Response();
- $this->obj->expects($this->any())
- ->method('run')
- ->will($this->returnValue($response));
-
$obj = $this->obj;
$res = $obj($request, $response);
$this->assertInstanceOf(Response::class, $res);
}
- public function testDefaultModeisJson()
+ public function testDefaultModeisJson(): void
{
- $request = $this->createMock(RequestInterface::class);
+ $request = $this->createStub(RequestInterface::class);
$response = new Response();
- $this->obj->expects($this->any())
- ->method('run')
- ->will($this->returnValue($response));
-
$obj = $this->obj;
$res = $obj($request, $response);
@@ -161,15 +160,11 @@ public function testDefaultModeisJson()
$this->assertEquals('application/json', $headers['Content-Type'][0]);
}
- public function testInvokeModeJson()
+ public function testInvokeModeJson(): void
{
- $request = $this->createMock(RequestInterface::class);
+ $request = $this->createStub(RequestInterface::class);
$response = new Response();
- $this->obj->expects($this->any())
- ->method('run')
- ->will($this->returnValue($response));
-
$this->obj->setMode('json');
$obj = $this->obj;
$res = $obj($request, $response);
@@ -178,15 +173,11 @@ public function testInvokeModeJson()
$this->assertEquals('application/json', $headers['Content-Type'][0]);
}
- public function testInvokeModeXml()
+ public function testInvokeModeXml(): void
{
- $request = $this->createMock(RequestInterface::class);
+ $request = $this->createStub(RequestInterface::class);
$response = new Response();
- $this->obj->expects($this->any())
- ->method('run')
- ->will($this->returnValue($response));
-
$this->obj->setMode('xml');
$obj = $this->obj;
$res = $obj($request, $response);
@@ -195,15 +186,11 @@ public function testInvokeModeXml()
$this->assertEquals('text/xml', $headers['Content-Type'][0]);
}
- public function testInvokeModeRedirect()
+ public function testInvokeModeRedirect(): void
{
- $request = $this->createMock(RequestInterface::class);
+ $request = $this->createStub(RequestInterface::class);
$response = new Response();
- $this->obj->expects($this->any())
- ->method('run')
- ->will($this->returnValue($response));
-
$this->obj->setMode('redirect');
$this->obj->setFailureUrl('example.com');
$obj = $this->obj;
@@ -215,20 +202,18 @@ public function testInvokeModeRedirect()
$this->assertEquals('example.com', $headers['Location'][0]);
}
- public function testInitIsTrue()
+ public function testInitIsTrue(): void
{
- $request = $this->createMock(RequestInterface::class);
+ $request = $this->createStub(RequestInterface::class);
$this->assertTrue($this->obj->init($request));
}
/**
* Set up the service container.
- *
- * @return Container
*/
- private function container()
+ private function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerLogger($container);
diff --git a/packages/app/tests/Charcoal/App/AppConfigTest.php b/packages/app/tests/Charcoal/App/AppConfigTest.php
index b699bd4d9..7047f7255 100644
--- a/packages/app/tests/Charcoal/App/AppConfigTest.php
+++ b/packages/app/tests/Charcoal/App/AppConfigTest.php
@@ -1,5 +1,7 @@
assertInstanceOf(AppConfig::class, $obj);
diff --git a/packages/app/tests/Charcoal/App/AppTest.php b/packages/app/tests/Charcoal/App/AppTest.php
index 65984146d..6d150b1db 100644
--- a/packages/app/tests/Charcoal/App/AppTest.php
+++ b/packages/app/tests/Charcoal/App/AppTest.php
@@ -1,5 +1,7 @@
obj = new App($container);
}
- public function testAppIsConstructed()
+ public function testAppIsConstructed(): void
{
$app = new App();
$this->assertInstanceOf(App::class, $app);
}
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(App::class, $this->obj);
}
- public function testRun()
+ public function testRun(): void
{
$res = $this->obj->run(true);
$this->assertInstanceOf(ResponseInterface::class, $res);
diff --git a/packages/app/tests/Charcoal/App/Config/DatabaseConfigTest.php b/packages/app/tests/Charcoal/App/Config/DatabaseConfigTest.php
index 980014fe5..9b9475041 100644
--- a/packages/app/tests/Charcoal/App/Config/DatabaseConfigTest.php
+++ b/packages/app/tests/Charcoal/App/Config/DatabaseConfigTest.php
@@ -17,7 +17,7 @@ public function setUp(): void
$this->obj = new DatabaseConfig();
}
- public function testDefaults()
+ public function testDefaults(): void
{
$this->assertEquals('mysql', $this->obj->type());
$this->assertEquals('localhost', $this->obj->hostname());
@@ -26,7 +26,7 @@ public function testDefaults()
$this->assertFalse($this->obj->disableUtf8());
}
- public function testSetType()
+ public function testSetType(): void
{
$ret = $this->obj->setType('sqlite');
$this->assertSame($ret, $this->obj);
@@ -36,7 +36,7 @@ public function testSetType()
$this->obj->setType([]);
}
- public function testSetHostname()
+ public function testSetHostname(): void
{
$ret = $this->obj->setHostname('foo');
$this->assertSame($ret, $this->obj);
@@ -46,7 +46,7 @@ public function testSetHostname()
$this->obj->setHostname([]);
}
- public function testSetUsername()
+ public function testSetUsername(): void
{
$ret = $this->obj->setUsername('foobar');
$this->assertSame($ret, $this->obj);
@@ -56,7 +56,7 @@ public function testSetUsername()
$this->obj->setUsername([]);
}
- public function testSetPassword()
+ public function testSetPassword(): void
{
$ret = $this->obj->setPassword('baz');
$this->assertSame($ret, $this->obj);
@@ -66,7 +66,7 @@ public function testSetPassword()
$this->obj->setPassword([]);
}
- public function testSetDatabase()
+ public function testSetDatabase(): void
{
$ret = $this->obj->setDatabase('barbaz');
$this->assertSame($ret, $this->obj);
@@ -76,7 +76,7 @@ public function testSetDatabase()
$this->obj->setDatabase([]);
}
- public function testSetDIsableUtf8()
+ public function testSetDIsableUtf8(): void
{
$ret = $this->obj->setDIsableUtf8(true);
$this->assertSame($ret, $this->obj);
diff --git a/packages/app/tests/Charcoal/App/Config/FilesystemConfigTest.php b/packages/app/tests/Charcoal/App/Config/FilesystemConfigTest.php
index 1c8357bab..5f0a4cc02 100644
--- a/packages/app/tests/Charcoal/App/Config/FilesystemConfigTest.php
+++ b/packages/app/tests/Charcoal/App/Config/FilesystemConfigTest.php
@@ -17,7 +17,7 @@ public function setUp(): void
$this->obj = new FilesystemConfig();
}
- public function testDefaultConnections()
+ public function testDefaultConnections(): void
{
$this->assertArrayHasKey('private', $this->obj->defaultConnections());
$this->assertArrayHasKey('public', $this->obj->defaultConnections());
@@ -26,7 +26,7 @@ public function testDefaultConnections()
$this->assertArrayHasKey('public', $this->obj->connections());
}
- public function testConnectionsAlwaysHaveDefaultConnections()
+ public function testConnectionsAlwaysHaveDefaultConnections(): void
{
$this->obj->setData([
'connections' => [
diff --git a/packages/app/tests/Charcoal/App/Config/LoggerConfigTest.php b/packages/app/tests/Charcoal/App/Config/LoggerConfigTest.php
index 3a71a17e6..8d71ac2b3 100644
--- a/packages/app/tests/Charcoal/App/Config/LoggerConfigTest.php
+++ b/packages/app/tests/Charcoal/App/Config/LoggerConfigTest.php
@@ -25,7 +25,7 @@ public function setUp(): void
$this->obj = new LoggerConfig();
}
- public function testDefaults()
+ public function testDefaults(): void
{
$this->assertEquals('charcoal', LoggerConfig::DEFAULT_CHANNEL);
@@ -46,14 +46,14 @@ public function testDefaults()
$this->assertEquals(LoggerConfig::DEFAULT_CHANNEL, $this->obj->channel());
}
- public function testSetActive()
+ public function testSetActive(): void
{
$ret = $this->obj->setActive(false);
$this->assertSame($ret, $this->obj);
$this->assertFalse($this->obj->active());
}
- public function testSetHandlers()
+ public function testSetHandlers(): void
{
$ret = $this->obj->setHandlers([ 'errlog' => [ 'type' => 'error-log' ], [ 'type' => 'mail' ] ]);
$this->assertSame($ret, $this->obj);
@@ -68,7 +68,7 @@ public function testSetHandlers()
$this->obj->setHandlers([ [ 'foo' => 'baz' ] ]);
}
- public function testSetProcessors()
+ public function testSetProcessors(): void
{
$ret = $this->obj->setProcessors([ 'web' => [ 'type' => 'web' ], [ 'type' => 'process-id' ] ]);
$this->assertSame($ret, $this->obj);
@@ -83,7 +83,7 @@ public function testSetProcessors()
$this->obj->setProcessors([ [ 'foo' => 'baz' ] ]);
}
- public function testSetChannel()
+ public function testSetChannel(): void
{
$ret = $this->obj->setChannel('foo');
$this->assertSame($ret, $this->obj);
diff --git a/packages/app/tests/Charcoal/App/ContainerProvider.php b/packages/app/tests/Charcoal/App/ContainerProvider.php
index f4286074c..cb24697d5 100644
--- a/packages/app/tests/Charcoal/App/ContainerProvider.php
+++ b/packages/app/tests/Charcoal/App/ContainerProvider.php
@@ -59,9 +59,8 @@ class ContainerProvider
* Register the unit tests required services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseServices(Container $container)
+ public function registerBaseServices(Container $container): void
{
$this->registerConfig($container);
$this->registerBaseUrl($container);
@@ -74,57 +73,47 @@ public function registerBaseServices(Container $container)
* Setup the application's base URI.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseUrl(Container $container)
+ public function registerBaseUrl(Container $container): void
{
- $container['base-url'] = function (Container $container) {
- return Uri::createFromString('https://example.com:8080/foo/bar?abc=123');
- };
+ $container['base-url'] = (fn(Container $container) => Uri::createFromString('https://example.com:8080/foo/bar?abc=123'));
}
/**
* Setup the application configset.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerConfig(Container $container)
+ public function registerConfig(Container $container): void
{
- $container['config'] = function (Container $container) {
- return new AppConfig([
- 'base_path' => realpath(__DIR__ . '/../../..'),
- ]);
- };
+ $container['config'] = (fn(Container $container): \Charcoal\App\AppConfig => new AppConfig([
+ 'base_path' => realpath(__DIR__ . '/../../..'),
+ ]));
}
- public function registerWidgetFactory(Container $container)
+ public function registerWidgetFactory(Container $container): void
{
$this->registerLogger($container);
- $container['widget/factory'] = function (Container $container) {
- return new Factory([
- 'resolver_options' => [
- 'suffix' => 'Widget'
- ],
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger']
- ]]
- ]);
- };
+ $container['widget/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'resolver_options' => [
+ 'suffix' => 'Widget'
+ ],
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger']
+ ]]
+ ]));
}
- public function registerWidgetBuilder(Container $container)
+ public function registerWidgetBuilder(Container $container): void
{
$this->registerWidgetFactory($container);
- $container['widget/builder'] = function (Container $container) {
- return new WidgetBuilder($container['widget/factory'], $container);
- };
+ $container['widget/builder'] = (fn(Container $container): \Charcoal\App\Template\WidgetBuilder => new WidgetBuilder($container['widget/factory'], $container));
}
- public function registerClimate(Container $container)
+ public function registerClimate(Container $container): void
{
$container['climate/system'] = function (Container $container) {
$system = Mockery::mock(Linux::class);
@@ -151,11 +140,9 @@ public function registerClimate(Container $container)
return $reader;
};
- $container['climate/util'] = function (Container $container) {
- return new UtilFactory($container['climate/system']);
- };
+ $container['climate/util'] = (fn(Container $container): \League\CLImate\Util\UtilFactory => new UtilFactory($container['climate/system']));
- $container['climate'] = function (Container $container) {
+ $container['climate'] = function (Container $container): \League\CLImate\CLImate {
$climate = new CLImate();
$climate->setOutput($container['climate/output']);
@@ -170,162 +157,136 @@ public function registerClimate(Container $container)
* Setup the framework's view renderer.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerView(Container $container)
+ public function registerView(Container $container): void
{
- $container['view/loader'] = function (Container $container) {
- return new MustacheLoader([
- 'logger' => $container['logger'],
- 'base_path' => $container['config']['base_path'],
- 'paths' => [
- 'views'
- ]
- ]);
- };
-
- $container['view/engine'] = function (Container $container) {
- return new MustacheEngine([
- 'logger' => $container['logger'],
- 'cache' => MustacheEngine::DEFAULT_CACHE_PATH,
- 'loader' => $container['view/loader']
- ]);
- };
-
- $container['view'] = function (Container $container) {
- return new GenericView([
- 'logger' => $container['logger'],
- 'engine' => $container['view/engine']
- ]);
- };
+ $container['view/loader'] = (fn(Container $container): \Charcoal\View\Mustache\MustacheLoader => new MustacheLoader([
+ 'logger' => $container['logger'],
+ 'base_path' => $container['config']['base_path'],
+ 'paths' => [
+ 'views'
+ ]
+ ]));
+
+ $container['view/engine'] = (fn(Container $container): \Charcoal\View\Mustache\MustacheEngine => new MustacheEngine([
+ 'logger' => $container['logger'],
+ 'cache' => MustacheEngine::DEFAULT_CACHE_PATH,
+ 'loader' => $container['view/loader']
+ ]));
+
+ $container['view'] = (fn(Container $container): \Charcoal\View\GenericView => new GenericView([
+ 'logger' => $container['logger'],
+ 'engine' => $container['view/engine']
+ ]));
}
/**
* Setup the application's translator service.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerTranslator(Container $container)
+ public function registerTranslator(Container $container): void
{
- $container['locales/manager'] = function (Container $container) {
- return new LocalesManager([
- 'locales' => [
- 'en' => [ 'locale' => 'en-US' ]
- ]
- ]);
- };
-
- $container['translator'] = function (Container $container) {
- return new Translator([
- 'manager' => $container['locales/manager']
- ]);
- };
+ $container['locales/manager'] = (fn(Container $container): \Charcoal\Translator\LocalesManager => new LocalesManager([
+ 'locales' => [
+ 'en' => [ 'locale' => 'en-US' ]
+ ]
+ ]));
+
+ $container['translator'] = (fn(Container $container): \Charcoal\Translator\Translator => new Translator([
+ 'manager' => $container['locales/manager']
+ ]));
}
/**
* Setup the application's logging interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerLogger(Container $container)
+ public function registerLogger(Container $container): void
{
- $container['logger'] = function (Container $container) {
- return new NullLogger();
- };
+ $container['logger'] = (fn(Container $container): \Psr\Log\NullLogger => new NullLogger());
}
/**
* Setup the application's caching interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerCache(Container $container)
+ public function registerCache(Container $container): void
{
- $container['cache/config'] = function (Container $container) {
- return new CacheConfig();
- };
+ $container['cache/config'] = (fn(Container $container): \Charcoal\Cache\CacheConfig => new CacheConfig());
- $container['cache'] = function ($container) {
- return new Pool();
- };
+ $container['cache'] = (fn($container): \Stash\Pool => new Pool());
}
- public function registerDatabase(Container $container)
+ public function registerDatabase(Container $container): void
{
- $container['database'] = function (Container $container) {
+ $container['database'] = function (Container $container): \PDO {
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
};
}
- public function registerMetadataLoader(Container $container)
+ public function registerMetadataLoader(Container $container): void
{
$this->registerLogger($container);
$this->registerCache($container);
- $container['metadata/loader'] = function (Container $container) {
- return new MetadataLoader([
- 'logger' => $container['logger'],
- 'cache' => $container['cache'],
- 'base_path' => $container['config']['base_path'],
- 'paths' => [
- 'metadata',
- // Standalone
- 'vendor/charcoal/object/metadata',
- 'vendor/charcoal/user/metadata',
- // Monorepo
- '/../object/metadata',
- '/../user/metadata'
- ]
- ]);
- };
+ $container['metadata/loader'] = (fn(Container $container): \Charcoal\Model\Service\MetadataLoader => new MetadataLoader([
+ 'logger' => $container['logger'],
+ 'cache' => $container['cache'],
+ 'base_path' => $container['config']['base_path'],
+ 'paths' => [
+ 'metadata',
+ // Standalone
+ 'vendor/charcoal/object/metadata',
+ 'vendor/charcoal/user/metadata',
+ // Monorepo
+ '/../object/metadata',
+ '/../user/metadata'
+ ]
+ ]));
}
- public function registerSourceFactory(Container $container)
+ public function registerSourceFactory(Container $container): void
{
$this->registerLogger($container);
$this->registerDatabase($container);
- $container['source/factory'] = function (Container $container) {
- return new Factory([
- 'map' => [
- 'database' => DatabaseSource::class
- ],
- 'arguments' => [[
- 'logger' => $container['logger'],
- 'pdo' => $container['database']
- ]]
- ]);
- };
+ $container['source/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'map' => [
+ 'database' => DatabaseSource::class
+ ],
+ 'arguments' => [[
+ 'logger' => $container['logger'],
+ 'pdo' => $container['database']
+ ]]
+ ]));
}
- public function registerPropertyFactory(Container $container)
+ public function registerPropertyFactory(Container $container): void
{
$this->registerTranslator($container);
$this->registerDatabase($container);
$this->registerLogger($container);
- $container['property/factory'] = function (Container $container) {
- return new Factory([
- 'resolver_options' => [
- 'prefix' => '\\Charcoal\\Property\\',
- 'suffix' => 'Property'
- ],
- 'arguments' => [[
- 'container' => $container,
- 'database' => $container['database'],
- 'translator' => $container['translator'],
- 'logger' => $container['logger']
- ]]
- ]);
- };
+ $container['property/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'resolver_options' => [
+ 'prefix' => '\\Charcoal\\Property\\',
+ 'suffix' => 'Property'
+ ],
+ 'arguments' => [[
+ 'container' => $container,
+ 'database' => $container['database'],
+ 'translator' => $container['translator'],
+ 'logger' => $container['logger']
+ ]]
+ ]));
}
- public function registerModelFactory(Container $container)
+ public function registerModelFactory(Container $container): void
{
$this->registerLogger($container);
$this->registerTranslator($container);
@@ -333,51 +294,45 @@ public function registerModelFactory(Container $container)
$this->registerPropertyFactory($container);
$this->registerSourceFactory($container);
- $container['model/factory'] = function (Container $container) {
- return new Factory([
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger'],
- 'metadata_loader' => $container['metadata/loader'],
- 'property_factory' => $container['property/factory'],
- 'source_factory' => $container['source/factory']
- ]]
- ]);
- };
+ $container['model/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger'],
+ 'metadata_loader' => $container['metadata/loader'],
+ 'property_factory' => $container['property/factory'],
+ 'source_factory' => $container['source/factory']
+ ]]
+ ]));
}
- public function registerCollectionLoader(Container $container)
+ public function registerCollectionLoader(Container $container): void
{
$this->registerLogger($container);
$this->registerModelFactory($container);
- $container['model/collection/loader'] = function (Container $container) {
- return new \Charcoal\Loader\CollectionLoader([
- 'logger' => $container['logger'],
- 'factory' => $container['model/factory']
- ]);
- };
+ $container['model/collection/loader'] = (fn(Container $container): \Charcoal\Loader\CollectionLoader => new \Charcoal\Loader\CollectionLoader([
+ 'logger' => $container['logger'],
+ 'factory' => $container['model/factory']
+ ]));
}
- public function registerModuleFactory(Container $container)
+ public function registerModuleFactory(Container $container): void
{
$this->registerLogger($container);
$this->registerDatabase($container);
- $container['module/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => ModuleInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Module'
- ],
- 'arguments' => [[
- 'logger' => $container['logger']
- ]]
- ]);
- };
+ $container['module/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => ModuleInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Module'
+ ],
+ 'arguments' => [[
+ 'logger' => $container['logger']
+ ]]
+ ]));
}
- public function registerAppDependencies(Container $container)
+ public function registerAppDependencies(Container $container): void
{
$this->registerConfig($container);
$this->registerBaseUrl($container);
@@ -387,21 +342,21 @@ public function registerAppDependencies(Container $container)
$this->registerModuleFactory($container);
}
- public function registerActionDependencies(Container $container)
+ public function registerActionDependencies(Container $container): void
{
$this->registerLogger($container);
$this->registerTranslator($container);
$this->registerBaseUrl($container);
}
- public function registerTemplateDependencies(Container $container)
+ public function registerTemplateDependencies(Container $container): void
{
$this->registerLogger($container);
$this->registerTranslator($container);
$this->registerBaseUrl($container);
}
- public function registerWidgetDependencies(Container $container)
+ public function registerWidgetDependencies(Container $container): void
{
$this->registerLogger($container);
$this->registerTranslator($container);
diff --git a/packages/app/tests/Charcoal/App/Route/ActionRouteConfigTest.php b/packages/app/tests/Charcoal/App/Route/ActionRouteConfigTest.php
index 49ee92040..d4ff47317 100644
--- a/packages/app/tests/Charcoal/App/Route/ActionRouteConfigTest.php
+++ b/packages/app/tests/Charcoal/App/Route/ActionRouteConfigTest.php
@@ -14,7 +14,7 @@ public function setUp(): void
$this->obj = new ActionRouteConfig();
}
- public function testSetActionData()
+ public function testSetActionData(): void
{
$ret = $this->obj->setActionData([ 'foo' => 'bar' ]);
$this->assertSame($ret, $this->obj);
diff --git a/packages/app/tests/Charcoal/App/Route/ActionRouteTest.php b/packages/app/tests/Charcoal/App/Route/ActionRouteTest.php
index d32b3bd4a..9eba4948e 100644
--- a/packages/app/tests/Charcoal/App/Route/ActionRouteTest.php
+++ b/packages/app/tests/Charcoal/App/Route/ActionRouteTest.php
@@ -14,17 +14,13 @@ class ActionRouteTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var ActionRoute
*/
- private $obj;
+ private \Charcoal\App\Route\ActionRoute $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
@@ -39,19 +35,17 @@ public function setUp(): void
]);
}
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(ActionRoute::class, $this->obj);
}
/**
* Set up the service container.
- *
- * @return Container
*/
- private function container()
+ private function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerLogger($container);
diff --git a/packages/app/tests/Charcoal/App/Route/RouteConfigTest.php b/packages/app/tests/Charcoal/App/Route/RouteConfigTest.php
index a2890b0b9..5a80df703 100644
--- a/packages/app/tests/Charcoal/App/Route/RouteConfigTest.php
+++ b/packages/app/tests/Charcoal/App/Route/RouteConfigTest.php
@@ -16,7 +16,7 @@ public function setUp(): void
$this->obj = new RouteConfig();
}
- public function testSetIdent()
+ public function testSetIdent(): void
{
$this->assertNull($this->obj->ident());
$ret = $this->obj->setIdent('foobar');
@@ -28,7 +28,7 @@ public function testSetIdent()
$this->obj->setIdent(false);
}
- public function testSetRoute()
+ public function testSetRoute(): void
{
$this->assertNull($this->obj->route());
$ret = $this->obj->setRoute('foobar');
@@ -40,7 +40,7 @@ public function testSetRoute()
$this->obj->setRoute(false);
}
- public function testSetGroups()
+ public function testSetGroups(): void
{
$this->assertEquals([], $this->obj->groups());
$ret = $this->obj->setGroups(['foo', 'bar']);
@@ -49,7 +49,7 @@ public function testSetGroups()
$this->assertEquals(['foo', 'bar'], $this->obj->groups());
}
- public function testAddGroup()
+ public function testAddGroup(): void
{
$this->obj->addGroup('foo');
$this->obj->addGroup('bar');
@@ -60,7 +60,7 @@ public function testAddGroup()
$this->obj->addGroup(false);
}
- public function testSetController()
+ public function testSetController(): void
{
$this->assertNull($this->obj->controller());
$ret = $this->obj->setController('foobar');
@@ -72,7 +72,7 @@ public function testSetController()
$this->obj->setController(false);
}
- public function testSetMethods()
+ public function testSetMethods(): void
{
$this->assertEquals(['GET'], $this->obj->methods());
$ret = $this->obj->setMethods(['POST']);
@@ -81,7 +81,7 @@ public function testSetMethods()
$this->assertEquals(['POST'], $this->obj->methods());
}
- public function testAddMethod()
+ public function testAddMethod(): void
{
$this->assertEquals(['GET'], $this->obj->methods());
$ret = $this->obj->addMethod('post');
@@ -93,13 +93,13 @@ public function testAddMethod()
$this->obj->addMethod([]);
}
- public function testAddMethodInvalidMethodThrowsException()
+ public function testAddMethodInvalidMethodThrowsException(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->addMethod('invalid');
}
- public function testSetHeaders()
+ public function testSetHeaders(): void
{
$this->assertEquals([], $this->obj->headers());
$ret = $this->obj->setHeaders(['Foo'=>'Bar']);
@@ -110,7 +110,7 @@ public function testSetHeaders()
$this->assertArrayNotHasKey('Foo', $this->obj->headers());
}
- public function testAddHeader()
+ public function testAddHeader(): void
{
$this->assertEquals([], $this->obj->headers());
$ret = $this->obj->addHeader('Foo', 'Bar');
diff --git a/packages/app/tests/Charcoal/App/Route/RouteManagerTest.php b/packages/app/tests/Charcoal/App/Route/RouteManagerTest.php
index f28385a3f..fc7ec11dd 100644
--- a/packages/app/tests/Charcoal/App/Route/RouteManagerTest.php
+++ b/packages/app/tests/Charcoal/App/Route/RouteManagerTest.php
@@ -1,5 +1,7 @@
obj->setupRoutes();
}
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(RouteManager::class, $this->obj);
}
- public function testSetupTemplate()
+ public function testSetupTemplate(): void
{
$config = [
'templates' => [
@@ -64,14 +66,13 @@ public function testSetupTemplate()
$reflector = new \ReflectionObject($obj);
$method = $reflector->getMethod('setupTemplate');
- $method->setAccessible(true);
foreach($config['templates'] as $routeIdent => $templateConfig) {
$ret = $method->invoke($obj, $routeIdent, $templateConfig);
$this->assertInstanceOf(RouteInterface::class, $ret);
}
}
- public function testSetupAction()
+ public function testSetupAction(): void
{
$config = [
'actions' => [
@@ -88,14 +89,13 @@ public function testSetupAction()
$reflector = new \ReflectionObject($obj);
$method = $reflector->getMethod('setupAction');
- $method->setAccessible(true);
foreach($config['actions'] as $routeIdent => $actionConfig) {
$ret = $method->invoke($obj, $routeIdent, $actionConfig);
$this->assertInstanceOf(RouteInterface::class, $ret);
}
}
- public function testSetupScript()
+ public function testSetupScript(): void
{
$config = [
'scripts' => [
@@ -112,7 +112,6 @@ public function testSetupScript()
$reflector = new \ReflectionObject($obj);
$method = $reflector->getMethod('setupScript');
- $method->setAccessible(true);
foreach($config['scripts'] as $routeIdent => $scriptConfig) {
$ret = $method->invoke($obj, $routeIdent, $scriptConfig);
$this->assertInstanceOf(RouteInterface::class, $ret);
diff --git a/packages/app/tests/Charcoal/App/Route/ScriptRouteTest.php b/packages/app/tests/Charcoal/App/Route/ScriptRouteTest.php
index 630f4ece7..f9f0d20c0 100644
--- a/packages/app/tests/Charcoal/App/Route/ScriptRouteTest.php
+++ b/packages/app/tests/Charcoal/App/Route/ScriptRouteTest.php
@@ -25,17 +25,13 @@ class ScriptRouteTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var ScriptRoute
*/
- private $obj;
+ private \Charcoal\App\Route\ScriptRoute $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
@@ -49,30 +45,26 @@ public function setUp(): void
]);
}
- public function testInvoke()
+ public function testInvoke(): void
{
$container = $this->container();
- $container['script/factory'] = function($c) {
- return new Factory();
- };
+ $container['script/factory'] = (fn($c): \Charcoal\Factory\GenericFactory => new Factory());
- $request = $this->createMock(RequestInterface::class);
- $response = $this->createMock(ResponseInterface::class);
+ $request = $this->createStub(RequestInterface::class);
+ $response = $this->createStub(ResponseInterface::class);
// Invalid because "foo/bar" is not a valid script controller
$this->expectException('\Exception');
- $ret = call_user_func([$this->obj, '__invoke'], $container, $request, $response);
+ call_user_func($this->obj->__invoke(...), $container, $request, $response);
}
/**
* Set up the service container.
- *
- * @return Container
*/
- private function container()
+ private function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerLogger($container);
diff --git a/packages/app/tests/Charcoal/App/Route/TemplateRouteConfigTest.php b/packages/app/tests/Charcoal/App/Route/TemplateRouteConfigTest.php
index 175db9cd8..b7d020fcc 100644
--- a/packages/app/tests/Charcoal/App/Route/TemplateRouteConfigTest.php
+++ b/packages/app/tests/Charcoal/App/Route/TemplateRouteConfigTest.php
@@ -14,7 +14,7 @@ public function setUp(): void
$this->obj = new TemplateRouteConfig();
}
- public function testSetEngine()
+ public function testSetEngine(): void
{
//$this->assertEquals('mustache', $this->obj->engine());
$ret = $this->obj->setEngine('twig');
@@ -28,7 +28,7 @@ public function testSetEngine()
$this->obj->setEngine(false);
}
- public function testSetTemplate()
+ public function testSetTemplate(): void
{
$this->assertNull($this->obj->template());
$ret = $this->obj->setTemplate('foobar');
@@ -40,7 +40,7 @@ public function testSetTemplate()
$this->obj->setTemplate(false);
}
- public function testRedirect()
+ public function testRedirect(): void
{
$this->assertNull($this->obj->redirect());
$ret = $this->obj->setRedirect('foobar');
@@ -49,7 +49,7 @@ public function testRedirect()
$this->assertEquals('foobar', $this->obj->redirect());
}
- public function testSetRedirectMode()
+ public function testSetRedirectMode(): void
{
$this->assertEquals(301, $this->obj->redirectMode());
$ret = $this->obj->setRedirectMode(302);
@@ -60,7 +60,7 @@ public function testSetRedirectMode()
$this->obj->setRedirectMode(666);
}
- public function testSetCache()
+ public function testSetCache(): void
{
$this->assertFalse($this->obj->cache());
$ret = $this->obj->setCache(true);
@@ -68,7 +68,7 @@ public function testSetCache()
$this->assertTrue($this->obj->cache());
}
- public function testSetCacheTtl()
+ public function testSetCacheTtl(): void
{
$this->assertEquals(0, $this->obj->cacheTtl());
$ret = $this->obj->setCacheTtl('42');
diff --git a/packages/app/tests/Charcoal/App/Script/AbstractScriptTest.php b/packages/app/tests/Charcoal/App/Script/AbstractScriptTest.php
index 990d0165a..7dca938d0 100644
--- a/packages/app/tests/Charcoal/App/Script/AbstractScriptTest.php
+++ b/packages/app/tests/Charcoal/App/Script/AbstractScriptTest.php
@@ -21,17 +21,13 @@ class AbstractScriptTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var AbstractScript
*/
- private $obj;
+ private \Charcoal\App\Script\AbstractScript $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
@@ -40,28 +36,33 @@ public function setUp(): void
{
$container = $this->container();
- $this->obj = $this->getMockForAbstractClass(AbstractScript::class, [[
+ $this->obj = new class ([
'climate' => $container['climate'],
'logger' => $container['logger'],
'container' => $container
- ]]);
+ ]) extends AbstractScript {
+ public function run(RequestInterface $request, ResponseInterface $response)
+ {
+ return $response;
+ }
+ };
}
- public function testSetIdent()
+ public function testSetIdent(): void
{
$ret = $this->obj->setIdent('foobar');
$this->assertSame($ret, $this->obj);
$this->assertEquals('foobar', $this->obj->ident());
}
- public function testSetDescription()
+ public function testSetDescription(): void
{
$ret = $this->obj->setDescription('Foo Description');
$this->assertSame($ret, $this->obj);
$this->assertEQuals('Foo Description', $this->obj->description());
}
- public function testSetQuiet()
+ public function testSetQuiet(): void
{
$this->assertFalse($this->obj->quiet());
$ret = $this->obj->setQuiet(true);
@@ -69,7 +70,7 @@ public function testSetQuiet()
$this->assertTrue($this->obj->quiet());
}
- public function testSetVerbose()
+ public function testSetVerbose(): void
{
$this->assertFalse($this->obj->verbose());
$ret = $this->obj->setVerbose(true);
@@ -77,9 +78,9 @@ public function testSetVerbose()
$this->assertTrue($this->obj->verbose());
}
- public function testSetArguments()
+ public function testSetArguments(): void
{
- $defaultArgs = $this->obj->arguments();
+ $this->obj->arguments();
$ret = $this->obj->setArguments([
'foo'=>[]
]);
@@ -90,12 +91,10 @@ public function testSetArguments()
/**
* Set up the service container.
- *
- * @return Container
*/
- private function container()
+ private function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerLogger($container);
diff --git a/packages/app/tests/Charcoal/App/ServerTestTrait.php b/packages/app/tests/Charcoal/App/ServerTestTrait.php
index ea84e6730..b7309e1f1 100644
--- a/packages/app/tests/Charcoal/App/ServerTestTrait.php
+++ b/packages/app/tests/Charcoal/App/ServerTestTrait.php
@@ -14,7 +14,7 @@ trait ServerTestTrait
/**
* @var mixed The process identifier of the built-in PHP server.
*/
- static private $serverProcess = null;
+ static private $serverProcess;
/**
* @var string The hostname for the built-in PHP server.
@@ -29,7 +29,7 @@ trait ServerTestTrait
/**
* @var null|string The server root directory, where it should be ran from.
*/
- static protected $serverRoot = null;
+ static protected $serverRoot;
/**
* @var string The APPLICATION_ENV environment variable.
@@ -44,15 +44,13 @@ trait ServerTestTrait
* @param boolean $checkForObjectIdentity Unused.
* @param string $message The error to report.
* @throws InvalidArgumentException
- * @return void
*/
abstract public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = ''): void;
/**
* Retrieve the built-in PHP server URL.
- * @return string
*/
- protected static function serverURL()
+ protected static function serverURL(): string
{
return static::$serverHost.':'.static::$serverPort;
}
@@ -71,18 +69,17 @@ protected static function serverRoot()
/**
* Retrieve wether the tests are run on windows or not.
- * @return boolean
*/
- protected static function isWindows()
+ protected static function isWindows(): bool
{
return (stristr(php_uname('s'), 'win') !== false);
}
/**
* Start a built-in PHP server process.
- * @beforeClass
*/
- public static function bootUpBuiltInServer()
+ #[\PHPUnit\Framework\Attributes\BeforeClass]
+ public static function bootUpBuiltInServer(): void
{
$command = sprintf(
'php -S %s -t %s',
@@ -110,18 +107,17 @@ public static function bootUpBuiltInServer()
/**
* Terminates the built-in PHP server process.
- * @afterClass
*/
- public static function turnDownBuiltInServer()
+ #[\PHPUnit\Framework\Attributes\AfterClass]
+ public static function turnDownBuiltInServer(): void
{
pclose(static::$serverProcess);
}
/**
* @param array $request The request data (method, route, options).
- * @return \Psr\Http\Message\ResponseInterface
*/
- protected function callRequest(array $request)
+ protected function callRequest(array $request): \Psr\Http\Message\ResponseInterface
{
$route = str_replace('.', '', $request['route']);
$client = new HttpClient();
@@ -132,10 +128,6 @@ protected function callRequest(array $request)
);
}
- /**
- * @param array $expected
- * @param ResponseInterface $response
- */
protected function assertResponseMatchesExpected(array $expected, ResponseInterface $response)
{
if (isset($expected['statusCode']) && $expected['statusCode']) {
@@ -157,7 +149,6 @@ protected function assertResponseMatchesExpected(array $expected, ResponseInterf
/**
* @param integer $expectedStatusCode
- * @param ResponseInterface $response
*/
protected function assertResponseHasStatusCode($expectedStatusCode, ResponseInterface $response)
{
@@ -166,7 +157,6 @@ protected function assertResponseHasStatusCode($expectedStatusCode, ResponseInte
/**
* @param array|string $json
- * @param ResponseInterface $response
*/
protected function assertResponseBodyMatchesJson($json, ResponseInterface $response)
{
@@ -187,7 +177,6 @@ protected function assertResponseBodyMatchesJson($json, ResponseInterface $respo
/**
* @param string $pattern
- * @param ResponseInterface $response
*/
protected function assertResponseBodyRegExp($pattern, ResponseInterface $response)
{
diff --git a/packages/app/tests/Charcoal/App/ServiceProvider/AppServiceProviderTest.php b/packages/app/tests/Charcoal/App/ServiceProvider/AppServiceProviderTest.php
index 790c95518..2061ad9ec 100644
--- a/packages/app/tests/Charcoal/App/ServiceProvider/AppServiceProviderTest.php
+++ b/packages/app/tests/Charcoal/App/ServiceProvider/AppServiceProviderTest.php
@@ -12,7 +12,7 @@
*/
class AppServiceProviderTest extends AbstractTestCase
{
- public function testProvider()
+ public function testProvider(): void
{
$container = new Container();
$provider = new AppServiceProvider();
diff --git a/packages/app/tests/Charcoal/App/ServiceProvider/DatabaseServiceProviderTest.php b/packages/app/tests/Charcoal/App/ServiceProvider/DatabaseServiceProviderTest.php
index c3b737005..f2238f152 100644
--- a/packages/app/tests/Charcoal/App/ServiceProvider/DatabaseServiceProviderTest.php
+++ b/packages/app/tests/Charcoal/App/ServiceProvider/DatabaseServiceProviderTest.php
@@ -12,7 +12,7 @@
*/
class DatabaseServiceProviderTest extends AbstractTestCase
{
- public function testProvider()
+ public function testProvider(): void
{
$container = new Container([
'config' => []
diff --git a/packages/app/tests/Charcoal/App/ServiceProvider/FilesystemServiceProviderTest.php b/packages/app/tests/Charcoal/App/ServiceProvider/FilesystemServiceProviderTest.php
index a9a6e9cc4..65416b0f3 100644
--- a/packages/app/tests/Charcoal/App/ServiceProvider/FilesystemServiceProviderTest.php
+++ b/packages/app/tests/Charcoal/App/ServiceProvider/FilesystemServiceProviderTest.php
@@ -30,14 +30,14 @@
*/
class FilesystemServiceProviderTest extends AbstractTestCase
{
- private $obj;
+ private \Charcoal\App\ServiceProvider\FilesystemServiceProvider $obj;
public function setUp(): void
{
$this->obj = new FilesystemServiceProvider();
}
- public function testProvider()
+ public function testProvider(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -54,7 +54,7 @@ public function testProvider()
$this->assertInstanceOf(Container::class, $container['filesystems']);
}
- public function testProviderDefaultAdapters()
+ public function testProviderDefaultAdapters(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -69,7 +69,7 @@ public function testProviderDefaultAdapters()
$this->assertInstanceOf(Filesystem::class, $container['filesystems']['public']);
}
- public function testProviderLocalAdapter()
+ public function testProviderLocalAdapter(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -88,7 +88,7 @@ public function testProviderLocalAdapter()
$this->assertInstanceOf(Filesystem::class, $container['filesystems']['local']);
}
- public function testProviderS3Adapter()
+ public function testProviderS3Adapter(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -110,7 +110,7 @@ public function testProviderS3Adapter()
$this->assertInstanceOf(Filesystem::class, $container['filesystems']['s3']);
}
- public function testProviderFtpAdapter()
+ public function testProviderFtpAdapter(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -131,7 +131,7 @@ public function testProviderFtpAdapter()
$this->assertInstanceOf(Filesystem::class, $container['filesystems']['ftp']);
}
- public function testProviderSftpAdapter()
+ public function testProviderSftpAdapter(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -152,7 +152,7 @@ public function testProviderSftpAdapter()
$this->assertInstanceOf(Filesystem::class, $container['filesystems']['sftp']);
}
- public function testProviderMemorypAdapter()
+ public function testProviderMemoryAdapter(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -171,7 +171,7 @@ public function testProviderMemorypAdapter()
$this->assertInstanceOf(Filesystem::class, $container['filesystems']['memory']);
}
- public function testProviderNullAdapter()
+ public function testProviderNullAdapter(): void
{
$container = $this->getContainer([
'config' => $this->createAppConfig([
@@ -189,7 +189,7 @@ public function testProviderNullAdapter()
$this->assertInstanceOf(Filesystem::class, $container['filesystems']['test']);
}
- public function testConfigWithoutTypeThrowsException()
+ public function testConfigWithoutTypeThrowsException(): void
{
$this->expectException('\Exception');
$container = $this->getContainer([
@@ -201,16 +201,15 @@ public function testConfigWithoutTypeThrowsException()
]
])
]);
-
- $test = $container['filesystem/test'];
+ $container['filesystems']['test'];
}
- private function createAppConfig($defaults = null)
+ private function createAppConfig($defaults = null): \Charcoal\App\AppConfig
{
return new AppConfig(array_replace(['base_path' => sys_get_temp_dir()], $defaults));
}
- private function getContainer($defaults = null)
+ private function getContainer($defaults = null): \Pimple\Container
{
$container = new Container($defaults);
$this->obj->register($container);
diff --git a/packages/app/tests/Charcoal/App/ServiceProvider/LoggerServiceProviderTest.php b/packages/app/tests/Charcoal/App/ServiceProvider/LoggerServiceProviderTest.php
index 31b04e18a..41b1d8565 100644
--- a/packages/app/tests/Charcoal/App/ServiceProvider/LoggerServiceProviderTest.php
+++ b/packages/app/tests/Charcoal/App/ServiceProvider/LoggerServiceProviderTest.php
@@ -12,7 +12,7 @@
*/
class LoggerServiceProviderTest extends AbstractTestCase
{
- public function testProvider()
+ public function testProvider(): void
{
$container = new Container([
'config' => []
diff --git a/packages/app/tests/Charcoal/App/ServiceProvider/ScriptServiceProviderTest.php b/packages/app/tests/Charcoal/App/ServiceProvider/ScriptServiceProviderTest.php
index 414ffc43a..1bd759abf 100644
--- a/packages/app/tests/Charcoal/App/ServiceProvider/ScriptServiceProviderTest.php
+++ b/packages/app/tests/Charcoal/App/ServiceProvider/ScriptServiceProviderTest.php
@@ -12,7 +12,7 @@
*/
class ScriptServiceProviderTest extends AbstractTestCase
{
- public function testProvider()
+ public function testProvider(): void
{
$container = new Container();
$provider = new ScriptServiceProvider();
diff --git a/packages/app/tests/Charcoal/App/Template/AbstractTemplateTest.php b/packages/app/tests/Charcoal/App/Template/AbstractTemplateTest.php
index b4b284e66..a453deef5 100644
--- a/packages/app/tests/Charcoal/App/Template/AbstractTemplateTest.php
+++ b/packages/app/tests/Charcoal/App/Template/AbstractTemplateTest.php
@@ -23,17 +23,13 @@ class AbstractTemplateTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var AbstractTemplate
*/
- private $obj;
+ private \Charcoal\App\Template\AbstractTemplate $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
@@ -42,26 +38,24 @@ public function setUp(): void
{
$container = $this->container();
- $this->obj = $this->getMockForAbstractClass(AbstractTemplate::class, [[
+ $this->obj = new class ([
'logger' => $container['logger'],
'container' => $container
- ]]);
+ ]) extends AbstractTemplate {};
}
- public function testInitIsTrue()
+ public function testInitIsTrue(): void
{
- $request = $this->createMock(RequestInterface::class);
+ $request = $this->createStub(RequestInterface::class);
$this->assertTrue($this->obj->init($request));
}
/**
* Set up the service container.
- *
- * @return Container
*/
- private function container()
+ private function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerLogger($container);
diff --git a/packages/app/tests/Charcoal/App/Template/AbstractWidgetTest.php b/packages/app/tests/Charcoal/App/Template/AbstractWidgetTest.php
index a2f526bba..80e415b74 100644
--- a/packages/app/tests/Charcoal/App/Template/AbstractWidgetTest.php
+++ b/packages/app/tests/Charcoal/App/Template/AbstractWidgetTest.php
@@ -23,17 +23,13 @@ class AbstractWidgetTest extends AbstractTestCase
{
/**
* Tested Class.
- *
- * @var AbstractWidget
*/
- private $obj;
+ private \Charcoal\App\Template\AbstractWidget $obj;
/**
* Store the service container.
- *
- * @var Container
*/
- private $container;
+ private ?\Pimple\Container $container = null;
/**
* Set up the test.
@@ -42,10 +38,10 @@ public function setUp(): void
{
$container = $this->container();
- $this->obj = $this->getMockForAbstractClass(AbstractWidget::class, [[
+ $this->obj = new class ([
'logger' => $container['logger'],
'container' => $container
- ]]);
+ ]) extends AbstractWidget {};
}
/**
@@ -54,7 +50,7 @@ public function setUp(): void
* - `setActive()` method is chainable
* - `setActive()` actually sets the active value.
*/
- public function testSetActive()
+ public function testSetActive(): void
{
$obj = $this->obj;
$this->assertTrue($obj->active());
@@ -65,12 +61,10 @@ public function testSetActive()
/**
* Set up the service container.
- *
- * @return Container
*/
- private function container()
+ private function container(): \Pimple\Container
{
- if ($this->container === null) {
+ if (!$this->container instanceof \Pimple\Container) {
$container = new Container();
$containerProvider = new ContainerProvider();
$containerProvider->registerConfig($container);
diff --git a/packages/app/tests/Charcoal/AssertionsTrait.php b/packages/app/tests/Charcoal/AssertionsTrait.php
index 47f7837dc..767f81794 100644
--- a/packages/app/tests/Charcoal/AssertionsTrait.php
+++ b/packages/app/tests/Charcoal/AssertionsTrait.php
@@ -16,14 +16,13 @@ trait AssertionsTrait
* @param array $haystack The actual haystack.
* @param boolean $strict Whether to check for object identity.
* @param string $message The error to report.
- * @return void
*/
public function assertArraySubsets(
array $expected,
array $haystack,
$strict = false,
$message = ''
- ) {
+ ): void {
foreach ($expected as $key => $val) {
$this->assertArraySubset([ $key => $val ], $haystack, $strict, $message);
}
@@ -40,18 +39,17 @@ public function assertArraySubsets(
* @param boolean $checkForObjectIdentity Unused.
* @param string $message The error to report.
* @throws InvalidArgumentException
- * @return void
*/
public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = ''): void
{
- if (!(is_array($subset) || $subset instanceof ArrayAccess)) {
+ if (!is_array($subset) && !$subset instanceof ArrayAccess) {
throw InvalidArgumentException::create(
1,
'array or ArrayAccess'
);
}
- if (!(is_array($array) || $array instanceof ArrayAccess)) {
+ if (!is_array($array) && !$array instanceof ArrayAccess) {
throw InvalidArgumentException::create(
2,
'array or ArrayAccess'
diff --git a/packages/app/tests/bootstrap.php b/packages/app/tests/bootstrap.php
index 53295f7d8..90929e3b5 100644
--- a/packages/app/tests/bootstrap.php
+++ b/packages/app/tests/bootstrap.php
@@ -1,10 +1,12 @@
-
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
-
-
+
+ ./src/Charcoal
-
-
+
+
+
+
+
+
+
+
-
+
-
-
-
-
diff --git a/packages/attachment/src/Charcoal/Admin/Action/AddJoinAction.php b/packages/attachment/src/Charcoal/Admin/Action/AddJoinAction.php
index 64d3cc65f..d9ed6abfb 100644
--- a/packages/attachment/src/Charcoal/Admin/Action/AddJoinAction.php
+++ b/packages/attachment/src/Charcoal/Admin/Action/AddJoinAction.php
@@ -21,9 +21,8 @@ class AddJoinAction extends AdminAction
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
$params = $request->getParams();
@@ -44,7 +43,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$group = $params['group'];
// Need more attachments...
- if (!count($attachments)) {
+ if (count($attachments) === 0) {
$this->setSuccess(false);
return $response;
@@ -53,7 +52,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
// Try loading the object
try {
$obj = $this->modelFactory()->create($objType)->load($objId);
- } catch (Exception $e) {
+ } catch (Exception) {
$this->setSuccess(false);
return $response;
diff --git a/packages/attachment/src/Charcoal/Admin/Action/JoinAction.php b/packages/attachment/src/Charcoal/Admin/Action/JoinAction.php
index 2f41bc59e..2e9663384 100644
--- a/packages/attachment/src/Charcoal/Admin/Action/JoinAction.php
+++ b/packages/attachment/src/Charcoal/Admin/Action/JoinAction.php
@@ -21,9 +21,8 @@ class JoinAction extends AdminAction
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
$params = $request->getParams();
@@ -44,7 +43,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
$group = $params['group'];
// Need more attachments...
- if (!count($attachments)) {
+ if (count($attachments) === 0) {
$this->setSuccess(false);
return $response;
@@ -53,7 +52,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
// Try loading the object
try {
$obj = $this->modelFactory()->create($objType)->load($objId);
- } catch (Exception $e) {
+ } catch (Exception) {
$this->setSuccess(false);
return $response;
diff --git a/packages/attachment/src/Charcoal/Admin/Action/RemoveJoinAction.php b/packages/attachment/src/Charcoal/Admin/Action/RemoveJoinAction.php
index b75fbcbaa..905b75272 100644
--- a/packages/attachment/src/Charcoal/Admin/Action/RemoveJoinAction.php
+++ b/packages/attachment/src/Charcoal/Admin/Action/RemoveJoinAction.php
@@ -22,9 +22,8 @@ class RemoveJoinAction extends AdminAction
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
$params = $request->getParams();
@@ -47,7 +46,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
// Try loading the object
try {
$obj = $this->modelFactory()->create($objType)->load($objId);
- } catch (Exception $e) {
+ } catch (Exception) {
$this->setSuccess(false);
return $response;
@@ -84,7 +83,7 @@ public function run(RequestInterface $request, ResponseInterface $response)
if ($attachment['id'] !== null) {
$attachment->delete();
}
- } catch (Exception $error) {
+ } catch (Exception) {
$this->setSuccess(false);
return $response;
}
diff --git a/packages/attachment/src/Charcoal/Admin/Widget/AddAttachmentWidget.php b/packages/attachment/src/Charcoal/Admin/Widget/AddAttachmentWidget.php
index 49094eb64..9cf191a40 100644
--- a/packages/attachment/src/Charcoal/Admin/Widget/AddAttachmentWidget.php
+++ b/packages/attachment/src/Charcoal/Admin/Widget/AddAttachmentWidget.php
@@ -1,5 +1,7 @@
'paperclip'
];
- /**
- * @var array
- */
- private $attachmentOptions;
+ private ?array $attachmentOptions = null;
/**
* Inject dependencies from a DI Container.
@@ -112,6 +114,7 @@ class AttachmentWidget extends AdminWidget implements
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -143,20 +146,16 @@ protected function createOrLoadObj()
/**
* Determine if the widget has any attachment types.
- *
- * @return boolean
*/
- public function hasAttachmentTypes()
+ public function hasAttachmentTypes(): bool
{
return !empty($this->attachableObjects());
}
/**
* Retrieve the attachment types with their collections.
- *
- * @return array
*/
- public function attachmentTypes()
+ public function attachmentTypes(): array
{
$attachableObjects = $this->attachableObjects();
@@ -172,17 +171,17 @@ public function attachmentTypes()
$label = $attMeta['label'];
$out[] = [
- 'id' => (isset($attMeta['att_id']) ? $attMeta['att_id'] : null),
+ 'id' => ($attMeta['att_id'] ?? null),
'ident' => $this->createIdent($attType),
'skipForm' => $attMeta['skipForm'],
'formIdent' => $attMeta['formIdent'],
'quickFormIdent' => $attMeta['quickFormIdent'],
- 'hasFaIcon' => !!$attMeta['faIcon'],
+ 'hasFaIcon' => (bool)$attMeta['faIcon'],
'faIcon' => $attMeta['faIcon'],
'label' => $label,
'val' => $attType,
'locked' => $attMeta['locked'],
- 'active' => ($i == 1)
+ 'active' => ($i === 1)
];
}
@@ -220,20 +219,16 @@ public function attachments()
/**
* Determine the number of attachments.
- *
- * @return boolean
*/
- public function hasAttachments()
+ public function hasAttachments(): int
{
return count(iterator_to_array($this->attachments()));
}
/**
* The default set of settings for attachment widget.
- *
- * @return array
*/
- public function defaultAttachmentOptions()
+ public function defaultAttachmentOptions(): array
{
return [
'header' => null,
@@ -251,9 +246,8 @@ public function defaultAttachmentOptions()
* @param string $key The setting to add/replace.
* @param mixed $val The settings's value to apply.
* @throws InvalidArgumentException If the identifier is not a string.
- * @return self
*/
- public function addAttachmentOption($key, $val)
+ public function addAttachmentOption($key, $val): static
{
if (!is_string($key)) {
throw new InvalidArgumentException(
@@ -291,20 +285,15 @@ public function attachmentOption($key)
$this->attachmentOptions();
}
- if (isset($this->attachmentOptions[$key])) {
- return $this->attachmentOptions[$key];
- }
-
- return null;
+ return ($this->attachmentOptions[$key] ?? null);
}
/**
* Merge (replacing or adding) attachment options.
*
* @param array $settings The attachment options.
- * @return self
*/
- public function mergeAttachmentOptions(array $settings)
+ public function mergeAttachmentOptions(array $settings): static
{
// Make sure default options are loaded.
if ($this->attachmentOptions === null) {
@@ -323,12 +312,10 @@ public function mergeAttachmentOptions(array $settings)
* @param array $settings The Attachment options.
* @return array Returns the parsed options.
*/
- protected function parseAttachmentOptions(array $settings)
+ protected function parseAttachmentOptions(array $settings): array
{
- if (isset($settings['show_header']) && isset($settings['show_preview'])) {
- if (!$settings['show_header'] && !$settings['show_preview']) {
- $settings['show_header'] = true;
- }
+ if (isset($settings['show_header']) && isset($settings['show_preview']) && (!$settings['show_header'] && !$settings['show_preview'])) {
+ $settings['show_header'] = true;
}
return $settings;
@@ -336,14 +323,13 @@ protected function parseAttachmentOptions(array $settings)
// Setters
// =========================================================================
-
/**
* Set the widget's data.
*
* @param array $data The widget data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
$this->isMergingData = true;
/**
@@ -375,14 +361,12 @@ public function setData(array $data)
* @throws InvalidArgumentException If the argument is not a string.
* @return UserDataInterface Chainable
*/
- public function setLang($lang)
+ public function setLang($lang): static
{
- if ($lang !== null) {
- if (!is_string($lang)) {
- throw new InvalidArgumentException(
- 'Language must be a string'
- );
- }
+ if ($lang !== null && !is_string($lang)) {
+ throw new InvalidArgumentException(
+ 'Language must be a string'
+ );
}
$this->lang = $lang;
@@ -394,9 +378,8 @@ public function setLang($lang)
* Set the attachment widget settings.
*
* @param array $settings Attachments options array.
- * @return self
*/
- public function setAttachmentOptions(array $settings)
+ public function setAttachmentOptions(array $settings): static
{
$this->attachmentOptions = array_merge(
$this->defaultAttachmentOptions(),
@@ -413,14 +396,13 @@ public function setAttachmentOptions(array $settings)
*
* @param string $group The group identifier.
* @throws InvalidArgumentException If the group key is invalid.
- * @return self
*/
- public function setGroup($group)
+ public function setGroup($group): static
{
if (!is_string($group) && $group !== null) {
throw new InvalidArgumentException(sprintf(
'Attachment group must be string, received %s',
- is_object($group) ? get_class($group) : gettype($group)
+ get_debug_type($group)
));
}
@@ -433,9 +415,8 @@ public function setGroup($group)
* Set an widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return self
*/
- protected function setWidgetFactory(FactoryInterface $factory)
+ protected function setWidgetFactory(FactoryInterface $factory): static
{
$this->widgetFactory = $factory;
@@ -446,9 +427,8 @@ protected function setWidgetFactory(FactoryInterface $factory)
* Set the widget's title.
*
* @param mixed $title The title for the current widget.
- * @return self
*/
- public function setTitle($title)
+ public function setTitle($title): static
{
$this->title = $this->translator()->translation($title);
@@ -460,9 +440,8 @@ public function setTitle($title)
*
* @param integer $num The number of results to retrieve, per page.
* @throws InvalidArgumentException If the parameter is not numeric or < 0.
- * @return self
*/
- public function setNumPerPage($num)
+ public function setNumPerPage($num): static
{
if (!is_numeric($num)) {
throw new InvalidArgumentException(
@@ -488,9 +467,8 @@ public function setNumPerPage($num)
*
* @param integer $page The current page. Start at 0.
* @throws InvalidArgumentException If the parameter is not numeric or < 0.
- * @return self
*/
- public function setPage($page)
+ public function setPage($page): static
{
if (!is_numeric($page)) {
throw new InvalidArgumentException(
@@ -520,7 +498,7 @@ public function setPage($page)
* @param array|AttachableInterface[] $attachableObjects A list of available attachment types.
* @return self|boolean
*/
- public function setAttachableObjects($attachableObjects)
+ public function setAttachableObjects($attachableObjects): false|self
{
if (!$this->isMergingData) {
$attachableObjects = $this->mergePresetAttachableObjects($attachableObjects);
@@ -564,7 +542,7 @@ public function setAttachableObjects($attachableObjects)
}
// Useful for attaching a pre-existing attachment
- $attId = (isset($attMeta['attachment_id']) ? $attMeta['attachment_id'] : null);
+ $attId = ($attMeta['attachment_id'] ?? null);
if (isset($attMeta['label'])) {
$label = $this->translator()->translation($attMeta['label']);
@@ -609,14 +587,14 @@ public function setAttachableObjects($attachableObjects)
$icon = 'fa fa-' . $icon;
}
} else {
- $attParts = explode('/', $attType);
+ $attParts = explode('/', (string)$attType);
if (isset($this->defaultIcons[end($attParts)])) {
$faIcon = 'fa fa-' . $this->defaultIcons[end($attParts)];
}
}
if (isset($attMeta['show_icon'])) {
- $showIcon = !!$attMeta['show_icon'];
+ $showIcon = (bool)$attMeta['show_icon'];
}
if (isset($attMeta['locked'])) {
@@ -633,7 +611,7 @@ public function setAttachableObjects($attachableObjects)
'skipForm' => $skipForm,
'formIdent' => $formIdent,
'quickFormIdent' => $quickFormIdent,
- 'hasFaIcon' => !!$faIcon,
+ 'hasFaIcon' => (bool)$faIcon,
'faIcon' => $faIcon,
'showIcon' => $showIcon,
'filters' => $filters,
@@ -652,19 +630,17 @@ public function setAttachableObjects($attachableObjects)
// Getters
// =========================================================================
-
/**
* Retrieve the widget factory.
*
* @throws RuntimeException If the widget factory was not previously set.
- * @return FactoryInterface
*/
- public function widgetFactory()
+ public function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->widgetFactory)) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Widget Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -683,10 +659,8 @@ public function lang()
/**
* Retrieve the attachment options.
- *
- * @return array
*/
- public function attachmentOptions()
+ public function attachmentOptions(): array
{
if ($this->attachmentOptions === null) {
$this->attachmentOptions = $this->defaultAttachmentOptions();
@@ -729,10 +703,8 @@ public function attachableObjects()
return $this->attachableObjects;
}
- /**
- * @return array
- */
- public function widgetDataForJs()
+ #[\Override]
+ public function widgetDataForJs(): array
{
return [
'obj_type' => $this->obj()->objType(),
@@ -743,10 +715,8 @@ public function widgetDataForJs()
/**
* Retrieve the widget's options.
- *
- * @return array
*/
- public function widgetOptions()
+ public function widgetOptions(): array
{
return [
'obj_type' => $this->obj()->objType(),
@@ -769,7 +739,7 @@ final public function widgetOptionsAsJson()
$options = (JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($this->debug()) {
- $options = ($options | JSON_PRETTY_PRINT);
+ $options |= JSON_PRETTY_PRINT;
}
return json_encode($this->widgetOptions(), $options);
@@ -780,7 +750,7 @@ final public function widgetOptionsAsJson()
*
* @return string Returns a stringified JSON object, protected from Mustache rendering.
*/
- final public function escapedWidgetOptionsAsJson()
+ final public function escapedWidgetOptionsAsJson(): string
{
return '{{=<% %>=}}' . $this->widgetOptionsAsJson() . '<%={{ }}=%>';
}
@@ -802,7 +772,7 @@ public function defaultIcons()
* @param string $string A dirty string to filter.
* @return string
*/
- public function createIdent($string)
+ public function createIdent($string): ?string
{
return preg_replace('~/~', '-', $string);
}
diff --git a/packages/attachment/src/Charcoal/Admin/Widget/FormGroup/AttachmentFormGroup.php b/packages/attachment/src/Charcoal/Admin/Widget/FormGroup/AttachmentFormGroup.php
index 3f32f6cf7..f1bcdd4d5 100644
--- a/packages/attachment/src/Charcoal/Admin/Widget/FormGroup/AttachmentFormGroup.php
+++ b/packages/attachment/src/Charcoal/Admin/Widget/FormGroup/AttachmentFormGroup.php
@@ -42,25 +42,21 @@ class AttachmentFormGroup extends AbstractFormGroup implements
/**
* Store the widget factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $widgetFactory;
+ private ?\Charcoal\Factory\FactoryInterface $widgetFactory = null;
/**
* Whether notes should be display before or after the form fields.
- *
- * @var boolean
*/
- private $showNotesAbove = false;
+ private bool $showNotesAbove = false;
/**
* Set the widget's data.
*
* @param array $data The widget data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
/**
* @todo Kinda hacky, but works with the concept of form.
@@ -80,10 +76,8 @@ public function setData(array $data)
/**
* Retrieve the default nested widget options.
- *
- * @return array
*/
- public function defaultWidgetData()
+ public function defaultWidgetData(): array
{
return [
'type' => 'charcoal/admin/widget/attachment',
@@ -114,9 +108,8 @@ public function widgetId()
* Set the widget's ID.
*
* @param string $widgetId The widget identifier.
- * @return self
*/
- public function setWidgetId($widgetId)
+ public function setWidgetId($widgetId): static
{
$this->widgetId = $widgetId;
@@ -126,7 +119,8 @@ public function setWidgetId($widgetId)
/**
* @return Translation|string|null
*/
- public function description()
+ #[\Override]
+ public function description(): string
{
return $this->renderTemplate((string)parent::description());
}
@@ -134,7 +128,8 @@ public function description()
/**
* @return Translation|string|null
*/
- public function notes()
+ #[\Override]
+ public function notes(): string
{
return $this->renderTemplate((string)parent::notes());
}
@@ -145,7 +140,8 @@ public function notes()
* @param boolean|string $show Whether to show or hide notes.
* @return self Chainable
*/
- public function setShowNotes($show)
+ #[\Override]
+ public function setShowNotes($show): static
{
$this->showNotesAbove = ($show === 'above');
parent::setShowNotes($show);
@@ -153,10 +149,7 @@ public function setShowNotes($show)
return $this;
}
- /**
- * @return boolean
- */
- public function showNotesAbove()
+ public function showNotesAbove(): bool
{
return $this->showNotesAbove && $this->showNotes();
}
@@ -165,6 +158,7 @@ public function showNotesAbove()
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -186,9 +180,8 @@ protected function setDependencies(Container $container)
* Set the widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return self
*/
- protected function setWidgetFactory(FactoryInterface $factory)
+ protected function setWidgetFactory(FactoryInterface $factory): static
{
$this->widgetFactory = $factory;
@@ -198,15 +191,14 @@ protected function setWidgetFactory(FactoryInterface $factory)
/**
* Retrieve the widget factory.
*
- * @return FactoryInterface
* @throws RuntimeException If the widget factory was not previously set.
*/
- protected function widgetFactory()
+ protected function widgetFactory(): \Charcoal\Factory\FactoryInterface
{
- if ($this->widgetFactory === null) {
+ if (!$this->widgetFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Widget Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
diff --git a/packages/attachment/src/Charcoal/Attachment/AttachmentsConfig.php b/packages/attachment/src/Charcoal/Attachment/AttachmentsConfig.php
index 481b508b4..fc4f3e65f 100644
--- a/packages/attachment/src/Charcoal/Attachment/AttachmentsConfig.php
+++ b/packages/attachment/src/Charcoal/Attachment/AttachmentsConfig.php
@@ -13,24 +13,18 @@ class AttachmentsConfig extends AbstractConfig
{
/**
* Available attachment widget structures.
- *
- * @var array
*/
- private $widgets = [];
+ private array $widgets = [];
/**
* Attachment type groupings.
- *
- * @var array
*/
- private $groups = [];
+ private array $groups = [];
/**
* Available attachment types.
- *
- * @var array
*/
- private $attachables = [];
+ private array $attachables = [];
/**
* Set attachments settings in a specific order.
@@ -38,6 +32,7 @@ class AttachmentsConfig extends AbstractConfig
* @param array $data New config values.
* @return AttachmentsConfig Chainable
*/
+ #[\Override]
public function setData(array $data)
{
if (isset($data['attachables'])) {
@@ -64,7 +59,7 @@ public function setData(array $data)
* @throws InvalidArgumentException If the attachment type or structure is invalid.
* @return AttachmentsConfig Chainable
*/
- public function setAttachables(array $attachables)
+ public function setAttachables(array $attachables): static
{
foreach ($attachables as $attType => $attStruct) {
if (!is_array($attStruct)) {
@@ -94,10 +89,8 @@ public function setAttachables(array $attachables)
/**
* Retrieve the available attachment types.
- *
- * @return array
*/
- public function attachables()
+ public function attachables(): array
{
return $this->attachables;
}
@@ -109,7 +102,7 @@ public function attachables()
* @throws InvalidArgumentException If the group identifier or structure is invalid.
* @return AttachmentsConfig Chainable
*/
- public function setGroups(array $groups)
+ public function setGroups(array $groups): static
{
foreach ($groups as $groupIdent => $groupStruct) {
if (!is_array($groupStruct)) {
@@ -144,10 +137,8 @@ public function setGroups(array $groups)
/**
* Retrieve the available attachment type groups.
- *
- * @return array
*/
- public function groups()
+ public function groups(): array
{
return $this->groups;
}
@@ -159,7 +150,7 @@ public function groups()
* @throws InvalidArgumentException If the widget identifier or structure is invalid.
* @return AttachmentsConfig Chainable
*/
- public function setWidgets(array $widgets)
+ public function setWidgets(array $widgets): static
{
foreach ($widgets as $widgetIdent => $widgetStruct) {
if (!is_array($widgetStruct)) {
@@ -188,10 +179,8 @@ public function setWidgets(array $widgets)
/**
* Retrieve the available attachment widget structures.
- *
- * @return array
*/
- public function widgets()
+ public function widgets(): array
{
return $this->widgets;
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Interfaces/AttachableInterface.php b/packages/attachment/src/Charcoal/Attachment/Interfaces/AttachableInterface.php
index d4dc9e187..311f27456 100644
--- a/packages/attachment/src/Charcoal/Attachment/Interfaces/AttachableInterface.php
+++ b/packages/attachment/src/Charcoal/Attachment/Interfaces/AttachableInterface.php
@@ -1,5 +1,7 @@
defaultData(...))) {
$defaultData = $this->metadata()->defaultData();
if ($defaultData) {
$this->setData($defaultData);
@@ -203,6 +197,7 @@ public function __construct(array $data = null)
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -217,7 +212,7 @@ protected function setDependencies(Container $container)
* @param boolean $presenter The presenter flag.
* @return boolean Returns TRUE if model is used for presentation; FALSE for editing.
*/
- public function isPresentable($presenter = null)
+ public function isPresentable($presenter = null): bool
{
if (is_bool($presenter)) {
$this->presentable = $presenter;
@@ -245,10 +240,8 @@ public function containerId()
/**
* Determine if the attachment belongs to a container.
- *
- * @return boolean
*/
- public function hasContainerObj()
+ public function hasContainerObj(): bool
{
return boolval($this->containerObj);
}
@@ -268,9 +261,8 @@ public function containerObj()
*
* @param AttachmentContainerInterface|null $obj The container object or NULL.
* @throws InvalidArgumentException If the given object is invalid.
- * @return Attachment
*/
- public function setContainerObj($obj)
+ public function setContainerObj($obj): static
{
if ($obj === null) {
$this->containerObj = null;
@@ -282,14 +274,14 @@ public function setContainerObj($obj)
throw new InvalidArgumentException(sprintf(
'Container object must be an instance of %s; received %s',
AttachmentContainerInterface::class,
- (is_object($obj) ? get_class($obj) : gettype($obj))
+ (get_debug_type($obj))
));
}
if (!$obj->id()) {
throw new InvalidArgumentException(sprintf(
'Container object must have an ID.',
- (is_object($obj) ? get_class($obj) : gettype($obj))
+ (get_debug_type($obj))
));
}
@@ -319,7 +311,7 @@ public function type()
* @throws InvalidArgumentException If provided argument is not of type 'string'.
* @return string
*/
- public function setType($type)
+ public function setType($type): static
{
if (!is_string($type)) {
throw new InvalidArgumentException('Attachment type must be a string.');
@@ -354,7 +346,7 @@ public function typeLabel()
*/
public function microType()
{
- $classname = get_called_class();
+ $classname = static::class;
if (!isset(static::$resolvedType[$classname])) {
$reflect = new ReflectionClass($this);
@@ -367,10 +359,8 @@ public function microType()
/**
* Retrieve the image attachment type.
- *
- * @return string
*/
- public function imageType()
+ public function imageType(): string
{
return self::IMAGE_TYPE;
}
@@ -384,7 +374,7 @@ public function heading()
{
$heading = $this->renderTemplate((string)$this->heading);
- if (!$heading) {
+ if ($heading === '' || $heading === '0') {
$heading = $this->translator()->translation('{{ objType }} #{{ id }}', [
'{{ objType }}' => $this->typeLabel(),
'{{ id }}' => $this->id()
@@ -410,7 +400,7 @@ public function rawHeading()
* @param string $template The attachment heading.
* @return Attachment Chainable
*/
- public function setHeading($template)
+ public function setHeading($template): static
{
$this->heading = $this->translator()->translation($template);
@@ -422,7 +412,7 @@ public function setHeading($template)
*
* @return Translation|string|null
*/
- public function preview()
+ public function preview(): string
{
if ($this->preview) {
return $this->renderTemplate((string)$this->preview);
@@ -447,7 +437,7 @@ public function rawPreview()
* @param string $template The attachment preview.
* @return Attachment Chainable
*/
- public function setPreview($template)
+ public function setPreview($template): static
{
$this->preview = $this->translator()->translation($template);
@@ -456,90 +446,72 @@ public function setPreview($template)
/**
* Determine if the attachment type is an image.
- *
- * @return boolean
*/
- public function isImage()
+ public function isImage(): bool
{
return ($this->microType() === 'image');
}
/**
* Determine if the attachment type is an embed object.
- *
- * @return boolean
*/
- public function isEmbed()
+ public function isEmbed(): bool
{
return ($this->microType() === 'embed');
}
/**
* Determine if the attachment type is a video.
- *
- * @return boolean
*/
- public function isVideo()
+ public function isVideo(): bool
{
return ($this->microType() === 'video');
}
/**
* Determine if the attachment type is a file attachment.
- *
- * @return boolean
*/
- public function isFile()
+ public function isFile(): bool
{
return ($this->microType() === 'file');
}
/**
* Determine if the attachment type is a text-area.
- *
- * @return boolean
*/
- public function isText()
+ public function isText(): bool
{
return ($this->microType() === 'text');
}
/**
* Determine if the attachment type is an image gallery.
- *
- * @return boolean
*/
- public function isGallery()
+ public function isGallery(): bool
{
return ($this->microType() === 'gallery');
}
/**
* Determine if the attachment type is an accordion.
- *
- * @return boolean
*/
- public function isAccordion()
+ public function isAccordion(): bool
{
return ($this->microType() === 'accordion');
}
/**
* Determine if the attachment type is a link.
- *
- * @return boolean
*/
- public function isLink()
+ public function isLink(): bool
{
return ($this->microType() === 'link');
}
/**
* Determine if this attachment is a container.
- *
- * @return boolean
*/
- public function isAttachmentContainer()
+ public function isAttachmentContainer(): bool
{
return ($this instanceof AttachmentContainerInterface);
}
@@ -553,9 +525,9 @@ public function isAttachmentContainer()
* @param boolean $show Show (TRUE) or hide (FALSE) the title.
* @return UiItemInterface Chainable
*/
- public function setShowTitle($show)
+ public function setShowTitle($show): static
{
- $this->showTitle = !!$show;
+ $this->showTitle = (bool)$show;
return $this;
}
@@ -564,9 +536,8 @@ public function setShowTitle($show)
* Set the attachment's title.
*
* @param string $title The object title.
- * @return self
*/
- public function setTitle($title)
+ public function setTitle($title): static
{
$this->title = $this->translator()->translation($title);
@@ -577,9 +548,8 @@ public function setTitle($title)
* Set the attachment's sub-title.
*
* @param string $title The object title.
- * @return self
*/
- public function setSubtitle($title)
+ public function setSubtitle($title): static
{
$this->subtitle = $this->translator()->translation($title);
@@ -590,9 +560,8 @@ public function setSubtitle($title)
* Set the attachment's description.
*
* @param string $description The description of the object.
- * @return self
*/
- public function setDescription($description)
+ public function setDescription($description): static
{
$this->description = $this->translator()->translation($description);
@@ -609,9 +578,8 @@ public function setDescription($description)
* Set the attachment's keywords.
*
* @param string|string[] $keywords One or more entries.
- * @return self
*/
- public function setKeywords($keywords)
+ public function setKeywords($keywords): static
{
$this->keywords = $keywords;
@@ -622,9 +590,8 @@ public function setKeywords($keywords)
* Set the path to the thumbnail associated with the object.
*
* @param string $path A path to an image.
- * @return self
*/
- public function setThumbnail($path)
+ public function setThumbnail($path): static
{
$this->thumbnail = $this->translator()->translation($path);
@@ -635,9 +602,8 @@ public function setThumbnail($path)
* Set the path to the attached file.
*
* @param string $path A path to a file.
- * @return self
*/
- public function setFile($path)
+ public function setFile($path): static
{
$this->file = $this->translator()->translation($path);
@@ -648,9 +614,8 @@ public function setFile($path)
* Set the URL.
*
* @param string $link An external url.
- * @return self
*/
- public function setLink($link)
+ public function setLink($link): static
{
$this->link = $this->translator()->translation($link);
@@ -661,9 +626,8 @@ public function setLink($link)
* Set the file label.
*
* @param string $label A descriptor.
- * @return self
*/
- public function setFileLabel($label)
+ public function setFileLabel($label): static
{
$this->fileLabel = $this->translator()->translation($label);
@@ -674,9 +638,8 @@ public function setFileLabel($label)
* Set the link label.
*
* @param string $label A descriptor.
- * @return self
*/
- public function setLinkLabel($label)
+ public function setLinkLabel($label): static
{
$this->linkLabel = $this->translator()->translation($label);
@@ -688,9 +651,8 @@ public function setLinkLabel($label)
*
* @param integer|float $size A file size in bytes; the one of the attached.
* @throws InvalidArgumentException If provided argument is not of type 'integer' or 'float'.
- * @return self
*/
- public function setFileSize($size)
+ public function setFileSize($size): static
{
if ($size === null) {
$this->fileSize = null;
@@ -711,9 +673,8 @@ public function setFileSize($size)
* Set file extension.
*
* @param string $type File extension.
- * @return self
*/
- public function setFileType($type)
+ public function setFileType($type): static
{
$this->fileType = $type;
@@ -725,9 +686,8 @@ public function setFileType($type)
*
* @param string $embed A URI or an HTML media element.
* @throws InvalidArgumentException If provided argument is not of type 'string'.
- * @return self
*/
- public function setEmbed($embed)
+ public function setEmbed($embed): static
{
$this->embed = $this->translator()->translation($embed);
@@ -736,9 +696,8 @@ public function setEmbed($embed)
/**
* @param string|\string[] $categories Category elements.
- * @return self
*/
- public function setCategories($categories)
+ public function setCategories($categories): static
{
$this->categories = $categories;
@@ -758,7 +717,7 @@ public function showTitle()
if (is_bool($this->showTitle)) {
return $this->showTitle;
} else {
- return !!$this->title();
+ return (bool)$this->title();
}
}
@@ -847,7 +806,7 @@ public function fileOrLink()
*
* @return string[]|null
*/
- public function fileAndLink()
+ public function fileAndLink(): array
{
$prop = $this->property('file');
$files = $prop->parseValAsFileList($this['file']);
@@ -855,16 +814,15 @@ public function fileAndLink()
$items = array_merge($files, $links);
$items = array_unique($items);
- $items = array_values($items);
- return $items;
+ return array_values($items);
}
/**
* Basename of the associated file.
* @return string Basename of file.
*/
- public function basename()
+ public function basename(): string
{
if (!$this->file()) {
return '';
@@ -940,9 +898,8 @@ public function presenter()
/**
* @param ModelInterface|mixed $presenter Presenter for Attachment.
- * @return self
*/
- public function setPresenter($presenter)
+ public function setPresenter($presenter): static
{
$this->presenter = $presenter;
@@ -951,15 +908,14 @@ public function setPresenter($presenter)
// Events
// =============================================================================
-
/**
* Event called before _deleting_ the attachment.
*
* @see Charcoal\Source\StorableTrait::preDelete() For the "create" Event.
* @see Charcoal\Attachment\Traits\AttachmentAwareTrait::removeJoins
- * @return boolean
*/
- public function preDelete()
+ #[\Override]
+ public function preDelete(): bool
{
$joinCollection = $this->collectionLoader()
->reset()
@@ -976,15 +932,13 @@ public function preDelete()
// Utilities
// =============================================================================
-
/**
* Set the base URI of the project.
*
* @see \Charcoal\Admin\Support\setBaseUrl::baseUrl()
* @param UriInterface $uri The base URI.
- * @return self
*/
- protected function setBaseUrl(UriInterface $uri)
+ protected function setBaseUrl(UriInterface $uri): static
{
$this->baseUrl = $uri;
@@ -995,14 +949,13 @@ protected function setBaseUrl(UriInterface $uri)
* Retrieve the base URI of the project.
*
* @throws RuntimeException If the base URI is missing.
- * @return UriInterface|null
*/
- public function baseUrl()
+ public function baseUrl(): \Psr\Http\Message\UriInterface
{
- if (!isset($this->baseUrl)) {
+ if (!$this->baseUrl instanceof \Psr\Http\Message\UriInterface) {
throw new RuntimeException(sprintf(
'The base URI is not defined for [%s]',
- get_class($this)
+ static::class
));
}
@@ -1024,9 +977,9 @@ public function createAbsoluteUrl($uri)
$uri = strval($uri);
if ($this->isRelativeUri($uri)) {
$parts = parse_url($uri);
- $path = isset($parts['path']) ? $parts['path'] : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
+ $path = ($parts['path'] ?? '');
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
return $this->baseUrl()->withPath($path)->withQuery($query)->withFragment($hash);
}
@@ -1040,7 +993,7 @@ public function createAbsoluteUrl($uri)
* @param string $text A string to parse relative URIs.
* @return UriInterface|null
*/
- protected function resolveUrls($text)
+ protected function resolveUrls($text): ?string
{
static $search;
@@ -1050,20 +1003,16 @@ protected function resolveUrls($text)
$search = sprintf(
'(?<=%1$s=")(?!%2$s)(\S+)(?=")',
- implode('="|', array_map('preg_quote', $attr, [ '~' ])),
- implode('|', array_map('preg_quote', $scheme, [ '~' ]))
+ implode('="|', array_map(preg_quote(...), $attr, [ '~' ])),
+ implode('|', array_map(preg_quote(...), $scheme, [ '~' ]))
);
}
- $text = preg_replace_callback(
+ return preg_replace_callback(
'~' . $search . '~i',
- function ($matches) {
- return $this->createAbsoluteUrl($matches[1]);
- },
+ fn($matches) => $this->createAbsoluteUrl($matches[1]),
$text
);
-
- return $text;
}
/**
@@ -1082,21 +1031,15 @@ protected function isRelativeUri($uri)
if (\parse_url($uri, PHP_URL_SCHEME)) {
return false;
}
-
- if (\preg_match('/^([\/\#\?]|[a-z][a-z0-9+.-]*:)/i', $uri)) {
- return false;
- }
-
- return true;
+ return !\preg_match('/^([\/\#\?]|[a-z][a-z0-9+.-]*:)/i', $uri);
}
/**
* Set a model collection loader.
*
* @param CollectionLoader $loader The collection loader.
- * @return self
*/
- protected function setCollectionLoader(CollectionLoader $loader)
+ protected function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
@@ -1107,14 +1050,13 @@ protected function setCollectionLoader(CollectionLoader $loader)
* Retrieve the model collection loader.
*
* @throws Exception If the collection loader was not previously set.
- * @return CollectionLoader
*/
- public function collectionLoader()
+ public function collectionLoader(): \Charcoal\Loader\CollectionLoader
{
- if (!isset($this->collectionLoader)) {
+ if (!$this->collectionLoader instanceof \Charcoal\Loader\CollectionLoader) {
throw new Exception(sprintf(
'Collection Loader is not defined for "%s"',
- get_class($this)
+ static::class
));
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Object/Category/Generic.php b/packages/attachment/src/Charcoal/Attachment/Object/Category/Generic.php
index 0c8506862..304d3e3ec 100644
--- a/packages/attachment/src/Charcoal/Attachment/Object/Category/Generic.php
+++ b/packages/attachment/src/Charcoal/Attachment/Object/Category/Generic.php
@@ -1,5 +1,7 @@
name = $this->translator()->translation($name);
@@ -42,10 +44,7 @@ public function name()
return $this->name;
}
- /**
- * @return array
- */
- public function loadCategoryItems()
+ public function loadCategoryItems(): array
{
return [];
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Object/Container.php b/packages/attachment/src/Charcoal/Attachment/Object/Container.php
index ea282fdcb..1933d8edc 100644
--- a/packages/attachment/src/Charcoal/Attachment/Object/Container.php
+++ b/packages/attachment/src/Charcoal/Attachment/Object/Container.php
@@ -33,6 +33,7 @@ class Container extends Attachment implements
* @param ServiceContainer $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(ServiceContainer $container)
{
parent::setDependencies($container);
@@ -54,14 +55,10 @@ protected function setDependencies(ServiceContainer $container)
public function attachments(...$args)
{
$attachables = $this->attachableObjects();
- $attachments = call_user_func_array([ $this, 'getAttachments' ], $args);
+ $attachments = call_user_func_array($this->getAttachments(...), $args);
foreach ($attachments as $attachment) {
- if (isset($attachables[$attachment->objType()])) {
- $attachment->attachmentType = $attachables[$attachment->objType()];
- } else {
- $attachment->attachmentType = [];
- }
+ $attachment->attachmentType = ($attachables[$attachment->objType()] ?? []);
}
return $attachments;
@@ -70,14 +67,14 @@ public function attachments(...$args)
/**
* Event called before _deleting_ the attachment.
*
- * @return boolean
* @see Charcoal\Attachment\Traits\AttachmentAwareTrait::removeJoins
* @see Charcoal\Source\StorableTrait::preDelete() For the "create" Event.
*/
- public function preDelete()
+ #[\Override]
+ public function preDelete(): bool
{
// Delete nested attachments
- array_map(function ($attachment) {
+ array_map(function ($attachment): void {
$attachment->delete();
}, $this->attachments()->values());
diff --git a/packages/attachment/src/Charcoal/Attachment/Object/Embed.php b/packages/attachment/src/Charcoal/Attachment/Object/Embed.php
index 0c7aa2fc0..a3bb35988 100644
--- a/packages/attachment/src/Charcoal/Attachment/Object/Embed.php
+++ b/packages/attachment/src/Charcoal/Attachment/Object/Embed.php
@@ -1,5 +1,7 @@
generateThumbnail();
@@ -56,9 +54,9 @@ public function preSave()
*
* @see StorableTrait::preUpdate() For the "update" Event.
* @param array $properties Optional. The list of properties to update.
- * @return boolean
*/
- public function preUpdate(array $properties = null)
+ #[\Override]
+ public function preUpdate(?array $properties = null): bool
{
$this->generateThumbnail();
diff --git a/packages/attachment/src/Charcoal/Attachment/Object/Gallery.php b/packages/attachment/src/Charcoal/Attachment/Object/Gallery.php
index f64628c1f..ab6bcd72f 100644
--- a/packages/attachment/src/Charcoal/Attachment/Object/Gallery.php
+++ b/packages/attachment/src/Charcoal/Attachment/Object/Gallery.php
@@ -21,10 +21,8 @@ class Gallery extends Container
/**
* Retrieve the container's attachments as rows containing columns.
- *
- * @return array
*/
- public function attachmentsAsRows()
+ public function attachmentsAsRows(): array
{
$rows = [];
@@ -32,7 +30,7 @@ public function attachmentsAsRows()
$rows = array_chunk($this->attachments()->values(), $this->numColumns);
/** Map row content with useful front-end properties. */
- array_walk($rows, function (&$attachment, $index) {
+ array_walk($rows, function (&$attachment, $index): void {
$attachment = [
'columns' => $attachment,
'isFirst' => ($index === 0),
@@ -45,10 +43,8 @@ public function attachmentsAsRows()
/**
* Retrieve the Bootstrap column width to be used in front-end templating.
- *
- * @return string
*/
- public function columnWidth()
+ public function columnWidth(): string
{
return (string)ceil(12 / $this->numColumns);
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Object/Image.php b/packages/attachment/src/Charcoal/Attachment/Object/Image.php
index 7af407710..f173e7117 100644
--- a/packages/attachment/src/Charcoal/Attachment/Object/Image.php
+++ b/packages/attachment/src/Charcoal/Attachment/Object/Image.php
@@ -14,6 +14,7 @@ class Image extends File
*
* @return string|null
*/
+ #[\Override]
public function src()
{
$src = $this->thumbnail();
@@ -31,9 +32,9 @@ public function src()
* @todo Generate thumbnail from the main image (or not.).
* @used-by StorableTrait::preSave() For the "create" Event.
* @used-by StorableTrait::preUpdate() For the "update" Event.
- * @return boolean
*/
- public function generateThumbnail()
+ #[\Override]
+ public function generateThumbnail(): bool
{
return true;
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Object/Join.php b/packages/attachment/src/Charcoal/Attachment/Object/Join.php
index be69ce330..a797cc864 100644
--- a/packages/attachment/src/Charcoal/Attachment/Object/Join.php
+++ b/packages/attachment/src/Charcoal/Attachment/Object/Join.php
@@ -112,14 +112,12 @@ class Join extends AbstractModel implements
*
* @var JoinInterface[]|null
*/
- private $hierarchy;
+ private ?array $hierarchy = null;
/**
* Store the factory instance.
- *
- * @var FactoryInterface
*/
- private $modelFactory;
+ private ?\Charcoal\Factory\FactoryInterface $modelFactory = null;
/**
* Set the model's dependencies.
@@ -127,6 +125,7 @@ class Join extends AbstractModel implements
* @param ServiceContainer $container Service container.
* @return void
*/
+ #[\Override]
protected function setDependencies(ServiceContainer $container)
{
parent::setDependencies($container);
@@ -234,9 +233,8 @@ public function getParent()
*
* @todo Add support for multiple masters.
* @throws LogicException If the relationship is broken or incomplete.
- * @return JoinInterface|null
*/
- public function getMaster()
+ public function getMaster(): ?\Charcoal\Attachment\Interfaces\JoinInterface
{
$hierarchy = $this->invertedHierarchy();
if (isset($hierarchy[0])) {
@@ -250,10 +248,8 @@ public function getMaster()
* Reset this relationship's hierarchy.
*
* The relationship's hierarchy can be rebuilt with {@see self::hierarchy()}.
- *
- * @return self
*/
- public function resetHierarchy()
+ public function resetHierarchy(): static
{
$this->hierarchy = null;
@@ -265,7 +261,7 @@ public function resetHierarchy()
*
* @return JoinInterface[]
*/
- public function hierarchy()
+ public function hierarchy(): array
{
if ($this->hierarchy === null) {
$hierarchy = [];
@@ -287,7 +283,7 @@ public function hierarchy()
*
* @return JoinInterface[]
*/
- public function invertedHierarchy()
+ public function invertedHierarchy(): array
{
return array_reverse($this->hierarchy());
}
@@ -295,16 +291,14 @@ public function invertedHierarchy()
// Setters
-// =============================================================================
-
+ // =============================================================================
/**
* Set the source object type.
*
* @param string $type The object type identifier.
* @throws InvalidArgumentException If provided argument is not of type 'string'.
- * @return self
*/
- public function setObjectType($type)
+ public function setObjectType($type): static
{
if (!is_string($type)) {
throw new InvalidArgumentException('Object type must be a string.');
@@ -320,9 +314,8 @@ public function setObjectType($type)
*
* @param mixed $id The object ID to join the attachment to.
* @throws InvalidArgumentException If provided argument is not a string or numerical value.
- * @return self
*/
- public function setObjectId($id)
+ public function setObjectId($id): static
{
if (!is_scalar($id)) {
throw new InvalidArgumentException(
@@ -340,9 +333,8 @@ public function setObjectId($id)
*
* @param mixed $id The object ID to attach.
* @throws InvalidArgumentException If provided argument is not a string or numerical value.
- * @return self
*/
- public function setAttachmentId($id)
+ public function setAttachmentId($id): static
{
if (!is_scalar($id)) {
throw new InvalidArgumentException(
@@ -360,9 +352,8 @@ public function setAttachmentId($id)
*
* @param mixed $id The group ID describing the relationship.
* @throws InvalidArgumentException If provided argument is not a string.
- * @return self
*/
- public function setGroup($id)
+ public function setGroup($id): static
{
if (!is_string($id)) {
throw new InvalidArgumentException(
@@ -383,9 +374,8 @@ public function setGroup($id)
*
* @param integer $position A position.
* @throws InvalidArgumentException If the position is not an integer (or numeric integer string).
- * @return self
*/
- public function setPosition($position)
+ public function setPosition($position): static
{
if ($position === null) {
$this->position = null;
@@ -407,11 +397,10 @@ public function setPosition($position)
* Enable/Disable the relationship.
*
* @param boolean $active The active flag.
- * @return self
*/
- public function setActive($active)
+ public function setActive($active): static
{
- $this->active = !!$active;
+ $this->active = (bool)$active;
return $this;
}
@@ -420,9 +409,8 @@ public function setActive($active)
* Set an model factory.
*
* @param FactoryInterface $factory The factory to create models.
- * @return self
*/
- protected function setModelFactory(FactoryInterface $factory)
+ protected function setModelFactory(FactoryInterface $factory): static
{
$this->modelFactory = $factory;
@@ -498,14 +486,13 @@ public function active()
* Retrieve the model factory.
*
* @throws RuntimeException If the model factory is missing.
- * @return FactoryInterface
*/
- public function modelFactory()
+ public function modelFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->modelFactory)) {
+ if (!$this->modelFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(sprintf(
'Model Factory is not defined for [%s]',
- get_class($this)
+ static::class
));
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Object/Link.php b/packages/attachment/src/Charcoal/Attachment/Object/Link.php
index 13b03ee17..f56ddd69c 100644
--- a/packages/attachment/src/Charcoal/Attachment/Object/Link.php
+++ b/packages/attachment/src/Charcoal/Attachment/Object/Link.php
@@ -1,5 +1,7 @@
setModelFactory($container['model/factory']);
}
- /**
- * @return boolean
- */
- public function interactive()
+ #[\Override]
+ public function interactive(): bool
{
return true;
}
/**
* Retrieve the script's supported arguments.
- *
- * @return array
*/
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'hard' => [
@@ -166,9 +165,8 @@ public function defaultArguments()
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
- public function run(RequestInterface $request, ResponseInterface $response)
+ public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
unset($request);
@@ -183,10 +181,8 @@ public function run(RequestInterface $request, ResponseInterface $response)
/**
* Execute the prime directive.
- *
- * @return self
*/
- public function start()
+ public function start(): static
{
$cli = $this->climate();
@@ -202,16 +198,13 @@ public function start()
/**
* Prune relationships of dead objects.
- *
- * @return self
*/
- protected function pruneRelationships()
+ protected function pruneRelationships(): static
{
- $cli = $this->climate();
- $ask = $this->interactive();
- $dry = $this->dryRun();
- $verb = $this->verbose();
- $mucho = ($dry || $verb);
+ $this->climate();
+ $this->interactive();
+ $this->dryRun();
+ $this->verbose();
$attach = $this->modelFactory()->get(Attachment::class);
$pivot = $this->modelFactory()->get(Join::class);
@@ -227,7 +220,7 @@ protected function pruneRelationships()
$sql = 'SELECT DISTINCT `%sourceType` FROM `%pivotTable`;';
$rows = $db->query(strtr($sql, $binds), PDO::FETCH_ASSOC);
if ($rows->rowCount()) {
- error_log(get_called_class() . '::' . __FUNCTION__);
+ error_log(static::class . '::' . __FUNCTION__);
/** @todo Confirm each distinct source type */
@@ -305,10 +298,8 @@ protected function pruneRelationships()
/**
* Prune orphan attachments.
- *
- * @return self
*/
- protected function pruneAttachments()
+ protected function pruneAttachments(): static
{
$cli = $this->climate();
$ask = $this->interactive();
@@ -366,7 +357,7 @@ protected function pruneAttachments()
$this->indent = str_repeat(' ', (($length * 2) + 4));
$prop = $attach->property($attach->key());
- if ($prop && preg_match('~\b\w+\((?\d+)\)~', $prop->sqlType(), $matches)) {
+ if ($prop && preg_match('~\b\w+\((?\d+)\)~', (string)$prop->sqlType(), $matches)) {
$pad = (intval($matches['length']) + 5);
} else {
$pad = 20;
@@ -396,8 +387,8 @@ protected function pruneAttachments()
if ($ask) {
$type = sprintf('[%s]', $obj->microType());
- $label = sprintf('#%1$s %2$s', str_pad($objId, $pad), str_pad($type, 20));
- if ($title) {
+ $label = sprintf('#%1$s %2$s', str_pad((string)$objId, $pad), str_pad($type, 20));
+ if ($title !== '' && $title !== '0') {
$label = sprintf('%1$s "%2$s"', $label, $title);
}
@@ -506,10 +497,8 @@ protected function pruneAttachments()
/**
* Display stored messages or a generic conclusion.
- *
- * @return self
*/
- protected function conclude()
+ protected function conclude(): static
{
$cli = $this->climate();
@@ -531,15 +520,14 @@ protected function conclude()
* @param string $singular The message when the count is 1.
* @param string $zero The message when the count is zero.
* @throws InvalidArgumentException If the given argument is not an integer.
- * @return boolean
*/
- protected function describeCount($count, $plural, $singular, $zero)
+ protected function describeCount($count, $plural, $singular, $zero): bool
{
if (!is_int($count)) {
throw new InvalidArgumentException(
sprintf(
'Must be an integer',
- is_object($count) ? get_class($count) : gettype($count)
+ get_debug_type($count)
)
);
}
@@ -573,9 +561,8 @@ protected function describeCount($count, $plural, $singular, $zero)
* @param integer|null $pruned Count the number of deleted objects.
* @param integer|null $failed Count the number of failed deletions.
* @param array|null $feedback Update the feedback.
- * @return boolean
*/
- protected function deleteObject(AttachableInterface $obj, &$pruned = null, &$failed = null, array &$feedback = null)
+ protected function deleteObject(AttachableInterface $obj, &$pruned = null, &$failed = null, ?array &$feedback = null): bool
{
$verb = $this->verbose();
diff --git a/packages/attachment/src/Charcoal/Attachment/Script/MigrateScript.php b/packages/attachment/src/Charcoal/Attachment/Script/MigrateScript.php
index ab745426b..0757de3c7 100644
--- a/packages/attachment/src/Charcoal/Attachment/Script/MigrateScript.php
+++ b/packages/attachment/src/Charcoal/Attachment/Script/MigrateScript.php
@@ -31,6 +31,7 @@ class MigrateScript extends AlterPrimaryKeyScript
/**
* @return void
*/
+ #[\Override]
protected function init()
{
$this->setArguments($this->defaultArguments());
@@ -44,10 +45,9 @@ protected function init()
/**
* Execute the prime directive.
- *
- * @return self
*/
- public function start()
+ #[\Override]
+ public function start(): static
{
$cli = $this->climate();
@@ -166,7 +166,6 @@ public function start()
// Alter Table
// =========================================================================
-
/**
* Sync the new primary keys to pivot table.
*
@@ -175,14 +174,14 @@ public function start()
* @param IdProperty $oldProp The previous ID property.
* @param PropertyField $oldField The previous ID field.
* @throws InvalidArgumentException If the new property does not implement the proper mode.
- * @return self
*/
+ #[\Override]
protected function syncRelatedFields(
IdProperty $newProp,
PropertyField $newField,
IdProperty $oldProp,
PropertyField $oldField
- ) {
+ ): static {
unset($newProp, $oldProp, $oldField);
$cli = $this->climate();
@@ -243,6 +242,7 @@ protected function syncRelatedFields(
*
* @return array
*/
+ #[\Override]
public function defaultArguments()
{
static $arguments;
@@ -267,9 +267,10 @@ public function defaultArguments()
*
* @return ModelInterface
*/
+ #[\Override]
public function targetModel()
{
- if (!isset($this->targetModel)) {
+ if ($this->targetModel === null) {
$this->targetModel = $this->modelFactory()->get(Attachment::class);
}
@@ -283,7 +284,7 @@ public function targetModel()
*/
public function pivotModel()
{
- if (!isset($this->pivotModel)) {
+ if ($this->pivotModel === null) {
$this->pivotModel = $this->modelFactory()->get(Join::class);
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php b/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php
index 29c269507..6a8a714b6 100644
--- a/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php
+++ b/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php
@@ -57,8 +57,8 @@ trait AttachmentAwareTrait
public function getAttachments(
$group = null,
$type = null,
- callable $before = null,
- callable $after = null
+ ?callable $before = null,
+ ?callable $after = null
) {
if (is_array($group)) {
$options = $group;
@@ -81,23 +81,20 @@ public function getAttachments(
$options = $this->parseAttachmentOptions($options);
extract($options);
- if ($group !== 0) {
- if (!is_string($group)) {
- throw new InvalidArgumentException(sprintf(
- 'The "group" must be a string, received %s',
- is_object($group) ? get_class($group) : gettype($group)
- ));
- }
+ if ($group !== 0 && !is_string($group)) {
+ throw new InvalidArgumentException(sprintf(
+ 'The "group" must be a string, received %s',
+ get_debug_type($group)
+ ));
}
if ($type !== 0) {
if (!is_string($type)) {
throw new InvalidArgumentException(sprintf(
'The "type" must be a string, received %s',
- is_object($type) ? get_class($type) : gettype($type)
+ get_debug_type($type)
));
}
-
$type = preg_replace('/([a-z])([A-Z])/', '$1-$2', $type);
$type = strtolower(str_replace('\\', '/', $type));
}
@@ -140,7 +137,7 @@ public function getAttachments(
attachment.active = 1';
}
- if ($type) {
+ if ($type !== '' && $type !== 0) {
$query .= sprintf('
AND
attachment.type = "%s"', $type);
@@ -152,7 +149,7 @@ public function getAttachments(
AND
joined.object_id = "%s"', $objType, $objId);
- if ($group) {
+ if ($group !== '' && $group !== 0) {
$query .= sprintf('
AND
joined.group = "%s"', $group);
@@ -165,7 +162,7 @@ public function getAttachments(
$loader->setModel($attProto);
$loader->setDynamicTypeField('type');
- $callable = function (&$att) use ($before) {
+ $callable = function (&$att) use ($before): void {
if ($this instanceof AttachableInterface) {
$att->setContainerObj($this);
}
@@ -194,17 +191,15 @@ public function getAttachments(
*
* @return boolean Whether $this has any nodes (TRUE) or not (FALSE).
*/
- public function hasAttachments()
+ public function hasAttachments(): bool
{
- return !!($this->numAttachments());
+ return (bool)$this->numAttachments();
}
/**
* Count the number of nodes associated to the current object.
- *
- * @return integer
*/
- public function numAttachments()
+ public function numAttachments(): int
{
return count($this->getAttachments([
'group' => null
@@ -243,9 +238,9 @@ public function addAttachment($attachment, $group = 'contents')
/**
* Remove all joins linked to a specific attachment.
*
- * @deprecated in favour of AttachmentAwareTrait::removeAttachmentJoins()
* @return boolean
*/
+ #[\Deprecated(message: 'in favour of AttachmentAwareTrait::removeAttachmentJoins()')]
public function removeJoins()
{
$this->logger->warning(
@@ -259,10 +254,8 @@ public function removeJoins()
/**
* Remove all joins linked to a specific attachment.
- *
- * @return boolean
*/
- public function removeAttachmentJoins()
+ public function removeAttachmentJoins(): bool
{
$joinProto = $this->modelFactory()->get(Join::class);
@@ -285,9 +278,8 @@ public function removeAttachmentJoins()
* Delete the objects associated to the current object.
*
* @param array $options Filter the attachments by an option list.
- * @return boolean
*/
- public function deleteAttachments(array $options = [])
+ public function deleteAttachments(array $options = []): bool
{
foreach ($this->getAttachments($options) as $attachment) {
$attachment->delete();
@@ -310,7 +302,7 @@ public function deleteAttachments(array $options = [])
* ]
* @return array Attachment obj_types.
*/
- public function attachmentObjTypes()
+ public function attachmentObjTypes(): array
{
$defaultEditDashboard = $this->metadata()->get('admin.default_edit_dashboard');
$dashboards = $this->metadata()->get('admin.dashboards');
@@ -318,7 +310,7 @@ public function attachmentObjTypes()
$widgets = $editDashboard['widgets'];
$formIdent = '';
- foreach ($widgets as $ident => $val) {
+ foreach ($widgets as $val) {
if ($val['type'] == 'charcoal/admin/widget/object-form') {
$formIdent = $val['form_ident'];
}
@@ -364,17 +356,15 @@ public function attachmentObjTypes()
* @param array $options A list of options.
* Option keys not present in {@see self::getDefaultAttachmentOptions() default options}
* are rejected.
- * @return array
*/
- protected function parseAttachmentOptions(array $options)
+ protected function parseAttachmentOptions(array $options): array
{
$defaults = $this->getDefaultAttachmentOptions();
$options = array_intersect_key($options, $defaults);
$options = array_filter($options, [ $this, 'filterAttachmentOption' ], ARRAY_FILTER_USE_BOTH);
- $options = array_replace($defaults, $options);
- return $options;
+ return array_replace($defaults, $options);
}
/**
@@ -389,25 +379,17 @@ protected function filterAttachmentOption($val, $key)
if ($val === null) {
return false;
}
-
- switch ($key) {
- case 'isActive':
- return is_bool($val);
-
- case 'before':
- case 'after':
- return is_callable($val);
- }
-
- return true;
+ return match ($key) {
+ 'isActive' => is_bool($val),
+ 'before', 'after' => is_callable($val),
+ default => true,
+ };
}
/**
* Retrieve the default options for loading a collection of attachments.
- *
- * @return array
*/
- protected function getDefaultAttachmentOptions()
+ protected function getDefaultAttachmentOptions(): array
{
return [
'group' => 0,
diff --git a/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php b/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php
index d3b6250c3..51296ffc0 100644
--- a/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php
+++ b/packages/attachment/src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php
@@ -126,10 +126,8 @@ public function attachmentGroup()
/**
* Retrieve the attachment types with their collections.
- *
- * @return array
*/
- public function attachmentTypes()
+ public function attachmentTypes(): array
{
return array_values($this->attachableObjects());
}
@@ -165,7 +163,7 @@ public function attachableObjects()
if (isset($attMeta['label'])) {
$attMeta['label'] = $this->translator()->translation($attMeta['label']);
} else {
- $attMeta['label'] = ucfirst(basename($attType));
+ $attMeta['label'] = ucfirst(basename((string)$attType));
}
$faIcon = '';
@@ -174,20 +172,12 @@ public function attachableObjects()
}
$attMeta['faIcon'] = $faIcon;
- $attMeta['hasFaIcon'] = !!$faIcon;
+ $attMeta['hasFaIcon'] = (bool)$faIcon;
// Custom forms
- if (isset($attMeta['form_ident'])) {
- $attMeta['formIdent'] = $attMeta['form_ident'];
- } else {
- $attMeta['formIdent'] = null;
- }
+ $attMeta['formIdent'] = ($attMeta['form_ident'] ?? null);
- if (isset($attMeta['quick_form_ident'])) {
- $attMeta['quickFormIdent'] = $attMeta['quick_form_ident'];
- } else {
- $attMeta['quickFormIdent'] = null;
- }
+ $attMeta['quickFormIdent'] = ($attMeta['quick_form_ident'] ?? null);
$this->attachableObjects[$attType] = $attMeta;
}
@@ -199,10 +189,8 @@ public function attachableObjects()
/**
* Determine if this attachment is a container.
- *
- * @return boolean
*/
- public function isAttachmentContainer()
+ public function isAttachmentContainer(): bool
{
return true;
}
diff --git a/packages/attachment/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php b/packages/attachment/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php
index f5455b41c..b6d5fcfbe 100644
--- a/packages/attachment/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php
+++ b/packages/attachment/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php
@@ -76,7 +76,7 @@ public function config($key = null)
* @param array|null $data Optional data to pass to the new configset.
* @return ConfigInterface
*/
- protected function createConfig($data = null)
+ protected function createConfig($data = null): \Charcoal\Attachment\AttachmentsConfig
{
return new AttachmentsConfig($data);
}
diff --git a/packages/attachment/tests/Charcoal/ContainerIntegrationTrait.php b/packages/attachment/tests/Charcoal/ContainerIntegrationTrait.php
index 4ad02d1c1..0f4c9eaa5 100644
--- a/packages/attachment/tests/Charcoal/ContainerIntegrationTrait.php
+++ b/packages/attachment/tests/Charcoal/ContainerIntegrationTrait.php
@@ -51,9 +51,8 @@ protected function getContainerProvider()
/**
* @see ContainerProvider
- * @return void
*/
- private function setupContainer()
+ private function setupContainer(): void
{
$provider = new ContainerProvider();
$container = new Container();
diff --git a/packages/attachment/tests/Charcoal/ContainerProvider.php b/packages/attachment/tests/Charcoal/ContainerProvider.php
index 1cacbbbd7..b192e8772 100644
--- a/packages/attachment/tests/Charcoal/ContainerProvider.php
+++ b/packages/attachment/tests/Charcoal/ContainerProvider.php
@@ -55,9 +55,8 @@ class ContainerProvider
* Register the unit tests required services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseServices(Container $container)
+ public function registerBaseServices(Container $container): void
{
$this->registerConfig($container);
$this->registerDatabase($container);
@@ -69,9 +68,8 @@ public function registerBaseServices(Container $container)
* Register the admin services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerAdminServices(Container $container)
+ public function registerAdminServices(Container $container): void
{
$this->registerBaseUrl($container);
$this->registerAdminConfig($container);
@@ -81,67 +79,57 @@ public function registerAdminServices(Container $container)
* Setup the application's base URI.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseUrl(Container $container)
+ public function registerBaseUrl(Container $container): void
{
- $container['base-url'] = function () {
- return Uri::createFromString('');
- };
+ $container['base-url'] = (fn() => Uri::createFromString(''));
- $container['admin/base-url'] = function () {
- return Uri::createFromString('admin');
- };
+ $container['admin/base-url'] = (fn() => Uri::createFromString('admin'));
}
/**
* Setup the application configset.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerConfig(Container $container)
+ public function registerConfig(Container $container): void
{
- $container['config'] = function () {
- return new AppConfig([
- 'base_path' => realpath(__DIR__ . '/../../..'),
- 'apis' => [
- 'google' => [
- 'recaptcha' => [
- 'public_key' => 'foobar',
- 'private_key' => 'bazqux',
- ],
- ],
- ],
- 'locales' => [
- 'en' => [
- 'locale' => 'en-US',
+ $container['config'] = (fn(): \Charcoal\App\AppConfig => new AppConfig([
+ 'base_path' => realpath(__DIR__ . '/../../..'),
+ 'apis' => [
+ 'google' => [
+ 'recaptcha' => [
+ 'public_key' => 'foobar',
+ 'private_key' => 'bazqux',
],
],
- 'translator' => [
- 'paths' => [],
+ ],
+ 'locales' => [
+ 'en' => [
+ 'locale' => 'en-US',
],
- 'metadata' => [
- 'paths' => [
- 'metadata',
- // Standalone
- 'vendor/charcoal/object/metadata',
- 'vendor/charcoal/user/metadata',
- // Monorepo
- '/../object/metadata',
- '/../user/metadata',
- ],
+ ],
+ 'translator' => [
+ 'paths' => [],
+ ],
+ 'metadata' => [
+ 'paths' => [
+ 'metadata',
+ // Standalone
+ 'vendor/charcoal/object/metadata',
+ 'vendor/charcoal/user/metadata',
+ // Monorepo
+ '/../object/metadata',
+ '/../user/metadata',
],
- ]);
- };
+ ],
+ ]));
/**
* List of Charcoal module classes.
*
* Explicitly defined in case of a version mismatch with dependencies. This parameter
* is normally defined by {@see \Charcoal\App\ServiceProvider\AppServiceProvider}.
- *
- * @var array
*/
$container['module/classes'] = [];
}
@@ -150,22 +138,18 @@ public function registerConfig(Container $container)
* Setup the admin module configset.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerAdminConfig(Container $container)
+ public function registerAdminConfig(Container $container): void
{
$this->registerConfig($container);
- $container['admin/config'] = function () {
- return new AdminConfig();
- };
+ $container['admin/config'] = (fn(): \Charcoal\Admin\Config => new AdminConfig());
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerClimate(Container $container)
+ public function registerClimate(Container $container): void
{
$container['climate/system'] = function () {
$system = Mockery::mock(Linux::class);
@@ -192,11 +176,9 @@ public function registerClimate(Container $container)
return $reader;
};
- $container['climate/util'] = function (Container $container) {
- return new UtilFactory($container['climate/system']);
- };
+ $container['climate/util'] = (fn(Container $container): \League\CLImate\Util\UtilFactory => new UtilFactory($container['climate/system']));
- $container['climate'] = function (Container $container) {
+ $container['climate'] = function (Container $container): \League\CLImate\CLImate {
$climate = new CLImate();
$climate->setOutput($container['climate/output']);
@@ -209,11 +191,10 @@ public function registerClimate(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerDatabase(Container $container)
+ public function registerDatabase(Container $container): void
{
- $container['database'] = function () {
+ $container['database'] = function (): \PDO {
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
@@ -222,9 +203,8 @@ public function registerDatabase(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerModelServiceProvider(Container $container)
+ public function registerModelServiceProvider(Container $container): void
{
static $provider = null;
@@ -237,9 +217,8 @@ public function registerModelServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerAuthServiceProvider(Container $container)
+ public function registerAuthServiceProvider(Container $container): void
{
static $provider = null;
@@ -252,9 +231,8 @@ public function registerAuthServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerTranslatorServiceProvider(Container $container)
+ public function registerTranslatorServiceProvider(Container $container): void
{
static $provider = null;
@@ -267,9 +245,8 @@ public function registerTranslatorServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerViewServiceProvider(Container $container)
+ public function registerViewServiceProvider(Container $container): void
{
static $provider = null;
@@ -282,9 +259,8 @@ public function registerViewServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerAdminServiceProvider(Container $container)
+ public function registerAdminServiceProvider(Container $container): void
{
static $provider = null;
@@ -297,23 +273,17 @@ public function registerAdminServiceProvider(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerLogger(Container $container)
+ public function registerLogger(Container $container): void
{
- $container['logger'] = function () {
- return new NullLogger();
- };
+ $container['logger'] = (fn(): \Psr\Log\NullLogger => new NullLogger());
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerCache(Container $container)
+ public function registerCache(Container $container): void
{
- $container['cache'] = function () {
- return new Pool();
- };
+ $container['cache'] = (fn(): \Stash\Pool => new Pool());
}
}
diff --git a/packages/attachment/tests/bootstrap.php b/packages/attachment/tests/bootstrap.php
new file mode 100644
index 000000000..90929e3b5
--- /dev/null
+++ b/packages/attachment/tests/bootstrap.php
@@ -0,0 +1,14 @@
+
-
->
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
-
-
+
+ ./src/Charcoal
-
-
+
+
+
+
+
+
+
+
-
+
-
-
-
-
diff --git a/packages/cache/src/Charcoal/Cache/CacheBuilder.php b/packages/cache/src/Charcoal/Cache/CacheBuilder.php
index a8b2123fa..ef099014d 100644
--- a/packages/cache/src/Charcoal/Cache/CacheBuilder.php
+++ b/packages/cache/src/Charcoal/Cache/CacheBuilder.php
@@ -27,31 +27,23 @@ final class CacheBuilder
/**
* Default logger instance.
- *
- * @var \Psr\Log\LoggerInterface|null
*/
- private $logger;
+ private ?\Psr\Log\LoggerInterface $logger = null;
/**
* Default namespace for new pools.
- *
- * @var string|null
*/
- private $namespace;
+ private ?string $namespace = null;
/**
* Default "Pool" class to use for making new pools.
- *
- * @var string
*/
- private $poolClass = Pool::class;
+ private string $poolClass = Pool::class;
/**
* Default "Item" class to use for making new items.
- *
- * @var string|null
*/
- private $itemClass;
+ private ?string $itemClass = null;
/**
* Create a cache pool builder.
@@ -88,7 +80,7 @@ public function __construct(array $data)
* @param mixed $poolOptions Optional settings for the new pool.
* @return PoolInterface
*/
- public function __invoke($cacheDriver, $poolOptions = null)
+ public function __invoke($cacheDriver, $poolOptions = null): object
{
return $this->build($cacheDriver, $poolOptions);
}
@@ -105,7 +97,7 @@ public function __invoke($cacheDriver, $poolOptions = null)
* Otherwise, the default settings are used.
* @return PoolInterface
*/
- public function build($cacheDriver, $poolOptions = null)
+ public function build($cacheDriver, $poolOptions = null): object
{
if (!($cacheDriver instanceof DriverInterface)) {
$cacheDriver = $this->resolveDriver($cacheDriver);
@@ -123,9 +115,8 @@ public function build($cacheDriver, $poolOptions = null)
* Prepare any pool options for the new pool object.
*
* @param mixed $options Settings for the new pool.
- * @return array
*/
- private function parsePoolOptions($options)
+ private function parsePoolOptions($options): array
{
$defaults = [
'pool_class' => $this->poolClass,
@@ -156,9 +147,8 @@ private function parsePoolOptions($options)
*
* @param PoolInterface $pool The new pool.
* @param array $options Settings for the new pool.
- * @return void
*/
- private function applyPoolOptions(PoolInterface $pool, array $options)
+ private function applyPoolOptions(PoolInterface $pool, array $options): void
{
if (isset($options['logger'])) {
$pool->setLogger($options['logger']);
@@ -188,7 +178,7 @@ private function resolveDriver($driver)
foreach ($driver as $drv) {
try {
return $this->resolveOneDriver($drv);
- } catch (InvalidArgumentException $e) {
+ } catch (InvalidArgumentException) {
continue;
}
}
@@ -223,7 +213,7 @@ private function resolveOneDriver($driver)
} else {
throw new InvalidArgumentException(sprintf(
'Driver class %s must implement %s',
- get_class($driver),
+ $driver::class,
DriverInterface::class
));
}
@@ -246,7 +236,7 @@ private function resolveOneDriver($driver)
throw new InvalidArgumentException(sprintf(
'Driver "%s": Class %s must implement %s',
$name,
- get_class($driver),
+ $driver::class,
DriverInterface::class
));
}
@@ -267,9 +257,8 @@ private function resolveOneDriver($driver)
*
* @param ArrayAccess|array $drivers The driver list used to create cache drivers.
* @throws InvalidArgumentException If the drivers list is invalid.
- * @return void
*/
- private function setDrivers($drivers)
+ private function setDrivers($drivers): void
{
if ($this->isAccessible($drivers)) {
$this->drivers = $drivers;
@@ -285,12 +274,11 @@ private function setDrivers($drivers)
*
* @param \Psr\Log\LoggerInterface $logger A PSR-3 logger.
* @throws InvalidArgumentException If the logger is invalid PSR-3 client.
- * @return void
*/
- private function setLogger($logger)
+ private function setLogger($logger): void
{
- $psr = 'Psr\\Log\\LoggerInterface';
- if (!is_a($logger, $psr)) {
+ $psr = \Psr\Log\LoggerInterface::class;
+ if (!$logger instanceof $psr) {
throw new InvalidArgumentException(
sprintf('Expected an instance of %s', $psr)
);
@@ -306,9 +294,8 @@ private function setLogger($logger)
*
* @param string $namespace The pool namespace.
* @throws InvalidArgumentException If the namespaces is invalid.
- * @return void
*/
- private function setNamespace($namespace)
+ private function setNamespace($namespace): void
{
if (!ctype_alnum($namespace)) {
throw new InvalidArgumentException(
@@ -326,9 +313,8 @@ private function setNamespace($namespace)
*
* @param string $class The pool class name.
* @throws InvalidArgumentException When passed an invalid or nonexistant class.
- * @return void
*/
- private function setPoolClass($class)
+ private function setPoolClass($class): void
{
if (!class_exists($class)) {
throw new InvalidArgumentException(
@@ -356,9 +342,8 @@ private function setPoolClass($class)
*
* @param string $class The item class name.
* @throws InvalidArgumentException When passed an invalid or nonexistant class.
- * @return void
*/
- private function setItemClass($class)
+ private function setItemClass($class): void
{
if (!class_exists($class)) {
throw new InvalidArgumentException(
@@ -385,9 +370,9 @@ private function setItemClass($class)
* @param mixed $var The value to check
* @return boolean TRUE if $var is iterable, FALSE otherwise.
*/
- private function isIterable($var)
+ private function isIterable($var): bool
{
- return is_array($var) || ($var instanceof Traversable);
+ return is_iterable($var);
}
/**
@@ -396,7 +381,7 @@ private function isIterable($var)
* @param mixed $var The value to check
* @return boolean TRUE if $var is an array or accessible like an array, FALSE otherwise.
*/
- private function isAccessible($var)
+ private function isAccessible($var): bool
{
return is_array($var) || ($var instanceof ArrayAccess);
}
diff --git a/packages/cache/src/Charcoal/Cache/CacheConfig.php b/packages/cache/src/Charcoal/Cache/CacheConfig.php
index 041df2bc9..6712684f8 100644
--- a/packages/cache/src/Charcoal/Cache/CacheConfig.php
+++ b/packages/cache/src/Charcoal/Cache/CacheConfig.php
@@ -33,40 +33,31 @@ class CacheConfig extends AbstractConfig
* Note:
* - When TRUE, the {@see self::$types} are used.
* - When FALSE, the "memory" type is used.
- *
- * @var boolean
*/
- private $active = true;
+ private bool $active = true;
/**
* Cache type(s) to use.
*
* Represents a cache driver.
- *
- * @var array
*/
- private $types;
+ private ?array $types = null;
/**
* Default maximum time an item will be cached.
- *
- * @var integer
*/
- private $defaultTtl = self::WEEK_IN_SECONDS;
+ private int $defaultTtl = self::WEEK_IN_SECONDS;
/**
* Cache namespace.
- *
- * @var string
*/
- private $prefix = self::DEFAULT_NAMESPACE;
+ private string $prefix = self::DEFAULT_NAMESPACE;
/**
* Retrieve the default values.
- *
- * @return array
*/
- public function defaults()
+ #[\Override]
+ public function defaults(): array
{
return [
'active' => true,
@@ -83,9 +74,9 @@ public function defaults()
* TRUE to enable, FALSE to disable.
* @return CacheConfig Chainable
*/
- public function setActive($active)
+ public function setActive($active): static
{
- $this->active = !!$active;
+ $this->active = (bool)$active;
return $this;
}
@@ -94,7 +85,7 @@ public function setActive($active)
*
* @return boolean TRUE if enabled, FALSE if disabled.
*/
- public function active()
+ public function active(): bool
{
return $this->active;
}
@@ -107,7 +98,7 @@ public function active()
* @param string[] $types One or more types to try as cache driver until success.
* @return CacheConfig Chainable
*/
- public function setTypes(array $types)
+ public function setTypes(array $types): static
{
$this->types = [];
$this->addTypes($types);
@@ -120,7 +111,7 @@ public function setTypes(array $types)
* @param string[] $types One or more types to try as cache driver until success.
* @return CacheConfig Chainable
*/
- public function addTypes(array $types)
+ public function addTypes(array $types): static
{
foreach ($types as $type) {
$this->addType($type);
@@ -135,7 +126,7 @@ public function addTypes(array $types)
* @throws InvalidArgumentException If the type is not a string or unsupported.
* @return CacheConfig Chainable
*/
- public function addType($type)
+ public function addType($type): static
{
if (!in_array($type, $this->validTypes())) {
throw new InvalidArgumentException(
@@ -153,10 +144,8 @@ public function addType($type)
* Note:
* 1. The default cache type is always appended.
* 2. Duplicate types are removed.
- *
- * @return array
*/
- public function types()
+ public function types(): array
{
$types = ($this->types + self::DEFAULT_TYPES);
return array_keys($types);
@@ -167,7 +156,7 @@ public function types()
*
* @return string[]
*/
- public function defaultTypes()
+ public function defaultTypes(): array
{
return array_keys(self::DEFAULT_TYPES);
}
@@ -177,7 +166,7 @@ public function defaultTypes()
*
* @return string[]
*/
- public function validTypes()
+ public function validTypes(): array
{
return [
'apc',
@@ -197,7 +186,7 @@ public function validTypes()
* @throws InvalidArgumentException If the TTL is not numeric.
* @return CacheConfig Chainable
*/
- public function setDefaultTtl($ttl)
+ public function setDefaultTtl($ttl): static
{
if (!is_numeric($ttl)) {
throw new InvalidArgumentException(
@@ -211,10 +200,8 @@ public function setDefaultTtl($ttl)
/**
* Retrieve the default time-to-live for cached items.
- *
- * @return integer
*/
- public function defaultTtl()
+ public function defaultTtl(): int
{
return $this->defaultTtl;
}
@@ -226,7 +213,7 @@ public function defaultTtl()
* @throws InvalidArgumentException If the prefix is not a string.
* @return CacheConfig Chainable
*/
- public function setPrefix($prefix)
+ public function setPrefix($prefix): static
{
if (!is_string($prefix)) {
throw new InvalidArgumentException(
@@ -247,10 +234,8 @@ public function setPrefix($prefix)
/**
* Retrieve the cache namespace.
- *
- * @return string
*/
- public function prefix()
+ public function prefix(): string
{
return $this->prefix;
}
diff --git a/packages/cache/src/Charcoal/Cache/CachePoolAwareTrait.php b/packages/cache/src/Charcoal/Cache/CachePoolAwareTrait.php
index 644d47dd7..e2039c0af 100644
--- a/packages/cache/src/Charcoal/Cache/CachePoolAwareTrait.php
+++ b/packages/cache/src/Charcoal/Cache/CachePoolAwareTrait.php
@@ -41,7 +41,7 @@ protected function cachePool()
if ($this->cachePool === null) {
throw new RuntimeException(sprintf(
'Cache Pool is not defined for "%s"',
- get_class($this)
+ $this::class
));
}
diff --git a/packages/cache/src/Charcoal/Cache/Facade/CachePoolFacade.php b/packages/cache/src/Charcoal/Cache/Facade/CachePoolFacade.php
index b053e8368..81878f734 100644
--- a/packages/cache/src/Charcoal/Cache/Facade/CachePoolFacade.php
+++ b/packages/cache/src/Charcoal/Cache/Facade/CachePoolFacade.php
@@ -61,7 +61,7 @@ public function __construct(array $data)
* @param mixed $ttl An integer, interval, date, or NULL to use the facade's default value.
* @return mixed The value corresponding to this cache item's $key, or NULL if not found.
*/
- public function get($key, callable $resolve = null, $ttl = null)
+ public function get(string $key, ?callable $resolve = null, $ttl = null)
{
$pool = $this->cachePool();
$item = $pool->getItem($key);
@@ -86,7 +86,7 @@ public function get($key, callable $resolve = null, $ttl = null)
* @param string $key The key for which to check existence.
* @return boolean TRUE if item exists in the cache, FALSE otherwise.
*/
- public function has($key)
+ public function has(string $key)
{
return $this->cachePool()->getItem($key)->isHit();
}
@@ -99,7 +99,7 @@ public function has($key)
* @param mixed $ttl An integer, interval, date, or NULL to use the facade's default value.
* @return boolean TRUE if the item was successfully persisted. FALSE if there was an error.
*/
- public function set($key, $value, $ttl = null)
+ public function set(string $key, $value, $ttl = null)
{
$item = $this->cachePool()->getItem($key);
@@ -163,9 +163,8 @@ public function defaultTtl()
* Set the facade's default time-to-live for cached items.
*
* @param mixed $ttl An integer, date interval, or date.
- * @return void
*/
- public function setDefaultTtl($ttl)
+ public function setDefaultTtl($ttl): void
{
$this->defaultTtl = $ttl;
}
diff --git a/packages/cache/src/Charcoal/Cache/Middleware/CacheMiddleware.php b/packages/cache/src/Charcoal/Cache/Middleware/CacheMiddleware.php
index 1c94a670c..a85b6f8e6 100644
--- a/packages/cache/src/Charcoal/Cache/Middleware/CacheMiddleware.php
+++ b/packages/cache/src/Charcoal/Cache/Middleware/CacheMiddleware.php
@@ -44,14 +44,14 @@ class CacheMiddleware
*
* @var string[]
*/
- private $methods;
+ private readonly array $methods;
/**
* Cache response if the request matches one of the HTTP status codes.
*
* @var integer[]
*/
- private $statusCodes;
+ private readonly array $statusCodes;
/**
* Time-to-live in seconds.
@@ -142,10 +142,8 @@ public function __construct(array $data)
/**
* Default middleware options.
- *
- * @return array
*/
- public function defaults()
+ public function defaults(): array
{
return [
'ttl' => CacheConfig::DAY_IN_SECONDS,
@@ -191,7 +189,7 @@ public function __invoke(RequestInterface $request, ResponseInterface $response,
return $next($request, $response);
}
- if ($this->isSkipCache($request)) {
+ if ($this->isSkipCache()) {
return $next($request, $response);
}
@@ -230,7 +228,7 @@ public function __invoke(RequestInterface $request, ResponseInterface $response,
if (!$this->isQueryIncluded($query)) {
$queryArr = $this->parseIgnoredParams($query);
- if (!empty($queryArr)) {
+ if ($queryArr !== []) {
return $this->disableCacheHeadersOnResponse($response);
}
}
@@ -286,20 +284,16 @@ private function cacheKeyFromRequest(RequestInterface $request)
* Determine if the HTTP request method matches the accepted choices.
*
* @param RequestInterface $request The PSR-7 HTTP request.
- * @return boolean
*/
- private function isRequestMethodValid(RequestInterface $request)
+ private function isRequestMethodValid(RequestInterface $request): bool
{
return in_array($request->getMethod(), $this->methods);
}
/**
* Determine if the HTTP request method matches the accepted choices.
- *
- * @param RequestInterface $request The PSR-7 HTTP request.
- * @return boolean
*/
- private function isSkipCache(RequestInterface $request)
+ private function isSkipCache(): bool
{
if (isset($this->skipCache['session_vars'])) {
$skip = $this->skipCache['session_vars'];
@@ -315,7 +309,6 @@ private function isSkipCache(RequestInterface $request)
}
}
}
-
return false;
}
@@ -323,9 +316,8 @@ private function isSkipCache(RequestInterface $request)
* Determine if the HTTP response status matches the accepted choices.
*
* @param ResponseInterface $response The PSR-7 HTTP response.
- * @return boolean
*/
- private function isResponseStatusValid(ResponseInterface $response)
+ private function isResponseStatusValid(ResponseInterface $response): bool
{
return in_array($response->getStatusCode(), $this->statusCodes);
}
@@ -334,9 +326,8 @@ private function isResponseStatusValid(ResponseInterface $response)
* Determine if the request should be cached based on the URI path.
*
* @param string $path The request path (route) to verify.
- * @return boolean
*/
- private function isPathIncluded($path)
+ private function isPathIncluded($path): bool
{
if ($this->includedPath === '*') {
return true;
@@ -345,23 +336,22 @@ private function isPathIncluded($path)
if (empty($this->includedPath) && !is_numeric($this->includedPath)) {
return false;
}
-
+ $found = false;
foreach ((array)$this->includedPath as $included) {
if (preg_match('@' . $included . '@', $path)) {
- return true;
+ $found = true;
+ break;
}
}
-
- return false;
+ return $found;
}
/**
* Determine if the request should NOT be cached based on the URI path.
*
* @param string $path The request path (route) to verify.
- * @return boolean
*/
- private function isPathExcluded($path)
+ private function isPathExcluded($path): bool
{
if ($this->excludedPath === '*') {
return true;
@@ -370,14 +360,14 @@ private function isPathExcluded($path)
if (empty($this->excludedPath) && !is_numeric($this->excludedPath)) {
return false;
}
-
+ $found = false;
foreach ((array)$this->excludedPath as $excluded) {
if (preg_match('@' . $excluded . '@', $path)) {
- return true;
+ $found = true;
+ break;
}
}
-
- return false;
+ return $found;
}
/**
@@ -388,7 +378,7 @@ private function isPathExcluded($path)
*/
private function isQueryIncluded(array $queryParams)
{
- if (empty($queryParams)) {
+ if ($queryParams === []) {
return true;
}
@@ -412,7 +402,7 @@ private function isQueryIncluded(array $queryParams)
*/
private function isQueryExcluded(array $queryParams)
{
- if (empty($queryParams)) {
+ if ($queryParams === []) {
return false;
}
@@ -432,11 +422,10 @@ private function isQueryExcluded(array $queryParams)
* Returns the query parameters that are NOT ignored.
*
* @param array $queryParams The query parameters to filter.
- * @return array
*/
- private function parseIgnoredParams(array $queryParams)
+ private function parseIgnoredParams(array $queryParams): array
{
- if (empty($queryParams)) {
+ if ($queryParams === []) {
return $queryParams;
}
@@ -479,9 +468,8 @@ private function disableCacheHeadersOnResponse(ResponseInterface $response)
/**
* @param Closure|null $processCacheKeyCallback ProcessCacheKeyCallback for CacheMiddleware.
- * @return self
*/
- public function setProcessCacheKeyCallback($processCacheKeyCallback)
+ public function setProcessCacheKeyCallback($processCacheKeyCallback): static
{
$this->processCacheKeyCallback = $processCacheKeyCallback;
diff --git a/packages/cache/src/Charcoal/Cache/ServiceProvider/CacheServiceProvider.php b/packages/cache/src/Charcoal/Cache/ServiceProvider/CacheServiceProvider.php
index 9070ee892..708a4b04b 100644
--- a/packages/cache/src/Charcoal/Cache/ServiceProvider/CacheServiceProvider.php
+++ b/packages/cache/src/Charcoal/Cache/ServiceProvider/CacheServiceProvider.php
@@ -44,9 +44,8 @@ class CacheServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container A container instance.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
$this->registerDrivers($container);
$this->registerService($container);
@@ -55,14 +54,11 @@ public function register(Container $container)
/**
* @param Container $container A container instance.
- * @return void
*/
- public function registerDrivers(Container $container)
+ public function registerDrivers(Container $container): void
{
/**
* The collection of cache drivers that are supported by this system.
- *
- * @var array An associative array structured as `"Driver Name" => "Class Name"`.
*/
$container['cache/available-drivers'] = DriverList::getAvailableDrivers();
@@ -72,14 +68,14 @@ public function registerDrivers(Container $container)
* @param Container $container The service container.
* @return Container Service container of cache drivers from Stash.
*/
- $container['cache/drivers'] = function (Container $container) {
+ $container['cache/drivers'] = function (Container $container): \Pimple\Container {
$drivers = new Container();
/**
* @param Container $container The service container.
* @return \Stash\Driver\Apc|null
*/
- $drivers['apc'] = function () use ($container) {
+ $drivers['apc'] = function () use ($container): ?object {
$drivers = $container['cache/available-drivers'];
if (!isset($drivers['Apc'])) {
// Apc is not available on system
@@ -99,7 +95,7 @@ public function registerDrivers(Container $container)
* @param Container $container A container instance.
* @return \Stash\Driver\Sqlite|null
*/
- $drivers['db'] = function () use ($container) {
+ $drivers['db'] = function () use ($container): ?object {
$drivers = $container['cache/available-drivers'];
if (!isset($drivers['SQLite'])) {
// SQLite is not available on system
@@ -113,7 +109,7 @@ public function registerDrivers(Container $container)
* @param Container $container A container instance.
* @return \Stash\Driver\FileSystem
*/
- $drivers['file'] = function () use ($container) {
+ $drivers['file'] = function () use ($container): object {
$drivers = $container['cache/available-drivers'];
return new $drivers['FileSystem']();
};
@@ -122,7 +118,7 @@ public function registerDrivers(Container $container)
* @param Container $container A container instance.
* @return \Stash\Driver\Memcache|null
*/
- $drivers['memcache'] = function () use ($container) {
+ $drivers['memcache'] = function () use ($container): ?object {
$drivers = $container['cache/available-drivers'];
if (!isset($drivers['Memcache'])) {
// Memcache is not available on system
@@ -152,7 +148,7 @@ public function registerDrivers(Container $container)
* @param Container $container A container instance.
* @return \Stash\Driver\Ephemeral
*/
- $drivers['memory'] = function () use ($container) {
+ $drivers['memory'] = function () use ($container): object {
$drivers = $container['cache/available-drivers'];
return new $drivers['Ephemeral']();
};
@@ -161,7 +157,7 @@ public function registerDrivers(Container $container)
* @param Container $container A container instance.
* @return \Stash\Driver\BlackHole
*/
- $drivers['noop'] = function () use ($container) {
+ $drivers['noop'] = function () use ($container): object {
$drivers = $container['cache/available-drivers'];
return new $drivers['BlackHole']();
};
@@ -170,7 +166,7 @@ public function registerDrivers(Container $container)
* @param Container $container A container instance.
* @return \Stash\Driver\Redis|null
*/
- $drivers['redis'] = function () use ($container) {
+ $drivers['redis'] = function () use ($container): ?object {
$drivers = $container['cache/available-drivers'];
if (!isset($drivers['Redis'])) {
// Redis is not available on system
@@ -186,9 +182,8 @@ public function registerDrivers(Container $container)
/**
* @param Container $container A container instance.
- * @return void
*/
- public function registerService(Container $container)
+ public function registerService(Container $container): void
{
/**
* The cache configset.
@@ -196,9 +191,9 @@ public function registerService(Container $container)
* @param Container $container The service container.
* @return CacheConfig
*/
- $container['cache/config'] = function (Container $container) {
- $appConfig = isset($container['config']) ? $container['config'] : [];
- $cacheConfig = isset($appConfig['cache']) ? $appConfig['cache'] : null;
+ $container['cache/config'] = function (Container $container): \Charcoal\Cache\CacheConfig {
+ $appConfig = ($container['config'] ?? []);
+ $cacheConfig = ($appConfig['cache'] ?? null);
return new CacheConfig($cacheConfig);
};
@@ -208,7 +203,7 @@ public function registerService(Container $container)
* @param Container $container A Pimple DI container.
* @return CacheBuilder
*/
- $container['cache/builder'] = function (Container $container) {
+ $container['cache/builder'] = function (Container $container): \Charcoal\Cache\CacheBuilder {
$cacheConfig = $container['cache/config'];
return new CacheBuilder([
@@ -224,9 +219,7 @@ public function registerService(Container $container)
* @param Container $container The service container.
* @return DriverInterface Primary cache driver from Stash.
*/
- $container['cache/driver'] = $container->factory(function (Container $container) {
- return $container['cache']->getDriver();
- });
+ $container['cache/driver'] = $container->factory(fn(Container $container) => $container['cache']->getDriver());
/**
* The main cache item pool.
@@ -238,11 +231,7 @@ public function registerService(Container $container)
$cacheBuilder = $container['cache/builder'];
$cacheConfig = $container['cache/config'];
- if ($cacheConfig['active'] === true) {
- $cacheDrivers = $cacheConfig['types'];
- } else {
- $cacheDrivers = $cacheConfig['default_types'];
- }
+ $cacheDrivers = $cacheConfig['active'] === true ? $cacheConfig['types'] : $cacheConfig['default_types'];
return $cacheBuilder($cacheDrivers);
};
@@ -253,7 +242,7 @@ public function registerService(Container $container)
* @param Container $container The service container.
* @return CachePoolFacade The facade for the main cache pool.
*/
- $container['cache/facade'] = function (Container $container) {
+ $container['cache/facade'] = function (Container $container): \Charcoal\Cache\Facade\CachePoolFacade {
$args = [
'cache' => $container['cache'],
];
@@ -269,9 +258,8 @@ public function registerService(Container $container)
/**
* @param Container $container A container instance.
- * @return void
*/
- private function registerMiddleware(Container $container)
+ private function registerMiddleware(Container $container): void
{
/**
* The cache middleware configset.
@@ -280,7 +268,7 @@ private function registerMiddleware(Container $container)
* @return array
*/
$container['cache/middleware/config'] = function (Container $container) {
- $appConfig = isset($container['config']) ? $container['config'] : [];
+ $appConfig = ($container['config'] ?? []);
if (isset($appConfig['middlewares']['charcoal/cache/middleware/cache'])) {
$wareConfig = $appConfig['middlewares']['charcoal/cache/middleware/cache'];
@@ -299,8 +287,6 @@ private function registerMiddleware(Container $container)
* @param Container $container A container instance.
* @return CacheMiddleware
*/
- $container['middlewares/charcoal/cache/middleware/cache'] = function (Container $container) {
- return new CacheMiddleware($container['cache/middleware/config']);
- };
+ $container['middlewares/charcoal/cache/middleware/cache'] = (fn(Container $container): \Charcoal\Cache\Middleware\CacheMiddleware => new CacheMiddleware($container['cache/middleware/config']));
}
}
diff --git a/packages/cache/tests/Charcoal/AbstractTestCase.php b/packages/cache/tests/Charcoal/AbstractTestCase.php
index 59ba12ea0..80f1772c4 100644
--- a/packages/cache/tests/Charcoal/AbstractTestCase.php
+++ b/packages/cache/tests/Charcoal/AbstractTestCase.php
@@ -1,5 +1,7 @@
assertEquals('charcoal', CacheConfig::DEFAULT_NAMESPACE);
$this->assertEquals((60 * 60), CacheConfig::HOUR_IN_SECONDS);
@@ -70,11 +73,7 @@ public function testDefaults()
$this->assertEquals($defaults['prefix'], $this->cfg->prefix());
}
- /**
- * @covers ::setActive
- * @covers ::active
- */
- public function testActive()
+ public function testActive(): void
{
// Chainable
$that = $this->cfg->setActive(false);
@@ -84,11 +83,7 @@ public function testActive()
$this->assertFalse($this->cfg->active());
}
- /**
- * @covers ::setTypes
- * @covers ::types
- */
- public function testReplaceDrivers()
+ public function testReplaceDrivers(): void
{
// Chainable
$that = $this->cfg->setTypes([ 'memcache', 'noop' ]);
@@ -99,10 +94,7 @@ public function testReplaceDrivers()
$this->assertEquals([ 'memcache', 'noop', 'memory' ], $types);
}
- /**
- * @covers ::types
- */
- public function testUniqueDrivers()
+ public function testUniqueDrivers(): void
{
$this->cfg->setTypes([ 'memcache', 'memory', 'file', 'memcache' ]);
@@ -110,12 +102,7 @@ public function testUniqueDrivers()
$this->assertEquals([ 'memcache', 'memory', 'file' ], $types);
}
- /**
- * @covers ::addTypes
- * @covers ::addType
- * @covers ::types
- */
- public function testAddDrivers()
+ public function testAddDrivers(): void
{
// Chainable
$that = $this->cfg->addTypes([ 'memcache', 'noop' ]);
@@ -128,22 +115,14 @@ public function testAddDrivers()
$this->assertContains('noop', $types);
}
- /**
- * @covers ::validTypes
- * @covers ::addType
- */
- public function testAddDriverOnInvalidType()
+ public function testAddDriverOnInvalidType(): void
{
$this->expectExceptionMessage('Invalid cache type: "foobar"');
$this->expectException(InvalidArgumentException::class);
$this->cfg->addType('foobar');
}
- /**
- * @covers ::setDefaultTtl
- * @covers ::defaultTtl
- */
- public function testDefaultTtl()
+ public function testDefaultTtl(): void
{
// Chainable
$that = $this->cfg->setDefaultTtl(42);
@@ -153,21 +132,14 @@ public function testDefaultTtl()
$this->assertEquals(42, $this->cfg->defaultTtl());
}
- /**
- * @covers ::setDefaultTtl
- */
- public function testSetDefaultTtlOnInvalidType()
+ public function testSetDefaultTtlOnInvalidType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('TTL must be an integer (seconds)');
$this->cfg->setDefaultTtl('foo');
}
- /**
- * @covers ::setPrefix
- * @covers ::prefix
- */
- public function testPrefix()
+ public function testPrefix(): void
{
// Chainable
$that = $this->cfg->setPrefix('foo');
@@ -177,20 +149,14 @@ public function testPrefix()
$this->assertEquals('foo', $this->cfg->prefix());
}
- /**
- * @covers ::setPrefix
- */
- public function testSetPrefixOnInvalidType()
+ public function testSetPrefixOnInvalidType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Prefix must be a string');
$this->cfg->setPrefix(false);
}
- /**
- * @covers ::setPrefix
- */
- public function testSetPrefixOnInvalidValue()
+ public function testSetPrefixOnInvalidValue(): void
{
$this->expectExceptionMessage('Prefix must be alphanumeric');
$this->expectException(InvalidArgumentException::class);
diff --git a/packages/cache/tests/Charcoal/Cache/CachePoolAwareTest.php b/packages/cache/tests/Charcoal/Cache/CachePoolAwareTest.php
index 2b9762e5b..37f708309 100644
--- a/packages/cache/tests/Charcoal/Cache/CachePoolAwareTest.php
+++ b/packages/cache/tests/Charcoal/Cache/CachePoolAwareTest.php
@@ -11,16 +11,13 @@
/**
* Test CachePoolAwareTrait
- *
- * @coversDefaultClass \Charcoal\Cache\CachePoolAwareTrait
*/
+#[\PHPUnit\Framework\Attributes\CoversTrait(\Charcoal\Cache\CachePoolAwareTrait::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CachePoolAwareTrait::class, 'setCachePool')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CachePoolAwareTrait::class, 'cachePool')]
class CachePoolAwareTest extends AbstractTestCase
{
- /**
- * @covers ::setCachePool
- * @covers ::cachePool
- */
- public function testCachePool()
+ public function testCachePool(): void
{
$obj = new CachePoolAware();
$pool = new Pool();
@@ -31,9 +28,8 @@ public function testCachePool()
/**
* testSetPrefixOnInvalidValue
- * @covers ::cachePool
*/
- public function testMissingPool()
+ public function testMissingPool(): void
{
$this->expectExceptionMessage('Cache Pool is not defined for "Charcoal\Tests\Mocks\CachePoolAware"');
$this->expectException(\RuntimeException::class);
diff --git a/packages/cache/tests/Charcoal/Cache/CachePoolTrait.php b/packages/cache/tests/Charcoal/Cache/CachePoolTrait.php
index 7e5adb1eb..bcbbeb46c 100644
--- a/packages/cache/tests/Charcoal/Cache/CachePoolTrait.php
+++ b/packages/cache/tests/Charcoal/Cache/CachePoolTrait.php
@@ -1,5 +1,7 @@
setNamespace('tests');
diff --git a/packages/cache/tests/Charcoal/Cache/Facade/CachePoolFacadeTest.php b/packages/cache/tests/Charcoal/Cache/Facade/CachePoolFacadeTest.php
index 561c8839b..62b721246 100644
--- a/packages/cache/tests/Charcoal/Cache/Facade/CachePoolFacadeTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Facade/CachePoolFacadeTest.php
@@ -23,9 +23,16 @@
* Test CachePoolFacade
*
* This class is based on {@see \Stash\Test\AbstractPoolTest}.
- *
- * @coversDefaultClass \Charcoal\Cache\Facade\CachePoolFacade
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\Facade\CachePoolFacade::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, '__construct')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, 'get')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, 'save')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, 'has')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, 'set')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, 'delete')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, 'defaultTtl')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Facade\CachePoolFacade::class, 'setDefaultTtl')]
class CachePoolFacadeTest extends AbstractTestCase
{
use CachePoolTrait;
@@ -43,8 +50,6 @@ class CachePoolFacadeTest extends AbstractTestCase
/**
* Prepare the cache pool.
- *
- * @return void
*/
public function setUp(): void
{
@@ -53,8 +58,6 @@ public function setUp(): void
/**
* Empty the cache pool.
- *
- * @return void
*/
public function tearDown(): void
{
@@ -65,9 +68,8 @@ public function tearDown(): void
* Create a new CachePoolFacade instance.
*
* @param array $args Parameters for the initialization of a CachePoolFacade.
- * @return CachePoolFacade
*/
- protected function facadeFactory(array $args = [])
+ protected function facadeFactory(array $args = []): \Charcoal\Cache\Facade\CachePoolFacade
{
if (!isset($args['cache'])) {
$args['cache'] = static::getCachePool();
@@ -76,10 +78,7 @@ protected function facadeFactory(array $args = [])
return new CachePoolFacade($args);
}
- /**
- * @covers ::__construct
- */
- public function testConstruct()
+ public function testConstruct(): void
{
$facade = $this->facadeFactory([
'default_ttl' => 120,
@@ -88,13 +87,7 @@ public function testConstruct()
$this->assertInstanceOf(CachePoolFacade::class, $facade);
}
- /**
- * @covers ::get
- * @covers ::save
- *
- * @return void
- */
- public function testGet()
+ public function testGet(): void
{
$facade = $this->facadeFactory();
@@ -105,19 +98,12 @@ public function testGet()
$data = $facade->get('base/one');
$this->assertEquals($this->data, $data);
- $func = function () {
- return $this->data;
- };
+ $func = (fn() => $this->data);
$data = $facade->get('base/two', $func);
$this->assertEquals($this->data, $data);
}
- /**
- * @covers ::has
- *
- * @return void
- */
- public function testHas()
+ public function testHas(): void
{
$facade = $this->facadeFactory();
@@ -128,8 +114,6 @@ public function testHas()
}
/**
- * @covers ::set
- * @covers ::save
*
* @return CachePoolFacade To use the same cache pool facade for the next test.
*/
@@ -150,13 +134,10 @@ public function testSet()
}
/**
- * @depends testSet
- * @covers ::delete
- *
* @param CachePoolFacade $facade The cache pool facade from the previous test.
- * @return void
*/
- public function testDelete(CachePoolFacade $facade)
+ #[\PHPUnit\Framework\Attributes\Depends('testSet')]
+ public function testDelete(CachePoolFacade $facade): void
{
$keys = array_keys($this->multiData);
@@ -170,17 +151,15 @@ public function testDelete(CachePoolFacade $facade)
/**
* Test a numeric expiration time for this cache item.
*
- * @covers ::save
*
- * @dataProvider provideTtlOnSave
*
* @param DateTimeInterface $expected The expected expiration time
* from {@see \Stash\Interfaces\ItemInterface::getExpiration()}.
* @param mixed $itemTtl The cache item's expiration time.
* @param DateTimeInterface $defaultTtl The facade default expiration time.
- * @return void
*/
- public function testTtlOnSave(DateTimeInterface $expected, $itemTtl, DateTimeInterface $defaultTtl)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideTtlOnSave')]
+ public function testTtlOnSave(DateTimeInterface $expected, $itemTtl, DateTimeInterface $defaultTtl): void
{
$stash = static::getCachePool();
$facade = $this->facadeFactory([
@@ -199,9 +178,8 @@ public function testTtlOnSave(DateTimeInterface $expected, $itemTtl, DateTimeInt
* Provide data for testing the expiration time per cache item.
*
* @used-by self::testTtlOnSave()
- * @return array
*/
- public function provideTtlOnSave()
+ public static function provideTtlOnSave(): array
{
$data = [];
$date = new DateTimeImmutable('now');
@@ -231,13 +209,7 @@ public function provideTtlOnSave()
return $data;
}
- /**
- * @covers ::defaultTtl
- * @covers ::setDefaultTtl
- *
- * @return void
- */
- public function testSetDefaultTtl()
+ public function testSetDefaultTtl(): void
{
$time = new \DateInterval('P1D');
$facade = $this->facadeFactory([
diff --git a/packages/cache/tests/Charcoal/Cache/Factory/AbstractCacheBuilderTest.php b/packages/cache/tests/Charcoal/Cache/Factory/AbstractCacheBuilderTest.php
index 6494b8a2b..83494c732 100644
--- a/packages/cache/tests/Charcoal/Cache/Factory/AbstractCacheBuilderTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Factory/AbstractCacheBuilderTest.php
@@ -115,9 +115,8 @@ public function getDefaultPoolAttributes()
* Reports an error if $builder does not use the default options.
*
* @param CacheBuilder $builder The cache builder to test.
- * @return void
*/
- public function assertCacheBuilderHasDefaultAttributes(CacheBuilder $builder)
+ public function assertCacheBuilderHasDefaultAttributes(CacheBuilder $builder): void
{
$builderDefaults = $this->getDefaultBuilderAttributes();
@@ -131,9 +130,8 @@ public function assertCacheBuilderHasDefaultAttributes(CacheBuilder $builder)
* Reports an error if $pool does not use the default options.
*
* @param PoolInterface $pool The cache pool to test.
- * @return void
*/
- public function assertCachePoolHasDefaultAttributes(PoolInterface $pool)
+ public function assertCachePoolHasDefaultAttributes(PoolInterface $pool): void
{
$builderDefaults = $this->getDefaultBuilderAttributes();
$poolDefaults = $this->getDefaultPoolAttributes();
diff --git a/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderClassTest.php b/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderClassTest.php
index ca178955b..7f02abd06 100644
--- a/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderClassTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderClassTest.php
@@ -14,42 +14,36 @@
/**
* Test constructor and class attributes from the CacheBuilder.
- *
- * @coversDefaultClass \Charcoal\Cache\CacheBuilder
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\CacheBuilder::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, '__construct')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'setDrivers')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'isAccessible')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'setLogger')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'setNamespace')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'setItemClass')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'setPoolClass')]
class CacheBuilderClassTest extends AbstractCacheBuilderTest
{
- /**
- * @covers ::__construct
- * @covers ::setDrivers
- * @covers ::isAccessible
- */
- public function testSetDriversWithInvalidType()
+ public function testSetDriversWithInvalidType(): void
{
$this->expectExceptionMessage('Driver list must be an accessible array');
$this->expectException(InvalidArgumentException::class);
- $builder = $this->createBuilder([
+ $this->createBuilder([
'drivers' => false,
]);
}
- /**
- * @covers ::setLogger
- */
- public function testSetLoggerWithInvalidType()
+ public function testSetLoggerWithInvalidType(): void
{
$this->expectExceptionMessage('Expected an instance of Psr\Log\LoggerInterface');
$this->expectException(InvalidArgumentException::class);
- $builder = $this->createBuilder([
+ $this->createBuilder([
'logger' => new \stdClass(),
]);
}
- /**
- * @covers ::__construct
- * @covers ::setNamespace
- */
- public function testSetNamespace()
+ public function testSetNamespace(): void
{
$driver = $this->createDriver('BlackHole');
$builder = $this->createBuilder([
@@ -65,26 +59,19 @@ public function testSetNamespace()
$this->assertEquals('foo', $pool->getNamespace());
}
- /**
- * @covers ::setNamespace
- */
- public function testSetInvalidNamespace()
+ public function testSetInvalidNamespace(): void
{
$this->expectExceptionMessage('Namespace must be alphanumeric');
$this->expectException(InvalidArgumentException::class);
- $builder = $this->createBuilder([
+ $this->createBuilder([
'namespace' => '!@#$%^&*(',
]);
}
- /**
- * @covers ::__construct
- * @covers ::setItemClass
- */
- public function testSetItemClass()
+ public function testSetItemClass(): void
{
- $mockItem = $this->createMock(ItemInterface::class);
- $mockClassName = get_class($mockItem);
+ $mockItem = $this->createStub(ItemInterface::class);
+ $mockClassName = $mockItem::class;
$driver = $this->createDriver('BlackHole');
$builder = $this->createBuilder([
@@ -97,40 +84,28 @@ public function testSetItemClass()
$this->assertInstanceOf($mockClassName, $item);
}
- /**
- *
- * @covers ::setItemClass
- */
- public function testSetFakeItemClass()
+ public function testSetFakeItemClass(): void
{
$this->expectExceptionMessage('Item class FakeClassName does not exist');
$this->expectException(InvalidArgumentException::class);
- $builder = $this->createBuilder([
+ $this->createBuilder([
'item_class' => 'FakeClassName',
]);
}
- /**
- *
- * @covers ::setItemClass
- */
- public function testSetInvalidItemClass()
+ public function testSetInvalidItemClass(): void
{
$this->expectExceptionMessage('Item class stdClass must inherit from Stash\Interfaces\ItemInterface');
$this->expectException(InvalidArgumentException::class);
- $builder = $this->createBuilder([
+ $this->createBuilder([
'item_class' => 'stdClass',
]);
}
- /**
- * @covers ::__construct
- * @covers ::setPoolClass
- */
- public function testSetPoolClass()
+ public function testSetPoolClass(): void
{
- $mockPool = $this->createMock(PoolInterface::class);
- $mockClassName = get_class($mockPool);
+ $mockPool = $this->createStub(PoolInterface::class);
+ $mockClassName = $mockPool::class;
$driver = $this->createDriver('BlackHole');
$builder = $this->createBuilder([
@@ -142,26 +117,20 @@ public function testSetPoolClass()
$this->assertInstanceOf($mockClassName, $pool);
}
- /**
- * @covers ::setPoolClass
- */
- public function testSetFakePoolClass()
+ public function testSetFakePoolClass(): void
{
$this->expectExceptionMessage('Pool class FakeClassName does not exist');
$this->expectException(InvalidArgumentException::class);
- $builder = $this->createBuilder([
+ $this->createBuilder([
'pool_class' => 'FakeClassName',
]);
}
- /**
- * @covers ::setPoolClass
- */
- public function testSetInvalidPoolClass()
+ public function testSetInvalidPoolClass(): void
{
$this->expectExceptionMessage('Pool class stdClass must inherit from Stash\Interfaces\PoolInterface');
$this->expectException(InvalidArgumentException::class);
- $builder = $this->createBuilder([
+ $this->createBuilder([
'pool_class' => 'stdClass',
]);
}
diff --git a/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderDriverTest.php b/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderDriverTest.php
index dd6c80ffa..57956de00 100644
--- a/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderDriverTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderDriverTest.php
@@ -13,17 +13,18 @@
/**
* Test the cache driver resolution from the CacheBuilder.
- *
- * @coversDefaultClass \Charcoal\Cache\CacheBuilder
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\CacheBuilder::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'build')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'isIterable')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'resolveDriver')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'resolveOneDriver')]
class CacheBuilderDriverTest extends AbstractCacheBuilderTest
{
/**
* Test builder with a {@see DriverInterface driver object}.
- *
- * @covers ::build
*/
- public function testBuildOnDriverInstance()
+ public function testBuildOnDriverInstance(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
@@ -36,16 +37,10 @@ public function testBuildOnDriverInstance()
// Resolve One Driver
// =========================================================================
-
/**
* Test builder with a driver class.
- *
- * @covers ::build
- * @covers ::isIterable
- * @covers ::resolveDriver
- * @covers ::resolveOneDriver
*/
- public function testBuildOnDriverClass()
+ public function testBuildOnDriverClass(): void
{
$builder = $this->createBuilder();
$driver = $this->getDriverClass('BlackHole');
@@ -56,13 +51,8 @@ public function testBuildOnDriverClass()
/**
* Test builder with a named driver associated to a {@see DriverInterface driver object}.
- *
- * @covers ::build
- * @covers ::isIterable
- * @covers ::resolveDriver
- * @covers ::resolveOneDriver
*/
- public function testBuildOnNamedDriverWithInstance()
+ public function testBuildOnNamedDriverWithInstance(): void
{
$driver = $this->createDriver('BlackHole');
$builder = $this->createBuilder([
@@ -77,13 +67,8 @@ public function testBuildOnNamedDriverWithInstance()
/**
* Test builder with a named driver associated to a driver class.
- *
- * @covers ::build
- * @covers ::isIterable
- * @covers ::resolveDriver
- * @covers ::resolveOneDriver
*/
- public function testBuildOnNamedDriverWithClass()
+ public function testBuildOnNamedDriverWithClass(): void
{
$driver = $this->getDriverClass('BlackHole');
$builder = $this->createBuilder([
@@ -97,13 +82,10 @@ public function testBuildOnNamedDriverWithClass()
}
// =================================
-
/**
* Test builder with an empty driver name.
- *
- * @covers ::resolveOneDriver
*/
- public function testBuildOnEmptyDriver()
+ public function testBuildOnEmptyDriver(): void
{
$this->expectExceptionMessage('Driver is empty');
$this->expectException(InvalidArgumentException::class);
@@ -114,10 +96,8 @@ public function testBuildOnEmptyDriver()
/**
* Test builder with an invalid driver instance.
- *
- * @covers ::resolveOneDriver
*/
- public function testBuildOnInvalidDriverInstance()
+ public function testBuildOnInvalidDriverInstance(): void
{
$this->expectExceptionMessage('Driver class stdClass must implement Stash\Interfaces\DriverInterface');
$this->expectException(InvalidArgumentException::class);
@@ -125,15 +105,13 @@ public function testBuildOnInvalidDriverInstance()
$builder = $this->createBuilder();
$driver = new StdClass();
- $pool = $builder->build($driver);
+ $builder->build($driver);
}
/**
* Test builder with a named driver associated to an empty value.
- *
- * @covers ::resolveOneDriver
*/
- public function testBuildOnNamedDriverWithEmptyEntry()
+ public function testBuildOnNamedDriverWithEmptyEntry(): void
{
$this->expectExceptionMessage('Driver "foobar" does not exist');
$this->expectException(InvalidArgumentException::class);
@@ -144,15 +122,13 @@ public function testBuildOnNamedDriverWithEmptyEntry()
]
]);
- $pool = $builder->build('foobar');
+ $builder->build('foobar');
}
/**
* Test builder with a named driver associated to an invalid instance.
- *
- * @covers ::resolveOneDriver
*/
- public function testBuildOnNamedDriverWithBadEntry()
+ public function testBuildOnNamedDriverWithBadEntry(): void
{
$this->expectExceptionMessage('Driver "foobar": Class stdClass must implement Stash\Interfaces\DriverInterface');
$this->expectException(InvalidArgumentException::class);
@@ -164,15 +140,13 @@ public function testBuildOnNamedDriverWithBadEntry()
]
]);
- $pool = $builder->build('foobar');
+ $builder->build('foobar');
}
/**
* Test builder with an invalid driver class.
- *
- * @covers ::resolveOneDriver
*/
- public function testBuildOnInvalidDriverClass()
+ public function testBuildOnInvalidDriverClass(): void
{
$this->expectExceptionMessage('Driver "FakeClassName" cannot be resolved');
$this->expectException(InvalidArgumentException::class);
@@ -180,23 +154,17 @@ public function testBuildOnInvalidDriverClass()
$builder = $this->createBuilder();
$driver = 'FakeClassName';
- $pool = $builder->build($driver);
+ $builder->build($driver);
}
// Resolve Many Drivers
// =========================================================================
-
/**
* Test builder with an array of {@see DriverInterface driver objects}.
- *
- * @covers ::build
- * @covers ::isIterable
- * @covers ::resolveDriver
- * @covers ::resolveOneDriver
*/
- public function testBuildOnArrayOfDriverInstances()
+ public function testBuildOnArrayOfDriverInstances(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
@@ -206,13 +174,10 @@ public function testBuildOnArrayOfDriverInstances()
}
// =================================
-
/**
* Test builder with an invalid array of drivers.
- *
- * @covers ::resolveDriver
*/
- public function testBuildOnArrayOfInvalidDrivers()
+ public function testBuildOnArrayOfInvalidDrivers(): void
{
$this->expectExceptionMessage('Drivers cannot be resolved');
$this->expectException(InvalidArgumentException::class);
diff --git a/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderPoolTest.php b/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderPoolTest.php
index 10aac436d..8de1ab3a1 100644
--- a/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderPoolTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Factory/CacheBuilderPoolTest.php
@@ -14,17 +14,17 @@
/**
* Test the cache pool creation and pool attributes from the CacheBuilder.
- *
- * @coversDefaultClass \Charcoal\Cache\CacheBuilder
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\CacheBuilder::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, '__invoke')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'parsePoolOptions')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\CacheBuilder::class, 'applyPoolOptions')]
class CacheBuilderPoolTest extends AbstractCacheBuilderTest
{
/**
* Asserts that the CacheBuilder is invokable.
- *
- * @covers ::__invoke
*/
- public function testBuildIsInvokable()
+ public function testBuildIsInvokable(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
@@ -35,11 +35,8 @@ public function testBuildIsInvokable()
/**
* Asserts that the Pool logger can be assigned from build options.
- *
- * @covers ::parsePoolOptions
- * @covers ::applyPoolOptions
*/
- public function testBuildWithLoggerOnOptions()
+ public function testBuildWithLoggerOnOptions(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
@@ -54,11 +51,8 @@ public function testBuildWithLoggerOnOptions()
/**
* Asserts that the Pool namespace can be customized from build options.
- *
- * @covers ::parsePoolOptions
- * @covers ::applyPoolOptions
*/
- public function testBuildWithNamespaceOnOptions()
+ public function testBuildWithNamespaceOnOptions(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
@@ -76,17 +70,14 @@ public function testBuildWithNamespaceOnOptions()
/**
* Asserts that the Item class can be customized from build options.
- *
- * @covers ::parsePoolOptions
- * @covers ::applyPoolOptions
*/
- public function testBuildWithItemClassOnOptions()
+ public function testBuildWithItemClassOnOptions(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
- $mockItem = $this->createMock(ItemInterface::class);
- $mockClassName = get_class($mockItem);
+ $mockItem = $this->createStub(ItemInterface::class);
+ $mockClassName = $mockItem::class;
$pool = $builder($driver, [
'item_class' => $mockClassName,
@@ -98,17 +89,14 @@ public function testBuildWithItemClassOnOptions()
/**
* Asserts that the Pool class can be customized from build options.
- *
- * @covers ::parsePoolOptions
- * @covers ::applyPoolOptions
*/
- public function testBuildWithPoolClassOnOptions()
+ public function testBuildWithPoolClassOnOptions(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
- $mockPool = $this->createMock(PoolInterface::class);
- $mockClassName = get_class($mockPool);
+ $mockPool = $this->createStub(PoolInterface::class);
+ $mockClassName = $mockPool::class;
// Custom Pool Class
$pool = $builder($driver, [
@@ -119,10 +107,8 @@ public function testBuildWithPoolClassOnOptions()
/**
* Asserts that the CacheBuilder uses default options when given NULL.
- *
- * @covers ::parsePoolOptions
*/
- public function testBuildWithNullOnOptions()
+ public function testBuildWithNullOnOptions(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
@@ -135,10 +121,8 @@ public function testBuildWithNullOnOptions()
/**
* Asserts that the CacheBuilder uses default options when given NULL.
- *
- * @covers ::parsePoolOptions
*/
- public function testBuildWithInvalidTypeOnOptions()
+ public function testBuildWithInvalidTypeOnOptions(): void
{
$builder = $this->createBuilder();
$driver = $this->createDriver('BlackHole');
diff --git a/packages/cache/tests/Charcoal/Cache/Middleware/AbstractCacheMiddlewareTest.php b/packages/cache/tests/Charcoal/Cache/Middleware/AbstractCacheMiddlewareTest.php
index 16b9bb5fa..02372cb7e 100644
--- a/packages/cache/tests/Charcoal/Cache/Middleware/AbstractCacheMiddlewareTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Middleware/AbstractCacheMiddlewareTest.php
@@ -24,9 +24,9 @@
/**
* Test CacheMiddleware
- *
- * @coversDefaultClass \Charcoal\Cache\Middleware\CacheMiddleware
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\Middleware\CacheMiddleware::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'disableCacheHeadersOnResponse')]
abstract class AbstractCacheMiddlewareTest extends AbstractTestCase
{
use CachePoolTrait;
@@ -41,9 +41,7 @@ protected function middlewareFactory(array $args = [])
{
if (!isset($args['cache'])) {
$args['cache'] = static::getCachePool();
- $args['processCacheKeyCallback'] = function ($key) {
- return $key;
- };
+ $args['processCacheKeyCallback'] = (fn($key) => $key);
}
return new CacheMiddleware($args);
@@ -56,9 +54,7 @@ protected function middlewareFactory(array $args = [])
*/
protected function mockNextMiddleware()
{
- return function ($request, $response) {
- return $response;
- };
+ return fn($request, $response) => $response;
}
/**
@@ -120,9 +116,7 @@ protected function createRequest($method = 'GET', $uri = '/', $query = null)
if ($query !== null) {
$env['QUERY_STRING'] = is_array($query) ? http_build_query($query) : $query;
}
-
- $request = Request::createFromEnvironment($env);
- return $request;
+ return Request::createFromEnvironment($env);
}
/**
@@ -156,19 +150,16 @@ protected function createResponse($status = 200, $body = null)
}
$headers = new Headers([ 'Content-Type' => 'text/html; charset=UTF-8' ]);
- $response = new Response($status, $headers, $body);
- return $response;
+ return new Response($status, $headers, $body);
}
/**
* Reports an error if the HTTP response headers does not have disabled cache headers.
*
- * @covers ::disableCacheHeadersOnResponse
*
* @param array $headers The HTTP response headers to test.
- * @return void
*/
- public function assertResponseHasDisabledCacheHeaders(array $headers)
+ public function assertResponseHasDisabledCacheHeaders(array $headers): void
{
$this->assertArrayHasKey('Cache-Control', $headers);
$this->assertContains('no-cache, no-store, must-revalidate', $headers['Cache-Control']);
diff --git a/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareRequestTest.php b/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareRequestTest.php
index 6c8ac02df..85f4d2e8c 100644
--- a/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareRequestTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareRequestTest.php
@@ -11,15 +11,21 @@
/**
* Test HTTP Requests with CacheMiddleware.
- *
- * @coversDefaultClass \Charcoal\Cache\Middleware\CacheMiddleware
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\Middleware\CacheMiddleware::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, '__invoke')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'isRequestMethodValid')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'isResponseStatusValid')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'isPathIncluded')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'isPathExcluded')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'isQueryIncluded')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'isQueryExcluded')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'parseIgnoredParams')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'disableCacheHeadersOnResponse')]
class CacheMiddlewareRequestTest extends AbstractCacheMiddlewareTest
{
/**
* Prepare the cache pool.
- *
- * @return void
*/
public function setUp(): void
{
@@ -28,8 +34,6 @@ public function setUp(): void
/**
* Empty the cache pool.
- *
- * @return void
*/
public function tearDown(): void
{
@@ -39,25 +43,15 @@ public function tearDown(): void
/**
* Test middleware with an invalid HTTP request method.
*
- * @covers ::__invoke
- * @covers ::isRequestMethodValid
- * @covers ::isResponseStatusValid
- * @covers ::isPathIncluded
- * @covers ::isPathExcluded
- * @covers ::isQueryIncluded
- * @covers ::isQueryExcluded
- * @covers ::parseIgnoredParams
- * @covers ::disableCacheHeadersOnResponse
*
- * @dataProvider provideInvokableSituations
*
* @param boolean $expected The expected result from {@see \Psr\Cache\CacheItemInterface::isHit()}.
* @param boolean $checkHttpHeaders Whether to test the HTTP response's headers.
* @param stromg $requestUri The request URI for {@see self::createRequest()}.
* @param array $cacheConfig The CacheMiddleware settings.
- * @return void
*/
- public function testInvoke($expected, $checkHttpHeaders, $requestUri, array $cacheConfig)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideInvokableSituations')]
+ public function testInvoke(bool $expected, bool $checkHttpHeaders, string $requestUri, array $cacheConfig): void
{
$middleware = $this->middlewareFactory($cacheConfig);
$request = $this->createRequest('GET', $requestUri);
@@ -85,9 +79,8 @@ public function testInvoke($expected, $checkHttpHeaders, $requestUri, array $cac
* Provide data for testing the middleware.
*
* @used-by self::testInvoke()
- * @return array
*/
- public function provideInvokableSituations()
+ public static function provideInvokableSituations(): array
{
$target1 = '/foo/bar';
$target2 = '/foo/bar?abc=123';
diff --git a/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareResponseTest.php b/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareResponseTest.php
index 4127bc4b3..61471fa20 100644
--- a/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareResponseTest.php
+++ b/packages/cache/tests/Charcoal/Cache/Middleware/CacheMiddlewareResponseTest.php
@@ -14,15 +14,14 @@
/**
* Test HTTP Responses from CacheMiddleware.
- *
- * @coversDefaultClass \Charcoal\Cache\Middleware\CacheMiddleware
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\Middleware\CacheMiddleware::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, '__invoke')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\Middleware\CacheMiddleware::class, 'cacheKeyFromRequest')]
class CacheMiddlewareResponseTest extends AbstractCacheMiddlewareTest
{
/**
* Prepare the cache pool.
- *
- * @return void
*/
public static function setUpBeforeClass(): void
{
@@ -31,8 +30,6 @@ public static function setUpBeforeClass(): void
/**
* Empty the cache pool.
- *
- * @return void
*/
public static function tearDownAfterClass(): void
{
@@ -42,8 +39,6 @@ public static function tearDownAfterClass(): void
/**
* Test the initial state.
*
- * @covers ::__invoke
- * @covers ::cacheKeyFromRequest
*
* @return CacheMiddleware To use the same cache middleware for the next test.
*/
@@ -83,14 +78,11 @@ public function testInitialState()
/**
* Test the cached state.
*
- * @covers ::__invoke
- * @covers ::cacheKeyFromRequest
- * @depends testInitialState
*
* @param CacheMiddleware $middleware The cache middleware from the previous test.
- * @return void
*/
- public function testCachedState(CacheMiddleware $middleware)
+ #[\PHPUnit\Framework\Attributes\Depends('testInitialState')]
+ public function testCachedState(CacheMiddleware $middleware): void
{
$txt = 'Lorem ipsum dolor sit amet.';
diff --git a/packages/cache/tests/Charcoal/Cache/ServiceProvider/CacheServiceProviderTest.php b/packages/cache/tests/Charcoal/Cache/ServiceProvider/CacheServiceProviderTest.php
index 198f9be5e..66884f185 100644
--- a/packages/cache/tests/Charcoal/Cache/ServiceProvider/CacheServiceProviderTest.php
+++ b/packages/cache/tests/Charcoal/Cache/ServiceProvider/CacheServiceProviderTest.php
@@ -26,18 +26,15 @@
/**
* Test CacheServiceProvider
- *
- * @coversDefaultClass \Charcoal\Cache\ServiceProvider\CacheServiceProvider
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Cache\ServiceProvider\CacheServiceProvider::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\ServiceProvider\CacheServiceProvider::class, 'register')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\ServiceProvider\CacheServiceProvider::class, 'registerDrivers')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\ServiceProvider\CacheServiceProvider::class, 'registerService')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Cache\ServiceProvider\CacheServiceProvider::class, 'registerMiddleware')]
class CacheServiceProviderTest extends AbstractTestCase
{
- /**
- * @covers ::register
- * @covers ::registerDrivers
- * @covers ::registerService
- * @covers ::registerMiddleware
- */
- public function testProvider()
+ public function testProvider(): void
{
$container = $this->providerFactory();
@@ -68,10 +65,8 @@ public function testProvider()
/**
* Test "middlewares/charcoal/cache/middleware/cache" with a user-preferences.
- *
- * @covers ::registerMiddleware
*/
- public function testCustomizedMiddleware()
+ public function testCustomizedMiddleware(): void
{
$container = $this->providerFactory([
'config' => [
@@ -87,17 +82,14 @@ public function testCustomizedMiddleware()
$middleware = $container['middlewares/charcoal/cache/middleware/cache'];
$reflection = new ReflectionClass($middleware);
$reflectionProperty = $reflection->getProperty('cacheTtl');
- $reflectionProperty->setAccessible(true);
$this->assertEquals(1, $reflectionProperty->getValue($middleware));
}
/**
* Test "cache/drivers"; basic drivers are instances of {@see DriverInterface}.
- *
- * @covers ::registerDrivers
*/
- public function testBasicDriverInstances()
+ public function testBasicDriverInstances(): void
{
$container = $this->providerFactory();
@@ -121,10 +113,8 @@ public function testBasicDriverInstances()
/**
* Test "cache/drivers"; vendor drivers are instances of {@see DriverInterface}.
- *
- * @covers ::registerDrivers
*/
- public function testAvailableVendorDriverInstances()
+ public function testAvailableVendorDriverInstances(): void
{
$container = $this->providerFactory();
@@ -146,7 +136,7 @@ public function testAvailableVendorDriverInstances()
try {
$driver = $driverCollection[$driverKey];
$this->assertInstanceOf($className, $driver);
- } catch (Throwable $t) {
+ } catch (Throwable) {
// Do nothing; Some cache drivers, such as Redis,
// are not correctly implemented.
}
@@ -160,10 +150,8 @@ public function testAvailableVendorDriverInstances()
/**
* Test "cache/drivers"; unavailable vendor drivers return NULL.
- *
- * @covers ::registerDrivers
*/
- public function testUnavailableVendorDriverInstances()
+ public function testUnavailableVendorDriverInstances(): void
{
$container = $this->providerFactory();
@@ -191,16 +179,13 @@ public function testUnavailableVendorDriverInstances()
/**
* Assert "cache/driver" resolves as expected.
*
- * @covers ::registerDrivers
- * @covers ::registerService
*
- * @dataProvider provideConfigsForMainDriver
*
* @param string $className The expected driver class name.
* @param array $cacheConfig The cache configset to resolve the main driver.
- * @return void
*/
- public function testMainDriverInstance($className, array $cacheConfig)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideConfigsForMainDriver')]
+ public function testMainDriverInstance(string $className, array $cacheConfig): void
{
$container = $this->providerFactory([
'config' => [
@@ -215,9 +200,8 @@ public function testMainDriverInstance($className, array $cacheConfig)
* Provide data for testing the "cache/driver" service.
*
* @used-by self::testMainDriverInstance()
- * @return array
*/
- public function provideConfigsForMainDriver()
+ public static function provideConfigsForMainDriver(): array
{
$driverClassNames = DriverList::getAvailableDrivers();
@@ -260,9 +244,8 @@ public function getKeys($value)
* Determine whether the given value is array accessible.
*
* @param mixed $value The variable being evaluated.
- * @return boolean
*/
- public function isAccessible($value)
+ public function isAccessible($value): bool
{
return is_array($value) || $value instanceof \ArrayAccess;
}
@@ -271,9 +254,8 @@ public function isAccessible($value)
* Create a new Container instance.
*
* @param array $args Parameters for the initialization of a Container.
- * @return Container
*/
- public function providerFactory(array $args = [])
+ public function providerFactory(array $args = []): \Pimple\Container
{
$container = new Container($args);
diff --git a/packages/cache/tests/Charcoal/Mocks/CachePoolAware.php b/packages/cache/tests/Charcoal/Mocks/CachePoolAware.php
index b38f09e22..d4bd63c4d 100644
--- a/packages/cache/tests/Charcoal/Mocks/CachePoolAware.php
+++ b/packages/cache/tests/Charcoal/Mocks/CachePoolAware.php
@@ -1,5 +1,7 @@
itemClass;
}
- /**
- * @return false|string
- */
- public function getNamespace(): ?string
- {
- return $this->namespace;
- }
-
/**
* @return Boolean|LoggerInterface
*/
diff --git a/packages/cache/tests/Charcoal/Mocks/DefaultsAwareCacheMiddlewares.php b/packages/cache/tests/Charcoal/Mocks/DefaultsAwareCacheMiddlewares.php
index 75ef83aa9..085f37406 100644
--- a/packages/cache/tests/Charcoal/Mocks/DefaultsAwareCacheMiddlewares.php
+++ b/packages/cache/tests/Charcoal/Mocks/DefaultsAwareCacheMiddlewares.php
@@ -1,5 +1,7 @@
logger;
diff --git a/packages/cache/tests/bootstrap.php b/packages/cache/tests/bootstrap.php
new file mode 100644
index 000000000..90929e3b5
--- /dev/null
+++ b/packages/cache/tests/bootstrap.php
@@ -0,0 +1,14 @@
+
-
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
-
-
+
+ ./src/Charcoal
-
-
+
+
+
+
+
+
+
+
-
+
-
-
-
-
diff --git a/packages/cms/src/Charcoal/Admin/Widget/Cms/HierarchicalSectionTableWidget.php b/packages/cms/src/Charcoal/Admin/Widget/Cms/HierarchicalSectionTableWidget.php
index 6dcba5266..36a534ebc 100644
--- a/packages/cms/src/Charcoal/Admin/Widget/Cms/HierarchicalSectionTableWidget.php
+++ b/packages/cms/src/Charcoal/Admin/Widget/Cms/HierarchicalSectionTableWidget.php
@@ -24,10 +24,9 @@ class HierarchicalSectionTableWidget extends TableWidget
/**
* Provide a template to fullfill UIItem interface.
- *
- * @return string
*/
- public function template()
+ #[\Override]
+ public function template(): string
{
return 'charcoal/admin/widget/table';
}
@@ -38,6 +37,7 @@ public function template()
* @see \Charcoal\Admin\Ui\CollectionContainerTrait::sortObjects()
* @return array
*/
+ #[\Override]
public function sortObjects()
{
$collection = new HierarchicalCollection($this->objects(), false);
@@ -55,6 +55,7 @@ public function sortObjects()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -71,6 +72,7 @@ protected function setDependencies(Container $container)
* @param PropertyInterface $property The current property.
* @return void
*/
+ #[\Override]
protected function setupDisplayPropertyValue(
ModelInterface $object,
PropertyInterface $property
diff --git a/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableTrait.php b/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableTrait.php
index 4ea99fb2b..d8501e2a7 100644
--- a/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableTrait.php
+++ b/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableTrait.php
@@ -48,7 +48,7 @@ public function sectionFactory()
{
if (!isset($this->sectionFactory)) {
throw new RuntimeException(
- sprintf('Section Model Factory is not defined for "%s"', get_class($this))
+ sprintf('Section Model Factory is not defined for "%s"', $this::class)
);
}
@@ -89,30 +89,26 @@ protected function parsePropertyCell(
case 'menu_label':
$sectionType = $object->sectionType();
- switch ($sectionType) {
- case AbstractSection::TYPE_EXTERNAL:
- $externalUrl = (string)$object->externalUrl();
- $linkExcerpt = '';
- $tagTemplate = '';
-
- if ($externalUrl) {
- $tagTemplate = '' .
- ' ' .
- 'URL: %3$s' .
- '';
-
- $linkExcerpt = $this->abridgeUri($externalUrl);
- }
-
- $p = $object->p('section_type');
- $propertyValue .= sprintf(
- ' ' . $tagTemplate,
- $p->displayVal($p->val()),
- $externalUrl,
- $linkExcerpt
- );
- break;
+ if ($sectionType === AbstractSection::TYPE_EXTERNAL) {
+ $externalUrl = (string)$object->externalUrl();
+ $linkExcerpt = '';
+ $tagTemplate = '';
+ if ($externalUrl !== '' && $externalUrl !== '0') {
+ $tagTemplate = '' .
+ ' ' .
+ 'URL: %3$s' .
+ '';
+
+ $linkExcerpt = $this->abridgeUri($externalUrl);
+ }
+ $p = $object->p('section_type');
+ $propertyValue .= sprintf(
+ ' ' . $tagTemplate,
+ $p->displayVal($p->val()),
+ $externalUrl,
+ $linkExcerpt
+ );
}
break;
}
diff --git a/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableWidget.php b/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableWidget.php
index 8586e3621..0733d7e75 100644
--- a/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableWidget.php
+++ b/packages/cms/src/Charcoal/Admin/Widget/Cms/SectionTableWidget.php
@@ -19,6 +19,7 @@ class SectionTableWidget extends TableWidget
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/cms/src/Charcoal/Admin/Widget/FormGroup/GroupAttachmentFormGroup.php b/packages/cms/src/Charcoal/Admin/Widget/FormGroup/GroupAttachmentFormGroup.php
index ab2f420a5..44c98700a 100644
--- a/packages/cms/src/Charcoal/Admin/Widget/FormGroup/GroupAttachmentFormGroup.php
+++ b/packages/cms/src/Charcoal/Admin/Widget/FormGroup/GroupAttachmentFormGroup.php
@@ -1,5 +1,7 @@
hasGroups()) {
diff --git a/packages/cms/src/Charcoal/Admin/Widget/FormGroup/MultiGroupFormGroup.php b/packages/cms/src/Charcoal/Admin/Widget/FormGroup/MultiGroupFormGroup.php
index 0e660bc4b..cfa828d7e 100644
--- a/packages/cms/src/Charcoal/Admin/Widget/FormGroup/MultiGroupFormGroup.php
+++ b/packages/cms/src/Charcoal/Admin/Widget/FormGroup/MultiGroupFormGroup.php
@@ -22,24 +22,19 @@ class MultiGroupFormGroup extends MultiGroupWidget implements
use FormGroupTrait;
use UiItemTrait;
- /**
- * @return string
- */
- public function template()
+ #[\Override]
+ public function template(): string
{
return 'charcoal/admin/widget/multi-group';
}
- /**
- * @return array
- */
- public function dataFromObject()
+ public function dataFromObject(): array
{
$obj = $this->obj();
$objMetadata = $obj->metadata();
- $adminMetadata = (isset($objMetadata['admin']) ? $objMetadata['admin'] : null);
- $adminFormGroups = (isset($adminMetadata['form_groups']) ? $adminMetadata['form_groups'] : null);
+ $adminMetadata = ($objMetadata['admin'] ?? null);
+ $adminFormGroups = ($adminMetadata['form_groups'] ?? null);
$groups = $this->groups();
@@ -70,8 +65,8 @@ public function dataFromMetadata()
return [];
}
- $adminMetadata = (isset($data['admin']) ? $data['admin'] : null);
- $adminFormGroups = (isset($adminMetadata['form_groups']) ? $adminMetadata['form_groups'] : null);
+ $adminMetadata = ($data['admin'] ?? null);
+ $adminFormGroups = ($adminMetadata['form_groups'] ?? null);
if (isset($data['groups']) && isset($adminFormGroups)) {
$extraFormGroups = array_intersect(
@@ -100,10 +95,10 @@ public function dataFromMetadata()
* @throws \UnexpectedValueException If a property data is invalid.
* @return FormPropertyWidget[]
*/
- public function formProperties(array $group = null)
+ public function formProperties(?array $group = null): array
{
if (
- !key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources())) ||
+ !array_key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources())) ||
!$this->widgetMetadata()
) {
return iterator_to_array($this->form()->formProperties());
@@ -114,7 +109,7 @@ public function formProperties(array $group = null)
try {
$store = $this->storageProperty();
- } catch (\Exception $e) {
+ } catch (\Exception) {
$store = null;
}
@@ -128,7 +123,7 @@ public function formProperties(array $group = null)
$props = $this->widgetMetadata()['properties'];
// We need to sort form properties by form group property order if a group exists
- if (!empty($group)) {
+ if ($group !== null && $group !== []) {
$props = array_merge(array_flip($group), $props);
}
@@ -139,7 +134,7 @@ public function formProperties(array $group = null)
throw new \UnexpectedValueException(sprintf(
'Invalid property data for "%1$s", received %2$s',
$propertyIdent,
- (is_object($propertyMetadata) ? get_class($propertyMetadata) : gettype($propertyMetadata))
+ (get_debug_type($propertyMetadata))
));
}
@@ -172,9 +167,10 @@ public function formProperties(array $group = null)
*
* @return FormInterface|self
*/
+ #[\Override]
protected function formWidget()
{
- if (!key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources()))) {
+ if (!array_key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources()))) {
return $this->form();
}
diff --git a/packages/cms/src/Charcoal/Admin/Widget/GroupAttachmentWidget.php b/packages/cms/src/Charcoal/Admin/Widget/GroupAttachmentWidget.php
index 39a5f6570..71231c669 100644
--- a/packages/cms/src/Charcoal/Admin/Widget/GroupAttachmentWidget.php
+++ b/packages/cms/src/Charcoal/Admin/Widget/GroupAttachmentWidget.php
@@ -32,10 +32,8 @@ class GroupAttachmentWidget extends AttachmentWidget implements
/**
* Store the metadata loader instance.
- *
- * @var MetadataLoader
*/
- private $metadataLoader;
+ private ?\Charcoal\Model\Service\MetadataLoader $metadataLoader = null;
/**
* @var boolean
@@ -57,21 +55,17 @@ class GroupAttachmentWidget extends AttachmentWidget implements
protected function sortItemsByPriority(
PrioritizableInterface $a,
PrioritizableInterface $b
- ) {
+ ): int {
$priorityA = $a->priority();
$priorityB = $b->priority();
-
- if ($priorityA === $priorityB) {
- return 0;
- }
-
- return ($priorityA < $priorityB) ? (-1) : 1;
+ return ($priorityA <=> $priorityB);
}
/**
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -87,9 +81,8 @@ protected function setDependencies(Container $container)
* Set a metadata loader.
*
* @param MetadataLoader $loader The loader instance, used to load metadata.
- * @return self
*/
- protected function setMetadataLoader(MetadataLoader $loader)
+ protected function setMetadataLoader(MetadataLoader $loader): static
{
$this->metadataLoader = $loader;
@@ -100,14 +93,13 @@ protected function setMetadataLoader(MetadataLoader $loader)
* Retrieve the metadata loader.
*
* @throws RuntimeException If the metadata loader was not previously set.
- * @return MetadataLoader
*/
- protected function metadataLoader()
+ protected function metadataLoader(): \Charcoal\Model\Service\MetadataLoader
{
- if ($this->metadataLoader === null) {
+ if (!$this->metadataLoader instanceof \Charcoal\Model\Service\MetadataLoader) {
throw new RuntimeException(sprintf(
'Metadata Loader is not defined for "%s"',
- \get_class($this)
+ static::class
));
}
@@ -123,16 +115,15 @@ protected function metadataLoader()
protected function loadMetadata($metadataIdent)
{
$metadataLoader = $this->metadataLoader();
- $metadata = $metadataLoader->load($metadataIdent, $this->createMetadata());
- return $metadata;
+ return $metadataLoader->load($metadataIdent, $this->createMetadata());
}
/**
* @throws InvalidArgumentException If structureMetadata $data is note defined.
* @return MetadataInterface
*/
- protected function createMetadata()
+ protected function createMetadata(): \Charcoal\Property\Structure\StructureMetadata
{
return new StructureMetadata();
}
@@ -141,9 +132,9 @@ protected function createMetadata()
* Sets data on this widget.
*
* @param array $data Key-value array of data to append.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -173,7 +164,7 @@ protected function addAttachmentGroupFromMetadata($reload = false)
$interfaces = [$this->objType()];
if ($controllerInterface) {
- array_push($interfaces, $controllerInterface);
+ $interfaces[] = $controllerInterface;
}
$structureMetadata = $this->createMetadata();
@@ -204,9 +195,8 @@ protected function addAttachmentGroupFromMetadata($reload = false)
* Set the form object's template controller identifier.
*
* @param mixed $ident The template controller identifier.
- * @return self
*/
- public function setControllerIdent($ident)
+ public function setControllerIdent(string $ident): static
{
if (class_exists($ident)) {
$this->controllerIdent = $ident;
@@ -214,7 +204,7 @@ public function setControllerIdent($ident)
return $this;
}
- if (substr($ident, -9) !== '-template') {
+ if (!str_ends_with($ident, '-template')) {
$ident .= '-template';
}
@@ -235,10 +225,8 @@ public function controllerIdent()
/**
* Disable the pill nav if there is only one group.
- *
- * @return boolean
*/
- public function displayPills()
+ public function displayPills(): bool
{
return $this->numGroups() > 1;
}
diff --git a/packages/cms/src/Charcoal/Admin/Widget/MultiGroupWidget.php b/packages/cms/src/Charcoal/Admin/Widget/MultiGroupWidget.php
index 51417f576..f283da9a7 100644
--- a/packages/cms/src/Charcoal/Admin/Widget/MultiGroupWidget.php
+++ b/packages/cms/src/Charcoal/Admin/Widget/MultiGroupWidget.php
@@ -81,22 +81,17 @@ class MultiGroupWidget extends AdminWidget implements
protected function sortItemsByPriority(
PrioritizableInterface $a,
PrioritizableInterface $b
- ) {
+ ): int {
$priorityA = $a->priority();
$priorityB = $b->priority();
-
- if ($priorityA === $priorityB) {
- return 0;
- }
-
- return ($priorityA < $priorityB) ? (-1) : 1;
+ return ($priorityA <=> $priorityB);
}
/**
* @param array $data The widget data.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -109,6 +104,7 @@ public function setData(array $data)
* @param Container $container The DI container.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -122,10 +118,7 @@ protected function setDependencies(Container $container)
$this->setLayoutBuilder($container['layout/builder']);
}
- /**
- * @return string
- */
- public function defaultGroupType()
+ public function defaultGroupType(): string
{
return 'charcoal/admin/widget/form-group/generic';
}
@@ -135,7 +128,8 @@ public function defaultGroupType()
*
* @return string[]
*/
- protected function defaultDataSources()
+ #[\Override]
+ protected function defaultDataSources(): array
{
return [self::DATA_SOURCE_OBJECT];
}
@@ -144,9 +138,8 @@ protected function defaultDataSources()
* Set an widget factory.
*
* @param FactoryInterface $factory The factory to create widgets.
- * @return self
*/
- protected function setWidgetFactory(FactoryInterface $factory)
+ protected function setWidgetFactory(FactoryInterface $factory): static
{
$this->widgetFactory = $factory;
@@ -161,10 +154,10 @@ protected function setWidgetFactory(FactoryInterface $factory)
*/
public function widgetFactory()
{
- if (!isset($this->widgetFactory)) {
+ if ($this->widgetFactory === null) {
throw new RuntimeException(sprintf(
'Widget Factory is not defined for "%s"',
- get_class($this)
+ static::class
));
}
@@ -181,9 +174,8 @@ public function formGroups()
/**
* @param mixed $formGroups FormGroups for MultiGroupWidget.
- * @return self
*/
- public function setFormGroups($formGroups)
+ public function setFormGroups($formGroups): static
{
$this->formGroups = $formGroups;
@@ -200,18 +192,13 @@ public function widgetMetadata()
/**
* @param array|mixed $widgetMetadata WidgetMetadata for MultiGroupWidget.
- * @return self
*/
- public function setWidgetMetadata($widgetMetadata)
+ public function setWidgetMetadata($widgetMetadata): static
{
if (is_string($widgetMetadata) && $this->view()) {
$widgetMetadata = $this->view()->renderTemplate($widgetMetadata, $this->obj());
- if ($widgetMetadata !== '') {
- $widgetMetadata = json_decode($widgetMetadata, true);
- } else {
- $widgetMetadata = null;
- }
+ $widgetMetadata = $widgetMetadata !== '' ? json_decode($widgetMetadata, true) : null;
}
$this->widgetMetadata = $widgetMetadata;
@@ -228,9 +215,8 @@ public function setWidgetMetadata($widgetMetadata)
* @param string|ModelStructureProperty $propertyIdent The property identifier—or instance—of a storage property.
* @throws \InvalidArgumentException If the property identifier is not a string.
* @throws \UnexpectedValueException If a property is invalid.
- * @return self
*/
- public function setStorageProperty($propertyIdent)
+ public function setStorageProperty($propertyIdent): static
{
$property = null;
if ($propertyIdent instanceof PropertyInterface) {
@@ -247,11 +233,11 @@ public function setStorageProperty($propertyIdent)
throw new \UnexpectedValueException(sprintf(
'The "%1$s" property is not defined on [%2$s]',
$propertyIdent,
- get_class($obj)
+ $obj::class
));
}
- if ($property === null) {
+ if (!$property instanceof \Charcoal\Property\PropertyInterface) {
$property = $obj->property($propertyIdent);
}
@@ -261,8 +247,8 @@ public function setStorageProperty($propertyIdent)
throw new \UnexpectedValueException(sprintf(
'"%s" [%s] is not a model structure property on [%s].',
$propertyIdent,
- (is_object($property) ? get_class($property) : gettype($property)),
- (is_object($obj) ? get_class($obj) : gettype($obj))
+ (get_debug_type($property)),
+ (get_debug_type($obj))
));
}
@@ -280,7 +266,7 @@ public function storageProperty()
if ($this->storageProperty === null) {
throw new RuntimeException(sprintf(
'Storage property owner is not defined for "%s"',
- get_class($this)
+ static::class
));
}
diff --git a/packages/cms/src/Charcoal/Cms/AbstractEvent.php b/packages/cms/src/Charcoal/Cms/AbstractEvent.php
index 99350d4bf..a214aeac3 100644
--- a/packages/cms/src/Charcoal/Cms/AbstractEvent.php
+++ b/packages/cms/src/Charcoal/Cms/AbstractEvent.php
@@ -50,15 +50,9 @@ abstract class AbstractEvent extends Content implements EventInterface
*/
private $image;
- /**
- * @var DateTimeInterface|null
- */
- private $startDate;
+ private ?\DateTimeInterface $startDate = null;
- /**
- * @var DateTimeInterface|null
- */
- private $endDate;
+ private ?\DateTimeInterface $endDate = null;
/**
* @var Translation|string|null
@@ -71,15 +65,9 @@ abstract class AbstractEvent extends Content implements EventInterface
private $infoPhone;
- /**
- * @var float|null
- */
- private $ticketPriceMin;
+ private ?float $ticketPriceMin = null;
- /**
- * @var float|null
- */
- private $ticketPriceMax;
+ private ?float $ticketPriceMax = null;
/**
* @var Translation|string|null
@@ -105,11 +93,11 @@ abstract class AbstractEvent extends Content implements EventInterface
* Section constructor.
* @param array $data The data.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
parent::__construct($data);
- if (is_callable([ $this, 'defaultData' ])) {
+ if (is_callable($this->defaultData(...))) {
$this->setData($this->defaultData());
}
}
@@ -125,9 +113,8 @@ public function canonicalUrl()
/**
* Some dates cannot be null
- * @return void
*/
- public function verifyDates()
+ public function verifyDates(): void
{
if (!$this['startDate']) {
$this->setStartDate('now');
@@ -150,13 +137,7 @@ public function adminDateFilter()
$start = $this['startDate']->format('Y-m-d');
$end = $this['endDate']->format('Y-m-d');
- if ($start === $end) {
- $date = $start;
- } else {
- $date = $start . ' - ' . $end;
- }
-
- return $date;
+ return $start === $end ? $start : $start . ' - ' . $end;
}
/**
@@ -506,10 +487,9 @@ public function isActiveRoute()
/**
* {@inheritdoc}
- *
- * @return boolean
*/
- protected function preSave()
+ #[\Override]
+ protected function preSave(): bool
{
$this->verifyDates();
$this->setSlug($this->generateSlug());
@@ -521,9 +501,9 @@ protected function preSave()
* {@inheritdoc}
*
* @param array $properties Optional properties to update.
- * @return boolean
*/
- protected function preUpdate(array $properties = null)
+ #[\Override]
+ protected function preUpdate(?array $properties = null): bool
{
$this->verifyDates();
$this->setSlug($this->generateSlug());
@@ -534,7 +514,8 @@ protected function preUpdate(array $properties = null)
/**
* @return boolean Parent postSave().
*/
- protected function postSave()
+ #[\Override]
+ protected function postSave(): bool
{
// RoutableTrait
$this->generateObjectRoute($this['slug']);
@@ -544,9 +525,9 @@ protected function postSave()
/**
* @param array|null $properties Properties.
- * @return boolean
*/
- protected function postUpdate(array $properties = null)
+ #[\Override]
+ protected function postUpdate(?array $properties = null): bool
{
// RoutableTrait
$this->generateObjectRoute($this['slug']);
diff --git a/packages/cms/src/Charcoal/Cms/AbstractFaq.php b/packages/cms/src/Charcoal/Cms/AbstractFaq.php
index 5db4eba6e..46a5aef10 100644
--- a/packages/cms/src/Charcoal/Cms/AbstractFaq.php
+++ b/packages/cms/src/Charcoal/Cms/AbstractFaq.php
@@ -1,5 +1,7 @@
defaultData(...))) {
$this->setData($this->defaultData());
}
}
@@ -92,9 +89,8 @@ public function dateTimeDate()
/**
* Some dates cannot be null
- * @return void
*/
- public function verifyDates()
+ public function verifyDates(): void
{
if (!$this['newsDate']) {
$this->setNewsDate('now');
@@ -350,9 +346,9 @@ public function isActiveRoute()
* {@inheritdoc}
*
* @see \Charcoal\Source\StorableTrait::preSave()
- * @return boolean
*/
- protected function preSave()
+ #[\Override]
+ protected function preSave(): bool
{
$this->verifyDates();
$this->setSlug($this->generateSlug());
@@ -365,9 +361,9 @@ protected function preSave()
*
* @see \Charcoal\Source\StorableTrait::preUpdate()
* @param array $properties Optional properties to update.
- * @return boolean
*/
- protected function preUpdate(array $properties = null)
+ #[\Override]
+ protected function preUpdate(?array $properties = null): bool
{
$this->verifyDates();
$this->setSlug($this->generateSlug());
@@ -379,7 +375,8 @@ protected function preUpdate(array $properties = null)
* @see \Charcoal\Source\StorableTrait::postSave()
* @return boolean Parent postSave().
*/
- protected function postSave()
+ #[\Override]
+ protected function postSave(): bool
{
// RoutableTrait
$this->generateObjectRoute($this['slug']);
@@ -390,9 +387,9 @@ protected function postSave()
/**
* @see \Charcoal\Source\StorableTrait::postUpdate()
* @param array|null $properties Properties.
- * @return boolean
*/
- protected function postUpdate(array $properties = null)
+ #[\Override]
+ protected function postUpdate(?array $properties = null): bool
{
// RoutableTrait
$this->generateObjectRoute($this['slug']);
diff --git a/packages/cms/src/Charcoal/Cms/AbstractSection.php b/packages/cms/src/Charcoal/Cms/AbstractSection.php
index 2076af6f2..0df37b219 100644
--- a/packages/cms/src/Charcoal/Cms/AbstractSection.php
+++ b/packages/cms/src/Charcoal/Cms/AbstractSection.php
@@ -47,10 +47,7 @@ abstract class AbstractSection extends Content implements SectionInterface
public const TYPE_EXTERNAL = 'charcoal/cms/section/external-section';
public const DEFAULT_TYPE = self::TYPE_CONTENT;
- /**
- * @var string
- */
- private $sectionType = self::DEFAULT_TYPE;
+ private string $sectionType = self::DEFAULT_TYPE;
/**
* @var Translation|string|null
@@ -103,11 +100,11 @@ abstract class AbstractSection extends Content implements SectionInterface
* Section constructor.
* @param array $data Init data.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
parent::__construct($data);
- if (is_callable([ $this, 'defaultData' ])) {
+ if (is_callable($this->defaultData(...))) {
$this->setData($this->defaultData());
}
}
@@ -119,7 +116,7 @@ public function __construct(array $data = null)
*/
public function isDeletable()
{
- return !!$this->id() && !$this->locked();
+ return (bool)$this->id() && !$this->locked();
}
/**
@@ -423,10 +420,9 @@ public function defaultMetaImage()
* Route generated on postSave in case
* it contains the ID of the section, which
* you only get once you have save
- *
- * @return boolean
*/
- protected function postSave()
+ #[\Override]
+ protected function postSave(): bool
{
// RoutableTrait
if (!$this->locked()) {
@@ -440,9 +436,9 @@ protected function postSave()
* Check whatever before the update.
*
* @param array|null $properties Properties.
- * @return boolean
*/
- protected function postUpdate(array $properties = null)
+ #[\Override]
+ protected function postUpdate(?array $properties = null): bool
{
if (!$this->locked()) {
$this->generateObjectRoute($this['slug']);
@@ -453,10 +449,9 @@ protected function postUpdate(array $properties = null)
/**
* {@inheritdoc}
- *
- * @return boolean
*/
- protected function preSave()
+ #[\Override]
+ protected function preSave(): bool
{
if (!$this->locked()) {
$this->setSlug($this->generateSlug());
@@ -469,9 +464,9 @@ protected function preSave()
* {@inheritdoc}
*
* @param array $properties Optional properties to update.
- * @return boolean
*/
- protected function preUpdate(array $properties = null)
+ #[\Override]
+ protected function preUpdate(?array $properties = null): bool
{
if (!$this->locked()) {
$this->setSlug($this->generateSlug());
@@ -484,9 +479,9 @@ protected function preUpdate(array $properties = null)
* Event called before _deleting_ the object.
*
* @see \Charcoal\Model\AbstractModel::preDelete() For the "delete" Event.
- * @return boolean
*/
- protected function preDelete()
+ #[\Override]
+ protected function preDelete(): bool
{
if ($this->locked()) {
return false;
diff --git a/packages/cms/src/Charcoal/Cms/AbstractTag.php b/packages/cms/src/Charcoal/Cms/AbstractTag.php
index 29f281069..bca5e1559 100644
--- a/packages/cms/src/Charcoal/Cms/AbstractTag.php
+++ b/packages/cms/src/Charcoal/Cms/AbstractTag.php
@@ -47,7 +47,7 @@ abstract class AbstractTag extends Content implements TagInterface
/**
* @param array $data The object's data options.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
parent::__construct($data);
diff --git a/packages/cms/src/Charcoal/Cms/AbstractWebTemplate.php b/packages/cms/src/Charcoal/Cms/AbstractWebTemplate.php
index f07337ca2..64804ae76 100644
--- a/packages/cms/src/Charcoal/Cms/AbstractWebTemplate.php
+++ b/packages/cms/src/Charcoal/Cms/AbstractWebTemplate.php
@@ -61,10 +61,8 @@ abstract class AbstractWebTemplate extends AbstractTemplate
/**
* Additional SEO metadata.
- *
- * @var array
*/
- private $seoMetadata = [];
+ private \ArrayIterator|array $seoMetadata = [];
/**
* Inject dependencies from a DI Container.
@@ -72,6 +70,7 @@ abstract class AbstractWebTemplate extends AbstractTemplate
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
@@ -343,7 +342,7 @@ public function opengraphImage()
$img = (string)$this->fallbackOpengraphImage();
}
- if ($img) {
+ if ($img !== '' && $img !== '0') {
$uri = $this->baseUrl();
return $uri->withPath(strval($img));
}
@@ -384,7 +383,7 @@ public function hasSeoMetadata()
return (count($this->seoMetadata) > 0);
}
- return !empty($this->seoMetadata);
+ return $this->seoMetadata !== [];
}
/**
@@ -443,12 +442,10 @@ public function appConfig($key = null, $default = null)
if ($key) {
if (isset($this->appConfig[$key])) {
return $this->appConfig[$key];
+ } elseif (!is_string($default) && is_callable($default)) {
+ return $default();
} else {
- if (!is_string($default) && is_callable($default)) {
- return $default();
- } else {
- return $default;
- }
+ return $default;
}
}
@@ -477,10 +474,10 @@ protected function setBaseUrl(UriInterface $uri)
*/
public function baseUrl()
{
- if (!isset($this->baseUrl)) {
+ if ($this->baseUrl === null) {
throw new RuntimeException(sprintf(
'The base URI is not defined for [%s]',
- get_class($this)
+ static::class
));
}
@@ -500,13 +497,11 @@ public function createAbsoluteUrl($uri)
$uri = $this->baseUrl()->withPath('');
} else {
$parts = parse_url($uri);
- if (!isset($parts['scheme'])) {
- if (!in_array($uri[0], [ '/', '#', '?' ])) {
- $path = isset($parts['path']) ? $parts['path'] : '';
- $query = isset($parts['query']) ? $parts['query'] : '';
- $hash = isset($parts['fragment']) ? $parts['fragment'] : '';
- $uri = $this->baseUrl()->withPath($path)->withQuery($query)->withFragment($hash);
- }
+ if (!isset($parts['scheme']) && !in_array($uri[0], [ '/', '#', '?' ])) {
+ $path = ($parts['path'] ?? '');
+ $query = ($parts['query'] ?? '');
+ $hash = ($parts['fragment'] ?? '');
+ $uri = $this->baseUrl()->withPath($path)->withQuery($query)->withFragment($hash);
}
}
diff --git a/packages/cms/src/Charcoal/Cms/Config.php b/packages/cms/src/Charcoal/Cms/Config.php
index 1a663185d..4c0bfdc09 100644
--- a/packages/cms/src/Charcoal/Cms/Config.php
+++ b/packages/cms/src/Charcoal/Cms/Config.php
@@ -53,11 +53,11 @@ class Config extends Content implements
* Section constructor.
* @param array $data The data.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
parent::__construct($data);
- if (is_callable([$this, 'defaultData'])) {
+ if (is_callable($this->defaultData(...))) {
$this->setData($this->defaultData());
}
}
@@ -65,12 +65,10 @@ public function __construct(array $data = null)
// ==========================================================================
// SETTERS
// ==========================================================================
-
/**
* @param mixed $defaultMetaTitle The default meta title.
- * @return self
*/
- public function setDefaultMetaTitle($defaultMetaTitle)
+ public function setDefaultMetaTitle($defaultMetaTitle): static
{
$this->defaultMetaTitle = $this->translator()->translation($defaultMetaTitle);
@@ -79,9 +77,8 @@ public function setDefaultMetaTitle($defaultMetaTitle)
/**
* @param mixed $defaultMetaDescription The default meta description.
- * @return self
*/
- public function setDefaultMetaDescription($defaultMetaDescription)
+ public function setDefaultMetaDescription($defaultMetaDescription): static
{
$this->defaultMetaDescription = $this->translator()->translation($defaultMetaDescription);
@@ -90,9 +87,8 @@ public function setDefaultMetaDescription($defaultMetaDescription)
/**
* @param mixed $defaultMetaImage The default meta image.
- * @return self
*/
- public function setDefaultMetaImage($defaultMetaImage)
+ public function setDefaultMetaImage($defaultMetaImage): static
{
$this->defaultMetaImage = $defaultMetaImage;
@@ -101,9 +97,8 @@ public function setDefaultMetaImage($defaultMetaImage)
/**
* @param mixed $defaultMetaUrl The default meta url.
- * @return self
*/
- public function setDefaultMetaUrl($defaultMetaUrl)
+ public function setDefaultMetaUrl($defaultMetaUrl): static
{
$this->defaultMetaUrl = $this->translator()->translation($defaultMetaUrl);
@@ -112,9 +107,8 @@ public function setDefaultMetaUrl($defaultMetaUrl)
/**
* @param array|StructureMetadata|mixed $socialMedias The social media array.
- * @return self
*/
- public function setSocialMedias($socialMedias)
+ public function setSocialMedias($socialMedias): static
{
$this->socialMedias = $socialMedias;
@@ -123,9 +117,8 @@ public function setSocialMedias($socialMedias)
/**
* @param string $defaultFromEmail The default email to send from.
- * @return self
*/
- public function setDefaultFromEmail($defaultFromEmail)
+ public function setDefaultFromEmail($defaultFromEmail): static
{
$this->defaultFromEmail = $defaultFromEmail;
diff --git a/packages/cms/src/Charcoal/Cms/Config/CmsConfig.php b/packages/cms/src/Charcoal/Cms/Config/CmsConfig.php
index 9e6862af0..201f87343 100644
--- a/packages/cms/src/Charcoal/Cms/Config/CmsConfig.php
+++ b/packages/cms/src/Charcoal/Cms/Config/CmsConfig.php
@@ -74,12 +74,10 @@ class CmsConfig extends AbstractConfig
// ==========================================================================
// INIT
// ==========================================================================
-
/**
* @param ModelInterface $model The object model.
- * @return void
*/
- public function addModel(ModelInterface $model)
+ public function addModel(ModelInterface $model): void
{
$this->setData($model->data());
}
@@ -87,12 +85,10 @@ public function addModel(ModelInterface $model)
// ==========================================================================
// SETTERS
// ==========================================================================
-
/**
* @param mixed $defaultFromEmail The default email for contact forms.
- * @return self
*/
- public function setDefaultFromEmail($defaultFromEmail)
+ public function setDefaultFromEmail($defaultFromEmail): static
{
$this->defaultFromEmail = $defaultFromEmail;
@@ -101,9 +97,8 @@ public function setDefaultFromEmail($defaultFromEmail)
/**
* @param mixed $homeNews The news to display on home page.
- * @return self
*/
- public function setHomeNews($homeNews)
+ public function setHomeNews($homeNews): static
{
$this->homeNews = $homeNews;
@@ -112,9 +107,8 @@ public function setHomeNews($homeNews)
/**
* @param mixed $homeEvents The events to display on home page.
- * @return self
*/
- public function setHomeEvents($homeEvents)
+ public function setHomeEvents($homeEvents): static
{
$this->homeEvents = $homeEvents;
@@ -125,7 +119,7 @@ public function setHomeEvents($homeEvents)
* @param array $newsConfig The news configuration object.
* @return $this
*/
- public function setNews(array $newsConfig)
+ public function setNews(array $newsConfig): static
{
if (!$this->newsConfig) {
$this->newsConfig = new NewsConfig();
@@ -140,7 +134,7 @@ public function setNews(array $newsConfig)
* @param array $eventConfig The event configuration object.
* @return $this
*/
- public function setEvent(array $eventConfig)
+ public function setEvent(array $eventConfig): static
{
if (!$this->eventConfig) {
$this->eventConfig = new EventConfig();
@@ -155,7 +149,7 @@ public function setEvent(array $eventConfig)
* @param array $sectionConfig The section configuration object.
* @return $this
*/
- public function setSection(array $sectionConfig)
+ public function setSection(array $sectionConfig): static
{
if (!$this->sectionConfig) {
$this->sectionConfig = new SectionConfig();
@@ -168,9 +162,8 @@ public function setSection(array $sectionConfig)
/**
* @param string $contactCategory Must conform City\\Support\\Interface\\ContactCategoryInterface.
- * @return self
*/
- public function setContactCategoryObj($contactCategory)
+ public function setContactCategoryObj($contactCategory): static
{
$this->contactCategoryObj = $contactCategory;
@@ -179,9 +172,8 @@ public function setContactCategoryObj($contactCategory)
/**
* @param string $contactObj Must conform City\\Support\\Interface\\ContactInterface.
- * @return self
*/
- public function setContactObj($contactObj)
+ public function setContactObj($contactObj): static
{
$this->contactObj = $contactObj;
@@ -190,9 +182,8 @@ public function setContactObj($contactObj)
/**
* @param string $defaultContactCategory The default contact category fallback.
- * @return self
*/
- public function setDefaultContactCategory($defaultContactCategory)
+ public function setDefaultContactCategory($defaultContactCategory): static
{
$this->defaultContactCategory = $defaultContactCategory;
@@ -201,9 +192,8 @@ public function setDefaultContactCategory($defaultContactCategory)
/**
* @param array $dateFormats Formats for full dates.
- * @return self
*/
- public function setDateFormats(array $dateFormats)
+ public function setDateFormats(array $dateFormats): static
{
$this->dateFormats = array_replace_recursive(
$this->dateFormats,
@@ -215,9 +205,8 @@ public function setDateFormats(array $dateFormats)
/**
* @param array $timeFormats Formats for time.
- * @return self
*/
- public function setTimeFormats(array $timeFormats)
+ public function setTimeFormats(array $timeFormats): static
{
$this->timeFormats = array_replace_recursive(
$this->timeFormats,
diff --git a/packages/cms/src/Charcoal/Cms/Config/EventConfig.php b/packages/cms/src/Charcoal/Cms/Config/EventConfig.php
index 4d70a901a..e10ccaffc 100644
--- a/packages/cms/src/Charcoal/Cms/Config/EventConfig.php
+++ b/packages/cms/src/Charcoal/Cms/Config/EventConfig.php
@@ -1,5 +1,7 @@
thumbnail;
}
@@ -120,7 +119,7 @@ public function parentSectionSlug()
* @param integer $numPerPage Number of event per page.
* @return EventConfig
*/
- public function setNumPerPage($numPerPage)
+ public function setNumPerPage($numPerPage): static
{
$this->numPerPage = $numPerPage;
@@ -131,7 +130,7 @@ public function setNumPerPage($numPerPage)
* @param boolean $entryCycle Cycle event or not.
* @return EventConfig
*/
- public function setEntryCycle($entryCycle)
+ public function setEntryCycle($entryCycle): static
{
$this->entryCycle = $entryCycle;
@@ -143,7 +142,7 @@ public function setEntryCycle($entryCycle)
* @param string $lifespan Event expiry.
* @return EventConfig
*/
- public function setLifespan($lifespan)
+ public function setLifespan($lifespan): static
{
$this->lifespan = $lifespan;
@@ -154,7 +153,7 @@ public function setLifespan($lifespan)
* @param string $objType Event object type.
* @return EventConfig
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
@@ -165,7 +164,7 @@ public function setObjType($objType)
* @param string $category Event category object.
* @return EventConfig
*/
- public function setCategory($category)
+ public function setCategory($category): static
{
$this->category = $category;
@@ -177,7 +176,7 @@ public function setCategory($category)
* @param string $configFeatIdent Config property containing featured event.
* @return EventConfig
*/
- public function setConfigFeatIdent($configFeatIdent)
+ public function setConfigFeatIdent($configFeatIdent): static
{
$this->configFeatIdent = $configFeatIdent;
@@ -189,7 +188,7 @@ public function setConfigFeatIdent($configFeatIdent)
* @param array $thumbnail Event thumbnail size.
* @return EventConfig
*/
- public function setThumbnail(array $thumbnail)
+ public function setThumbnail(array $thumbnail): static
{
$this->thumbnail = $thumbnail;
@@ -200,7 +199,7 @@ public function setThumbnail(array $thumbnail)
* @param string $parentSectionSlug Event parent section (slug).
* @return EventConfig
*/
- public function setParentSectionSlug($parentSectionSlug)
+ public function setParentSectionSlug($parentSectionSlug): static
{
$this->parentSectionSlug = $parentSectionSlug;
diff --git a/packages/cms/src/Charcoal/Cms/Config/NewsConfig.php b/packages/cms/src/Charcoal/Cms/Config/NewsConfig.php
index 68f6f100f..debefc86e 100644
--- a/packages/cms/src/Charcoal/Cms/Config/NewsConfig.php
+++ b/packages/cms/src/Charcoal/Cms/Config/NewsConfig.php
@@ -1,5 +1,7 @@
thumbnail;
}
@@ -131,9 +130,8 @@ public function parentSectionSlug()
/**
* @param integer $numPerPage Number of news per page.
- * @return NewsConfig
*/
- public function setNumPerPage($numPerPage)
+ public function setNumPerPage($numPerPage): static
{
$this->numPerPage = $numPerPage;
@@ -142,9 +140,8 @@ public function setNumPerPage($numPerPage)
/**
* @param boolean $entryCycle Cycle news or not.
- * @return NewsConfig
*/
- public function setEntryCycle($entryCycle)
+ public function setEntryCycle($entryCycle): static
{
$this->entryCycle = $entryCycle;
@@ -154,9 +151,8 @@ public function setEntryCycle($entryCycle)
/**
* Accept all DateTime string.
* @param string $defaultExpiry Expiry.
- * @return NewsConfig
*/
- public function setDefaultExpiry($defaultExpiry)
+ public function setDefaultExpiry($defaultExpiry): static
{
$this->defaultExpiry = $defaultExpiry;
@@ -165,9 +161,8 @@ public function setDefaultExpiry($defaultExpiry)
/**
* @param string $median DateTime string.
- * @return NewsConfig
*/
- public function setMedian($median)
+ public function setMedian($median): static
{
$this->median = $median;
@@ -176,9 +171,8 @@ public function setMedian($median)
/**
* @param string $objType News object type.
- * @return NewsConfig
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
@@ -187,9 +181,8 @@ public function setObjType($objType)
/**
* @param string $category News category object.
- * @return NewsConfig
*/
- public function setCategory($category)
+ public function setCategory($category): static
{
$this->category = $category;
@@ -199,9 +192,8 @@ public function setCategory($category)
/**
* Might be overkill.
* @param string $configFeatIdent Config property containing featured news.
- * @return NewsConfig
*/
- public function setConfigFeatIdent($configFeatIdent)
+ public function setConfigFeatIdent($configFeatIdent): static
{
$this->configFeatIdent = $configFeatIdent;
@@ -211,9 +203,8 @@ public function setConfigFeatIdent($configFeatIdent)
/**
* resize -> width.
* @param array $thumbnail News thumbnail size.
- * @return NewsConfig
*/
- public function setThumbnail(array $thumbnail)
+ public function setThumbnail(array $thumbnail): static
{
$this->thumbnail = $thumbnail;
@@ -222,9 +213,8 @@ public function setThumbnail(array $thumbnail)
/**
* @param string $parentSectionSlug News parent section (slug).
- * @return NewsConfig
*/
- public function setParentSectionSlug($parentSectionSlug)
+ public function setParentSectionSlug($parentSectionSlug): static
{
$this->parentSectionSlug = $parentSectionSlug;
diff --git a/packages/cms/src/Charcoal/Cms/Config/SectionConfig.php b/packages/cms/src/Charcoal/Cms/Config/SectionConfig.php
index ce6f8eb95..e324e26cc 100644
--- a/packages/cms/src/Charcoal/Cms/Config/SectionConfig.php
+++ b/packages/cms/src/Charcoal/Cms/Config/SectionConfig.php
@@ -1,5 +1,7 @@
baseSection = $baseSection;
@@ -45,9 +46,8 @@ public function setBaseSection($baseSection)
* Set the available section types
*
* @param mixed $sectionTypes Section types.
- * @return SectionConfig
*/
- public function setSectionTypes($sectionTypes)
+ public function setSectionTypes($sectionTypes): static
{
$this->sectionTypes = $sectionTypes;
return $this;
@@ -55,9 +55,8 @@ public function setSectionTypes($sectionTypes)
/**
* @param string $objType Section object type.
- * @return SectionConfig
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
diff --git a/packages/cms/src/Charcoal/Cms/ConfigInterface.php b/packages/cms/src/Charcoal/Cms/ConfigInterface.php
index 9c64641bb..047272138 100644
--- a/packages/cms/src/Charcoal/Cms/ConfigInterface.php
+++ b/packages/cms/src/Charcoal/Cms/ConfigInterface.php
@@ -1,5 +1,7 @@
defaultData(...))) {
$this->setData($this->defaultData());
}
}
/**
* CategoryTrait > itemType()
- *
- * @return string
*/
- public function itemType()
+ public function itemType(): string
{
return Event::class;
}
@@ -48,7 +46,7 @@ public function itemType()
/**
* @return \Charcoal\Model\Collection|array
*/
- public function loadCategoryItems()
+ public function loadCategoryItems(): array
{
return [];
}
@@ -63,9 +61,8 @@ public function name()
/**
* @param mixed $name The category name.
- * @return self
*/
- public function setName($name)
+ public function setName($name): static
{
$this->name = $this->translator()->translation($name);
@@ -74,9 +71,9 @@ public function setName($name)
/**
* @param ValidatorInterface $v Optional. A custom validator object to use for validation. If null, use object's.
- * @return boolean
*/
- public function validate(ValidatorInterface &$v = null)
+ #[\Override]
+ public function validate(?ValidatorInterface &$v = null): bool
{
parent::validate($v);
diff --git a/packages/cms/src/Charcoal/Cms/EventInterface.php b/packages/cms/src/Charcoal/Cms/EventInterface.php
index 01426e2e7..2934c471a 100644
--- a/packages/cms/src/Charcoal/Cms/EventInterface.php
+++ b/packages/cms/src/Charcoal/Cms/EventInterface.php
@@ -1,5 +1,7 @@
categoryType()
- *
- * @return string
*/
- public function categoryType()
+ public function categoryType(): string
{
return FaqCategory::class;
}
diff --git a/packages/cms/src/Charcoal/Cms/FaqCategory.php b/packages/cms/src/Charcoal/Cms/FaqCategory.php
index fd1d9b41a..180ac340b 100644
--- a/packages/cms/src/Charcoal/Cms/FaqCategory.php
+++ b/packages/cms/src/Charcoal/Cms/FaqCategory.php
@@ -1,5 +1,7 @@
itemType()
- *
- * @return string
*/
- public function itemType()
+ public function itemType(): string
{
return Faq::class;
}
@@ -27,7 +27,7 @@ public function itemType()
/**
* @return \Charcoal\Model\Collection|array
*/
- public function loadCategoryItems()
+ public function loadCategoryItems(): array
{
return [];
}
diff --git a/packages/cms/src/Charcoal/Cms/FaqInterface.php b/packages/cms/src/Charcoal/Cms/FaqInterface.php
index 04c82a310..ce78ec5e0 100644
--- a/packages/cms/src/Charcoal/Cms/FaqInterface.php
+++ b/packages/cms/src/Charcoal/Cms/FaqInterface.php
@@ -1,5 +1,7 @@
data() as $lang => $val) {
+ foreach ($meta->data() as $val) {
if ($val && $val != '') {
$empty = false;
}
diff --git a/packages/cms/src/Charcoal/Cms/Mixin/HasContentBlocksInterface.php b/packages/cms/src/Charcoal/Cms/Mixin/HasContentBlocksInterface.php
index d5685c7ce..31218c3be 100644
--- a/packages/cms/src/Charcoal/Cms/Mixin/HasContentBlocksInterface.php
+++ b/packages/cms/src/Charcoal/Cms/Mixin/HasContentBlocksInterface.php
@@ -1,5 +1,7 @@
numContentBlocks());
+ return (bool)$this->numContentBlocks();
}
/**
* Count the number of content blocks associated to this object.
- *
- * @return integer
*/
- public function numContentBlocks()
+ public function numContentBlocks(): int
{
return count($this->contentBlocks());
}
@@ -78,9 +74,7 @@ private function metaDescFromAttachments()
if ($attachment->isText()) {
$content = $attachment->description();
- $content = $this->ellipsis($content);
-
- return $content;
+ return $this->ellipsis($content);
}
}
@@ -122,7 +116,7 @@ private function ellipsis($content, $length = 200)
abstract public function getAttachments(
$group = null,
$type = null,
- callable $before = null,
- callable $after = null
+ ?callable $before = null,
+ ?callable $after = null
);
}
diff --git a/packages/cms/src/Charcoal/Cms/News.php b/packages/cms/src/Charcoal/Cms/News.php
index c1bf4913c..842615668 100644
--- a/packages/cms/src/Charcoal/Cms/News.php
+++ b/packages/cms/src/Charcoal/Cms/News.php
@@ -1,5 +1,7 @@
categoryType()
- *
- * @return string
*/
- public function categoryType()
+ public function categoryType(): string
{
return NewsCategory::class;
}
diff --git a/packages/cms/src/Charcoal/Cms/NewsCategory.php b/packages/cms/src/Charcoal/Cms/NewsCategory.php
index f09b9337a..e1afce7bc 100644
--- a/packages/cms/src/Charcoal/Cms/NewsCategory.php
+++ b/packages/cms/src/Charcoal/Cms/NewsCategory.php
@@ -26,21 +26,19 @@ class NewsCategory extends Content implements CategoryInterface
* Section constructor.
* @param array $data Init data.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
parent::__construct($data);
- if (is_callable([ $this, 'defaultData' ])) {
+ if (is_callable($this->defaultData(...))) {
$this->setData($this->defaultData());
}
}
/**
* CategoryTrait > itemType()
- *
- * @return string
*/
- public function itemType()
+ public function itemType(): string
{
return News::class;
}
@@ -48,7 +46,7 @@ public function itemType()
/**
* @return \Charcoal\Model\Collection|array
*/
- public function loadCategoryItems()
+ public function loadCategoryItems(): array
{
return [];
}
@@ -63,9 +61,8 @@ public function name()
/**
* @param mixed $name The category name.
- * @return self
*/
- public function setName($name)
+ public function setName($name): static
{
$this->name = $this->translator()->translation($name);
@@ -74,14 +71,14 @@ public function setName($name)
/**
* @param ValidatorInterface $v Optional. A custom validator object to use for validation. If null, use object's.
- * @return boolean
*/
- public function validate(ValidatorInterface &$v = null)
+ #[\Override]
+ public function validate(?ValidatorInterface &$v = null): bool
{
parent::validate($v);
foreach ($this->translator()->locales() as $locale => $value) {
- if (!(string)$this['name'][$locale]) {
+ if ((string)$this['name'][$locale] === '' || (string)$this['name'][$locale] === '0') {
$this->validator()->error(
(string)$this->translator()->translation([
'fr' => 'Le NOM doit être rempli dans toutes les langues.',
diff --git a/packages/cms/src/Charcoal/Cms/NewsInterface.php b/packages/cms/src/Charcoal/Cms/NewsInterface.php
index ba3fc7b4f..cc785d5e8 100644
--- a/packages/cms/src/Charcoal/Cms/NewsInterface.php
+++ b/packages/cms/src/Charcoal/Cms/NewsInterface.php
@@ -1,5 +1,7 @@
path = ltrim($data['path'], '/');
+ $this->path = ltrim((string)$data['path'], '/');
}
/**
* Determine if the URI path resolves to an object.
*
* @param Container $container A DI (Pimple) container.
- * @return boolean
*/
- public function pathResolvable(Container $container)
+ public function pathResolvable(Container $container): bool
{
$event = $this->loadEventFromPath($container);
return ($event instanceof EventInterface) && $event->id();
@@ -72,6 +67,7 @@ public function pathResolvable(Container $container)
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
*/
+ #[\Override]
public function __invoke(
Container $container,
RequestInterface $request,
@@ -87,11 +83,11 @@ public function __invoke(
$templateIdent = (string)$event['templateIdent'];
$templateController = (string)$event['templateIdent'];
- if (!$templateController) {
+ if ($templateController === '' || $templateController === '0') {
$container['logger']->warning(sprintf(
'[%s] Missing template controller on model [%s] for ID [%s]',
- get_class($this),
- get_class($event),
+ static::class,
+ $event::class,
$event['id']
));
return $response->withStatus(500);
@@ -110,8 +106,8 @@ public function __invoke(
if ($templateContent === $templateIdent || $templateContent === '') {
$container['logger']->warning(sprintf(
'[%s] Missing or bad template identifier on model [%s] for ID [%s]',
- get_class($this),
- get_class($event),
+ static::class,
+ $event::class,
$templateIdent
));
return $response->withStatus(500);
@@ -131,7 +127,7 @@ protected function loadEventFromPath(Container $container)
{
if ($this->event === null) {
$config = $this->config();
- $objType = (isset($config['obj_type']) ? $config['obj_type'] : $this->objType);
+ $objType = ($config['obj_type'] ?? $this->objType);
try {
$model = $container['model/factory']->create($objType);
@@ -146,11 +142,11 @@ protected function loadEventFromPath(Container $container)
$this->event = $model;
return $model;
}
- } catch (Exception $e) {
+ } catch (Exception) {
$container['logger']->debug(sprintf(
'[%s] Unable to load model [%s] for path [%s]',
- get_class($this),
- get_class($model),
+ static::class,
+ $model::class,
$this->path
));
}
diff --git a/packages/cms/src/Charcoal/Cms/Route/GenericRoute.php b/packages/cms/src/Charcoal/Cms/Route/GenericRoute.php
index 08e66ee41..39401a3ea 100644
--- a/packages/cms/src/Charcoal/Cms/Route/GenericRoute.php
+++ b/packages/cms/src/Charcoal/Cms/Route/GenericRoute.php
@@ -58,17 +58,13 @@ class GenericRoute extends TemplateRoute
/**
* Store the factory instance for the current class.
- *
- * @var FactoryInterface
*/
- private $modelFactory;
+ private ?\Charcoal\Factory\FactoryInterface $modelFactory = null;
/**
* Store the collection loader for the current class.
- *
- * @var CollectionLoader
*/
- private $collectionLoader;
+ private ?\Charcoal\Loader\CollectionLoader $collectionLoader = null;
/**
* Track the state of required dependencies.
@@ -103,7 +99,7 @@ public function __construct(array $data)
{
parent::__construct($data);
- $this->setPath(ltrim($data['path'], '/'));
+ $this->setPath(ltrim((string)$data['path'], '/'));
}
/**
@@ -124,11 +120,7 @@ public function pathResolvable(Container $container)
}
$contextObject = $this->getContextObject();
- if (!$contextObject || !$this->isValidContextObject($contextObject)) {
- return false;
- }
-
- return true;
+ return $contextObject && $this->isValidContextObject($contextObject);
}
/**
@@ -139,6 +131,7 @@ public function pathResolvable(Container $container)
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
*/
+ #[\Override]
public function __invoke(
Container $container,
RequestInterface $request,
@@ -173,8 +166,8 @@ public function __invoke(
if ($templateContent === $templateIdent || $templateContent === '') {
$container['logger']->warning(sprintf(
'[%s] Missing or bad template identifier on model [%s] for ID [%s]',
- get_class($this),
- get_class($this->getContextObject()),
+ static::class,
+ $this->getContextObject()::class,
$templateIdent
));
return $response->withStatus(500);
@@ -193,9 +186,7 @@ public function __invoke(
*/
public function createRouteObject()
{
- $route = $this->modelFactory()->create($this->objectRouteClass());
-
- return $route;
+ return $this->modelFactory()->create($this->objectRouteClass());
}
/**
@@ -253,10 +244,7 @@ protected function resolveLatestObjectRoute(
return $response;
}
- /**
- * @return self
- */
- protected function resolveTemplateContextObject()
+ protected function resolveTemplateContextObject(): static
{
$config = $this->config();
@@ -320,10 +308,8 @@ protected function resolveTemplateContextObject()
}
// Overwrite from custom object template_options
- if ($contextObject instanceof TemplateableInterface) {
- if (!empty($contextObject['templateOptions'])) {
- $templateOptions = $contextObject['templateOptions'];
- }
+ if ($contextObject instanceof TemplateableInterface && !empty($contextObject['templateOptions'])) {
+ $templateOptions = $contextObject['templateOptions'];
}
if (isset($templateOptions) && $templateOptions) {
@@ -347,6 +333,7 @@ protected function resolveTemplateContextObject()
* @param RequestInterface $request The request to intialize the template with.
* @return string
*/
+ #[\Override]
protected function createTemplate(Container $container, RequestInterface $request)
{
$template = parent::createTemplate($container, $request);
@@ -362,9 +349,8 @@ protected function createTemplate(Container $container, RequestInterface $reques
*
* @param string $className The class name of the object route model.
* @throws InvalidArgumentException If the class name is not a string.
- * @return self
*/
- protected function setObjectRouteClass($className)
+ protected function setObjectRouteClass($className): static
{
if (!is_string($className)) {
throw new InvalidArgumentException(
@@ -402,16 +388,7 @@ protected function isValidContextObject(RoutableInterface $contextObject)
if (!$contextObject->id()) {
return false;
}
-
- if ($contextObject instanceof RoutableInterface) {
- return $contextObject->isActiveRoute();
- }
-
- if (isset($contextObject['active'])) {
- return (bool)$contextObject['active'];
- }
-
- return true;
+ return $contextObject->isActiveRoute();
}
/**
@@ -467,9 +444,8 @@ protected function assertValidObjectRoute(ObjectRouteInterface $route)
* Determine if the object route is valid.
*
* @param ObjectRouteInterface $route An object route to test.
- * @return boolean
*/
- protected function isValidObjectRoute(ObjectRouteInterface $route)
+ protected function isValidObjectRoute(ObjectRouteInterface $route): bool
{
return ($route->id() && $route->getRouteObjType() && $route->getRouteObjId());
}
@@ -552,14 +528,12 @@ public function getLatestObjectPathHistory(ObjectRouteInterface $route)
/**
* SETTERS
*/
-
/**
* Set the specified URI path.
*
* @param string $path The path to use for route resolution.
- * @return self
*/
- protected function setPath($path)
+ protected function setPath($path): static
{
$this->path = $path;
@@ -570,9 +544,8 @@ protected function setPath($path)
* Set an object model factory.
*
* @param FactoryInterface $factory The model factory, to create objects.
- * @return self
*/
- protected function setModelFactory(FactoryInterface $factory)
+ protected function setModelFactory(FactoryInterface $factory): static
{
$this->modelFactory = $factory;
@@ -583,9 +556,8 @@ protected function setModelFactory(FactoryInterface $factory)
* Set a model collection loader.
*
* @param CollectionLoader $loader The collection loader.
- * @return self
*/
- public function setCollectionLoader(CollectionLoader $loader)
+ public function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
@@ -598,7 +570,7 @@ public function setCollectionLoader(CollectionLoader $loader)
* @param string $langCode The locale's language code.
* @return void
*/
- protected function setLocale($langCode)
+ protected function setLocale(string $langCode)
{
$translator = $this->translator();
$translator->setLocale($langCode);
@@ -617,14 +589,14 @@ protected function setLocale($langCode)
$choices = (array)$locale['locales'];
array_push($locales, ...$choices);
} elseif (isset($locale['locale'])) {
- array_push($locales, $locale['locale']);
+ $locales[] = $locale['locale'];
}
}
}
$locales = array_unique($locales);
- if ($locales) {
+ if ($locales !== []) {
setlocale(LC_ALL, $locales);
}
}
@@ -647,13 +619,12 @@ protected function path()
* Retrieve the object model factory.
*
* @throws RuntimeException If the model factory was not previously set.
- * @return FactoryInterface
*/
- public function modelFactory()
+ public function modelFactory(): \Charcoal\Factory\FactoryInterface
{
- if (!isset($this->modelFactory)) {
+ if (!$this->modelFactory instanceof \Charcoal\Factory\FactoryInterface) {
throw new RuntimeException(
- sprintf('Model Factory is not defined for "%s"', get_class($this))
+ sprintf('Model Factory is not defined for "%s"', static::class)
);
}
@@ -664,13 +635,12 @@ public function modelFactory()
* Retrieve the model collection loader.
*
* @throws RuntimeException If the collection loader was not previously set.
- * @return CollectionLoader
*/
- protected function collectionLoader()
+ protected function collectionLoader(): \Charcoal\Loader\CollectionLoader
{
- if (!isset($this->collectionLoader)) {
+ if (!$this->collectionLoader instanceof \Charcoal\Loader\CollectionLoader) {
throw new RuntimeException(
- sprintf('Collection Loader is not defined for "%s"', get_class($this))
+ sprintf('Collection Loader is not defined for "%s"', static::class)
);
}
@@ -680,6 +650,7 @@ protected function collectionLoader()
/**
* @return boolean
*/
+ #[\Override]
protected function cacheEnabled()
{
$obj = $this->getContextObject();
@@ -689,16 +660,15 @@ protected function cacheEnabled()
/**
* @return integer
*/
+ #[\Override]
protected function cacheTtl()
{
$obj = $this->getContextObject();
return $obj['cache_ttl'] ?: 0;
}
- /**
- * @return string
- */
- protected function cacheIdent()
+ #[\Override]
+ protected function cacheIdent(): string
{
$obj = $this->getContextObject();
return $obj->objType() . '.' . $obj->id();
diff --git a/packages/cms/src/Charcoal/Cms/Route/NewsRoute.php b/packages/cms/src/Charcoal/Cms/Route/NewsRoute.php
index dc33433e5..146a7c2af 100644
--- a/packages/cms/src/Charcoal/Cms/Route/NewsRoute.php
+++ b/packages/cms/src/Charcoal/Cms/Route/NewsRoute.php
@@ -26,10 +26,8 @@ class NewsRoute extends TemplateRoute
/**
* URI path.
- *
- * @var string
*/
- private $path;
+ private string $path;
/**
* The news entry matching the URI path.
@@ -40,10 +38,8 @@ class NewsRoute extends TemplateRoute
/**
* The news entry model.
- *
- * @var string
*/
- private $objType = 'charcoal/cms/news';
+ private string $objType = 'charcoal/cms/news';
/**
* @param array $data Class depdendencies.
@@ -51,16 +47,15 @@ class NewsRoute extends TemplateRoute
public function __construct(array $data)
{
parent::__construct($data);
- $this->path = ltrim($data['path'], '/');
+ $this->path = ltrim((string)$data['path'], '/');
}
/**
* Determine if the URI path resolves to an object.
*
* @param Container $container A DI (Pimple) container.
- * @return boolean
*/
- public function pathResolvable(Container $container)
+ public function pathResolvable(Container $container): bool
{
$news = $this->loadNewsFromPath($container);
return ($news instanceof NewsInterface) && $news->id();
@@ -72,6 +67,7 @@ public function pathResolvable(Container $container)
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
*/
+ #[\Override]
public function __invoke(
Container $container,
RequestInterface $request,
@@ -87,11 +83,11 @@ public function __invoke(
$templateIdent = (string)$news['templateIdent'];
$templateController = (string)$news['templateIdent'];
- if (!$templateController) {
+ if ($templateController === '' || $templateController === '0') {
$container['logger']->warning(sprintf(
'[%s] Missing template controller on model [%s] for ID [%s]',
- get_class($this),
- get_class($news),
+ static::class,
+ $news::class,
$news['id']
));
return $response->withStatus(500);
@@ -110,8 +106,8 @@ public function __invoke(
if ($templateContent === $templateIdent || $templateContent === '') {
$container['logger']->warning(sprintf(
'[%s] Missing or bad template identifier on model [%s] for ID [%s]',
- get_class($this),
- get_class($news),
+ static::class,
+ $news::class,
$templateIdent
));
return $response->withStatus(500);
@@ -131,7 +127,7 @@ protected function loadNewsFromPath(Container $container)
{
if ($this->news === null) {
$config = $this->config();
- $objType = (isset($config['obj_type']) ? $config['obj_type'] : $this->objType);
+ $objType = ($config['obj_type'] ?? $this->objType);
try {
$model = $container['model/factory']->create($objType);
@@ -146,11 +142,11 @@ protected function loadNewsFromPath(Container $container)
$this->news = $model;
return $model;
}
- } catch (Exception $e) {
+ } catch (Exception) {
$container['logger']->debug(sprintf(
'[%s] Unable to load model [%s] for path [%s]',
- get_class($this),
- get_class($model),
+ static::class,
+ $model::class,
$this->path
));
}
diff --git a/packages/cms/src/Charcoal/Cms/Route/SectionRoute.php b/packages/cms/src/Charcoal/Cms/Route/SectionRoute.php
index 797233234..1abc3a768 100644
--- a/packages/cms/src/Charcoal/Cms/Route/SectionRoute.php
+++ b/packages/cms/src/Charcoal/Cms/Route/SectionRoute.php
@@ -26,10 +26,8 @@ class SectionRoute extends TemplateRoute
/**
* URI path.
- *
- * @var string
*/
- private $path;
+ private string $path;
/**
* The section object matching the URI path.
@@ -40,10 +38,8 @@ class SectionRoute extends TemplateRoute
/**
* The section model.
- *
- * @var string
*/
- private $objType = 'charcoal/cms/section';
+ private string $objType = 'charcoal/cms/section';
/**
* @param array $data Class depdendencies.
@@ -52,16 +48,15 @@ public function __construct(array $data)
{
parent::__construct($data);
- $this->path = ltrim($data['path'], '/');
+ $this->path = ltrim((string)$data['path'], '/');
}
/**
* Determine if the URI path resolves to an object.
*
* @param Container $container A DI (Pimple) container.
- * @return boolean
*/
- public function pathResolvable(Container $container)
+ public function pathResolvable(Container $container): bool
{
$section = $this->loadSectionFromPath($container);
return ($section instanceof SectionInterface) && $section->id();
@@ -73,6 +68,7 @@ public function pathResolvable(Container $container)
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
*/
+ #[\Override]
public function __invoke(
Container $container,
RequestInterface $request,
@@ -88,11 +84,11 @@ public function __invoke(
$templateIdent = (string)$section['templateIdent'];
$templateController = (string)$section['templateIdent'];
- if (!$templateController) {
+ if ($templateController === '' || $templateController === '0') {
$container['logger']->warning(sprintf(
'[%s] Missing template controller on model [%s] for ID [%s]',
- get_class($this),
- get_class($section),
+ static::class,
+ $section::class,
$section['id']
));
return $response->withStatus(500);
@@ -112,8 +108,8 @@ public function __invoke(
if ($templateContent === $templateIdent || $templateContent === '') {
$container['logger']->warning(sprintf(
'[%s] Missing or bad template identifier on model [%s] for ID [%s]',
- get_class($this),
- get_class($section),
+ static::class,
+ $section::class,
$templateIdent
));
return $response->withStatus(500);
@@ -133,7 +129,7 @@ protected function loadSectionFromPath(Container $container)
{
if ($this->section === null) {
$config = $this->config();
- $objType = (isset($config['obj_type']) ? $config['obj_type'] : $this->objType);
+ $objType = ($config['obj_type'] ?? $this->objType);
try {
$model = $container['model/factory']->create($objType);
@@ -148,11 +144,11 @@ protected function loadSectionFromPath(Container $container)
$this->section = $model;
return $model;
}
- } catch (Exception $e) {
+ } catch (Exception) {
$container['logger']->debug(sprintf(
'[%s] Unable to load model [%s] for path [%s]',
- get_class($this),
- get_class($model),
+ static::class,
+ $model::class,
$this->path
));
}
diff --git a/packages/cms/src/Charcoal/Cms/SearchableInterface.php b/packages/cms/src/Charcoal/Cms/SearchableInterface.php
index 89c794a6e..57aa639c9 100644
--- a/packages/cms/src/Charcoal/Cms/SearchableInterface.php
+++ b/packages/cms/src/Charcoal/Cms/SearchableInterface.php
@@ -1,5 +1,7 @@
externalUrl = $this->translator()->translation($url);
@@ -31,6 +33,7 @@ public function setExternalUrl($url)
/**
* @return Translation|string|null
*/
+ #[\Override]
public function externalUrl()
{
return $this->externalUrl;
diff --git a/packages/cms/src/Charcoal/Cms/SectionInterface.php b/packages/cms/src/Charcoal/Cms/SectionInterface.php
index e4a924d5b..982de3435 100644
--- a/packages/cms/src/Charcoal/Cms/SectionInterface.php
+++ b/packages/cms/src/Charcoal/Cms/SectionInterface.php
@@ -1,5 +1,7 @@
modelFactory = $factory;
@@ -85,9 +84,9 @@ protected function setModelFactory(FactoryInterface $factory)
*/
public function modelFactory()
{
- if (!isset($this->modelFactory)) {
+ if ($this->modelFactory === null) {
throw new RuntimeException(
- sprintf('Model Factory is not defined for "%s"', get_class($this))
+ sprintf('Model Factory is not defined for "%s"', static::class)
);
}
@@ -98,9 +97,8 @@ public function modelFactory()
* Set a model collection loader.
*
* @param CollectionLoader $loader The collection loader.
- * @return self
*/
- protected function setCollectionLoader(CollectionLoader $loader)
+ protected function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
@@ -115,9 +113,9 @@ protected function setCollectionLoader(CollectionLoader $loader)
*/
public function collectionLoader()
{
- if (!isset($this->collectionLoader)) {
+ if ($this->collectionLoader === null) {
throw new RuntimeException(
- sprintf('Collection Loader is not defined for "%s"', get_class($this))
+ sprintf('Collection Loader is not defined for "%s"', static::class)
);
}
diff --git a/packages/cms/src/Charcoal/Cms/Service/Loader/EventLoader.php b/packages/cms/src/Charcoal/Cms/Service/Loader/EventLoader.php
index c536ab4e2..730a04a85 100644
--- a/packages/cms/src/Charcoal/Cms/Service/Loader/EventLoader.php
+++ b/packages/cms/src/Charcoal/Cms/Service/Loader/EventLoader.php
@@ -137,7 +137,7 @@ public function objType()
* @param string $lifespan The lifespan of events.
* @return self Chainable
*/
- public function setLifespan($lifespan)
+ public function setLifespan($lifespan): static
{
$this->lifespan = $lifespan;
@@ -148,7 +148,7 @@ public function setLifespan($lifespan)
* @param object $objType The object type.
* @return self Chainable
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
@@ -159,7 +159,7 @@ public function setObjType($objType)
* @param mixed $date The date to convert.
* @return DateTime
*/
- private function parseAsDate($date)
+ private function parseAsDate($date): \DateTimeInterface|\DateTime
{
if ($date instanceof DateTimeInterface) {
return $date;
diff --git a/packages/cms/src/Charcoal/Cms/Service/Loader/NewsLoader.php b/packages/cms/src/Charcoal/Cms/Service/Loader/NewsLoader.php
index 11a21edda..266876b06 100644
--- a/packages/cms/src/Charcoal/Cms/Service/Loader/NewsLoader.php
+++ b/packages/cms/src/Charcoal/Cms/Service/Loader/NewsLoader.php
@@ -75,9 +75,7 @@ public function expired()
*/
public function upcoming()
{
- $loader = $this->published();
-
- return $loader;
+ return $this->published();
}
/**
@@ -86,9 +84,7 @@ public function upcoming()
*/
public function archive()
{
- $loader = $this->expired();
-
- return $loader;
+ return $this->expired();
}
/**
@@ -109,9 +105,8 @@ public function objType()
/**
* @param string $median The median between upcoming and archive.
- * @return self
*/
- public function setMedian($median)
+ public function setMedian($median): static
{
$this->median = $median;
@@ -120,9 +115,8 @@ public function setMedian($median)
/**
* @param object $objType The object type.
- * @return self
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
diff --git a/packages/cms/src/Charcoal/Cms/Service/Loader/SectionLoader.php b/packages/cms/src/Charcoal/Cms/Service/Loader/SectionLoader.php
index 47c67e1e8..5b78d2aae 100644
--- a/packages/cms/src/Charcoal/Cms/Service/Loader/SectionLoader.php
+++ b/packages/cms/src/Charcoal/Cms/Service/Loader/SectionLoader.php
@@ -77,7 +77,7 @@ public function all()
/**
* @return \ArrayAccess|\Traversable
*/
- public function masters()
+ public function masters(): \ArrayAccess|array
{
$loader = $this->all();
$operator = [];
@@ -92,7 +92,7 @@ public function masters()
/**
* @return \ArrayAccess|\Traversable
*/
- public function children()
+ public function children(): array
{
$masters = $this->masters();
@@ -144,7 +144,7 @@ public function sectionRoutes()
$loader->setModel($proto);
$filters = [];
- foreach ($sectionTypes as $key => $val) {
+ foreach ($sectionTypes as $val) {
$filters[] = 'route_obj_type = \'' . $val . '\'';
}
$q = 'SELECT * FROM `' . $proto->source()->table() . '`
@@ -213,9 +213,7 @@ public function resolveSectionId($route)
return '';
}
- $sId = $routes['routes'][$route];
-
- return $sId;
+ return $routes['routes'][$route];
}
/**
@@ -244,9 +242,8 @@ public function sectionTypes()
/**
* @param object $objType The object type.
- * @return self
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
@@ -255,9 +252,8 @@ public function setObjType($objType)
/**
* @param integer $baseSection The base section id.
- * @return self
*/
- public function setBaseSection($baseSection)
+ public function setBaseSection($baseSection): static
{
$this->baseSection = $baseSection;
@@ -266,9 +262,8 @@ public function setBaseSection($baseSection)
/**
* @param array|null $sectionTypes Available section types.
- * @return self
*/
- public function setSectionTypes(array $sectionTypes = null)
+ public function setSectionTypes(?array $sectionTypes = null): static
{
$this->sectionTypes = $sectionTypes;
@@ -282,7 +277,7 @@ public function setSectionTypes(array $sectionTypes = null)
* @param string $delimiter The word delimiter.
* @return string
*/
- public static function snake($value, $delimiter = '-')
+ public static function snake($value, string $delimiter = '-')
{
$key = $value;
if (isset(static::$snakeCache[$key][$delimiter])) {
@@ -290,7 +285,7 @@ public static function snake($value, $delimiter = '-')
}
if (!ctype_lower($value)) {
$value = preg_replace('/\s+/u', '', $value);
- $value = mb_strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1' . $delimiter, $value), 'UTF-8');
+ $value = mb_strtolower((string)preg_replace('/(.)(?=[A-Z])/u', '$1' . $delimiter, (string)$value), 'UTF-8');
}
static::$snakeCache[$key][$delimiter] = $value;
diff --git a/packages/cms/src/Charcoal/Cms/Service/Manager/AbstractManager.php b/packages/cms/src/Charcoal/Cms/Service/Manager/AbstractManager.php
index daaac2faf..1a20fb22a 100644
--- a/packages/cms/src/Charcoal/Cms/Service/Manager/AbstractManager.php
+++ b/packages/cms/src/Charcoal/Cms/Service/Manager/AbstractManager.php
@@ -47,13 +47,13 @@ public function __construct(array $data)
if (!isset($data['factory'])) {
throw new Exception(sprintf(
'Model Factory must be defined in the %s constructor.',
- get_called_class()
+ static::class
));
}
if (!isset($data['loader'])) {
throw new Exception(sprintf(
'CollectionLoader must be defined in the %s constructor.',
- get_called_class()
+ static::class
));
}
if (!isset($data['cms/config'])) {
@@ -73,9 +73,8 @@ public function __construct(array $data)
* Set an object model factory.
*
* @param FactoryInterface $factory The model factory, to create objects.
- * @return self
*/
- protected function setModelFactory(FactoryInterface $factory)
+ protected function setModelFactory(FactoryInterface $factory): static
{
$this->modelFactory = $factory;
@@ -90,9 +89,9 @@ protected function setModelFactory(FactoryInterface $factory)
*/
public function modelFactory()
{
- if (!isset($this->modelFactory)) {
+ if ($this->modelFactory === null) {
throw new RuntimeException(
- sprintf('Model Factory is not defined for "%s"', get_class($this))
+ sprintf('Model Factory is not defined for "%s"', static::class)
);
}
@@ -103,9 +102,8 @@ public function modelFactory()
* Set a model collection loader.
*
* @param CollectionLoader $loader The collection loader.
- * @return self
*/
- protected function setCollectionLoader(CollectionLoader $loader)
+ protected function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
@@ -120,9 +118,9 @@ protected function setCollectionLoader(CollectionLoader $loader)
*/
public function collectionLoader()
{
- if (!isset($this->collectionLoader)) {
+ if ($this->collectionLoader === null) {
throw new RuntimeException(
- sprintf('Collection Loader is not defined for "%s"', get_class($this))
+ sprintf('Collection Loader is not defined for "%s"', static::class)
);
}
@@ -131,9 +129,8 @@ public function collectionLoader()
/**
* @param mixed $adminConfig The admin configuration.
- * @return self
*/
- public function setAdminConfig($adminConfig)
+ public function setAdminConfig($adminConfig): static
{
$this->adminConfig = $adminConfig;
diff --git a/packages/cms/src/Charcoal/Cms/Service/Manager/EventManager.php b/packages/cms/src/Charcoal/Cms/Service/Manager/EventManager.php
index c6442b579..12365277a 100644
--- a/packages/cms/src/Charcoal/Cms/Service/Manager/EventManager.php
+++ b/packages/cms/src/Charcoal/Cms/Service/Manager/EventManager.php
@@ -28,13 +28,13 @@ class EventManager extends AbstractManager
private $currentEvent;
/** @var integer $currentPage The current Page. */
- private $currentPage;
+ private int|float|null $currentPage = null;
/** @var integer $numPerPage Events by page. */
private $numPerPage = 0;
/** @var integer $numPage How many pages. */
- private $numPage;
+ private float|int|null $numPage = null;
/** @var boolean $entryCycle Does the pager can cycle indefinitely. */
private $entryCycle = false;
@@ -55,13 +55,13 @@ class EventManager extends AbstractManager
private $all = [];
/** @var EventInterface[] $entries The event collection. */
- private $entries = [];
+ private array $entries = [];
/** @var EventInterface[] $archive The archive events collection. */
- private $archive = [];
+ private array $archive = [];
/** @var EventInterface $entry An event. */
- private $entry;
+ private ?array $entry = null;
/** @var object $objType The event object model. */
private $objType;
@@ -76,19 +76,19 @@ class EventManager extends AbstractManager
private $loader;
/** @var array $mapEvents The events mapped per [year][month][date]. */
- private $mapEvents = [];
+ private array $mapEvents = [];
/** @var datetime $date Datetime filter */
- private $date;
+ private ?\DateTime $date = null;
/** @var mixed $year Year filter. */
- private $year;
+ private int|float|string|bool|null $year = null;
/** @var mixed $month Month filter. */
- private $month;
+ private int|float|string|bool|null $month = null;
/** @var mixed $day Day filter. */
- private $day;
+ private int|float|string|bool|null $day = null;
/**
* EventManager constructor.
@@ -149,7 +149,7 @@ public function entries()
}
// Get event from specific date.
- if ($date) {
+ if ($date instanceof \DateTime) {
$loader = $this->loader()->all();
$proto = $this->loader()->proto();
$table = $proto->source()->table();
@@ -161,9 +161,7 @@ public function entries()
AND
active = 1' . $extraSql;
- $collection = $loader->loadFromQuery($q);
-
- return $collection;
+ return $loader->loadFromQuery($q);
}
// YEAR only filter.
@@ -179,9 +177,7 @@ public function entries()
AND
active = 1' . $extraSql;
- $collection = $loader->loadFromQuery($q);
-
- return $collection;
+ return $loader->loadFromQuery($q);
}
// Year AND month filter.
@@ -200,15 +196,11 @@ public function entries()
AND
active = 1' . $extraSql;
- $collection = $loader->loadFromQuery($q);
-
- return $collection;
+ return $loader->loadFromQuery($q);
}
- if (isset($this->entries[$cat])) {
- if (isset($this->entries[$cat][$page])) {
- return $this->entries[$cat][$page];
- }
+ if (isset($this->entries[$cat]) && isset($this->entries[$cat][$page])) {
+ return $this->entries[$cat][$page];
}
if ($this->category()) {
@@ -264,7 +256,7 @@ public function all()
/**
* @return CategoryInterface[]|Collection The category collection.
*/
- public function loadCategoryItems()
+ public function loadCategoryItems(): \ArrayAccess|array
{
/** @var Model $model */
$model = $this->modelFactory();
@@ -306,7 +298,7 @@ public function featList(array $options = [])
throw new Exception(sprintf(
'The featured news ident "%s" doesn\'t exist the class "%s"',
$ident,
- get_class($config)
+ $config::class
));
}
$ids = $config->{$ident}();
@@ -315,32 +307,30 @@ public function featList(array $options = [])
return null;
}
- $ids = explode(',', $ids);
+ $ids = explode(',', (string)$ids);
$loader->addFilter('id', $ids, [ 'operator' => 'in' ])
->addOrder('id', 'values', [ 'values' => $ids ]);
- if (count($options) > 0) {
- foreach ($options as $key => $option) {
- switch ($key) {
- case 'filters':
- $filters = $option;
- foreach ($filters as $f) {
- $filter[] = $f['property'] ?: '';
- $filter[] = $f['value'] ?: '';
- $filter[] = $f['options'] ?: '';
- $filter = join(',', $filter);
-
- $loader->addFilter($filter);
- }
- break;
- case 'page':
- $loader->setPage($option);
- break;
- case 'numPerPage':
- $loader->setNumPerPage($option);
- break;
- }
+ foreach ($options as $key => $option) {
+ switch ($key) {
+ case 'filters':
+ $filters = $option;
+ foreach ($filters as $f) {
+ $filter[] = $f['property'] ?: '';
+ $filter[] = $f['value'] ?: '';
+ $filter[] = $f['options'] ?: '';
+ $filter = implode(',', $filter);
+
+ $loader->addFilter($filter);
+ }
+ break;
+ case 'page':
+ $loader->setPage($option);
+ break;
+ case 'numPerPage':
+ $loader->setNumPerPage($option);
+ break;
}
}
@@ -356,10 +346,8 @@ public function archive()
{
$page = $this->page();
$cat = $this->category();
- if (isset($this->archive[$cat])) {
- if (isset($this->archive[$cat][$page])) {
- return $this->archive[$cat][$page];
- }
+ if (isset($this->archive[$cat]) && isset($this->archive[$cat][$page])) {
+ return $this->archive[$cat][$page];
}
$loader = $this->loader()->archive();
@@ -420,7 +408,7 @@ public function next()
/**
* @return float|integer The current event index page ident.
*/
- public function currentPage()
+ public function currentPage(): float|int
{
if ($this->currentPage) {
return $this->currentPage;
@@ -459,11 +447,7 @@ public function getEventsByDate($date)
$month = $date->format('m');
$day = $date->format('d');
- if (isset($map[$year][$month][$day])) {
- return $map[$year][$month][$day];
- }
-
- return [];
+ return ($map[$year][$month][$day] ?? []);
}
/**
@@ -498,38 +482,29 @@ public function entryCycle()
* Amount of event (total)
* @return integer How many event?
*/
- public function numEvent()
+ public function numEvent(): bool
{
- return !!(count($this->entries()));
+ return (bool)count($this->entries());
}
/**
* The total amount of pages.
* @return float
*/
- public function numPages()
+ public function numPages(): float|int
{
- if ($this->numPage) {
- $this->numPage;
- };
-
$entries = $this->entries();
$count = count($entries);
- if ($this->numPerPage()) {
- $this->numPage = ceil($count / $this->numPerPage());
- } else {
- $this->numPage = 1;
- }
+ $this->numPage = $this->numPerPage() ? ceil($count / $this->numPerPage()) : 1;
return $this->numPage;
}
/**
* Is there a pager.
- * @return boolean
*/
- public function hasPager()
+ public function hasPager(): bool
{
return ($this->numPages() > 1);
}
@@ -578,7 +553,7 @@ public function loader()
* Datetime object OR null.
* @return mixed Datetime or null.
*/
- public function date()
+ public function date(): ?\DateTime
{
return $this->date;
}
@@ -587,7 +562,7 @@ public function date()
* Full year
* @return integer Full year.
*/
- public function year()
+ public function year(): int|float|string|bool|null
{
return $this->year;
}
@@ -596,7 +571,7 @@ public function year()
* Month
* @return mixed month.
*/
- public function month()
+ public function month(): int|float|string|bool|null
{
return $this->month;
}
@@ -605,16 +580,15 @@ public function month()
* Day
* @return mixed day.
*/
- public function day()
+ public function day(): int|float|string|bool|null
{
return $this->day;
}
/**
* @param mixed $currentEvent The current event context.
- * @return self
*/
- public function setCurrentEvent($currentEvent)
+ public function setCurrentEvent($currentEvent): static
{
$this->currentEvent = $currentEvent;
@@ -623,9 +597,8 @@ public function setCurrentEvent($currentEvent)
/**
* @param integer $numPerPage The number of event per page.
- * @return self
*/
- public function setNumPerPage($numPerPage)
+ public function setNumPerPage($numPerPage): static
{
$this->numPerPage = $numPerPage;
@@ -634,9 +607,8 @@ public function setNumPerPage($numPerPage)
/**
* @param boolean $entryCycle Next and Prev cycles indefinitely.
- * @return self
*/
- public function setEntryCycle($entryCycle)
+ public function setEntryCycle($entryCycle): static
{
$this->entryCycle = $entryCycle;
@@ -645,9 +617,8 @@ public function setEntryCycle($entryCycle)
/**
* @param integer $page The page number to load.
- * @return self
*/
- public function setPage($page)
+ public function setPage($page): static
{
$this->page = $page;
@@ -656,9 +627,8 @@ public function setPage($page)
/**
* @param integer $category The current entry category.
- * @return self
*/
- public function setCategory($category)
+ public function setCategory($category): static
{
$this->category = $category;
@@ -667,9 +637,8 @@ public function setCategory($category)
/**
* @param mixed $objType The object type.
- * @return self
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
@@ -678,9 +647,8 @@ public function setObjType($objType)
/**
* @param mixed $featIdent The featured list ident.
- * @return self
*/
- public function setFeatIdent($featIdent)
+ public function setFeatIdent($featIdent): static
{
$this->featIdent = $featIdent;
@@ -689,9 +657,8 @@ public function setFeatIdent($featIdent)
/**
* @param EventLoader|null $loader The event loader provider.
- * @return self
*/
- public function setLoader($loader)
+ public function setLoader($loader): static
{
$this->loader = $loader;
@@ -701,9 +668,8 @@ public function setLoader($loader)
/**
* Set date filter.
* @param DateTime $date Date filter.
- * @return self
*/
- public function setDate(DateTime $date)
+ public function setDate(DateTime $date): static
{
$this->date = $date;
@@ -716,7 +682,7 @@ public function setDate(DateTime $date)
* @throws Exception If argument is not scalar.
* @return EventManager
*/
- public function setYear($year)
+ public function setYear($year): int|float|string|bool
{
if (!is_scalar($year)) {
throw new Exception('Year must be a string or an integer in EventManager setYear method.');
@@ -730,9 +696,8 @@ public function setYear($year)
* Month.
* @param mixed $month Specific month.
* @throws Exception If argument is not scalar.
- * @return EventManager
*/
- public function setMonth($month)
+ public function setMonth($month): static
{
if (!is_scalar($month)) {
throw new Exception('Month must be a string or an integer in EventManager setMonth method.');
@@ -746,9 +711,8 @@ public function setMonth($month)
* Day.
* @param mixed $day Specific day.
* @throws Exception If argument is not scalar.
- * @return EventManager
*/
- public function setDay($day)
+ public function setDay($day): static
{
if (!is_scalar($day)) {
throw new Exception('Day must be a string or an integer in EventManager setDay method.');
@@ -762,7 +726,7 @@ public function setDay($day)
* Set the Prev and Next event
* @return $this
*/
- public function setPrevNext()
+ public function setPrevNext(): static
{
if ($this->prevEvent && $this->nextEvent) {
return $this;
@@ -815,7 +779,7 @@ public function setPrevNext()
* Mapping between events and dates
* @return array The array containing events stored as [$year][$month][$day][event]
*/
- public function mapEvents()
+ public function mapEvents(): array
{
if ($this->mapEvents) {
return $this->mapEvents;
diff --git a/packages/cms/src/Charcoal/Cms/Service/Manager/NewsManager.php b/packages/cms/src/Charcoal/Cms/Service/Manager/NewsManager.php
index 09c86071d..91bc358f3 100644
--- a/packages/cms/src/Charcoal/Cms/Service/Manager/NewsManager.php
+++ b/packages/cms/src/Charcoal/Cms/Service/Manager/NewsManager.php
@@ -109,10 +109,8 @@ public function entries()
{
$page = $this->page();
$cat = $this->category();
- if (isset($this->entries[$cat])) {
- if (isset($this->entries[$cat][$page])) {
- return $this->entries[$cat][$page];
- }
+ if (isset($this->entries[$cat]) && isset($this->entries[$cat][$page])) {
+ return $this->entries[$cat][$page];
}
$loader = $this->entriesLoader();
@@ -136,7 +134,7 @@ public function entriesLoader()
if ($this->numPerPage()) {
$loader->setPage($this->page());
- $numPerPage = !!($this->page()) ? $this->numPerPage() : 0;
+ $numPerPage = $this->page() ? $this->numPerPage() : 0;
$loader->setNumPerPage($numPerPage);
}
@@ -179,7 +177,7 @@ public function all()
/**
* @return CategoryInterface[]|Collection The category collection.
*/
- public function loadCategoryItems()
+ public function loadCategoryItems(): \ArrayAccess|array
{
$proto = $this->modelFactory()->create($this->categoryItemType());
$loader = $this->collectionLoader()->setModel($proto);
@@ -223,7 +221,7 @@ public function featList(array $options = [])
throw new Exception(sprintf(
'The featured news ident "%s" doesn\'t exist the class "%s"',
$ident,
- get_class($config)
+ $config::class
));
}
$ids = $config->{$ident}();
@@ -232,32 +230,30 @@ public function featList(array $options = [])
return null;
}
- $ids = explode(',', $ids);
+ $ids = explode(',', (string)$ids);
$loader->addFilter('id', $ids, [ 'operator' => 'in' ])
->addOrder('id', 'values', [ 'values' => $ids ]);
- if (count($options) > 0) {
- foreach ($options as $key => $option) {
- switch ($key) {
- case 'filters':
- $filters = $option;
- foreach ($filters as $f) {
- $filter[] = $f['property'] ?: '';
- $filter[] = $f['value'] ?: '';
- $filter[] = $f['options'] ?: '';
- $filter = join(',', $filter);
-
- $loader->addFilter($filter);
- }
- break;
- case 'page':
- $loader->setPage($option);
- break;
- case 'numPerPage':
- $loader->setNumPerPage($option);
- break;
- }
+ foreach ($options as $key => $option) {
+ switch ($key) {
+ case 'filters':
+ $filters = $option;
+ foreach ($filters as $f) {
+ $filter[] = $f['property'] ?: '';
+ $filter[] = $f['value'] ?: '';
+ $filter[] = $f['options'] ?: '';
+ $filter = implode(',', $filter);
+
+ $loader->addFilter($filter);
+ }
+ break;
+ case 'page':
+ $loader->setPage($option);
+ break;
+ case 'numPerPage':
+ $loader->setNumPerPage($option);
+ break;
}
}
@@ -273,10 +269,8 @@ public function archive()
{
$page = $this->page();
$cat = $this->category();
- if (isset($this->archive[$cat])) {
- if (isset($this->archive[$cat][$page])) {
- return $this->archive[$cat][$page];
- }
+ if (isset($this->archive[$cat]) && isset($this->archive[$cat][$page])) {
+ return $this->archive[$cat][$page];
}
$loader = $this->loader()->archive();
@@ -394,25 +388,23 @@ public function entryCycle()
* Amount of news (total)
* @return integer How many news?
*/
- public function numNews()
+ public function numNews(): bool
{
- return !!(count($this->entries()));
+ return (bool)count($this->entries());
}
/**
* The total amount of pages.
- * @return float
*/
- public function numPages()
+ public function numPages(): float
{
return ceil($this->entriesLoader()->loadCount() / $this->numPerPage());
}
/**
* Is there a pager.
- * @return boolean
*/
- public function hasPager()
+ public function hasPager(): bool
{
return ($this->numPages() > 1);
}
@@ -461,7 +453,7 @@ public function loader()
* @param mixed $currentNews The current news context.
* @return self .
*/
- public function setCurrentNews($currentNews)
+ public function setCurrentNews($currentNews): static
{
$this->currentNews = $currentNews;
@@ -470,9 +462,8 @@ public function setCurrentNews($currentNews)
/**
* @param integer $numPerPage The number of news per page.
- * @return self
*/
- public function setNumPerPage($numPerPage)
+ public function setNumPerPage($numPerPage): static
{
$this->numPerPage = $numPerPage;
@@ -481,9 +472,8 @@ public function setNumPerPage($numPerPage)
/**
* @param boolean $entryCycle Next and Prev cycles indefinitely.
- * @return self
*/
- public function setEntryCycle($entryCycle)
+ public function setEntryCycle($entryCycle): static
{
$this->entryCycle = $entryCycle;
@@ -492,9 +482,8 @@ public function setEntryCycle($entryCycle)
/**
* @param integer $page The page number to load.
- * @return self
*/
- public function setPage($page)
+ public function setPage($page): static
{
$this->page = $page;
@@ -503,9 +492,8 @@ public function setPage($page)
/**
* @param integer $category The current news category.
- * @return self
*/
- public function setCategory($category)
+ public function setCategory($category): static
{
$this->category = $category;
@@ -514,9 +502,8 @@ public function setCategory($category)
/**
* @param mixed $objType The object type.
- * @return self
*/
- public function setObjType($objType)
+ public function setObjType($objType): static
{
$this->objType = $objType;
@@ -525,9 +512,8 @@ public function setObjType($objType)
/**
* @param mixed $featIdent The featured list ident.
- * @return self
*/
- public function setFeatIdent($featIdent)
+ public function setFeatIdent($featIdent): static
{
$this->featIdent = $featIdent;
@@ -536,9 +522,8 @@ public function setFeatIdent($featIdent)
/**
* @param NewsLoader $loader The news loader provider.
- * @return self
*/
- public function setLoader(NewsLoader $loader)
+ public function setLoader(NewsLoader $loader): static
{
$this->loader = $loader;
@@ -549,7 +534,7 @@ public function setLoader(NewsLoader $loader)
* Set the Prev and Next news
* @return $this
*/
- public function setPrevNext()
+ public function setPrevNext(): static
{
if ($this->nextNews && $this->prevNews) {
return $this;
diff --git a/packages/cms/src/Charcoal/Cms/ServiceProvider/CmsServiceProvider.php b/packages/cms/src/Charcoal/Cms/ServiceProvider/CmsServiceProvider.php
index d5dd3ef4d..e9633ecec 100644
--- a/packages/cms/src/Charcoal/Cms/ServiceProvider/CmsServiceProvider.php
+++ b/packages/cms/src/Charcoal/Cms/ServiceProvider/CmsServiceProvider.php
@@ -36,9 +36,8 @@ class CmsServiceProvider implements ServiceProviderInterface
* It should not get services.
*
* @param \Pimple\Container $container Pimple DI Container.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
$this->registerConfig($container);
$this->reggisterDateHelper($container);
@@ -49,15 +48,14 @@ public function register(Container $container)
/**
* @param Container $container Pimple DI Container.
- * @return void
*/
- private function registerConfig(Container $container)
+ private function registerConfig(Container $container): void
{
/**
* @param Container $container Pimple DI Container.
* @return CmsConfig Website configurations (from cms.json).
*/
- $container['cms/config'] = function (Container $container) {
+ $container['cms/config'] = function (Container $container): \Charcoal\Cms\Config\CmsConfig {
$appConfig = $container['config'];
$cms = $appConfig->get('cms');
@@ -73,7 +71,7 @@ private function registerConfig(Container $container)
$model = $container['model/factory']->create($configType);
$model->load($configId);
- if (!!$model->id()) {
+ if ((bool)$model->id()) {
$cmsConfig->addModel($model);
}
}
@@ -84,21 +82,18 @@ private function registerConfig(Container $container)
/**
* @param Container $container Pimple DI Container.
- * @return void
*/
- private function reggisterDateHelper(Container $container)
+ private function reggisterDateHelper(Container $container): void
{
/**
* @param Container $container Pimple DI Container.
* @return DateHelper
*/
- $container['cms/date/helper'] = function (Container $container) {
- return new DateHelper([
- 'date_formats' => $container['cms/config']->get('date_formats'),
- 'time_formats' => $container['cms/config']->get('time_formats'),
- 'translator' => $container['translator']
- ]);
- };
+ $container['cms/date/helper'] = (fn(Container $container): \Charcoal\Cms\Support\Helpers\DateHelper => new DateHelper([
+ 'date_formats' => $container['cms/config']->get('date_formats'),
+ 'time_formats' => $container['cms/config']->get('time_formats'),
+ 'translator' => $container['translator']
+ ]));
/**
* @param Container $container Pimple DI Container.
@@ -117,29 +112,26 @@ private function reggisterDateHelper(Container $container)
/**
* @param Container $container Pimple DI Container.
- * @return void
*/
- private function registerSectionServices(Container $container)
+ private function registerSectionServices(Container $container): void
{
/**
* @param Container $container Pimple DI Container.
* @return Factory
*/
- $container['cms/section/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => SectionInterface::class,
- 'arguments' => $container['model/factory']->arguments(),
- 'resolver_options' => [
- 'suffix' => 'Section'
- ]
- ]);
- };
+ $container['cms/section/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => SectionInterface::class,
+ 'arguments' => $container['model/factory']->arguments(),
+ 'resolver_options' => [
+ 'suffix' => 'Section'
+ ]
+ ]));
/**
* @param Container $container Pimple DI Container.
* @return SectionLoader
*/
- $container['cms/section/loader'] = function (Container $container) {
+ $container['cms/section/loader'] = function (Container $container): \Charcoal\Cms\Service\Loader\SectionLoader {
$sectionLoader = new SectionLoader([
'loader' => $container['model/collection/loader'],
'factory' => $container['model/factory'],
@@ -160,15 +152,14 @@ private function registerSectionServices(Container $container)
/**
* @param Container $container Pimple DI Container.
- * @return void
*/
- private function registerNewsServices(Container $container)
+ private function registerNewsServices(Container $container): void
{
/**
* @param Container $container Pimple DI Container.
* @return NewsLoader
*/
- $container['cms/news/loader'] = function (Container $container) {
+ $container['cms/news/loader'] = function (Container $container): \Charcoal\Cms\Service\Loader\NewsLoader {
$newsLoader = new NewsLoader([
'loader' => $container['model/collection/loader'],
'factory' => $container['model/factory'],
@@ -189,32 +180,26 @@ private function registerNewsServices(Container $container)
* @param Container $container
* @return NewsManager
*/
- $container['cms/news/manager'] = function (Container $container) {
-
- $newsManager = new NewsManager([
- 'loader' => $container['model/collection/loader'],
- 'factory' => $container['model/factory'],
- 'news/loader' => $container['cms/news/loader'],
- 'cache' => $container['cache'],
- 'cms/config' => $container['cms/config'],
- 'translator' => $container['translator']
- ]);
-
- return $newsManager;
- };
+ $container['cms/news/manager'] = (fn(Container $container): \Charcoal\Cms\Service\Manager\NewsManager => new NewsManager([
+ 'loader' => $container['model/collection/loader'],
+ 'factory' => $container['model/factory'],
+ 'news/loader' => $container['cms/news/loader'],
+ 'cache' => $container['cache'],
+ 'cms/config' => $container['cms/config'],
+ 'translator' => $container['translator']
+ ]));
}
/**
* @param Container $container Pimple DI Container.
- * @return void
*/
- private function registerEventServices(Container $container)
+ private function registerEventServices(Container $container): void
{
/**
* @param Container $container Pimple DI Container.
* @return EventLoader
*/
- $container['cms/event/loader'] = function (Container $container) {
+ $container['cms/event/loader'] = function (Container $container): \Charcoal\Cms\Service\Loader\EventLoader {
$eventLoader = new EventLoader([
'loader' => $container['model/collection/loader'],
'factory' => $container['model/factory'],
@@ -238,18 +223,13 @@ private function registerEventServices(Container $container)
* @param Container $container
* @return EventManager
*/
- $container['cms/event/manager'] = function (Container $container) {
-
- $eventManager = new EventManager([
- 'loader' => $container['model/collection/loader'],
- 'factory' => $container['model/factory'],
- 'event/loader' => $container['cms/event/loader'],
- 'cache' => $container['cache'],
- 'cms/config' => $container['cms/config'],
- 'translator' => $container['translator']
- ]);
-
- return $eventManager;
- };
+ $container['cms/event/manager'] = (fn(Container $container): \Charcoal\Cms\Service\Manager\EventManager => new EventManager([
+ 'loader' => $container['model/collection/loader'],
+ 'factory' => $container['model/factory'],
+ 'event/loader' => $container['cms/event/loader'],
+ 'cache' => $container['cache'],
+ 'cms/config' => $container['cms/config'],
+ 'translator' => $container['translator']
+ ]));
}
}
diff --git a/packages/cms/src/Charcoal/Cms/Support/ContextualTemplateTrait.php b/packages/cms/src/Charcoal/Cms/Support/ContextualTemplateTrait.php
index 02e23d9b3..413bce5d9 100644
--- a/packages/cms/src/Charcoal/Cms/Support/ContextualTemplateTrait.php
+++ b/packages/cms/src/Charcoal/Cms/Support/ContextualTemplateTrait.php
@@ -138,7 +138,7 @@ protected function createGenericContext()
$base = $uri->getBasePath();
$path = $uri->getPath();
- $path = $base . '/' . ltrim($path, '/');
+ $path = $base . '/' . ltrim((string)$path, '/');
$endpoint[$lang] = $path;
}
@@ -181,7 +181,7 @@ public function setRouteGroup($path)
$group = $this->translator()->translation($path);
foreach ($this->translator()->availableLocales() as $lang) {
- $group[$lang] = trim($group[$lang], '/');
+ $group[$lang] = trim((string)$group[$lang], '/');
}
$this->routeGroup = $group;
@@ -200,7 +200,7 @@ public function setRouteEndpoint($path)
$endpoint = $this->translator()->translation($path);
foreach ($this->translator()->availableLocales() as $lang) {
- $endpoint[$lang] = trim($endpoint[$lang], '/');
+ $endpoint[$lang] = trim((string)$endpoint[$lang], '/');
}
$this->routeEndpoint = $endpoint;
diff --git a/packages/cms/src/Charcoal/Cms/Support/DocumentTrait.php b/packages/cms/src/Charcoal/Cms/Support/DocumentTrait.php
index 0779daec5..56556f458 100644
--- a/packages/cms/src/Charcoal/Cms/Support/DocumentTrait.php
+++ b/packages/cms/src/Charcoal/Cms/Support/DocumentTrait.php
@@ -14,7 +14,7 @@ trait DocumentTrait
*
* @return string[]
*/
- protected function documentTitleParts()
+ protected function documentTitleParts(): array
{
return [
'title' => $this->title(),
@@ -24,23 +24,19 @@ protected function documentTitleParts()
/**
* Retrieve the document title separator.
- *
- * @return string
*/
- protected function documentTitleSeparator()
+ protected function documentTitleSeparator(): string
{
return '—';
}
/**
* Parse the document title separator.
- *
- * @return string
*/
- protected function parseDocumentTitleSeparator()
+ protected function parseDocumentTitleSeparator(): string
{
$delim = trim($this->documentTitleSeparator());
- if (empty($delim)) {
+ if ($delim === '' || $delim === '0') {
return '';
}
@@ -53,13 +49,12 @@ protected function parseDocumentTitleSeparator()
* @param array $parts The document title parts.
* @return string The concatenated title.
*/
- protected function parseDocumentTitle(array $parts)
+ protected function parseDocumentTitle(array $parts): string
{
$parts = $this->parseDocumentTitleParts($parts);
$delim = $this->parseDocumentTitleSeparator();
- $title = implode($delim, $parts);
- return $title;
+ return implode($delim, $parts);
}
/**
@@ -73,7 +68,7 @@ protected function parseDocumentTitle(array $parts)
* @param array $parts The document title parts.
* @return array The parsed and filtered segments.
*/
- protected function parseDocumentTitleParts(array $parts)
+ protected function parseDocumentTitleParts(array $parts): array
{
$segments = [];
foreach ($parts as $key => $value) {
diff --git a/packages/cms/src/Charcoal/Cms/Support/Helpers/DateHelper.php b/packages/cms/src/Charcoal/Cms/Support/Helpers/DateHelper.php
index 35a0f6877..48ed9ae82 100644
--- a/packages/cms/src/Charcoal/Cms/Support/Helpers/DateHelper.php
+++ b/packages/cms/src/Charcoal/Cms/Support/Helpers/DateHelper.php
@@ -4,6 +4,7 @@
use DateTime;
use Exception;
+use IntlDateFormatter;
// From 'charcoal-translator'
use Charcoal\Translator\TranslatorAwareTrait;
@@ -44,6 +45,11 @@ class DateHelper
*/
protected $timeFormat;
+ /**
+ * @var string $locale The current locale for date formatting
+ */
+ protected $locale;
+
/**
* DateHelper constructor.
* @param array $data DateHelper data.
@@ -64,6 +70,7 @@ public function __construct(array $data)
$this->setTranslator($data['translator']);
$this->dateFormats = $data['date_formats'];
$this->timeFormats = $data['time_formats'];
+ $this->locale = $this->translator()->getLocale();
}
/**
@@ -72,21 +79,20 @@ public function __construct(array $data)
* DateTimeInterface
* string.
* @param string $format The format to use.
- * @return string
*/
- public function formatDate($date, $format = 'default')
+ public function formatDate($date, $format = 'default'): string
{
$this->dateFormat = $format;
if (is_array($date)) {
$this->from = $this->parseAsDate($date[0]);
- $this->to = !!($date[1]) ? $this->parseAsDate($date[1]) : null;
+ $this->to = $date[1] ? $this->parseAsDate($date[1]) : null;
} else {
$this->from = $this->parseAsDate($date);
$this->to = null;
}
- return (string)$this->formatDateFromCase($this->getDateCase());
+ return $this->formatDateFromCase($this->getDateCase());
}
/**
@@ -95,9 +101,8 @@ public function formatDate($date, $format = 'default')
* DateTimeInterface
* string.
* @param string $format The format to use.
- * @return string
*/
- public function formatTime($date, $format = 'default')
+ public function formatTime($date, $format = 'default'): string
{
$this->timeFormat = $format;
@@ -116,7 +121,7 @@ public function formatTime($date, $format = 'default')
* Get the usage case by comparing two dates.
* @return string
*/
- private function getDateCase()
+ private function getDateCase(): ?string
{
$from = $this->from;
$to = $this->to;
@@ -141,16 +146,15 @@ private function getDateCase()
$case = null;
$case = $fromDate['day'] !== $toDate['day'] ? 'different_day' : $case;
$case = $fromDate['month'] !== $toDate['month'] ? 'different_month' : $case;
- $case = $fromDate['year'] !== $toDate['year'] ? 'different_year' : $case;
- return $case;
+ return $fromDate['year'] !== $toDate['year'] ? 'different_year' : $case;
}
/**
* Get the usage case by comparing two hours.
* @return string
*/
- private function getTimeCase()
+ private function getTimeCase(): ?string
{
$from = $this->from;
$to = $this->to;
@@ -177,16 +181,14 @@ private function getTimeCase()
$case = null;
$case = $fromTime['hour'] !== $toTime['hour'] ? 'different_time' : $case;
$case = $fromTime['minute'] == 0 ? 'different_time_round' : $case;
- $case = $fromTime['minute'] != $toTime['minute'] ? 'different_time' : $case;
- return $case;
+ return $fromTime['minute'] != $toTime['minute'] ? 'different_time' : $case;
}
/**
* @param string $case The use case.
- * @return string
*/
- private function formatDateFromCase($case)
+ private function formatDateFromCase(array $case): string
{
$dateFormats = $this->dateFormats;
$case = $dateFormats[$this->dateFormat][$case];
@@ -202,24 +204,47 @@ private function formatDateFromCase($case)
$formats['to'] = $this->crossPlatformFormat((string)$formats['to']);
if (!$this->to || !$formats['to']) {
+ $formatter = new IntlDateFormatter(
+ $this->locale,
+ IntlDateFormatter::FULL,
+ IntlDateFormatter::FULL,
+ null,
+ null,
+ $formats['from']
+ );
return sprintf(
(string)$content,
- strftime($formats['from'], $this->from->getTimestamp())
+ $formatter->format($this->from)
);
}
+ $formatterFrom = new IntlDateFormatter(
+ $this->locale,
+ IntlDateFormatter::FULL,
+ IntlDateFormatter::FULL,
+ null,
+ null,
+ $formats['from']
+ );
+ $formatterTo = new IntlDateFormatter(
+ $this->locale,
+ IntlDateFormatter::FULL,
+ IntlDateFormatter::FULL,
+ null,
+ null,
+ $formats['to']
+ );
return sprintf(
(string)$content,
- strftime($formats['from'], $this->from->getTimestamp()),
- strftime($formats['to'], $this->to->getTimestamp())
+ $formatterFrom->format($this->from),
+ $formatterTo->format($this->to)
);
}
/**
* @param string $case The use case.
- * @return string
*/
- private function formatTimeFromCase($case)
+ private function formatTimeFromCase(array $case): string
{
$timeFormats = $this->timeFormats;
$case = $timeFormats[$this->timeFormat][$case];
@@ -227,22 +252,46 @@ private function formatTimeFromCase($case)
$content = $this->translator()->translation($case['content']);
$formats['from'] = $case['formats']['from'];
- $formats['to'] = isset($case['formats']['to']) ? $case['formats']['to'] : null;
+ $formats['to'] = ($case['formats']['to'] ?? null);
$formats['from'] = $this->translator()->translation($formats['from']);
$formats['to'] = $this->translator()->translation($formats['to']);
if (!$this->to || !$formats['to']) {
+ $formatter = new IntlDateFormatter(
+ $this->locale,
+ IntlDateFormatter::FULL,
+ IntlDateFormatter::FULL,
+ null,
+ null,
+ $formats['from']
+ );
return sprintf(
(string)$content,
- strftime($formats['from'], $this->from->getTimestamp())
+ $formatter->format($this->from)
);
}
+ $formatterFrom = new IntlDateFormatter(
+ $this->locale,
+ IntlDateFormatter::FULL,
+ IntlDateFormatter::FULL,
+ null,
+ null,
+ $formats['from']
+ );
+ $formatterTo = new IntlDateFormatter(
+ $this->locale,
+ IntlDateFormatter::FULL,
+ IntlDateFormatter::FULL,
+ null,
+ null,
+ $formats['to']
+ );
return sprintf(
(string)$content,
- strftime($formats['from'], $this->from->getTimestamp()),
- strftime($formats['to'], $this->to->getTimestamp())
+ $formatterFrom->format($this->from),
+ $formatterTo->format($this->to)
);
}
@@ -250,7 +299,7 @@ private function formatTimeFromCase($case)
* @param mixed $date The date to convert.
* @return DateTime
*/
- private function parseAsDate($date)
+ private function parseAsDate($date): \DateTimeInterface|\DateTime
{
if ($date instanceof \DateTimeInterface) {
return $date;
@@ -258,17 +307,4 @@ private function parseAsDate($date)
return new DateTime($date);
}
-
- /**
- * @param mixed $format DateTime to be formatted.
- * @return mixed
- */
- private function crossPlatformFormat($format)
- {
- if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
- $format = preg_replace('#(?locales());
}
@@ -117,10 +114,8 @@ protected function availableLanguages()
* Build the alternate translations associated with the current route.
*
* This method _excludes_ the current route's canonical URI.
- *
- * @return array
*/
- protected function buildAlternateTranslations()
+ protected function buildAlternateTranslations(): array
{
$translations = [];
@@ -171,7 +166,7 @@ protected function getAlternateTranslations()
* @param array $localeStruct The currently iterated language.
* @return array Returns a link structure.
*/
- protected function formatAlternateTranslation($context, array $localeStruct)
+ protected function formatAlternateTranslation(\ArrayAccess|array $context, array $localeStruct): array
{
return [
'id' => ($context['id']) ? : $this->templateName(),
@@ -222,10 +217,8 @@ public function alternateTranslations()
/**
* Determine if there exists alternate translations associated with the current route.
- *
- * @return boolean
*/
- public function hasAlternateTranslations()
+ public function hasAlternateTranslations(): bool
{
return !empty($this->getAlternateTranslations());
}
diff --git a/packages/cms/src/Charcoal/Cms/Support/Traits/DateHelperAwareTrait.php b/packages/cms/src/Charcoal/Cms/Support/Traits/DateHelperAwareTrait.php
index f4a657ab4..0fe5cd202 100644
--- a/packages/cms/src/Charcoal/Cms/Support/Traits/DateHelperAwareTrait.php
+++ b/packages/cms/src/Charcoal/Cms/Support/Traits/DateHelperAwareTrait.php
@@ -26,7 +26,7 @@ protected function dateHelper()
if (!$this->dateHelper instanceof DateHelper) {
throw new ContainerException(sprintf(
'Missing dependency for %s: %s',
- get_called_class(),
+ static::class,
DateHelper::class
));
}
diff --git a/packages/cms/src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php b/packages/cms/src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php
index c29b95372..e53e3dde2 100644
--- a/packages/cms/src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php
+++ b/packages/cms/src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php
@@ -231,7 +231,7 @@ protected function getEventTimeFormat(EventInterface $event)
* @param EventInterface $event Charcoal\Cms\EventInterface.
* @return array The needed event properties.
*/
- protected function eventFormatShort(EventInterface $event)
+ protected function eventFormatShort(EventInterface $event): array
{
return [
'title' => (string)$event->title(),
@@ -251,7 +251,7 @@ protected function eventFormatShort(EventInterface $event)
* @param EventInterface $event Charcoal\Cms\EventInterface.
* @return array The needed event properties.
*/
- protected function eventFormatNav(EventInterface $event)
+ protected function eventFormatNav(EventInterface $event): array
{
return [
'startDate' => $this->getEventStartDateFormat($event),
@@ -269,7 +269,7 @@ protected function eventFormatNav(EventInterface $event)
* @param EventInterface $event The current event.
* @return array The needed properties.
*/
- protected function eventFormatFull(EventInterface $event)
+ protected function eventFormatFull(EventInterface $event): array
{
$contentBlocks = $event->getAttachments('content-blocks');
$gallery = $event->getAttachments('image-gallery');
@@ -288,11 +288,11 @@ protected function eventFormatFull(EventInterface $event)
'date' => $this->getEventDateFormat($event),
'time' => $this->getEventTimeFormat($event),
'contentBlocks' => $contentBlocks,
- 'hasContentBlocks' => !!(count($contentBlocks)),
+ 'hasContentBlocks' => (bool)count($contentBlocks),
'documents' => $documents,
- 'hasDocuments' => !!(count($documents)),
+ 'hasDocuments' => (bool)count($documents),
'gallery' => $gallery,
- 'hasGallery' => !!(count($gallery)),
+ 'hasGallery' => (bool)count($gallery),
'url' => $event->url(),
'metaTitle' => (string)$event->metaTitle(),
'locationName' => (string)$event->locationName(),
@@ -305,7 +305,7 @@ protected function eventFormatFull(EventInterface $event)
* @param CategoryInterface $category The category item.
* @return array The formatted category item.
*/
- protected function eventFormatCategory(CategoryInterface $category)
+ protected function eventFormatCategory(CategoryInterface $category): array
{
return [
'id' => $category->id(),
@@ -326,7 +326,7 @@ protected function eventManager()
if (!$this->eventManager instanceof EventManager) {
throw new ContainerException(sprintf(
'Missing dependency for %s: %s',
- get_called_class(),
+ static::class,
EventManager::class
));
}
diff --git a/packages/cms/src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php b/packages/cms/src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php
index 92cb9c80f..a9f02b93a 100644
--- a/packages/cms/src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php
+++ b/packages/cms/src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php
@@ -190,7 +190,7 @@ protected function getNewsDateFormat(NewsInterface $news)
* @param NewsInterface $news A single news.
* @return array The needed news properties.
*/
- protected function newsFormatShort(NewsInterface $news)
+ protected function newsFormatShort(NewsInterface $news): array
{
return [
'title' => (string)$news->title(),
@@ -208,7 +208,7 @@ protected function newsFormatShort(NewsInterface $news)
* @param NewsInterface $news A single news.
* @return array The needed news properties.
*/
- protected function newsFormatNav(NewsInterface $news)
+ protected function newsFormatNav(NewsInterface $news): array
{
return [
'date' => $this->getNewsDateFormat($news),
@@ -224,7 +224,7 @@ protected function newsFormatNav(NewsInterface $news)
* @param NewsInterface $news The current news.
* @return array The needed properties.
*/
- protected function newsFormatFull(NewsInterface $news)
+ protected function newsFormatFull(NewsInterface $news): array
{
$contentBlocks = $news->getAttachments('content-blocks');
$gallery = $news->getAttachments('image-gallery');
@@ -239,11 +239,11 @@ protected function newsFormatFull(NewsInterface $news)
'date' => $this->getNewsDateFormat($news),
'dateTime' => $news->newsDate()->format('Y-m-d h:i'),
'contentBlocks' => $contentBlocks,
- 'hasContentBlocks' => !!(count($contentBlocks)),
+ 'hasContentBlocks' => (bool)count($contentBlocks),
'documents' => $documents,
- 'hasDocuments' => !!(count($documents)),
+ 'hasDocuments' => (bool)count($documents),
'gallery' => $gallery,
- 'hasGallery' => !!(count($gallery)),
+ 'hasGallery' => (bool)count($gallery),
'url' => $news->url(),
'metaTitle' => (string)$news->metaTitle(),
'category' => $news->category(),
@@ -255,7 +255,7 @@ protected function newsFormatFull(NewsInterface $news)
* @param CategoryInterface $category The category item.
* @return array The formatted category item.
*/
- protected function newsFormatCategory(CategoryInterface $category)
+ protected function newsFormatCategory(CategoryInterface $category): array
{
return [
'id' => $category->id(),
@@ -276,7 +276,7 @@ protected function newsManager()
if (!$this->newsManager instanceof NewsManager) {
throw new ContainerException(sprintf(
'Missing dependency for %s: %s',
- get_called_class(),
+ static::class,
NewsManager::class
));
}
diff --git a/packages/cms/src/Charcoal/Cms/Support/Traits/SectionLoaderAwareTrait.php b/packages/cms/src/Charcoal/Cms/Support/Traits/SectionLoaderAwareTrait.php
index bf6aa89ae..3ed31cafd 100644
--- a/packages/cms/src/Charcoal/Cms/Support/Traits/SectionLoaderAwareTrait.php
+++ b/packages/cms/src/Charcoal/Cms/Support/Traits/SectionLoaderAwareTrait.php
@@ -81,9 +81,7 @@ public function childrenSections()
*/
public function routes()
{
- return function ($arg) {
- return $this->sectionLoader()->resolveRoute($arg);
- };
+ return fn($arg) => $this->sectionLoader()->resolveRoute($arg);
}
/**
@@ -149,7 +147,7 @@ protected function sectionLoader()
if (!$this->sectionLoader instanceof SectionLoader) {
throw new ContainerException(sprintf(
'Missing dependency for %s: %s',
- get_called_class(),
+ static::class,
SectionLoader::class
));
}
@@ -171,12 +169,10 @@ protected function setSectionLoader(SectionLoader $loader)
// ==========================================================================
// FORMATTER
// ==========================================================================
-
/**
* @param SectionInterface $section The section to format.
- * @return array
*/
- protected function formatSection(SectionInterface $section)
+ protected function formatSection(SectionInterface $section): array
{
$contentBlocks = $section->getAttachments('content-blocks');
$gallery = $section->getAttachments('image-gallery');
diff --git a/packages/cms/src/Charcoal/Cms/Support/Traits/SocialNetworksAwareTrait.php b/packages/cms/src/Charcoal/Cms/Support/Traits/SocialNetworksAwareTrait.php
index 4735e1257..e2e2724fa 100644
--- a/packages/cms/src/Charcoal/Cms/Support/Traits/SocialNetworksAwareTrait.php
+++ b/packages/cms/src/Charcoal/Cms/Support/Traits/SocialNetworksAwareTrait.php
@@ -21,10 +21,8 @@ trait SocialNetworksAwareTrait
/**
* Determine if the website has a social presence.
- *
- * @return integer|boolean
*/
- public function hasSocialNetworks()
+ public function hasSocialNetworks(): int
{
return count($this->socialNetworks());
}
@@ -41,7 +39,7 @@ public function socialNetworks()
return $this->socialNetworks;
}
- $socials = json_decode($this->cmsConfig()['social_medias'], true);
+ $socials = json_decode((string)$this->cmsConfig()['social_medias'], true);
$configMeta = $this->configModel()->p('social_medias')->structureMetadata();
foreach ($socials as $ident => $account) {
diff --git a/packages/cms/src/Charcoal/Cms/Tag.php b/packages/cms/src/Charcoal/Cms/Tag.php
index 670e0ea09..30e2ef6b1 100644
--- a/packages/cms/src/Charcoal/Cms/Tag.php
+++ b/packages/cms/src/Charcoal/Cms/Tag.php
@@ -1,5 +1,7 @@
property($key);
$val = $this->propertyValue($key);
- $obj = $prop->structureVal($val, $this->templateOptionsMetadata());
- return $obj;
+ return $prop->structureVal($val, $this->templateOptionsMetadata());
}
/**
@@ -238,7 +235,7 @@ final protected function assertValidTemplateStructureDependencies()
if (!$this instanceof TemplateableInterface) {
throw new RuntimeException(sprintf(
'Class [%s] must implement [%s]',
- get_class($this),
+ $this::class,
TemplateableInterface::class
));
}
@@ -260,7 +257,7 @@ final protected function assertValidTemplateStructureDependencies()
* @param boolean $recursive Whether we should traverse structure properties.
* @return ModelInterface The localized object.
*/
- protected function translateTemplateOptionsModel(ModelInterface $obj, $recursive = false)
+ protected function translateTemplateOptionsModel(ModelInterface $obj, $recursive = false): ModelInterface
{
unset($recursive);
foreach ($obj->properties() as $propertyIdent => $property) {
@@ -271,7 +268,7 @@ protected function translateTemplateOptionsModel(ModelInterface $obj, $recursive
$struct = $property->structureVal($obj[$propertyIdent]);
/** Provide support for dynamically wrapping translation sets. */
- if (in_array(get_class($struct), [ Model::class, StructureModel::class ])) {
+ if (in_array($struct::class, [ Model::class, StructureModel::class ])) {
$struct = $this->translateTemplateOptionsModel($struct);
}
@@ -287,7 +284,7 @@ protected function translateTemplateOptionsModel(ModelInterface $obj, $recursive
*
* @return string[]
*/
- protected function defaultTemplateProperties()
+ protected function defaultTemplateProperties(): array
{
return [
'template_ident'
@@ -303,7 +300,7 @@ protected function defaultTemplateProperties()
* @param PropertyInterface|string ...$properties The properties to lookup.
* @return string[]|null
*/
- protected function extractTemplateInterfacesFrom(...$properties)
+ protected function extractTemplateInterfacesFrom(...$properties): array
{
$interfaces = [];
foreach ($properties as $property) {
@@ -321,10 +318,8 @@ protected function extractTemplateInterfacesFrom(...$properties)
if (isset($choice[$key])) {
$interface = $choice[$key];
- if ($key === 'template' || $key === 'controller') {
- if (substr($interface, -9) !== '-template') {
- $interface .= '-template';
- }
+ if (($key === 'template' || $key === 'controller') && !str_ends_with((string)$interface, '-template')) {
+ $interface .= '-template';
}
$interfaces[] = $interface;
@@ -345,9 +340,8 @@ protected function extractTemplateInterfacesFrom(...$properties)
*
* @uses self::assertValidTemplateStructureDependencies() Validates that the model meets requirements.
* @param (PropertyInterface|string)[]|null $templateIdentProperties The template key properties to parse.
- * @return boolean
*/
- protected function prepareTemplateOptions(array $templateIdentProperties = null)
+ protected function prepareTemplateOptions(?array $templateIdentProperties = null): bool
{
$this->assertValidTemplateStructureDependencies();
@@ -384,7 +378,7 @@ protected function prepareTemplateOptions(array $templateIdentProperties = null)
* @param (PropertyInterface|string)[]|null $properties The template properties to parse.
* @return void
*/
- protected function saveTemplateOptions(array $properties = null)
+ protected function saveTemplateOptions(?array $properties = null)
{
if ($properties === null) {
$properties = $this->defaultTemplateProperties();
diff --git a/packages/cms/src/Charcoal/Property/TemplateOptionsProperty.php b/packages/cms/src/Charcoal/Property/TemplateOptionsProperty.php
index f9346e6df..7eef161ac 100644
--- a/packages/cms/src/Charcoal/Property/TemplateOptionsProperty.php
+++ b/packages/cms/src/Charcoal/Property/TemplateOptionsProperty.php
@@ -14,10 +14,9 @@ class TemplateOptionsProperty extends ModelStructureProperty
{
/**
* Retrieve the property's type identifier.
- *
- * @return string
*/
- public function type()
+ #[\Override]
+ public function type(): string
{
return 'template-options';
}
@@ -28,9 +27,9 @@ public function type()
* @see StructureProperty::addStructureInterface()
* @param string $interface A metadata interface to use.
* @throws InvalidArgumentException If the template property value is invalid.
- * @return TemplateOptionsProperty
*/
- public function addStructureInterface($interface)
+ #[\Override]
+ public function addStructureInterface($interface): static
{
if ($interface instanceof TemplateProperty) {
$interface = (string)$interface;
diff --git a/packages/cms/src/Charcoal/Property/TemplateProperty.php b/packages/cms/src/Charcoal/Property/TemplateProperty.php
index fbdb492ea..ce2c3bdb8 100644
--- a/packages/cms/src/Charcoal/Property/TemplateProperty.php
+++ b/packages/cms/src/Charcoal/Property/TemplateProperty.php
@@ -23,15 +23,10 @@ class TemplateProperty extends AbstractProperty implements SelectablePropertyInt
/**
* The available selectable templates.
- *
- * @var array|null
*/
- private $availableTemplates;
+ private ?array $availableTemplates = null;
- /**
- * @return string
- */
- public function type()
+ public function type(): string
{
return 'template';
}
@@ -41,9 +36,8 @@ public function type()
*
* @param string $choiceIdent The choice identifier (will be key / default ident).
* @param string|array $choice A string representing the choice label or a structure.
- * @return self
*/
- public function addChoice($choiceIdent, $choice)
+ public function addChoice($choiceIdent, $choice): static
{
$choice = $this->parseTemplateChoice($choice, strval($choiceIdent));
@@ -79,7 +73,7 @@ protected function parseTemplateChoice($choice, $choiceIdent)
$choice
));
}
- } elseif (is_bool($choice) && $choice === true) {
+ } elseif (is_bool($choice) && $choice) {
if (isset($this->availableTemplates[$choiceIdent])) {
return $this->availableTemplates[$choiceIdent];
} else {
@@ -120,9 +114,9 @@ protected function parseTemplateChoice($choice, $choiceIdent)
*
* @param mixed $val The value to to convert for display.
* @param array $options Optional display options.
- * @return string
*/
- public function displayVal($val, array $options = [])
+ #[\Override]
+ public function displayVal($val, array $options = []): string
{
if ($val === null || $val === '') {
return '';
@@ -143,10 +137,8 @@ public function displayVal($val, array $options = [])
$separator = $this->multipleSeparator();
/** Parse multiple values / ensure they are of array type. */
- if ($this['multiple']) {
- if (!is_array($propertyValue)) {
- $propertyValue = explode($separator, $propertyValue);
- }
+ if ($this['multiple'] && !is_array($propertyValue)) {
+ $propertyValue = explode($separator, (string)$propertyValue);
}
if ($separator === ',') {
@@ -175,10 +167,9 @@ public function displayVal($val, array $options = [])
/**
* Retrieve the selected template's FQCN.
- *
- * @return string
*/
- public function __toString()
+ #[\Override]
+ public function __toString(): string
{
$val = $this->val();
if ($this->hasChoice($val)) {
@@ -186,7 +177,7 @@ public function __toString()
$keys = [ 'controller', 'template', 'class' ];
foreach ($keys as $key) {
if (isset($choice[$key])) {
- return $choice[$key];
+ return (string)$choice[$key];
}
}
}
@@ -194,10 +185,7 @@ public function __toString()
return '';
}
- /**
- * @return string
- */
- public function sqlExtra()
+ public function sqlExtra(): ?string
{
return '';
}
@@ -207,7 +195,7 @@ public function sqlExtra()
*
* @return string The SQL type
*/
- public function sqlType()
+ public function sqlType(): string
{
if ($this['multiple']) {
return 'TEXT';
@@ -216,10 +204,7 @@ public function sqlType()
return 'VARCHAR(255)';
}
- /**
- * @return integer
- */
- public function sqlPdoType()
+ public function sqlPdoType(): int
{
return PDO::PARAM_STR;
}
@@ -230,6 +215,7 @@ public function sqlPdoType()
* @param Container $container A dependencies container instance.
* @return void
*/
+ #[\Override]
protected function setDependencies(Container $container)
{
parent::setDependencies($container);
diff --git a/packages/cms/tests/Charcoal/AbstractTestCase.php b/packages/cms/tests/Charcoal/AbstractTestCase.php
index 59ba12ea0..80f1772c4 100644
--- a/packages/cms/tests/Charcoal/AbstractTestCase.php
+++ b/packages/cms/tests/Charcoal/AbstractTestCase.php
@@ -1,5 +1,7 @@
getContainer();
@@ -56,10 +54,8 @@ protected function getModelDependenciesWithContainer()
/**
* Retrieve the property's mock dependencies with the service locator.
- *
- * @return array
*/
- protected function getPropertyDependenciesWithContainer()
+ protected function getPropertyDependenciesWithContainer(): array
{
$container = $this->getContainer();
@@ -97,9 +93,8 @@ protected function getContainerProvider()
/**
* @see ContainerProvider
- * @return void
*/
- private function setupContainer()
+ private function setupContainer(): void
{
$provider = new ContainerProvider();
$container = new Container();
diff --git a/packages/cms/tests/Charcoal/Cms/ContainerProvider.php b/packages/cms/tests/Charcoal/Cms/ContainerProvider.php
index a5d9c3930..61739d673 100644
--- a/packages/cms/tests/Charcoal/Cms/ContainerProvider.php
+++ b/packages/cms/tests/Charcoal/Cms/ContainerProvider.php
@@ -45,9 +45,8 @@ class ContainerProvider
{
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseServices(Container $container)
+ public function registerBaseServices(Container $container): void
{
$this->registerLogger($container);
$this->registerCache($container);
@@ -59,9 +58,8 @@ public function registerBaseServices(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerModelDependencies(Container $container)
+ public function registerModelDependencies(Container $container): void
{
$this->registerDatabase($container);
$this->registerViewServices($container);
@@ -70,44 +68,40 @@ public function registerModelDependencies(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerConfig(Container $container)
+ public function registerConfig(Container $container): void
{
- $container['config'] = function () {
- return new AppConfig([
- 'base_path' => realpath(__DIR__ . '/../../..'),
- 'templates' => [],
- 'metadata' => [
- 'paths' => [
- 'metadata',
- 'tests/Charcoal/Cms/Fixture/metadata',
- // Standalone
- 'vendor/charcoal/object/metadata',
- // Monorepo
- '/../object/metadata',
- ],
+ $container['config'] = (fn(): \Charcoal\App\AppConfig => new AppConfig([
+ 'base_path' => realpath(__DIR__ . '/../../..'),
+ 'templates' => [],
+ 'metadata' => [
+ 'paths' => [
+ 'metadata',
+ 'tests/Charcoal/Cms/Fixture/metadata',
+ // Standalone
+ 'vendor/charcoal/object/metadata',
+ // Monorepo
+ '/../object/metadata',
],
- 'view' => [
- 'paths' => [
- 'views',
- 'tests/Charcoal/Cms/Fixture/views',
- ],
- 'default_controller' => GenericTemplate::class,
+ ],
+ 'view' => [
+ 'paths' => [
+ 'views',
+ 'tests/Charcoal/Cms/Fixture/views',
],
- ]);
- };
+ 'default_controller' => GenericTemplate::class,
+ ],
+ ]));
}
/**
* Extend the application configset for a unilingual setup.
*
* @param Container $container A DI container.
- * @return void
*/
- public function withUnilingualConfig(Container $container)
+ public function withUnilingualConfig(Container $container): void
{
- $container->extend('config', function (AppConfig $config) {
+ $container->extend('config', function (AppConfig $config): \Charcoal\App\AppConfig {
$config['locales'] = [
'languages' => [
'en' => [
@@ -133,11 +127,10 @@ public function withUnilingualConfig(Container $container)
* Extend the application configset for a multilingual setup.
*
* @param Container $container A DI container.
- * @return void
*/
- public function withMultilingualConfig(Container $container)
+ public function withMultilingualConfig(Container $container): void
{
- $container->extend('config', function (AppConfig $config) {
+ $container->extend('config', function (AppConfig $config): \Charcoal\App\AppConfig {
$config['locales'] = [
'languages' => [
'en' => [
@@ -194,11 +187,10 @@ public function withMultilingualConfig(Container $container)
* Extend the application configset with templates.
*
* @param Container $container A DI container.
- * @return void
*/
- public function withTemplatesConfig(Container $container)
+ public function withTemplatesConfig(Container $container): void
{
- $container->extend('config', function (AppConfig $config) {
+ $container->extend('config', function (AppConfig $config): \Charcoal\App\AppConfig {
$config['templates'] = [
[
'value' => 'foo',
@@ -239,11 +231,10 @@ public function withTemplatesConfig(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerDatabase(Container $container)
+ public function registerDatabase(Container $container): void
{
- $container['database'] = function () {
+ $container['database'] = function (): \PDO {
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
@@ -253,33 +244,26 @@ public function registerDatabase(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerLogger(Container $container)
+ public function registerLogger(Container $container): void
{
- $container['logger'] = function () {
- return new NullLogger();
- };
+ $container['logger'] = (fn(): \Psr\Log\NullLogger => new NullLogger());
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerCache(Container $container)
+ public function registerCache(Container $container): void
{
- $container['cache'] = function () {
- return new Pool();
- };
+ $container['cache'] = (fn(): \Stash\Pool => new Pool());
}
/**
* Register the admin services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerModelServices(Container $container)
+ public function registerModelServices(Container $container): void
{
static $provider = null;
@@ -294,9 +278,8 @@ public function registerModelServices(Container $container)
* Register the admin services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerAuthServices(Container $container)
+ public function registerAuthServices(Container $container): void
{
static $provider = null;
@@ -311,9 +294,8 @@ public function registerAuthServices(Container $container)
* Setup the application's translator service.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerTranslatorServices(Container $container)
+ public function registerTranslatorServices(Container $container): void
{
static $provider = null;
@@ -328,9 +310,8 @@ public function registerTranslatorServices(Container $container)
* Setup the framework's view renderer.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerViewServices(Container $container)
+ public function registerViewServices(Container $container): void
{
static $provider = null;
@@ -343,48 +324,39 @@ public function registerViewServices(Container $container)
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerCmsConfig(Container $container)
+ public function registerCmsConfig(Container $container): void
{
- $container['cms/config'] = function () {
- return new CmsConfig();
- };
+ $container['cms/config'] = (fn(): \Charcoal\Cms\Config\CmsConfig => new CmsConfig());
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerDateHelper(Container $container)
+ public function registerDateHelper(Container $container): void
{
- $container['date/helper'] = function () {
- return new DateHelper([
- 'date_formats' => '',
- 'time_formats' => '',
- ]);
- };
+ $container['date/helper'] = (fn(): \Charcoal\Cms\Support\Helpers\DateHelper => new DateHelper([
+ 'date_formats' => '',
+ 'time_formats' => '',
+ ]));
}
/**
* @param Container $container A DI container.
- * @return void
*/
- public function registerTemplateFactory(Container $container)
+ public function registerTemplateFactory(Container $container): void
{
- $container['template/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => TemplateInterface::class,
- 'resolver_options' => [
- 'suffix' => 'Template',
- ],
- 'arguments' => [
- [
- 'container' => $container,
- 'logger' => $container['logger'],
- ],
+ $container['template/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => TemplateInterface::class,
+ 'resolver_options' => [
+ 'suffix' => 'Template',
+ ],
+ 'arguments' => [
+ [
+ 'container' => $container,
+ 'logger' => $container['logger'],
],
- ]);
- };
+ ],
+ ]));
}
}
diff --git a/packages/cms/tests/Charcoal/Cms/EventCategoryTest.php b/packages/cms/tests/Charcoal/Cms/EventCategoryTest.php
index cc74529db..856d5e933 100644
--- a/packages/cms/tests/Charcoal/Cms/EventCategoryTest.php
+++ b/packages/cms/tests/Charcoal/Cms/EventCategoryTest.php
@@ -17,15 +17,11 @@ class EventCategoryTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var EventCategory
*/
- private $obj;
+ private \Charcoal\Cms\EventCategory $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -34,18 +30,12 @@ protected function setUp(): void
$this->obj = new EventCategory($dependencies);
}
- /**
- * @return void
- */
- public function testItemType()
+ public function testItemType(): void
{
$this->assertEquals(Event::class, $this->obj->itemType());
}
- /**
- * @return void
- */
- public function testValidate()
+ public function testValidate(): void
{
$this->assertFalse($this->obj->validate());
$this->obj->setName([ 'fr' => 'Titre' ]);
diff --git a/packages/cms/tests/Charcoal/Cms/EventTest.php b/packages/cms/tests/Charcoal/Cms/EventTest.php
index 86178a2eb..a03c935c9 100644
--- a/packages/cms/tests/Charcoal/Cms/EventTest.php
+++ b/packages/cms/tests/Charcoal/Cms/EventTest.php
@@ -22,15 +22,11 @@ class EventTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var Event
*/
- private $obj;
+ private \Charcoal\Cms\Event|array $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -46,10 +42,7 @@ protected function setUp(): void
$this->obj = new Event($dependencies);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$ret = $this->obj->setData([
'title' => 'Example title',
@@ -80,10 +73,7 @@ public function testSetData()
$this->assertEquals(50, $this->obj->ticketPriceMax());
}
- /**
- * @return void
- */
- public function testSetTitle()
+ public function testSetTitle(): void
{
$this->assertEquals('', (string)$this->obj->title());
$ret = $this->obj->setTitle('Foo bar');
@@ -97,10 +87,7 @@ public function testSetTitle()
$this->assertEquals('Hello', (string)$this->obj['title']);
}
- /**
- * @return void
- */
- public function testSetSubtitle()
+ public function testSetSubtitle(): void
{
$this->assertEquals('', (string)$this->obj->subtitle());
$ret = $this->obj->setSubtitle('Bar foo');
@@ -114,10 +101,7 @@ public function testSetSubtitle()
$this->assertEquals('foo', (string)$this->obj['subtitle']);
}
- /**
- * @return void
- */
- public function testSetSummary()
+ public function testSetSummary(): void
{
$this->assertEquals('', (string)$this->obj->summary());
$ret = $this->obj->setSummary('Bar foo baz');
@@ -131,10 +115,7 @@ public function testSetSummary()
$this->assertEquals('foo', (string)$this->obj['summary']);
}
- /**
- * @return void
- */
- public function testSetContent()
+ public function testSetContent(): void
{
$this->assertEquals('', (string)$this->obj->content());
$ret = $this->obj->setContent('Bar foo');
@@ -148,10 +129,7 @@ public function testSetContent()
$this->assertEquals('foo', (string)$this->obj['content']);
}
- /**
- * @return void
- */
- public function testSetStartDate()
+ public function testSetStartDate(): void
{
$this->assertEquals(null, $this->obj->startDate());
$ret = $this->obj->setStartDate('2016-02-02');
@@ -165,19 +143,13 @@ public function testSetStartDate()
$this->obj->setStartDate([]);
}
- /**
- * @return void
- */
- public function testSetStartDateInvalidString()
+ public function testSetStartDateInvalidString(): void
{
$this->expectException('\Exception');
$this->obj->setStartDate('foo.bar');
}
- /**
- * @return void
- */
- public function testSetEndDate()
+ public function testSetEndDate(): void
{
$this->assertEquals(null, $this->obj->endDate());
$ret = $this->obj->setEndDate('2016-02-02');
@@ -191,27 +163,18 @@ public function testSetEndDate()
$this->obj->setEndDate([]);
}
- /**
- * @return void
- */
- public function testSetEndDateInvalidString()
+ public function testSetEndDateInvalidString(): void
{
$this->expectException('\Exception');
$this->obj->setEndDate('foo.bar');
}
- /**
- * @return void
- */
- public function testCategoryType()
+ public function testCategoryType(): void
{
$this->assertEquals(EventCategory::class, $this->obj->categoryType());
}
- /**
- * @return void
- */
- public function testMetaTitleDefaultsToTitle()
+ public function testMetaTitleDefaultsToTitle(): void
{
$this->assertEquals('', (string)$this->obj->metaTitle());
@@ -223,10 +186,7 @@ public function testMetaTitleDefaultsToTitle()
$this->assertEquals('Barfoo', (string)$this->obj->metaTitle());
}
- /**
- * @return void
- */
- public function testMetaDescriptionDefaultsToDescription()
+ public function testMetaDescriptionDefaultsToDescription(): void
{
$this->assertEquals('', (string)$this->obj->metaDescription());
@@ -238,27 +198,20 @@ public function testMetaDescriptionDefaultsToDescription()
$this->assertEquals('Barfoo', (string)$this->obj->metaDescription());
}
- /**
- * @return void
- */
/*
public function testMetaImageDefaultsToImage()
{
$this->assertEquals('', (string)$this->obj->metaImage());
-
+
$this->obj->setImage('Foo.png');
$this->assertSame($this->obj->image(), $this->obj->metaImage());
$this->assertEquals('Foo.png', (string)$this->obj->metaImage());
-
+
$this->obj->setMetaImage('Bar.jpg');
$this->assertEquals('Bar.jpg', (string)$this->obj->metaImage());
}
*/
-
- /**
- * @return void
- */
- public function testSaveGeneratesSlug()
+ public function testSaveGeneratesSlug(): void
{
$this->assertEquals('', $this->obj['slug']);
$this->obj->setData([
@@ -269,10 +222,7 @@ public function testSaveGeneratesSlug()
$this->assertEquals('en/events/foo', (string)$this->obj['slug']);
}
- /**
- * @return void
- */
- public function testUpdateGeneratesSlug()
+ public function testUpdateGeneratesSlug(): void
{
$this->assertEquals('', $this->obj['slug']);
$this->obj->setData([
diff --git a/packages/cms/tests/Charcoal/Cms/FaqCategoryTest.php b/packages/cms/tests/Charcoal/Cms/FaqCategoryTest.php
index a7e5a54c7..ccfebb70e 100644
--- a/packages/cms/tests/Charcoal/Cms/FaqCategoryTest.php
+++ b/packages/cms/tests/Charcoal/Cms/FaqCategoryTest.php
@@ -17,15 +17,11 @@ class FaqCategoryTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var FaqCategory
*/
- private $obj;
+ private \Charcoal\Cms\FaqCategory $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -34,10 +30,7 @@ protected function setUp(): void
$this->obj = new FaqCategory($dependencies);
}
- /**
- * @return void
- */
- public function testItemType()
+ public function testItemType(): void
{
$this->assertEquals(Faq::class, $this->obj->itemType());
}
diff --git a/packages/cms/tests/Charcoal/Cms/FaqTest.php b/packages/cms/tests/Charcoal/Cms/FaqTest.php
index 95422a5ac..95cfa2c83 100644
--- a/packages/cms/tests/Charcoal/Cms/FaqTest.php
+++ b/packages/cms/tests/Charcoal/Cms/FaqTest.php
@@ -17,15 +17,11 @@ class FaqTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var Faq
*/
- private $obj;
+ private \Charcoal\Cms\Faq $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -34,10 +30,7 @@ protected function setUp(): void
$this->obj = new Faq($dependencies);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$ret = $this->obj->setData([
'question' => 'Foo?',
@@ -48,30 +41,21 @@ public function testSetData()
$this->assertEquals('Bar', (string)$this->obj->answer());
}
- /**
- * @return void
- */
- public function testSetQuestion()
+ public function testSetQuestion(): void
{
$ret = $this->obj->setQuestion('Foo?');
$this->assertSame($ret, $this->obj);
$this->assertEquals('Foo?', $this->obj->question());
}
- /**
- * @return void
- */
- public function testSetAnswer()
+ public function testSetAnswer(): void
{
$ret = $this->obj->setAnswer('Bar');
$this->assertSame($ret, $this->obj);
$this->assertEquals('Bar', $this->obj->answer());
}
- /**
- * @return void
- */
- public function testCategoryType()
+ public function testCategoryType(): void
{
$this->assertEquals(FaqCategory::class, $this->obj->categoryType());
}
diff --git a/packages/cms/tests/Charcoal/Cms/MetatagTraitTest.php b/packages/cms/tests/Charcoal/Cms/MetatagTraitTest.php
index f66380b25..1762f4695 100644
--- a/packages/cms/tests/Charcoal/Cms/MetatagTraitTest.php
+++ b/packages/cms/tests/Charcoal/Cms/MetatagTraitTest.php
@@ -23,9 +23,6 @@ class MetatagTraitTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
protected function setUp(): void
{
$container = $this->getContainer();
@@ -42,19 +39,14 @@ protected function setUp(): void
/**
* Asserts that the object implements MetatagInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testMetatagInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testMetatagInterface(): void
{
$this->assertInstanceOf(MetatagInterface::class, $this->obj);
}
- /**
- * @return void
- */
- public function testSaveGeneratesMetaTags()
+ public function testSaveGeneratesMetaTags(): void
{
$this->assertEquals('', (string)$this->obj->metaTitle());
$this->assertEquals('', (string)$this->obj->metaDescription());
@@ -72,10 +64,7 @@ public function testSaveGeneratesMetaTags()
$this->assertEquals('x.jpg', (string)$this->obj->metaImage());
}
- /**
- * @return void
- */
- public function testUpdateGeneratesMetaTags()
+ public function testUpdateGeneratesMetaTags(): void
{
$this->assertEquals('', (string)$this->obj->metaTitle());
$this->assertEquals('', (string)$this->obj->metaDescription());
diff --git a/packages/cms/tests/Charcoal/Cms/Mock/BrokenTemplate.php b/packages/cms/tests/Charcoal/Cms/Mock/BrokenTemplate.php
index f04e6ae62..be6c9c688 100644
--- a/packages/cms/tests/Charcoal/Cms/Mock/BrokenTemplate.php
+++ b/packages/cms/tests/Charcoal/Cms/Mock/BrokenTemplate.php
@@ -1,5 +1,7 @@
event;
}
/**
* @param EventInterface $event The current event.
- * @return self
*/
- public function setEvent(EventInterface $event)
+ public function setEvent(EventInterface $event): static
{
$this->event = $event;
@@ -52,16 +44,15 @@ public function setEvent(EventInterface $event)
/**
* @return NewsInterface
*/
- public function news()
+ public function news(): ?\Charcoal\Cms\NewsInterface
{
return $this->news;
}
/**
* @param NewsInterface $news The current news.
- * @return self
*/
- public function setNews(NewsInterface $news)
+ public function setNews(NewsInterface $news): static
{
$this->news = $news;
@@ -71,16 +62,15 @@ public function setNews(NewsInterface $news)
/**
* @return SectionInterface
*/
- public function section()
+ public function section(): ?\Charcoal\Cms\SectionInterface
{
return $this->section;
}
/**
* @param SectionInterface $section The current section.
- * @return self
*/
- public function setSection(SectionInterface $section)
+ public function setSection(SectionInterface $section): static
{
$this->section = $section;
diff --git a/packages/cms/tests/Charcoal/Cms/Mock/EventTemplate.php b/packages/cms/tests/Charcoal/Cms/Mock/EventTemplate.php
index d99e5b990..3d2a94c9c 100644
--- a/packages/cms/tests/Charcoal/Cms/Mock/EventTemplate.php
+++ b/packages/cms/tests/Charcoal/Cms/Mock/EventTemplate.php
@@ -1,5 +1,7 @@
event;
}
/**
* @param EventInterface $event The current event.
- * @return self
*/
- public function setEvent(EventInterface $event)
+ public function setEvent(EventInterface $event): static
{
$this->event = $event;
diff --git a/packages/cms/tests/Charcoal/Cms/Mock/GenericTemplate.php b/packages/cms/tests/Charcoal/Cms/Mock/GenericTemplate.php
index 16b7ae678..dccd43c7c 100644
--- a/packages/cms/tests/Charcoal/Cms/Mock/GenericTemplate.php
+++ b/packages/cms/tests/Charcoal/Cms/Mock/GenericTemplate.php
@@ -1,5 +1,7 @@
section;
}
/**
* @param SectionInterface $section The current section.
- * @return self
*/
- public function setSection(SectionInterface $section)
+ public function setSection(SectionInterface $section): static
{
$this->section = $section;
diff --git a/packages/cms/tests/Charcoal/Cms/Mock/HomeTemplate.php b/packages/cms/tests/Charcoal/Cms/Mock/HomeTemplate.php
index cabc511b1..3c8969c04 100644
--- a/packages/cms/tests/Charcoal/Cms/Mock/HomeTemplate.php
+++ b/packages/cms/tests/Charcoal/Cms/Mock/HomeTemplate.php
@@ -1,5 +1,7 @@
section;
}
/**
* @param SectionInterface $section The current section.
- * @return self
*/
- public function setSection(SectionInterface $section)
+ public function setSection(SectionInterface $section): static
{
$this->section = $section;
diff --git a/packages/cms/tests/Charcoal/Cms/Mock/NewsTemplate.php b/packages/cms/tests/Charcoal/Cms/Mock/NewsTemplate.php
index cab71e68f..ea2114d92 100644
--- a/packages/cms/tests/Charcoal/Cms/Mock/NewsTemplate.php
+++ b/packages/cms/tests/Charcoal/Cms/Mock/NewsTemplate.php
@@ -1,5 +1,7 @@
news;
}
/**
* @param NewsInterface $news The current news.
- * @return self
*/
- public function setNews(NewsInterface $news)
+ public function setNews(NewsInterface $news): static
{
$this->news = $news;
diff --git a/packages/cms/tests/Charcoal/Cms/Mock/TemplateableModel.php b/packages/cms/tests/Charcoal/Cms/Mock/TemplateableModel.php
index c32909ae1..90dde6fa6 100644
--- a/packages/cms/tests/Charcoal/Cms/Mock/TemplateableModel.php
+++ b/packages/cms/tests/Charcoal/Cms/Mock/TemplateableModel.php
@@ -1,5 +1,7 @@
saveTemplateOptions();
@@ -36,7 +39,8 @@ public function preSave()
* @param array $properties Optional. The list of properties to update.
* @return boolean
*/
- public function preUpdate(array $properties = null)
+ #[\Override]
+ public function preUpdate(?array $properties = null)
{
if ($properties === null || array_search('template_options', $properties)) {
$this->saveTemplateOptions();
diff --git a/packages/cms/tests/Charcoal/Cms/Mock/WebPage.php b/packages/cms/tests/Charcoal/Cms/Mock/WebPage.php
index efba18a59..f7a18c6ab 100644
--- a/packages/cms/tests/Charcoal/Cms/Mock/WebPage.php
+++ b/packages/cms/tests/Charcoal/Cms/Mock/WebPage.php
@@ -1,5 +1,7 @@
generateDefaultMetaTags();
@@ -26,9 +27,9 @@ public function preSave()
* Update object in storage.
*
* @param array $properties Optional. The list of properties to update.
- * @return boolean
*/
- public function preUpdate(array $properties = null)
+ #[\Override]
+ public function preUpdate(?array $properties = null): bool
{
$this->generateDefaultMetaTags();
diff --git a/packages/cms/tests/Charcoal/Cms/NewsCategoryTest.php b/packages/cms/tests/Charcoal/Cms/NewsCategoryTest.php
index ce606199d..0632a25b9 100644
--- a/packages/cms/tests/Charcoal/Cms/NewsCategoryTest.php
+++ b/packages/cms/tests/Charcoal/Cms/NewsCategoryTest.php
@@ -17,15 +17,11 @@ class NewsCategoryTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var NewsCategory
*/
- private $obj;
+ private \Charcoal\Cms\NewsCategory $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -34,10 +30,7 @@ protected function setUp(): void
$this->obj = new NewsCategory($dependencies);
}
- /**
- * @return void
- */
- public function testItemType()
+ public function testItemType(): void
{
$this->assertEquals(News::class, $this->obj->itemType());
}
diff --git a/packages/cms/tests/Charcoal/Cms/NewsTest.php b/packages/cms/tests/Charcoal/Cms/NewsTest.php
index 89b992c62..bbad38b48 100644
--- a/packages/cms/tests/Charcoal/Cms/NewsTest.php
+++ b/packages/cms/tests/Charcoal/Cms/NewsTest.php
@@ -22,15 +22,11 @@ class NewsTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var News
*/
- private $obj;
+ private \Charcoal\Cms\News|array $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -46,10 +42,7 @@ protected function setUp(): void
$this->obj = new News($dependencies);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$ret = $this->obj->setData([
'title' => 'Example title',
@@ -65,10 +58,7 @@ public function testSetData()
$this->assertEquals(new DateTime('2015-01-01 20:00:00'), $this->obj->newsDate());
}
- /**
- * @return void
- */
- public function testSetTitle()
+ public function testSetTitle(): void
{
$this->assertEquals('', (string)$this->obj->title());
$ret = $this->obj->setTitle('Foo bar');
@@ -82,10 +72,7 @@ public function testSetTitle()
$this->assertEquals('Hello', (string)$this->obj['title']);
}
- /**
- * @return void
- */
- public function testSetSubtitle()
+ public function testSetSubtitle(): void
{
$this->assertEquals('', (string)$this->obj->subtitle());
$ret = $this->obj->setSubtitle('Bar foo');
@@ -99,10 +86,7 @@ public function testSetSubtitle()
$this->assertEquals('foo', (string)$this->obj['subtitle']);
}
- /**
- * @return void
- */
- public function testSetSummary()
+ public function testSetSummary(): void
{
$this->assertEquals('', (string)$this->obj->summary());
$ret = $this->obj->setSummary('Bar foo');
@@ -116,10 +100,7 @@ public function testSetSummary()
$this->assertEquals('foo', (string)$this->obj['summary']);
}
- /**
- * @return void
- */
- public function testSetContent()
+ public function testSetContent(): void
{
$this->assertEquals('', (string)$this->obj->content());
$ret = $this->obj->setContent('Bar foo');
@@ -133,10 +114,7 @@ public function testSetContent()
$this->assertEquals('foo', (string)$this->obj['content']);
}
- /**
- * @return void
- */
- public function testSetNewsDate()
+ public function testSetNewsDate(): void
{
$this->assertEquals(null, $this->obj->newsDate());
$ret = $this->obj->setNewsDate('2016-02-02');
@@ -150,19 +128,13 @@ public function testSetNewsDate()
$this->obj->setNewsDate([]);
}
- /**
- * @return void
- */
- public function testSetNewsDateInvalidString()
+ public function testSetNewsDateInvalidString(): void
{
$this->expectException('\Exception');
$this->obj->setNewsDate('foo.bar');
}
- /**
- * @return void
- */
- public function testMetaTitleDefaultsToTitle()
+ public function testMetaTitleDefaultsToTitle(): void
{
$this->assertEquals('', (string)$this->obj->metaTitle());
@@ -174,10 +146,7 @@ public function testMetaTitleDefaultsToTitle()
$this->assertEquals('Barfoo', (string)$this->obj->metaTitle());
}
- /**
- * @return void
- */
- public function testMetaDescriptionDefaultsToDescription()
+ public function testMetaDescriptionDefaultsToDescription(): void
{
$this->assertEquals('', (string)$this->obj->metaDescription());
@@ -189,45 +158,31 @@ public function testMetaDescriptionDefaultsToDescription()
$this->assertEquals('Barfoo', (string)$this->obj->metaDescription());
}
- /**
- * @return void
- */
/*
public function testMetaImageDefaultsToImage()
{
$this->assertEquals('', (string)$this->obj->metaImage());
-
+
$this->obj->setImage('Foo.png');
$this->assertSame($this->obj->image(), $this->obj->metaImage());
$this->assertEquals('Foo.png', (string)$this->obj->metaImage());
-
+
$this->obj->setMetaImage('Bar.jpg');
$this->assertEquals('Bar.jpg', (string)$this->obj->metaImage());
}
*/
-
- /**
- * @return void
- */
- public function testCategoryType()
+ public function testCategoryType(): void
{
$this->assertEquals(NewsCategory::class, $this->obj->categoryType());
}
- /**
- * @return void
- */
/*
public function testSave()
{
$this->obj->save();
}
*/
-
- /**
- * @return void
- */
- public function testSaveGeneratesSlug()
+ public function testSaveGeneratesSlug(): void
{
$this->assertEquals('', $this->obj['slug']);
$this->obj->setData([
@@ -238,10 +193,7 @@ public function testSaveGeneratesSlug()
$this->assertEquals('en/news/foo', (string)$this->obj['slug']);
}
- /**
- * @return void
- */
- public function testUpdateGeneratesSlug()
+ public function testUpdateGeneratesSlug(): void
{
$this->assertEquals('', $this->obj['slug']);
$this->obj->setData([
diff --git a/packages/cms/tests/Charcoal/Cms/Route/AbstractRouteTestCase.php b/packages/cms/tests/Charcoal/Cms/Route/AbstractRouteTestCase.php
index 9c541127b..d53c97813 100644
--- a/packages/cms/tests/Charcoal/Cms/Route/AbstractRouteTestCase.php
+++ b/packages/cms/tests/Charcoal/Cms/Route/AbstractRouteTestCase.php
@@ -3,6 +3,7 @@
namespace Charcoal\Tests\Cms\Route;
// From PSR-7
+use Charcoal\App\Route\RouteInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
@@ -26,8 +27,6 @@ abstract class AbstractRouteTestCase extends AbstractTestCase
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -86,10 +85,8 @@ protected function createHttpResponse()
/**
* Assertion when given an empty path.
- *
- * @return void
*/
- public function testPathResolvableOnEmptyPath()
+ public function testPathResolvableOnEmptyPath(): void
{
$container = $this->getContainer();
$router = $this->createRouter([
@@ -149,9 +146,8 @@ abstract public function testInvokeOnExistingModelWithTemplateIdent();
* Create the dynamic route to test.
*
* @param array $data The dynamic route dependencies.
- * @return \Charcoal\App\Route\RouteInterface
*/
- abstract protected function createRouter(array $data = []);
+ abstract protected function createRouter(array $data = []): RouteInterface;
/**
* Create the model's database table to test lookup.
diff --git a/packages/cms/tests/Charcoal/Cms/Route/EventRouteTest.php b/packages/cms/tests/Charcoal/Cms/Route/EventRouteTest.php
index dbf5924d3..45015660a 100644
--- a/packages/cms/tests/Charcoal/Cms/Route/EventRouteTest.php
+++ b/packages/cms/tests/Charcoal/Cms/Route/EventRouteTest.php
@@ -16,10 +16,8 @@ class EventRouteTest extends AbstractRouteTestCase
/**
* Asserts that `EventRoute::__invoke()` method returns an HTTP Response object
* with a 404 status code if the path does not resolve to any routable model.
- *
- * @return void
*/
- public function testInvokeOnNonexistentModel()
+ public function testInvokeOnNonexistentModel(): void
{
$container = $this->getContainer();
$router = $this->createRouter([
@@ -41,10 +39,8 @@ public function testInvokeOnNonexistentModel()
* if the resolved model has a nonexistent template controller.
*
* The "template/factory" service throws an Exception when a model's template controller can not be found.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithMissingTemplateController()
+ public function testInvokeOnExistingModelWithMissingTemplateController(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'nonexistent',
@@ -62,16 +58,14 @@ public function testInvokeOnExistingModelWithMissingTemplateController()
$response = $this->createHttpResponse();
$this->expectException(InvalidArgumentException::class);
- $response = $router($container, $request, $response);
+ $router($container, $request, $response);
}
/**
* Asserts that `EventRoute::__invoke()` method returns an HTTP Response object
* with a 500 status code if the resolved model does not have a template identifier.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithoutTemplateIdent()
+ public function testInvokeOnExistingModelWithoutTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => '',
@@ -95,10 +89,8 @@ public function testInvokeOnExistingModelWithoutTemplateIdent()
/**
* Asserts that `EventRoute::__invoke()` method returns an HTTP Response object
* with a 500 status code if the resolved model does not have a rendered template view.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithBadTemplateIdent()
+ public function testInvokeOnExistingModelWithBadTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'charcoal/tests/cms/mock/broken',
@@ -122,10 +114,8 @@ public function testInvokeOnExistingModelWithBadTemplateIdent()
/**
* Asserts that `EventRoute::__invoke()` method returns an HTTP Response object
* with a 2XX status code if the path does resolve to a specific routable model.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithTemplateIdent()
+ public function testInvokeOnExistingModelWithTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'charcoal/tests/cms/mock/event',
@@ -151,9 +141,8 @@ public function testInvokeOnExistingModelWithTemplateIdent()
* Create the dynamic route to test.
*
* @param array $data The dynamic route dependencies.
- * @return EventRoute
*/
- protected function createRouter(array $data = [])
+ protected function createRouter(array $data = []): \Charcoal\Cms\Route\EventRoute
{
return new EventRoute($data + [
'config' => [],
diff --git a/packages/cms/tests/Charcoal/Cms/Route/GenericRouteTest.php b/packages/cms/tests/Charcoal/Cms/Route/GenericRouteTest.php
index 160ece978..9cff3b738 100644
--- a/packages/cms/tests/Charcoal/Cms/Route/GenericRouteTest.php
+++ b/packages/cms/tests/Charcoal/Cms/Route/GenericRouteTest.php
@@ -2,6 +2,7 @@
namespace Charcoal\Tests\Cms\Route;
+use Charcoal\App\Route\RouteInterface;
use InvalidArgumentException;
// From 'charcoal-object'
@@ -21,10 +22,9 @@ class GenericRouteTest extends SectionRouteTest
* with a 500 status code if the resolved model does not have a template identifier.
*
* The route's config throws an Exception when a model's template controller is invalid.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithoutTemplateIdent()
+ #[\Override]
+ public function testInvokeOnExistingModelWithoutTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => '',
@@ -43,16 +43,14 @@ public function testInvokeOnExistingModelWithoutTemplateIdent()
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Route view controller must be a string.');
- $response = $router($container, $request, $response);
+ $router($container, $request, $response);
}
/**
* Asserts that `SectionRoute::__invoke()` method returns an HTTP Response object
* with a 404 status code if the path does resolve but the routable model does not.
- *
- * @return void
*/
- public function testInvokeOnExistingObjectRouteWithMissingModel()
+ public function testInvokeOnExistingObjectRouteWithMissingModel(): void
{
$container = $this->getContainer();
@@ -83,9 +81,9 @@ public function testInvokeOnExistingObjectRouteWithMissingModel()
* Create the dynamic route to test.
*
* @param array $data The dynamic route dependencies.
- * @return GenericRoute
*/
- protected function createRouter(array $data = [])
+ #[\Override]
+ protected function createRouter(array $data = []): RouteInterface
{
return new GenericRoute($data + [
'config' => [],
diff --git a/packages/cms/tests/Charcoal/Cms/Route/NewsRouteTest.php b/packages/cms/tests/Charcoal/Cms/Route/NewsRouteTest.php
index 3448d8f52..31675ca68 100644
--- a/packages/cms/tests/Charcoal/Cms/Route/NewsRouteTest.php
+++ b/packages/cms/tests/Charcoal/Cms/Route/NewsRouteTest.php
@@ -16,10 +16,8 @@ class NewsRouteTest extends AbstractRouteTestCase
/**
* Asserts that `NewsRoute::__invoke()` method returns an HTTP Response object
* with a 404 status code if the path does not resolve to any routable model.
- *
- * @return void
*/
- public function testInvokeOnNonexistentModel()
+ public function testInvokeOnNonexistentModel(): void
{
$container = $this->getContainer();
$router = $this->createRouter([
@@ -41,10 +39,8 @@ public function testInvokeOnNonexistentModel()
* if the resolved model has a nonexistent template controller.
*
* The "template/factory" service throws an Exception when a model's template controller can not be found.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithMissingTemplateController()
+ public function testInvokeOnExistingModelWithMissingTemplateController(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'nonexistent',
@@ -62,16 +58,14 @@ public function testInvokeOnExistingModelWithMissingTemplateController()
$response = $this->createHttpResponse();
$this->expectException(InvalidArgumentException::class);
- $response = $router($container, $request, $response);
+ $router($container, $request, $response);
}
/**
* Asserts that `NewsRoute::__invoke()` method returns an HTTP Response object
* with a 500 status code if the resolved model does not have a template identifier.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithoutTemplateIdent()
+ public function testInvokeOnExistingModelWithoutTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => '',
@@ -95,10 +89,8 @@ public function testInvokeOnExistingModelWithoutTemplateIdent()
/**
* Asserts that `NewsRoute::__invoke()` method returns an HTTP Response object
* with a 500 status code if the resolved model does not have a rendered template view.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithBadTemplateIdent()
+ public function testInvokeOnExistingModelWithBadTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'charcoal/tests/cms/mock/broken',
@@ -122,10 +114,8 @@ public function testInvokeOnExistingModelWithBadTemplateIdent()
/**
* Asserts that `NewsRoute::__invoke()` method returns an HTTP Response object
* with a 2XX status code if the path does resolve to a specific routable model.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithTemplateIdent()
+ public function testInvokeOnExistingModelWithTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'charcoal/tests/cms/mock/news',
@@ -151,9 +141,8 @@ public function testInvokeOnExistingModelWithTemplateIdent()
* Create the dynamic route to test.
*
* @param array $data The dynamic route dependencies.
- * @return NewsRoute
*/
- protected function createRouter(array $data = [])
+ protected function createRouter(array $data = []): \Charcoal\Cms\Route\NewsRoute
{
return new NewsRoute($data + [
'config' => [],
diff --git a/packages/cms/tests/Charcoal/Cms/Route/SectionRouteTest.php b/packages/cms/tests/Charcoal/Cms/Route/SectionRouteTest.php
index 1c79b174a..d3062c795 100644
--- a/packages/cms/tests/Charcoal/Cms/Route/SectionRouteTest.php
+++ b/packages/cms/tests/Charcoal/Cms/Route/SectionRouteTest.php
@@ -2,6 +2,7 @@
namespace Charcoal\Tests\Cms\Route;
+use Charcoal\App\Route\RouteInterface;
use InvalidArgumentException;
// From 'charcoal-cms'
@@ -16,10 +17,8 @@ class SectionRouteTest extends AbstractRouteTestCase
/**
* Asserts that `SectionRoute::__invoke()` method returns an HTTP Response object
* with a 404 status code if the path does not resolve to any routable model.
- *
- * @return void
*/
- public function testInvokeOnNonexistentModel()
+ public function testInvokeOnNonexistentModel(): void
{
$container = $this->getContainer();
$router = $this->createRouter([
@@ -43,10 +42,8 @@ public function testInvokeOnNonexistentModel()
*
* The "config.view.defaultController" option ensures the "template/factory" service
* does not throw an Exception when a model's template controller can not be found.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithMissingTemplateController()
+ public function testInvokeOnExistingModelWithMissingTemplateController(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'nonexistent',
@@ -70,10 +67,8 @@ public function testInvokeOnExistingModelWithMissingTemplateController()
/**
* Asserts that `SectionRoute::__invoke()` method returns an HTTP Response object
* with a 500 status code if the resolved model does not have a template identifier.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithoutTemplateIdent()
+ public function testInvokeOnExistingModelWithoutTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => '',
@@ -97,10 +92,8 @@ public function testInvokeOnExistingModelWithoutTemplateIdent()
/**
* Asserts that `SectionRoute::__invoke()` method returns an HTTP Response object
* with a 500 status code if the resolved model does not have a rendered template view.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithBadTemplateIdent()
+ public function testInvokeOnExistingModelWithBadTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'charcoal/tests/cms/mock/broken',
@@ -124,10 +117,8 @@ public function testInvokeOnExistingModelWithBadTemplateIdent()
/**
* Asserts that `SectionRoute::__invoke()` method returns an HTTP Response object
* with a 2XX status code if the path does resolve to a specific routable model.
- *
- * @return void
*/
- public function testInvokeOnExistingModelWithTemplateIdent()
+ public function testInvokeOnExistingModelWithTemplateIdent(): void
{
$this->insertMockRoutableContextObjects([
'templateIdent' => 'charcoal/tests/cms/mock/home',
@@ -153,9 +144,8 @@ public function testInvokeOnExistingModelWithTemplateIdent()
* Create the dynamic route to test.
*
* @param array $data The dynamic route dependencies.
- * @return SectionRoute
*/
- protected function createRouter(array $data = [])
+ protected function createRouter(array $data = []): RouteInterface
{
return new SectionRoute($data + [
'config' => [],
diff --git a/packages/cms/tests/Charcoal/Cms/SectionTest.php b/packages/cms/tests/Charcoal/Cms/SectionTest.php
index 24dfe7aca..e9043194c 100644
--- a/packages/cms/tests/Charcoal/Cms/SectionTest.php
+++ b/packages/cms/tests/Charcoal/Cms/SectionTest.php
@@ -19,15 +19,11 @@ class SectionTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var Section
*/
- private $obj;
+ private \Charcoal\Cms\Section|array $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp():void
{
@@ -43,10 +39,7 @@ protected function setUp():void
$this->obj = new Section($dependencies);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -71,10 +64,7 @@ public function testSetData()
$this->assertEquals([ 'x' => 'y' ], $obj->templateOptions());
}
- /**
- * @return void
- */
- public function testSetSectionType()
+ public function testSetSectionType(): void
{
$ret = $this->obj->setSectionType(Section::TYPE_EMPTY);
$this->assertSame($ret, $this->obj);
@@ -84,10 +74,7 @@ public function testSetSectionType()
$this->obj->setSectionType(false);
}
- /**
- * @return void
- */
- public function testSetTitle()
+ public function testSetTitle(): void
{
$this->assertEquals('', (string)$this->obj->title());
$ret = $this->obj->setTitle('Foo bar');
@@ -101,10 +88,7 @@ public function testSetTitle()
$this->assertEquals('Hello', (string)$this->obj['title']);
}
- /**
- * @return void
- */
- public function testSetSubtitle()
+ public function testSetSubtitle(): void
{
$this->assertEquals('', (string)$this->obj->subtitle());
$ret = $this->obj->setSubtitle('Bar foo');
@@ -118,10 +102,7 @@ public function testSetSubtitle()
$this->assertEquals('foo', (string)$this->obj['subtitle']);
}
- /**
- * @return void
- */
- public function testSetContent()
+ public function testSetContent(): void
{
$this->assertEquals('', (string)$this->obj->content());
$ret = $this->obj->setContent('Bar foo');
@@ -135,10 +116,7 @@ public function testSetContent()
$this->assertEquals('foo', (string)$this->obj['content']);
}
- /**
- * @return void
- */
- public function testSetImage()
+ public function testSetImage(): void
{
$this->assertEquals('', (string)$this->obj->image());
$ret = $this->obj->setImage('foo.png');
@@ -152,10 +130,7 @@ public function testSetImage()
$this->assertEquals('foo.webp', $this->obj['image']);
}
- /**
- * @return void
- */
- public function testMetaTitleDefaultsToTitle()
+ public function testMetaTitleDefaultsToTitle(): void
{
$this->assertEquals('', (string)$this->obj->metaTitle());
@@ -167,10 +142,7 @@ public function testMetaTitleDefaultsToTitle()
$this->assertEquals('Barfoo', (string)$this->obj->metaTitle());
}
- /**
- * @return void
- */
- public function testMetaDescriptionDefaultsToDescription()
+ public function testMetaDescriptionDefaultsToDescription(): void
{
$this->assertEquals('', (string)$this->obj->metaDescription());
@@ -182,10 +154,7 @@ public function testMetaDescriptionDefaultsToDescription()
$this->assertEquals('Barfoo', (string)$this->obj->metaDescription());
}
- /**
- * @return void
- */
- public function testMetaImageDefaultsToImage()
+ public function testMetaImageDefaultsToImage(): void
{
$this->assertEquals('', (string)$this->obj->metaImage());
@@ -197,10 +166,7 @@ public function testMetaImageDefaultsToImage()
$this->assertEquals('Bar.jpg', (string)$this->obj->metaImage());
}
- /**
- * @return void
- */
- public function testSaveGeneratesSlug()
+ public function testSaveGeneratesSlug(): void
{
$this->assertEquals('', $this->obj['slug']);
$this->obj->setData([
@@ -211,10 +177,7 @@ public function testSaveGeneratesSlug()
$this->assertEquals('en/foo', (string)$this->obj['slug']);
}
- /**
- * @return void
- */
- public function testUpdateGeneratesSlug()
+ public function testUpdateGeneratesSlug(): void
{
$this->assertEquals('', $this->obj['slug']);
$this->obj->setData([
diff --git a/packages/cms/tests/Charcoal/Cms/TagTest.php b/packages/cms/tests/Charcoal/Cms/TagTest.php
index 7b57b57b8..7fb77c686 100644
--- a/packages/cms/tests/Charcoal/Cms/TagTest.php
+++ b/packages/cms/tests/Charcoal/Cms/TagTest.php
@@ -17,15 +17,11 @@ class TagTest extends AbstractTestCase
/**
* Tested Class.
- *
- * @var Tag
*/
- private $obj;
+ private \Charcoal\Cms\Tag $obj;
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -34,10 +30,7 @@ protected function setUp(): void
$this->obj = new Tag($dependencies);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$ret = $this->obj->setData([
'name' => 'Foo?',
@@ -54,34 +47,28 @@ public function testSetData()
$this->assertEquals(42, $this->obj->searchWeight());
}
- /**
- * @return void
- */
- public function testSetName()
+ public function testSetName(): void
{
$ret = $this->obj->setName('Foo?');
$this->assertSame($ret, $this->obj);
$this->assertEquals('Foo?', $this->obj->name());
}
- /**
- * @return void
- */
- public function testSetColor()
+ public function testSetColor(): void
{
$ret = $this->obj->setColor('Bar');
$this->assertSame($ret, $this->obj);
$this->assertEquals('Bar', $this->obj->color());
}
- public function testSetVariations()
+ public function testSetVariations(): void
{
$ret = $this->obj->setVariations('foo,bar,baz');
$this->assertSame($ret, $this->obj);
$this->assertEquals('foo,bar,baz', $this->obj->variations());
}
- public function testSetSearchWeight()
+ public function testSetSearchWeight(): void
{
$ret = $this->obj->setSearchWeight(1984);
$this->assertSame($ret, $this->obj);
diff --git a/packages/cms/tests/Charcoal/Cms/TemplateableTraitTest.php b/packages/cms/tests/Charcoal/Cms/TemplateableTraitTest.php
index a53c7aaad..3ed508874 100644
--- a/packages/cms/tests/Charcoal/Cms/TemplateableTraitTest.php
+++ b/packages/cms/tests/Charcoal/Cms/TemplateableTraitTest.php
@@ -29,8 +29,6 @@ class TemplateableTraitTest extends AbstractTestCase
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -58,8 +56,6 @@ protected function setUp(): void
* Tear down the test.
*
* Drop any existing SQL table.
- *
- * @return void
*/
protected function tearDown(): void
{
@@ -68,10 +64,8 @@ protected function tearDown(): void
/**
* Drop the SQL table.
- *
- * @return void
*/
- private function dropTable()
+ private function dropTable(): void
{
$container = $this->getContainer();
@@ -80,10 +74,8 @@ private function dropTable()
/**
* Retrieve the model's mock metadata.
- *
- * @return array
*/
- public function getModelMetadata()
+ public function getModelMetadata(): array
{
return [
'properties' => [
@@ -124,30 +116,23 @@ public function getModelMetadata()
];
}
- /**
- * @return void
- */
- public function testMissingPropertyDependency()
+ public function testMissingPropertyDependency(): void
{
$this->expectException(RuntimeException::class);
$obj = new TemplateableModel($this->getModelDependencies());
$obj->templateOptionsStructure();
}
- /**
- * @return void
- */
- public function testMissingInterfaceDependency()
+ public function testMissingInterfaceDependency(): void
{
$this->expectException(RuntimeException::class);
- $obj = $this->getMockForTrait(TemplateableTrait::class);
+ $obj = new class {
+ use TemplateableTrait;
+ };
$obj->templateOptionsStructure();
}
- /**
- * @return void
- */
- public function testTemplateIdent()
+ public function testTemplateIdent(): void
{
$this->assertEmpty($this->obj->templateIdent());
@@ -155,10 +140,7 @@ public function testTemplateIdent()
$this->assertEquals('foobar', $this->obj->templateIdent());
}
- /**
- * @return void
- */
- public function testControllerIdent()
+ public function testControllerIdent(): void
{
$this->assertNull($this->obj->controllerIdent());
@@ -166,10 +148,7 @@ public function testControllerIdent()
$this->assertEquals('foobar', $this->obj->controllerIdent());
}
- /**
- * @return void
- */
- public function testTemplateOptions()
+ public function testTemplateOptions(): void
{
$this->assertIsArray($this->obj->templateOptions());
$this->assertEmpty($this->obj->templateOptions());
@@ -194,10 +173,7 @@ public function testTemplateOptions()
$this->assertEquals($obj, $this->obj->templateOptions());
}
- /**
- * @return void
- */
- public function testSavingTemplateOptions()
+ public function testSavingTemplateOptions(): void
{
$obj = $this->obj;
$obj->setTemplateIdent('foo');
@@ -214,10 +190,7 @@ public function testSavingTemplateOptions()
$this->assertTrue($result);
}
- /**
- * @return void
- */
- public function testTemplateOptionsStructure()
+ public function testTemplateOptionsStructure(): void
{
$templateData = [ 'foo' => 'Huxley' ];
$basePath = $this->getContainer()['config']['base_path'];
diff --git a/packages/cms/tests/Charcoal/Property/TemplateOptionsPropertyTest.php b/packages/cms/tests/Charcoal/Property/TemplateOptionsPropertyTest.php
index cc33465de..7154d21fd 100644
--- a/packages/cms/tests/Charcoal/Property/TemplateOptionsPropertyTest.php
+++ b/packages/cms/tests/Charcoal/Property/TemplateOptionsPropertyTest.php
@@ -26,8 +26,6 @@ class TemplateOptionsPropertyTest extends AbstractTestCase
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -52,18 +50,12 @@ protected function setUp(): void
$this->obj = new TemplateOptionsProperty($dependencies);
}
- /**
- * @return void
- */
- public function testType()
+ public function testType(): void
{
$this->assertEquals('template-options', $this->obj->type());
}
- /**
- * @return void
- */
- public function testAddStructureInterface()
+ public function testAddStructureInterface(): void
{
$container = $this->getContainer();
$property = $container['property/factory']->create(TemplateProperty::class);
@@ -76,10 +68,7 @@ public function testAddStructureInterface()
$this->assertEquals([ 'charcoal/tests/cms/mock/generic' ], $interfaces);
}
- /**
- * @return void
- */
- public function testAddStructureInterfaceException()
+ public function testAddStructureInterfaceException(): void
{
$container = $this->getContainer();
$property = $container['property/factory']->create(TemplateProperty::class);
diff --git a/packages/cms/tests/Charcoal/Property/TemplatePropertyTest.php b/packages/cms/tests/Charcoal/Property/TemplatePropertyTest.php
index 79ed83b9e..7b45bbb3d 100644
--- a/packages/cms/tests/Charcoal/Property/TemplatePropertyTest.php
+++ b/packages/cms/tests/Charcoal/Property/TemplatePropertyTest.php
@@ -27,8 +27,6 @@ class TemplatePropertyTest extends AbstractTestCase
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -43,26 +41,17 @@ protected function setUp(): void
$this->obj = new TemplateProperty($dependencies);
}
- /**
- * @return void
- */
- public function testType()
+ public function testType(): void
{
$this->assertEquals('template', $this->obj->type());
}
- /**
- * @return void
- */
- public function testSqlExtra()
+ public function testSqlExtra(): void
{
$this->assertEquals('', $this->obj->sqlExtra());
}
- /**
- * @return void
- */
- public function testSqlType()
+ public function testSqlType(): void
{
$this->obj->setMultiple(false);
$this->assertEquals('VARCHAR(255)', $this->obj->sqlType());
@@ -71,18 +60,12 @@ public function testSqlType()
$this->assertEquals('TEXT', $this->obj->sqlType());
}
- /**
- * @return void
- */
- public function testSqlPdoType()
+ public function testSqlPdoType(): void
{
$this->assertEquals(PDO::PARAM_STR, $this->obj->sqlPdoType());
}
- /**
- * @return void
- */
- public function testChoices()
+ public function testChoices(): void
{
$container = $this->getContainer();
$templates = $container['config']['templates'];
@@ -109,59 +92,40 @@ public function testChoices()
$this->assertArrayHasKey('zyx', $this->obj->choices());
}
- /**
- * @return void
- */
- public function testChoicesInvalidKey()
+ public function testChoicesInvalidKey(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->addChoice(3, 'boo');
}
- /**
- * @return void
- */
- public function testChoicesInvalidString()
+ public function testChoicesInvalidString(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->addChoice('boo', 'boo');
}
- /**
- * @return void
- */
- public function testChoicesInvalidBoolean()
+ public function testChoicesInvalidBoolean(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->addChoice('boo', true);
}
- /**
- * @return void
- */
- public function testChoicesInvalidArray()
+ public function testChoicesInvalidArray(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->addChoice('boo', [ 'foo' => 'boo' ]);
}
- /**
- * @return void
- */
- public function testChoicesInvalidType()
+ public function testChoicesInvalidType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->addChoice('xyz', null);
}
- /**
- * @return void
- */
- public function testDisplayVal()
+ public function testDisplayVal(): void
{
$container = $this->getContainer();
$translator = $container['translator'];
- $templates = $container['config']['templates'];
$this->assertEquals('', $this->obj->displayVal(null));
$this->assertEquals('', $this->obj->displayVal(''));
@@ -189,10 +153,7 @@ public function testDisplayVal()
$this->assertEquals('Oofoof, Zabzab, Xuqxuq', $this->obj->displayVal('foo,baz,qux', [ 'lang' => 'fr' ]));
}
- /**
- * @return void
- */
- public function testToString()
+ public function testToString(): void
{
$this->assertEquals('', (string)$this->obj);
diff --git a/packages/cms/tests/bootstrap.php b/packages/cms/tests/bootstrap.php
new file mode 100644
index 000000000..90929e3b5
--- /dev/null
+++ b/packages/cms/tests/bootstrap.php
@@ -0,0 +1,14 @@
+
-
->
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
@@ -18,17 +19,19 @@
-
-
+
+ ./src/Charcoal
-
-
+
+
+
+
+
+
+
+
-
+
-
-
-
-
diff --git a/packages/config/src/Charcoal/Config/AbstractConfig.php b/packages/config/src/Charcoal/Config/AbstractConfig.php
index d9a33d9e8..cea8098f8 100644
--- a/packages/config/src/Charcoal/Config/AbstractConfig.php
+++ b/packages/config/src/Charcoal/Config/AbstractConfig.php
@@ -41,7 +41,7 @@ abstract class AbstractConfig extends AbstractEntity implements
* @param EntityInterface[] $delegates An array of delegates (config) to set.
* @throws InvalidArgumentException If $data is invalid.
*/
- final public function __construct($data = null, array $delegates = null)
+ final public function __construct($data = null, ?array $delegates = null)
{
// Always set the default chaining notation
$this->setSeparator(self::DEFAULT_SEPARATOR);
@@ -108,9 +108,8 @@ public function merge($data)
* Create a new iterator from the configuration instance.
*
* @see IteratorAggregate
- * @return ArrayIterator
*/
- public function getIterator()
+ public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->data());
}
@@ -131,7 +130,8 @@ public function getIterator()
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
* @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise.
*/
- public function offsetExists($key)
+ #[\Override]
+ public function offsetExists($key): bool
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -192,7 +192,8 @@ public function offsetExists($key)
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
* @return mixed Value of the requested $key on success, NULL if the $key is not set.
*/
- public function offsetGet($key)
+ #[\Override]
+ public function offsetGet($key): mixed
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -228,13 +229,8 @@ public function offsetGet($key)
if ($this->mutatorCache[$key]) {
return $this->{$key}();
}
- // -- END DEPRECATED
-
- if (isset($this->{$key})) {
- return $this->{$key};
- }
- return $this->getInDelegates($key);
+ return ($this->{$key} ?? $this->getInDelegates($key));
}
/**
@@ -249,9 +245,9 @@ public function offsetGet($key)
* @param string $key The data key to assign $value to.
* @param mixed $value The data value to assign to $key.
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
- * @return void
*/
- public function offsetSet($key, $value)
+ #[\Override]
+ public function offsetSet($key, $value): void
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -298,9 +294,8 @@ public function offsetSet($key, $value)
* @param string $key The data key to assign or merge $value to.
* @param mixed $value The data value to assign to or merge with $key.
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
- * @return void
*/
- public function offsetReplace($key, $value)
+ public function offsetReplace($key, $value): void
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
diff --git a/packages/config/src/Charcoal/Config/AbstractEntity.php b/packages/config/src/Charcoal/Config/AbstractEntity.php
index d14fab59e..1c59dce18 100644
--- a/packages/config/src/Charcoal/Config/AbstractEntity.php
+++ b/packages/config/src/Charcoal/Config/AbstractEntity.php
@@ -2,6 +2,7 @@
namespace Charcoal\Config;
+use AllowDynamicProperties;
use ArrayAccess;
use InvalidArgumentException;
@@ -17,6 +18,7 @@
* - A key-value pair is internally passed to a (non-private / non-static) setter method (if present)
* or assigned to a (non-private / non-static) property (declared or not) and tracks affected keys.
*/
+#[AllowDynamicProperties]
abstract class AbstractEntity implements EntityInterface
{
/**
@@ -58,7 +60,7 @@ public function keys()
* @param string[] $keys Optional. Extracts only the requested data.
* @return array Key-value array of data, excluding pairs with NULL values.
*/
- public function data(array $keys = null)
+ public function data(?array $keys = null)
{
if ($keys === null) {
$keys = $this->keys();
@@ -66,7 +68,7 @@ public function data(array $keys = null)
$data = [];
foreach ($keys as $key) {
- if (strtolower($key) === 'data') {
+ if (strtolower((string)$key) === 'data') {
/** @internal Edge Case: Avoid recursive call */
continue;
}
@@ -88,7 +90,7 @@ public function data(array $keys = null)
public function setData(array $data)
{
foreach ($data as $key => $value) {
- if (strtolower($key) === 'data') {
+ if (strtolower((string)$key) === 'data') {
/** @internal Edge Case: Avoid recursive call */
continue;
}
@@ -150,7 +152,7 @@ public function set($key, $value)
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
* @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise.
*/
- public function offsetExists($key)
+ public function offsetExists($key): bool
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -183,12 +185,7 @@ public function offsetExists($key)
return ($this->{$key}() !== null);
}
// -- END DEPRECATED
-
- if (isset($this->{$key})) {
- return true;
- }
-
- return false;
+ return isset($this->{$key});
}
/**
@@ -205,7 +202,7 @@ public function offsetExists($key)
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
* @return mixed Value of the requested $key on success, NULL if the $key is not set.
*/
- public function offsetGet($key)
+ public function offsetGet($key): mixed
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -237,13 +234,8 @@ public function offsetGet($key)
if ($this->mutatorCache[$key]) {
return $this->{$key}();
}
- // -- END DEPRECATED
- if (isset($this->{$key})) {
- return $this->{$key};
- }
-
- return null;
+ return ($this->{$key} ?? null);
}
/**
@@ -259,9 +251,8 @@ public function offsetGet($key)
* @param string $key The data key to assign $value to.
* @param mixed $value The data value to assign to $key.
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
- * @return void
*/
- public function offsetSet($key, $value)
+ public function offsetSet($key, $value): void
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -301,9 +292,8 @@ public function offsetSet($key, $value)
* @uses self::offsetSet()
* @param string $key The data key to remove.
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
- * @return void
*/
- public function offsetUnset($key)
+ public function offsetUnset($key): void
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -328,32 +318,18 @@ public function offsetUnset($key)
* @see \JsonSerializable
* @return array Key-value array of data.
*/
- public function jsonSerialize()
+ public function jsonSerialize(): mixed
{
return $this->data();
}
- /**
- * Serializes the data on this entity.
- *
- * @see \Serializable
- * @return string Returns a string containing a byte-stream representation of the object.
- */
- public function serialize()
+ public function __serialize(): array
{
- return serialize($this->data());
+ return $this->data();
}
- /**
- * Applies the serialized data to this entity.
- *
- * @see \Serializable
- * @param string $data The serialized data to extract.
- * @return void
- */
- public function unserialize($data)
+ public function __unserialize(array $data): void
{
- $data = unserialize($data);
$this->setData($data);
}
@@ -371,8 +347,8 @@ final protected function camelize($value)
return static::$camelCache[$key];
}
- if (strpos($value, '_') !== false) {
- $value = implode('', array_map('ucfirst', explode('_', $value)));
+ if (str_contains($value, '_')) {
+ $value = implode('', array_map(ucfirst(...), explode('_', $value)));
}
static::$camelCache[$key] = lcfirst($value);
diff --git a/packages/config/src/Charcoal/Config/ConfigInterface.php b/packages/config/src/Charcoal/Config/ConfigInterface.php
index 780dcd384..8d1d19dba 100644
--- a/packages/config/src/Charcoal/Config/ConfigInterface.php
+++ b/packages/config/src/Charcoal/Config/ConfigInterface.php
@@ -1,5 +1,7 @@
delegates as $delegate) {
if (isset($delegate[$key])) {
diff --git a/packages/config/src/Charcoal/Config/EntityInterface.php b/packages/config/src/Charcoal/Config/EntityInterface.php
index b64045c0a..66ec2161c 100644
--- a/packages/config/src/Charcoal/Config/EntityInterface.php
+++ b/packages/config/src/Charcoal/Config/EntityInterface.php
@@ -1,5 +1,7 @@
getMessage());
- throw new UnexpectedValueException($message, 0, $e);
- } catch (Throwable $e) {
+ } catch (Exception | Throwable $e) {
$message = sprintf('PHP file "%s" could not be parsed: %s', $path, $e->getMessage());
throw new UnexpectedValueException($message, 0, $e);
}
- if (is_array($data) || ($data instanceof Traversable)) {
+ if (is_iterable($data)) {
return $data;
}
@@ -156,9 +153,9 @@ private function loadPhpFile($path)
* @return array An array on success.
* If the file is parsed as any other type, an empty array is returned.
*/
- private function loadYamlFile($path)
+ private function loadYamlFile(string $path): array
{
- if (!class_exists('Symfony\Component\Yaml\Parser')) {
+ if (!class_exists(\Symfony\Component\Yaml\Parser::class)) {
throw new LogicException('YAML format requires the Symfony YAML component');
}
diff --git a/packages/config/src/Charcoal/Config/GenericConfig.php b/packages/config/src/Charcoal/Config/GenericConfig.php
index 6be9b26eb..cb9a17927 100644
--- a/packages/config/src/Charcoal/Config/GenericConfig.php
+++ b/packages/config/src/Charcoal/Config/GenericConfig.php
@@ -1,5 +1,7 @@
separator, $key);
diff --git a/packages/config/tests/Charcoal/AbstractTestCase.php b/packages/config/tests/Charcoal/AbstractTestCase.php
index 3fdbb598d..a382decca 100644
--- a/packages/config/tests/Charcoal/AbstractTestCase.php
+++ b/packages/config/tests/Charcoal/AbstractTestCase.php
@@ -1,5 +1,7 @@
assertCount(count($expected), $haystack, $message);
$this->assertEquals($expected, $haystack, $message);
@@ -27,9 +26,8 @@ public function assertArrayEquals(array $expected, array $haystack, $message = '
* @param array $expected The expected haystack.
* @param array $haystack The actual haystack.
* @param string $message The error to report.
- * @return void
*/
- public function assertArrayContains(array $expected, array $haystack, $message = '')
+ public function assertArrayContains(array $expected, array $haystack, $message = ''): void
{
foreach ($expected as $item) {
$this->assertContains($item, $haystack, $message);
@@ -42,9 +40,8 @@ public function assertArrayContains(array $expected, array $haystack, $message =
* @param array $expected The expected haystack.
* @param array $haystack The actual haystack.
* @param string $message The error to report.
- * @return void
*/
- public function assertArrayHasKeys(array $expected, array $haystack, $message = '')
+ public function assertArrayHasKeys(array $expected, array $haystack, $message = ''): void
{
foreach ($expected as $item) {
$this->assertArrayHasKey($item, $haystack, $message);
@@ -58,14 +55,13 @@ public function assertArrayHasKeys(array $expected, array $haystack, $message =
* @param array $haystack The actual haystack.
* @param boolean $strict Whether to check for object identity.
* @param string $message The error to report.
- * @return void
*/
public function assertArraySubsets(
array $expected,
array $haystack,
$strict = false,
$message = ''
- ) {
+ ): void {
foreach ($expected as $key => $val) {
$this->assertArraySubset([ $key => $val ], $haystack, $strict, $message);
}
diff --git a/packages/config/tests/Charcoal/Config/Config/AbstractConfigTestCase.php b/packages/config/tests/Charcoal/Config/Config/AbstractConfigTestCase.php
index 427c6edf8..812d5ad6c 100644
--- a/packages/config/tests/Charcoal/Config/Config/AbstractConfigTestCase.php
+++ b/packages/config/tests/Charcoal/Config/Config/AbstractConfigTestCase.php
@@ -22,7 +22,7 @@ abstract class AbstractConfigTestCase extends AbstractTestCase
* @param array $delegates Delegates to pre-populate the object.
* @return MacroConfig
*/
- public function createConfig($data = null, array $delegates = null)
+ public function createConfig($data = null, ?array $delegates = null)
{
return new MacroConfig($data, $delegates);
}
@@ -36,6 +36,6 @@ public function createConfig($data = null, array $delegates = null)
*/
public function mockConfig($data = null, $delegates = null)
{
- return $this->getMockForAbstractClass(AbstractConfig::class, [ $data, $delegates ]);
+ return new class($data, $delegates) extends AbstractConfig {};
}
}
diff --git a/packages/config/tests/Charcoal/Config/Config/ConfigArrayAccessTest.php b/packages/config/tests/Charcoal/Config/Config/ConfigArrayAccessTest.php
index 1b957e0ac..7a72d9325 100644
--- a/packages/config/tests/Charcoal/Config/Config/ConfigArrayAccessTest.php
+++ b/packages/config/tests/Charcoal/Config/Config/ConfigArrayAccessTest.php
@@ -12,9 +12,14 @@
/**
* Test ArrayAccess implementation in AbstractConfig
- *
- * @coversDefaultClass \Charcoal\Config\AbstractConfig
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractConfig::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetExists()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetGet()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetSet()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetUnset()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Tests\Config\Mock\MacroConfig::class, 'foo()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Tests\Config\Mock\MacroConfig::class, 'setFoo()')]
class ConfigArrayAccessTest extends AbstractConfigTestCase
{
use ArrayAccessTestTrait;
@@ -26,8 +31,6 @@ class ConfigArrayAccessTest extends AbstractConfigTestCase
/**
* Create a concrete MacroConfig instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -41,9 +44,9 @@ protected function setUp(): void
/**
* Asserts that the object implements ArrayAccess.
*
- * @coversNothing
* @return MacroConfig
*/
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
public function testArrayAccess()
{
$this->assertInstanceOf(ArrayAccess::class, $this->cfg);
@@ -54,17 +57,12 @@ public function testArrayAccess()
// Test ArrayAccess on non-private properties
// =========================================================================
-
- /**
- * @covers ::offsetExists()
- * @return void
- */
- public function testOffsetExists()
+ public function testOffsetExists(): void
{
$cfg = $this->cfg;
// MacroConfig::$name
- $this->assertObjectHasAttribute('name', $cfg);
+ $this->assertTrue(property_exists($cfg, 'name'));
$this->assertTrue(isset($cfg['name']));
// MacroConfig::foo()
@@ -74,11 +72,7 @@ public function testOffsetExists()
$this->assertTrue(isset($cfg['erd']));
}
- /**
- * @covers ::offsetGet()
- * @return void
- */
- public function testOffsetGet()
+ public function testOffsetGet(): void
{
$cfg = $this->cfg;
@@ -92,29 +86,21 @@ public function testOffsetGet()
$this->assertEquals(true, $cfg['erd']);
}
- /**
- * @covers ::offsetSet()
- * @return void
- */
- public function testOffsetSet()
+ public function testOffsetSet(): void
{
$cfg = $this->cfg;
$cfg['baz'] = 'waldo';
- $this->assertObjectHasAttribute('baz', $cfg);
+ $this->assertTrue(property_exists($cfg, 'baz'));
$this->assertEquals('waldo', $cfg['baz']);
}
- /**
- * @covers ::offsetUnset()
- * @return void
- */
- public function testOffsetUnset()
+ public function testOffsetUnset(): void
{
$cfg = $this->cfg;
unset($cfg['name']);
- $this->assertObjectHasAttribute('name', $cfg);
+ $this->assertTrue(property_exists($cfg, 'name'));
$this->assertNull($cfg['name']);
}
@@ -122,38 +108,22 @@ public function testOffsetUnset()
// Test ArrayAccess on encapsulated properties
// =========================================================================
-
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroConfig::foo()
- * @covers ::offsetExists()
- * @return void
- */
- public function testOffsetExistsOnEncapsulatedMethod()
+ public function testOffsetExistsOnEncapsulatedMethod(): void
{
$cfg = $this->cfg;
- $this->assertObjectHasAttribute('foo', $cfg);
+ $this->assertTrue(property_exists($cfg, 'foo'));
$this->assertTrue(isset($cfg['foo']));
}
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroConfig::foo()
- * @covers ::offsetGet()
- * @return void
- */
- public function testOffsetGetOnEncapsulatedMethod()
+ public function testOffsetGetOnEncapsulatedMethod(): void
{
$cfg = $this->cfg;
$this->assertEquals('foo is 20', $cfg['foo']);
}
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroConfig::setFoo()
- * @covers ::offsetSet()
- * @return void
- */
- public function testOffsetSetOnEncapsulatedMethod()
+ public function testOffsetSetOnEncapsulatedMethod(): void
{
$cfg = $this->cfg;
@@ -161,17 +131,12 @@ public function testOffsetSetOnEncapsulatedMethod()
$this->assertEquals('foo is 42', $cfg['foo']);
}
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroConfig::setFoo()
- * @covers ::offsetUnset()
- * @return void
- */
- public function testOffsetUnsetOnEncapsulatedMethod()
+ public function testOffsetUnsetOnEncapsulatedMethod(): void
{
$cfg = $this->cfg;
unset($cfg['foo']);
- $this->assertObjectHasAttribute('foo', $cfg);
+ $this->assertTrue(property_exists($cfg, 'foo'));
$this->assertEquals('foo is 10', $cfg['foo']);
}
}
diff --git a/packages/config/tests/Charcoal/Config/Config/ConfigArrayMergeTest.php b/packages/config/tests/Charcoal/Config/Config/ConfigArrayMergeTest.php
index f286d35e1..d5eabb354 100644
--- a/packages/config/tests/Charcoal/Config/Config/ConfigArrayMergeTest.php
+++ b/packages/config/tests/Charcoal/Config/Config/ConfigArrayMergeTest.php
@@ -14,9 +14,10 @@
/**
* Test data merging in AbstractConfig
- *
- * @coversDefaultClass \Charcoal\Config\AbstractConfig
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractConfig::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetReplace()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'merge()')]
class ConfigArrayMergeTest extends AbstractConfigTestCase
{
use AssertionsTrait;
@@ -28,8 +29,6 @@ class ConfigArrayMergeTest extends AbstractConfigTestCase
/**
* Create a concrete GenericConfig instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -41,23 +40,18 @@ protected function setUp(): void
*
* @param mixed $data Data to pre-populate the object.
* @param array $delegates Delegates to pre-populate the object.
- * @return GenericConfig
*/
- public function createConfig($data = null, array $delegates = null)
+ #[\Override]
+ public function createConfig($data = null, ?array $delegates = null): \Charcoal\Config\GenericConfig
{
return new GenericConfig($data, $delegates);
}
// =========================================================================
-
/**
* Test {@see AbstractEntity::merge()} with array.
- *
- * @covers ::offsetReplace()
- * @covers ::merge()
- * @return void
*/
- public function testMergeDataWithArray()
+ public function testMergeDataWithArray(): void
{
$cfg = $this->cfg;
@@ -74,12 +68,8 @@ public function testMergeDataWithArray()
/**
* Test {@see AbstractEntity::merge()} with another Config instance.
- *
- * @covers ::offsetReplace()
- * @covers ::merge()
- * @return void
*/
- public function testMergeDataWithConfigInstance()
+ public function testMergeDataWithConfigInstance(): void
{
$cfg = $this->cfg;
@@ -95,10 +85,8 @@ public function testMergeDataWithConfigInstance()
/**
* Gets the intiial Config data.
- *
- * @return array
*/
- public function getInitialConfigData()
+ public function getInitialConfigData(): array
{
return [
'name' => 'vendor/my-cool-app',
@@ -116,10 +104,8 @@ public function getInitialConfigData()
/**
* Gets the mutations for the Config.
- *
- * @return array
*/
- public function getMutatedConfigData()
+ public function getMutatedConfigData(): array
{
return [
'name' => 'vendor/my-awesome-app',
@@ -138,10 +124,8 @@ public function getMutatedConfigData()
/**
* Gets the expected Config data.
- *
- * @return array
*/
- public function getExpectedConfigData()
+ public function getExpectedConfigData(): array
{
return [
'name' => 'vendor/my-awesome-app',
@@ -159,15 +143,11 @@ public function getExpectedConfigData()
}
// =========================================================================
-
/**
* Asserts that the container assigns a value to the endpoint
* {@see SeparatorAwareTrait::setWithSeparator() of the keypath}.
- *
- * @covers ::offsetReplace()
- * @return void
*/
- public function testOffsetMergeOnEndKeyPath()
+ public function testOffsetMergeOnEndKeyPath(): void
{
$cfg = $this->cfg;
@@ -185,11 +165,8 @@ public function testOffsetMergeOnEndKeyPath()
/**
* Asserts that the container assigns a value to the endpoint of a nonexistent midpoint
* {@see SeparatorAwareTrait::setWithSeparator() in the keypath}.
- *
- * @covers ::offsetReplace()
- * @return void
*/
- public function testOffsetMergeOnNonexistentMidKeyPath()
+ public function testOffsetMergeOnNonexistentMidKeyPath(): void
{
$cfg = $this->cfg;
@@ -206,22 +183,13 @@ public function testOffsetMergeOnNonexistentMidKeyPath()
}
// =========================================================================
-
- /**
- * @covers ::offsetReplace()
- * @return void
- */
- public function testOffsetMergeIgnoredOnZeroLengthKey()
+ public function testOffsetMergeIgnoredOnZeroLengthKey(): void
{
$this->cfg->offsetReplace('', 'waldo');
$this->assertNull($this->cfg['']);
}
- /**
- * @covers ::offsetReplace()
- * @return void
- */
- public function testOffsetMergeIgnoredOnUnderscoreKey()
+ public function testOffsetMergeIgnoredOnUnderscoreKey(): void
{
$this->cfg->offsetReplace('_', 'waldo');
$this->assertNull($this->cfg['_']);
@@ -229,11 +197,8 @@ public function testOffsetMergeIgnoredOnUnderscoreKey()
/**
* Asserts that a numeric key throws an exception, when merging a value.
- *
- * @covers ::offsetReplace()
- * @return void
*/
- public function testOffsetMergeThrowsExceptionOnNumericKey()
+ public function testOffsetMergeThrowsExceptionOnNumericKey(): void
{
$this->expectExceptionMessage("Entity array access only supports non-numeric keys");
$this->expectException(InvalidArgumentException::class);
diff --git a/packages/config/tests/Charcoal/Config/Config/ConfigDelegatesAwareTest.php b/packages/config/tests/Charcoal/Config/Config/ConfigDelegatesAwareTest.php
index b777d94b7..058a28bbf 100644
--- a/packages/config/tests/Charcoal/Config/Config/ConfigDelegatesAwareTest.php
+++ b/packages/config/tests/Charcoal/Config/Config/ConfigDelegatesAwareTest.php
@@ -10,9 +10,14 @@
/**
* Test DelegatesAwareTrait implementation in AbstractConfig
- *
- * @coversDefaultClass \Charcoal\Config\AbstractConfig
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractConfig::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, '__construct()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'setDelegates()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'addDelegate()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'prependDelegate()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetExists()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetGet()')]
class ConfigDelegatesAwareTest extends AbstractConfigTestCase
{
/**
@@ -27,8 +32,6 @@ class ConfigDelegatesAwareTest extends AbstractConfigTestCase
/**
* Create a concrete MacroConfig instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -62,11 +65,9 @@ protected function setUp(): void
/**
* Asserts that the object implements DelegatesAwareInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testDelegatesAwareInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testDelegatesAwareInterface(): void
{
$this->assertInstanceOf(DelegatesAwareInterface::class, $this->cfg);
}
@@ -75,15 +76,7 @@ public function testDelegatesAwareInterface()
// Test Delegate Collecting
// =========================================================================
-
- /**
- * @covers ::__construct()
- * @covers ::setDelegates()
- * @covers ::addDelegate()
- * @covers ::prependDelegate()
- * @return void
- */
- public function testSetDelegates()
+ public function testSetDelegates(): void
{
$cfg = $this->createConfig(null, [ $this->delegates[0] ]);
$this->assertEquals(0, $cfg['bop']);
@@ -99,100 +92,83 @@ public function testSetDelegates()
// Test ArrayAccess on delegated properties
// =========================================================================
-
/**
* Asserts that the delegate container returns TRUE if a data key is found
* {@see DelegatesAwareTrait::hasInDelegates() among its delegates}.
- *
- * @covers ::offsetExists()
- * @return void
*/
- public function testOffsetExistsInDelegates()
+ public function testOffsetExistsInDelegates(): void
{
$cfg = $this->cfg;
- $this->assertObjectNotHasAttribute('bar', $cfg);
- $this->assertObjectHasAttribute('bar', $this->delegates[1]);
+ $this->assertFalse(property_exists($cfg, 'bar'));
+ $this->assertTrue(property_exists($this->delegates[1], 'bar'));
$this->assertTrue(isset($cfg['bar']));
}
/**
* Asserts that the delegate container returns FALSE if a data key is nonexistent
* {@see DelegatesAwareTrait::hasInDelegates() among its delegates}.
- *
- * @covers ::offsetExists()
- * @return void
*/
- public function testOffsetExistsReturnsFalseOnNonexistentKeyInDelegates()
+ public function testOffsetExistsReturnsFalseOnNonexistentKeyInDelegates(): void
{
$cfg = $this->cfg;
- $this->assertObjectNotHasAttribute('zyx', $cfg);
+ $this->assertFalse(property_exists($cfg, 'zyx'));
$this->assertFalse(isset($cfg['zyx']));
}
/**
* Asserts that the delegate container returns the value of a data key found
* {@see DelegatesAwareTrait::getInDelegates() among its delegates}.
- *
- * @covers ::offsetGet()
- * @return void
*/
- public function testOffsetGetInDelegates()
+ public function testOffsetGetInDelegates(): void
{
$cfg = $this->cfg;
- $this->assertObjectNotHasAttribute('qux', $cfg);
- $this->assertObjectHasAttribute('qux', $this->delegates[2]);
+ $this->assertFalse(property_exists($cfg, 'qux'));
+ $this->assertTrue(property_exists($this->delegates[2], 'qux'));
$this->assertEquals($this->delegates[2]['qux'], $cfg['qux']);
}
/**
* Asserts that the delegate container returns NULL if a data key is nonexistent
* {@see DelegatesAwareTrait::getInDelegates() among its delegates}.
- *
- * @covers ::offsetExists()
- * @return void
*/
- public function testOffsetGetReturnsNullOnNonexistentKeyInDelegates()
+ public function testOffsetGetReturnsNullOnNonexistentKeyInDelegates(): void
{
$cfg = $this->cfg;
- $this->assertObjectNotHasAttribute('xyz', $cfg);
+ $this->assertFalse(property_exists($cfg, 'xyz'));
$this->assertNull($cfg['xyz']);
}
/**
* Asserts that attributes in delegates cannot be mutated by the delegate container.
- *
- * @coversNothing
- * @return void
*/
- public function testOffsetSetDoesNotPerformMutationsInDelegates()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testOffsetSetDoesNotPerformMutationsInDelegates(): void
{
$cfg = $this->cfg;
- $this->assertObjectNotHasAttribute('qux', $cfg);
- $this->assertObjectHasAttribute('qux', $this->delegates[2]);
+ $this->assertFalse(property_exists($cfg, 'qux'));
+ $this->assertTrue(property_exists($this->delegates[2], 'qux'));
$cfg['qux'] = 'garply';
- $this->assertObjectHasAttribute('qux', $cfg);
+ $this->assertTrue(property_exists($cfg, 'qux'));
$this->assertEquals('garply', $cfg['qux']);
$this->assertEquals('xyzzy', $this->delegates[2]['qux']);
}
/**
* Asserts that attributes in delegates cannot be removed by the delegate container.
- *
- * @coversNothing
- * @return void
*/
- public function testOffsetUnsetDoesNotPerformMutationsInDelegates()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testOffsetUnsetDoesNotPerformMutationsInDelegates(): void
{
$cfg = $this->cfg;
- $this->assertObjectNotHasAttribute('qux', $cfg);
- $this->assertObjectHasAttribute('qux', $this->delegates[2]);
+ $this->assertFalse(property_exists($cfg, 'qux'));
+ $this->assertTrue(property_exists($this->delegates[2], 'qux'));
unset($cfg['qux']);
$this->assertEquals($this->delegates[2]['qux'], $cfg['qux']);
@@ -201,15 +177,13 @@ public function testOffsetUnsetDoesNotPerformMutationsInDelegates()
/**
* Asserts that removing a value from the delegate container allows subsequent requests
* to lookup a fallback in a delegate.
- *
- * @coversNothing
- * @return void
*/
- public function testOffsetUnsetOnConfigWithFallbackInDelegates()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testOffsetUnsetOnConfigWithFallbackInDelegates(): void
{
$cfg = $this->cfg;
- $this->assertObjectHasAttribute('hud', $cfg);
+ $this->assertTrue(property_exists($cfg, 'hud'));
$this->assertEquals('flob', $cfg['hud']);
unset($cfg['hud']);
diff --git a/packages/config/tests/Charcoal/Config/Config/ConfigFileAwareTest.php b/packages/config/tests/Charcoal/Config/Config/ConfigFileAwareTest.php
index 1648c8040..af45165b9 100644
--- a/packages/config/tests/Charcoal/Config/Config/ConfigFileAwareTest.php
+++ b/packages/config/tests/Charcoal/Config/Config/ConfigFileAwareTest.php
@@ -18,9 +18,10 @@
* @todo ::addFile()
* @todo ::merge()
*
- *
- * @coversDefaultClass \Charcoal\Config\AbstractConfig
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractConfig::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, '__construct()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'addFile()')]
class ConfigFileAwareTest extends AbstractConfigTestCase
{
/**
@@ -30,8 +31,6 @@ class ConfigFileAwareTest extends AbstractConfigTestCase
/**
* Create a concrete GenericConfig instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -43,31 +42,23 @@ protected function setUp(): void
*
* @param mixed $data Data to pre-populate the object.
* @param array $delegates Delegates to pre-populate the object.
- * @return GenericConfig
*/
- public function createConfig($data = null, array $delegates = null)
+ #[\Override]
+ public function createConfig($data = null, ?array $delegates = null): \Charcoal\Config\GenericConfig
{
return new GenericConfig($data, $delegates);
}
/**
* Asserts that the object implements FileAwareInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testFileAwareInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testFileAwareInterface(): void
{
$this->assertInstanceOf(FileAwareInterface::class, $this->cfg);
}
- /**
- * @covers ::__construct()
- * @covers ::addFile()
- *
- * @return void
- */
- public function testConstructWithSupportedFormat()
+ public function testConstructWithSupportedFormat(): void
{
$path = $this->getPathToFixture('pass/valid.json');
$cfg = $this->createConfig($path);
@@ -78,14 +69,11 @@ public function testConstructWithSupportedFormat()
// Test INI
// =========================================================================
-
/**
* INI: Asserts that the Config supports INI config files.
- *
- * @coversNothing
- * @return void
*/
- public function testAddIniFile()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testAddIniFile(): void
{
$path = $this->getPathToFixture('pass/valid1.ini');
$this->cfg->addFile($path);
@@ -104,11 +92,9 @@ public function testAddIniFile()
/**
* INI: Asserts that the Config supports key-paths in INI config files.
- *
- * @coversNothing
- * @return void
*/
- public function testAddIniFileWithDelimitedData()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testAddIniFileWithDelimitedData(): void
{
$path = $this->getPathToFixture('pass/valid2.ini');
$this->cfg->addFile($path);
@@ -126,11 +112,8 @@ public function testAddIniFileWithDelimitedData()
/**
* INI: Asserts that an ordered list is NOT ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddIniFileWithInvalidArray()
+ public function testAddIniFileWithInvalidArray(): void
{
$this->expectExceptionMessage('Entity array access only supports non-numeric keys');
$this->expectException(InvalidArgumentException::class);
@@ -141,11 +124,8 @@ public function testAddIniFileWithInvalidArray()
/**
* INI: Asserts that an unparsable file is silently ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddUnparsableIniFile()
+ public function testAddUnparsableIniFile(): void
{
// phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
$path = $this->getPathToFixture('pass/unparsable.ini');
@@ -159,14 +139,11 @@ public function testAddUnparsableIniFile()
// Test JSON
// =========================================================================
-
/**
* JSON: Asserts that the Config supports JSON config files.
- *
- * @coversNothing
- * @return void
*/
- public function testAddJsonFile()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testAddJsonFile(): void
{
$path = $this->getPathToFixture('pass/valid.json');
$this->cfg->addFile($path);
@@ -185,11 +162,8 @@ public function testAddJsonFile()
/**
* JSON: Asserts that an ordered list is NOT ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddJsonFileWithInvalidArray()
+ public function testAddJsonFileWithInvalidArray(): void
{
$this->expectExceptionMessage('Entity array access only supports non-numeric keys');
$this->expectException(InvalidArgumentException::class);
@@ -200,11 +174,8 @@ public function testAddJsonFileWithInvalidArray()
/**
* JSON: Asserts that an invalid file is silently ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddJsonFileWithInvalidType()
+ public function testAddJsonFileWithInvalidType(): void
{
$path = $this->getPathToFixture('pass/invalid2.json');
$this->cfg->addFile($path);
@@ -216,14 +187,11 @@ public function testAddJsonFileWithInvalidType()
// Test PHP
// =========================================================================
-
/**
* PHP: Asserts that the Config supports PHP config files.
- *
- * @coversNothing
- * @return void
*/
- public function testAddPhpFile()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testAddPhpFile(): void
{
$path = $this->getPathToFixture('pass/valid1.php');
$this->cfg->addFile($path);
@@ -242,11 +210,9 @@ public function testAddPhpFile()
/**
* PHP: Asserts that the scope of PHP config files is bound to the Config.
- *
- * @coversNothing
- * @return void
*/
- public function testAddPhpFileThatMutatesContext()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testAddPhpFileThatMutatesContext(): void
{
$path = $this->getPathToFixture('pass/valid2.php');
$this->cfg->addFile($path);
@@ -265,11 +231,8 @@ public function testAddPhpFileThatMutatesContext()
/**
* PHP: Asserts that an ordered list is NOT ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddPhpFileWithInvalidArray()
+ public function testAddPhpFileWithInvalidArray(): void
{
$this->expectExceptionMessage('Entity array access only supports non-numeric keys');
$this->expectException(InvalidArgumentException::class);
@@ -280,11 +243,8 @@ public function testAddPhpFileWithInvalidArray()
/**
* PHP: Asserts that an invalid file is silently ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddPhpFileWithInvalidType()
+ public function testAddPhpFileWithInvalidType(): void
{
$path = $this->getPathToFixture('pass/invalid2.php');
$this->cfg->addFile($path);
@@ -296,14 +256,11 @@ public function testAddPhpFileWithInvalidType()
// Test YAML
// =========================================================================
-
/**
* YAML: Asserts that the Config supports '.yml' YAML config files.
- *
- * @coversNothing
- * @return void
*/
- public function testAddYamlFile()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testAddYamlFile(): void
{
$path = $this->getPathToFixture('pass/valid1.yml');
$this->cfg->addFile($path);
@@ -322,11 +279,8 @@ public function testAddYamlFile()
/**
* YAML: Asserts that an ordered list is NOT ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddYamlFileWithInvalidArray()
+ public function testAddYamlFileWithInvalidArray(): void
{
$this->expectExceptionMessage('Entity array access only supports non-numeric keys');
$this->expectException(InvalidArgumentException::class);
@@ -337,11 +291,8 @@ public function testAddYamlFileWithInvalidArray()
/**
* YAML: Asserts that an invalid file is silently ignored.
- *
- * @covers ::addFile()
- * @return void
*/
- public function testAddYamlFileWithInvalidType()
+ public function testAddYamlFileWithInvalidType(): void
{
$path = $this->getPathToFixture('pass/invalid2.yml');
$this->cfg->addFile($path);
diff --git a/packages/config/tests/Charcoal/Config/Config/ConfigSeparatorAwareTest.php b/packages/config/tests/Charcoal/Config/Config/ConfigSeparatorAwareTest.php
index e9580b4e2..0cfd4b02d 100644
--- a/packages/config/tests/Charcoal/Config/Config/ConfigSeparatorAwareTest.php
+++ b/packages/config/tests/Charcoal/Config/Config/ConfigSeparatorAwareTest.php
@@ -11,9 +11,14 @@
/**
* Test SeparatorAwareTrait implementation in AbstractConfig
- *
- * @coversDefaultClass \Charcoal\Config\AbstractConfig
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractConfig::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, '__construct()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'setSeparator()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'separator()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetExists()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetGet()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'offsetSet()')]
class ConfigSeparatorAwareTest extends AbstractConfigTestCase
{
use AssertionsTrait;
@@ -30,8 +35,6 @@ class ConfigSeparatorAwareTest extends AbstractConfigTestCase
/**
* Create a MacroConfig instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -62,22 +65,14 @@ protected function setUp(): void
/**
* Asserts that the object implements SeparatorAwareInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testSeparatorAwareInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testSeparatorAwareInterface(): void
{
$this->assertInstanceOf(SeparatorAwareInterface::class, $this->cfg);
}
- /**
- * @covers ::__construct()
- * @covers ::setSeparator()
- * @covers ::separator()
- * @return void
- */
- public function testDefaultSeparator()
+ public function testDefaultSeparator(): void
{
$cfg = $this->createConfig();
$this->assertEquals(AbstractConfig::DEFAULT_SEPARATOR, $cfg->separator());
@@ -87,45 +82,35 @@ public function testDefaultSeparator()
// Test ArrayAccess on nested properties
// =========================================================================
-
/**
* Asserts that the container returns TRUE if an endpoint is found
* {@see SeparatorAwareTrait::hasWithSeparator() in a keypath}.
- *
- * @covers ::offsetExists()
- * @return void
*/
- public function testOffsetExistsOnEndKeyPath()
+ public function testOffsetExistsOnEndKeyPath(): void
{
$cfg = $this->cfg;
- $this->assertObjectHasAttribute('connections', $cfg);
+ $this->assertTrue(property_exists($cfg, 'connections'));
$this->assertTrue(isset($cfg['connections.default.host']));
}
/**
* Asserts that the container returns TRUE if a midpoint is found
* {@see SeparatorAwareTrait::hasWithSeparator() in a keypath}.
- *
- * @covers ::offsetExists()
- * @return void
*/
- public function testOffsetExistsOnMidKeyPath()
+ public function testOffsetExistsOnMidKeyPath(): void
{
$cfg = $this->cfg;
- $this->assertObjectHasAttribute('connections', $cfg);
+ $this->assertTrue(property_exists($cfg, 'connections'));
$this->assertTrue(isset($cfg['connections.default']));
}
/**
* Asserts that the container returns FALSE if an endpoint is nonexistent
* {@see SeparatorAwareTrait::hasWithSeparator() in a keypath}.
- *
- * @covers ::offsetExists()
- * @return void
*/
- public function testOffsetExistsReturnsFalseOnNonexistentEndKeyPath()
+ public function testOffsetExistsReturnsFalseOnNonexistentEndKeyPath(): void
{
$cfg = $this->cfg;
@@ -135,11 +120,8 @@ public function testOffsetExistsReturnsFalseOnNonexistentEndKeyPath()
/**
* Asserts that the container returns FALSE if a midpoint is nonexistent
* {@see SeparatorAwareTrait::hasWithSeparator() in a keypath}.
- *
- * @covers ::offsetExists()
- * @return void
*/
- public function testOffsetExistsReturnsFalseOnNonexistentMidKeyPath()
+ public function testOffsetExistsReturnsFalseOnNonexistentMidKeyPath(): void
{
$cfg = $this->cfg;
@@ -149,11 +131,8 @@ public function testOffsetExistsReturnsFalseOnNonexistentMidKeyPath()
/**
* Asserts that the container returns the value of the endpoint found
* {@see SeparatorAwareTrait::getWithSeparator() in a keypath}.
- *
- * @covers ::offsetGet()
- * @return void
*/
- public function testOffsetGetOnEndKeyPath()
+ public function testOffsetGetOnEndKeyPath(): void
{
$cfg = $this->cfg;
@@ -166,11 +145,8 @@ public function testOffsetGetOnEndKeyPath()
/**
* Asserts that the container returns the value of the midpoint found
* {@see SeparatorAwareTrait::getWithSeparator() in a keypath}.
- *
- * @covers ::offsetGet()
- * @return void
*/
- public function testOffsetGetOnMidKeyPath()
+ public function testOffsetGetOnMidKeyPath(): void
{
$cfg = $this->cfg;
@@ -183,11 +159,8 @@ public function testOffsetGetOnMidKeyPath()
/**
* Asserts that the container returns NULL if the endpoint is nonexistent
* {@see SeparatorAwareTrait::getWithSeparator() in a keypath}.
- *
- * @covers ::offsetGet()
- * @return void
*/
- public function testOffsetGetReturnsNullOnNonexistentEndKeyPath()
+ public function testOffsetGetReturnsNullOnNonexistentEndKeyPath(): void
{
$cfg = $this->cfg;
@@ -197,11 +170,8 @@ public function testOffsetGetReturnsNullOnNonexistentEndKeyPath()
/**
* Asserts that the container returns NULL if the midpoint is nonexistent
* {@see SeparatorAwareTrait::getWithSeparator() in a keypath}.
- *
- * @covers ::offsetGet()
- * @return void
*/
- public function testOffsetGetReturnsNullOnNonexistentMidKeyPath()
+ public function testOffsetGetReturnsNullOnNonexistentMidKeyPath(): void
{
$cfg = $this->cfg;
@@ -211,11 +181,8 @@ public function testOffsetGetReturnsNullOnNonexistentMidKeyPath()
/**
* Asserts that the container assigns a value to the endpoint
* {@see SeparatorAwareTrait::setWithSeparator() of the keypath}.
- *
- * @covers ::offsetSet()
- * @return void
*/
- public function testOffsetSetOnEndKeyPath()
+ public function testOffsetSetOnEndKeyPath(): void
{
$cfg = $this->cfg;
@@ -226,11 +193,8 @@ public function testOffsetSetOnEndKeyPath()
/**
* Asserts that the container assigns a value to the endpoint of a nonexistent midpoint
* {@see SeparatorAwareTrait::setWithSeparator() in the keypath}.
- *
- * @covers ::offsetSet()
- * @return void
*/
- public function testOffsetSetOnNonexistentMidKeyPath()
+ public function testOffsetSetOnNonexistentMidKeyPath(): void
{
$cfg = $this->cfg;
$this->assertNull($cfg['connections.analytics']);
@@ -242,11 +206,9 @@ public function testOffsetSetOnNonexistentMidKeyPath()
/**
* Asserts that the container assigns NULL to the endpoint
* {@see SeparatorAwareTrait::setWithSeparator() of the keypath} to "remove".
- *
- * @coversNothing
- * @return void
*/
- public function testOffsetUnsetOnEndKeyPath()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testOffsetUnsetOnEndKeyPath(): void
{
$cfg = $this->cfg;
@@ -257,11 +219,9 @@ public function testOffsetUnsetOnEndKeyPath()
/**
* Asserts that the container assigns NULL to the midpoint
* {@see SeparatorAwareTrait::setWithSeparator() of the keypath} to "remove".
- *
- * @coversNothing
- * @return void
*/
- public function testOffsetUnsetOnMidKeyPath()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testOffsetUnsetOnMidKeyPath(): void
{
$cfg = $this->cfg;
diff --git a/packages/config/tests/Charcoal/Config/Config/ConfigTest.php b/packages/config/tests/Charcoal/Config/Config/ConfigTest.php
index d76d7d5ae..8ac73eb39 100644
--- a/packages/config/tests/Charcoal/Config/Config/ConfigTest.php
+++ b/packages/config/tests/Charcoal/Config/Config/ConfigTest.php
@@ -26,9 +26,13 @@
* - ConfigSeparatorAwareTest
* - ConfigFileAwareTest
* - FileLoader/*
- *
- * @coversDefaultClass \Charcoal\Config\AbstractConfig
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractConfig::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'getIterator()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, '__construct')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'merge')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'setData')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractConfig::class, 'defaults')]
class ConfigTest extends AbstractConfigTestCase
{
use AssertionsTrait;
@@ -40,8 +44,6 @@ class ConfigTest extends AbstractConfigTestCase
/**
* Create a concrete MacroConfig instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -50,33 +52,23 @@ protected function setUp(): void
/**
* Asserts that the object implements PSR-11.
- *
- * @coversNothing
- * @return void
*/
- public function testPsr11()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testPsr11(): void
{
$this->assertInstanceOf(ContainerInterface::class, $this->cfg);
}
/**
* Asserts that the object implements IteratorAggregate.
- *
- * @covers ::getIterator()
- * @return void
*/
- public function testIteratorAggregate()
+ public function testIteratorAggregate(): void
{
$this->assertInstanceOf(IteratorAggregate::class, $this->cfg);
$this->assertInstanceOf(ArrayIterator::class, $this->cfg->getIterator());
}
- /**
- * @covers ::__construct
- * @covers ::merge
- * @return void
- */
- public function testConstructWithArray()
+ public function testConstructWithArray(): void
{
$cfg = $this->mockConfig([
'name' => 'Charcoal'
@@ -84,23 +76,13 @@ public function testConstructWithArray()
$this->assertEquals('Charcoal', $cfg['name']);
}
- /**
- * @covers ::__construct
- * @covers ::merge
- * @return void
- */
- public function testConstructWithConfigInstance()
+ public function testConstructWithConfigInstance(): void
{
$cfg = $this->mockConfig($this->cfg);
$this->assertEquals('garply', $cfg['baz']);
}
- /**
- * @covers ::__construct
- * @covers ::merge
- * @return void
- */
- public function testConstructWithTraversableInstance()
+ public function testConstructWithTraversableInstance(): void
{
$iter = new ArrayIterator([
'name' => 'Charcoal'
@@ -109,35 +91,23 @@ public function testConstructWithTraversableInstance()
$this->assertEquals('Charcoal', $cfg['name']);
}
- /**
- *
- * @covers ::__construct
- * @covers ::merge
- * @return void
- */
- public function testConstructWithInvalidData()
+ public function testConstructWithInvalidData(): void
{
$this->expectExceptionMessage('Data must be a config file, an associative array, or an object implementing Traversable');
$this->expectException(InvalidArgumentException::class);
$std = new StdClass;
- $cfg = $this->mockConfig($std);
+ $this->mockConfig($std);
}
// Test Defaults
// =========================================================================
-
/**
* Asserts that, when defined, a Config will apply the class' default data.
- *
- * @covers ::__construct
- * @covers ::setData
- * @covers ::defaults
- * @return void
*/
- public function testConstructWithDefaults()
+ public function testConstructWithDefaults(): void
{
/** @var array $defaults {@see \Charcoal\Tests\Config\Mock\MacroConfig::defaults()} */
$defaults = [
@@ -173,11 +143,8 @@ public function testConstructWithDefaults()
/**
* Asserts that, by default, a Config has no default data.
- *
- * @covers ::defaults
- * @return void
*/
- public function testEmptyDefaults()
+ public function testEmptyDefaults(): void
{
$cfg = $this->mockConfig();
$this->assertEmpty($cfg->defaults());
diff --git a/packages/config/tests/Charcoal/Config/Entity/AbstractEntityTestCase.php b/packages/config/tests/Charcoal/Config/Entity/AbstractEntityTestCase.php
index 85a2b9a78..0bbc42971 100644
--- a/packages/config/tests/Charcoal/Config/Entity/AbstractEntityTestCase.php
+++ b/packages/config/tests/Charcoal/Config/Entity/AbstractEntityTestCase.php
@@ -18,7 +18,7 @@ abstract class AbstractEntityTestCase extends AbstractTestCase
* @param array $data Data to assign to the object.
* @return MacroEntity
*/
- public function createEntity(array $data = null)
+ public function createEntity(?array $data = null)
{
return new MacroEntity($data);
}
@@ -29,7 +29,7 @@ public function createEntity(array $data = null)
* @param array $data Data to assign to the object.
* @return AbstractEntity
*/
- public function mockEntity(array $data = null)
+ public function mockEntity(?array $data = null)
{
$obj = $this->getMockForAbstractClass(AbstractEntity::class);
diff --git a/packages/config/tests/Charcoal/Config/Entity/EntityArrayAccessTest.php b/packages/config/tests/Charcoal/Config/Entity/EntityArrayAccessTest.php
index 9873e25b0..2269bdf40 100644
--- a/packages/config/tests/Charcoal/Config/Entity/EntityArrayAccessTest.php
+++ b/packages/config/tests/Charcoal/Config/Entity/EntityArrayAccessTest.php
@@ -12,9 +12,17 @@
/**
* Test ArrayAccess implementation in AbstractEntity
- *
- * @coversDefaultClass \Charcoal\Config\AbstractEntity
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractEntity::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'offsetExists()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'offsetGet()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'offsetSet()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'offsetUnset()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Tests\Config\Mock\MacroEntity::class, 'foo()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Tests\Config\Mock\MacroEntity::class, 'setFoo()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'has()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'get()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'set()')]
class EntityArrayAccessTest extends AbstractEntityTestCase
{
use ArrayAccessTestTrait;
@@ -26,8 +34,6 @@ class EntityArrayAccessTest extends AbstractEntityTestCase
/**
* Create a concrete MacroEntity instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -41,9 +47,9 @@ protected function setUp(): void
/**
* Asserts that the object implements ArrayAccess.
*
- * @coversNothing
* @return MacroEntity
*/
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
public function testArrayAccess()
{
$this->assertInstanceOf(ArrayAccess::class, $this->obj);
@@ -54,17 +60,12 @@ public function testArrayAccess()
// Test ArrayAccess on non-private properties
// =========================================================================
-
- /**
- * @covers ::offsetExists()
- * @return void
- */
- public function testOffsetExists()
+ public function testOffsetExists(): void
{
$obj = $this->obj;
// MacroEntity::$name
- $this->assertObjectHasAttribute('name', $obj);
+ $this->assertTrue(property_exists($obj, 'name'));
$this->assertTrue(isset($obj['name']));
// MacroEntity::foo()
@@ -74,11 +75,7 @@ public function testOffsetExists()
$this->assertTrue(isset($obj['erd']));
}
- /**
- * @covers ::offsetGet()
- * @return void
- */
- public function testOffsetGet()
+ public function testOffsetGet(): void
{
$obj = $this->obj;
@@ -92,29 +89,21 @@ public function testOffsetGet()
$this->assertEquals(true, $obj['erd']);
}
- /**
- * @covers ::offsetSet()
- * @return void
- */
- public function testOffsetSet()
+ public function testOffsetSet(): void
{
$obj = $this->obj;
$obj['baz'] = 'waldo';
- $this->assertObjectHasAttribute('baz', $obj);
+ $this->assertTrue(property_exists($obj, 'baz'));
$this->assertEquals('waldo', $obj['baz']);
}
- /**
- * @covers ::offsetUnset()
- * @return void
- */
- public function testOffsetUnset()
+ public function testOffsetUnset(): void
{
$obj = $this->obj;
unset($obj['name']);
- $this->assertObjectHasAttribute('name', $obj);
+ $this->assertTrue(property_exists($obj, 'name'));
$this->assertNull($obj['name']);
}
@@ -122,38 +111,22 @@ public function testOffsetUnset()
// Test ArrayAccess on encapsulated properties
// =========================================================================
-
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroEntity::foo()
- * @covers ::offsetExists()
- * @return void
- */
- public function testOffsetExistsOnEncapsulatedMethod()
+ public function testOffsetExistsOnEncapsulatedMethod(): void
{
$obj = $this->obj;
- $this->assertObjectHasAttribute('foo', $obj);
+ $this->assertTrue(property_exists($obj, 'foo'));
$this->assertTrue(isset($obj['foo']));
}
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroEntity::foo()
- * @covers ::offsetGet()
- * @return void
- */
- public function testOffsetGetOnEncapsulatedMethod()
+ public function testOffsetGetOnEncapsulatedMethod(): void
{
$obj = $this->obj;
$this->assertEquals('foo is 20', $obj['foo']);
}
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroEntity::setFoo()
- * @covers ::offsetSet()
- * @return void
- */
- public function testOffsetSetOnEncapsulatedMethod()
+ public function testOffsetSetOnEncapsulatedMethod(): void
{
$obj = $this->obj;
@@ -161,17 +134,12 @@ public function testOffsetSetOnEncapsulatedMethod()
$this->assertEquals('foo is 42', $obj['foo']);
}
- /**
- * @covers \Charcoal\Tests\Config\Mock\MacroEntity::setFoo()
- * @covers ::offsetUnset()
- * @return void
- */
- public function testOffsetUnsetOnEncapsulatedMethod()
+ public function testOffsetUnsetOnEncapsulatedMethod(): void
{
$obj = $this->obj;
unset($obj['foo']);
- $this->assertObjectHasAttribute('foo', $obj);
+ $this->assertTrue(property_exists($obj, 'foo'));
$this->assertEquals('foo is 10', $obj['foo']);
}
@@ -179,44 +147,31 @@ public function testOffsetUnsetOnEncapsulatedMethod()
// Test ArrayAccess via aliases
// =========================================================================
-
- /**
- * @covers ::has()
- * @return void
- */
- public function testHas()
+ public function testHas(): void
{
$obj = $this->obj;
- $this->assertObjectHasAttribute('name', $obj);
+ $this->assertTrue(property_exists($obj, 'name'));
$this->assertTrue($obj->has('name'));
unset($obj['name']);
$this->assertFalse($obj->has('name'));
}
- /**
- * @covers ::get()
- * @return void
- */
- public function testGet()
+ public function testGet(): void
{
$obj = $this->obj;
$this->assertEquals('Charcoal', $obj->get('name'));
}
- /**
- * @covers ::set()
- * @return void
- */
- public function testSet()
+ public function testSet(): void
{
$obj = $this->obj;
$that = $obj->set('baz', 'waldo');
$this->assertEquals($obj, $that);
- $this->assertObjectHasAttribute('baz', $obj);
+ $this->assertTrue(property_exists($obj, 'baz'));
$this->assertEquals('waldo', $obj->get('baz'));
}
}
diff --git a/packages/config/tests/Charcoal/Config/Entity/EntityTest.php b/packages/config/tests/Charcoal/Config/Entity/EntityTest.php
index 4f381c79d..5fdfeabe2 100644
--- a/packages/config/tests/Charcoal/Config/Entity/EntityTest.php
+++ b/packages/config/tests/Charcoal/Config/Entity/EntityTest.php
@@ -10,9 +10,17 @@
/**
* Test AbstractEntity
- *
- * @coversDefaultClass \Charcoal\Config\AbstractEntity
*/
+#[\PHPUnit\Framework\Attributes\CoversClass(\Charcoal\Config\AbstractEntity::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'keys()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'setData()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'data()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'offsetSet()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'offsetGet()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'camelize()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'jsonSerialize()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'serialize()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\AbstractEntity::class, 'unserialize()')]
class EntityTest extends AbstractEntityTestCase
{
use AssertionsTrait;
@@ -24,8 +32,6 @@ class EntityTest extends AbstractEntityTestCase
/**
* Create a concrete MacroEntity instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -39,11 +45,8 @@ protected function setUp(): void
* - Keys are empty by default
* - Keys are added automatically when setting a value via {@see ArrayAccess::offsetSet()}
* - Keys are removed automatically when unsetting a value via {@see ArrayAccess::offsetUnset()}
- *
- * @covers ::keys()
- * @return void
*/
- public function testKeys()
+ public function testKeys(): void
{
$obj = $this->obj;
@@ -64,15 +67,13 @@ public function testKeys()
// Test Data Methods
// =========================================================================
-
/**
* Retrieve data for {@see AbstractEntity::setData()}.
*
* @used-by self::testSetData()
* @used-by self::testGetDataSubset()
- * @return array
*/
- public function getSetData()
+ public function getSetData(): array
{
return [
'name' => 'Charcoal',
@@ -96,12 +97,8 @@ public function getSetData()
* - When assigning data, the entity will ignore the key "data"
* to prevent recursion calls.
* - The key-value pair "foo" will be passed to {@see MacroEntity::setFoo()}
- *
- * @covers ::setData()
- * @covers ::data()
- * @return void
*/
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
@@ -129,11 +126,8 @@ public function testSetData()
* - The entity will ignore "data" to prevent recursion calls
* - The entity will accept "name", "type", "foo", "baz"
* - The entity will pass "foo" to {@see MacroEntity::setFoo()}
- *
- * @covers ::data()
- * @return void
*/
- public function testGetDataSubset()
+ public function testGetDataSubset(): void
{
$obj = $this->obj;
@@ -150,14 +144,8 @@ public function testGetDataSubset()
/**
* Test {@see AbstractEntity::setData()} via {@see \ArrayAccess::offsetSet()}.
- *
- * @covers ::offsetSet()
- * @covers ::offsetGet()
- * @covers ::setData()
- * @covers ::data()
- * @return void
*/
- public function testSetDataViaArrayAccess()
+ public function testSetDataViaArrayAccess(): void
{
$obj = $this->obj;
@@ -177,7 +165,6 @@ public function testSetDataViaArrayAccess()
// Test Internals
// =========================================================================
-
/**
* Test camelization of entity keys.
*
@@ -185,16 +172,13 @@ public function testSetDataViaArrayAccess()
* - Keys are interchangeable between "snake_case" and "camelCase"
* - Keys are converted to "camelCase" for method calls or property assignments
* - Keys are memorized as "camelCase"
- *
- * @covers ::camelize()
- * @return void
*/
- public function testCamelize()
+ public function testCamelize(): void
{
$obj = $this->obj;
$obj->set('foo_bar', 'waldo');
- $this->assertObjectHasAttribute('fooBar', $obj);
+ $this->assertTrue(property_exists($obj, 'fooBar'));
$this->assertEquals('waldo', $obj['fooBar']);
$this->assertEquals('waldo', $obj['foo___bar']);
$this->assertArrayContains([ 'fooBar' ], $obj->keys());
@@ -206,11 +190,8 @@ public function testCamelize()
* Assertions:
* 1. Serialization from default state
* 2. Serialization from mutated state
- *
- * @covers ::jsonSerialize()
- * @return void
*/
- public function testJsonSerializable()
+ public function testJsonSerializable(): void
{
$obj = $this->obj;
@@ -237,18 +218,14 @@ public function testJsonSerializable()
* Assertions:
* 1. Serialization from default state
* 2. Serialization from mutated state
- *
- * @covers ::serialize()
- * @covers ::unserialize()
- * @return void
*/
- public function testSerializable()
+ public function testSerializable(): void
{
$obj = $this->obj;
/** 1. Serialization from default state */
$that = unserialize(serialize($obj));
- $this->assertInstanceOf(get_class($obj), $that);
+ $this->assertInstanceOf($obj::class, $that);
$this->assertEquals($obj, $that);
$this->assertEmpty($that->data());
@@ -258,7 +235,7 @@ public function testSerializable()
];
$obj->setData($mutation);
$that = unserialize(serialize($obj));
- $this->assertInstanceOf(get_class($obj), $that);
+ $this->assertInstanceOf($obj::class, $that);
$this->assertEquals($obj->data(), $that->data());
$this->assertEquals('Charcoal', $that['name']);
}
diff --git a/packages/config/tests/Charcoal/Config/Fixture/fail/exception.php b/packages/config/tests/Charcoal/Config/Fixture/fail/exception.php
index c3a551b6d..fcba7eb8a 100644
--- a/packages/config/tests/Charcoal/Config/Fixture/fail/exception.php
+++ b/packages/config/tests/Charcoal/Config/Fixture/fail/exception.php
@@ -1,3 +1,5 @@
'localhost',
'port' => 11211,
diff --git a/packages/config/tests/Charcoal/Config/Mixin/ArrayAccessTestTrait.php b/packages/config/tests/Charcoal/Config/Mixin/ArrayAccessTestTrait.php
index c52a67c77..e7dadadc7 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/ArrayAccessTestTrait.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/ArrayAccessTestTrait.php
@@ -15,9 +15,9 @@ trait ArrayAccessTestTrait
/**
* Asserts that the object implements ArrayAccess.
*
- * @coversNothing
* @return ArrayAccess The ArrayAccess implementation to test.
*/
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
abstract public function testArrayAccess();
/**
@@ -48,27 +48,24 @@ abstract public function testOffsetUnset();
// Test Nonexistent Key
// =========================================================================
-
/**
* @covers ::offsetGet()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetGetReturnsNullOnNonexistentKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetGetReturnsNullOnNonexistentKey(ArrayAccess $obj): void
{
$this->assertNull($obj['xyz']);
}
/**
* @covers ::offsetExists()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetExistsReturnsFalseOnNonexistentKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetExistsReturnsFalseOnNonexistentKey(ArrayAccess $obj): void
{
$this->assertFalse(isset($obj['xyz']));
}
@@ -77,39 +74,35 @@ public function testOffsetExistsReturnsFalseOnNonexistentKey(ArrayAccess $obj)
// Test Zero-Length Key
// =========================================================================
-
/**
* @covers ::offsetGet()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetGetReturnsNullOnZeroLengthKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetGetReturnsNullOnZeroLengthKey(ArrayAccess $obj): void
{
$this->assertNull($obj['']);
}
/**
* @covers ::offsetExists()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetExistsReturnsFalseOnZeroLengthKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetExistsReturnsFalseOnZeroLengthKey(ArrayAccess $obj): void
{
$this->assertFalse(isset($obj['']));
}
/**
* @covers ::offsetSet()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetSetIgnoredOnZeroLengthKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetSetIgnoredOnZeroLengthKey(ArrayAccess $obj): void
{
$obj[''] = 'waldo';
$this->assertNull($obj['']);
@@ -117,12 +110,11 @@ public function testOffsetSetIgnoredOnZeroLengthKey(ArrayAccess $obj)
/**
* @covers ::offsetUnset()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetUnsetIgnoredOnZeroLengthKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetUnsetIgnoredOnZeroLengthKey(ArrayAccess $obj): void
{
unset($obj['']);
$this->assertNull($obj['']);
@@ -132,39 +124,35 @@ public function testOffsetUnsetIgnoredOnZeroLengthKey(ArrayAccess $obj)
// Test Snake-Case Delimiter Key
// =========================================================================
-
/**
* @covers ::offsetGet()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetGetReturnsNullOnUnderscoreKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetGetReturnsNullOnUnderscoreKey(ArrayAccess $obj): void
{
$this->assertNull($obj['_']);
}
/**
* @covers ::offsetExists()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetExistsReturnsFalseOnUnderscoreKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetExistsReturnsFalseOnUnderscoreKey(ArrayAccess $obj): void
{
$this->assertFalse(isset($obj['_']));
}
/**
* @covers ::offsetSet()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetSetIgnoredOnUnderscoreKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetSetIgnoredOnUnderscoreKey(ArrayAccess $obj): void
{
$obj['_'] = 'waldo';
$this->assertNull($obj['_']);
@@ -172,12 +160,11 @@ public function testOffsetSetIgnoredOnUnderscoreKey(ArrayAccess $obj)
/**
* @covers ::offsetUnset()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetUnsetIgnoredOnUnderscoreKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetUnsetIgnoredOnUnderscoreKey(ArrayAccess $obj): void
{
unset($obj['']);
$this->assertNull($obj['_']);
@@ -186,17 +173,15 @@ public function testOffsetUnsetIgnoredOnUnderscoreKey(ArrayAccess $obj)
// Test Numeric Key
// =========================================================================
-
/**
* Asserts that a numeric key throws an exception, when retrieving a value.
*
* @covers ::offsetGet()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetGetThrowsExceptionOnNumericKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetGetThrowsExceptionOnNumericKey(ArrayAccess $obj): void
{
$this->expectException(InvalidArgumentException::class);
$obj[0];
@@ -206,12 +191,11 @@ public function testOffsetGetThrowsExceptionOnNumericKey(ArrayAccess $obj)
* Asserts that a numeric key throws an exception, when assigning a value.
*
* @covers ::offsetSet()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetSetThrowsExceptionOnNumericKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetSetThrowsExceptionOnNumericKey(ArrayAccess $obj): void
{
$this->expectException(InvalidArgumentException::class);
$obj[0] = 'waldo';
@@ -221,27 +205,25 @@ public function testOffsetSetThrowsExceptionOnNumericKey(ArrayAccess $obj)
* Asserts that a numeric key throws an exception, when looking up if a key/value exists.
*
* @covers ::offsetExists()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetExistsThrowsExceptionOnNumericKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetExistsThrowsExceptionOnNumericKey(ArrayAccess $obj): void
{
$this->expectException(InvalidArgumentException::class);
- isset($obj[0]);
+ $obj[0];
}
/**
* Asserts that a numeric key throws an exception, when deleting a key/value.
*
* @covers ::offsetUnset()
- * @depends testArrayAccess
*
* @param ArrayAccess $obj The ArrayAccess implementation to test.
- * @return void
*/
- public function testOffsetUnsetThrowsExceptionOnNumericKey(ArrayAccess $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testArrayAccess')]
+ public function testOffsetUnsetThrowsExceptionOnNumericKey(ArrayAccess $obj): void
{
$this->expectException(InvalidArgumentException::class);
unset($obj[0]);
diff --git a/packages/config/tests/Charcoal/Config/Mixin/ConfigurableTest.php b/packages/config/tests/Charcoal/Config/Mixin/ConfigurableTest.php
index 66abc36fd..d00c78ae5 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/ConfigurableTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/ConfigurableTest.php
@@ -15,9 +15,11 @@
/**
* Test ConfigurableTrait
- *
- * @coversDefaultClass \Charcoal\Config\ConfigurableTrait
*/
+#[\PHPUnit\Framework\Attributes\CoversTrait(\Charcoal\Config\ConfigurableTrait::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\ConfigurableTrait::class, 'createConfig()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\ConfigurableTrait::class, 'setConfig()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\ConfigurableTrait::class, 'config()')]
class ConfigurableTest extends AbstractTestCase
{
use AssertionsTrait;
@@ -40,8 +42,6 @@ class ConfigurableTest extends AbstractTestCase
/**
* Create a ConfigurableObject instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -58,10 +58,8 @@ protected function setUp(): void
/**
* Create a ConfigurableObject instance.
- *
- * @return ConfigurableObject
*/
- public function createObject()
+ public function createObject(): \Charcoal\Tests\Config\Mock\ConfigurableObject
{
return new ConfigurableObject();
}
@@ -71,20 +69,17 @@ public function createObject()
*
* @param mixed $data Data to pre-populate the object.
* @param array $delegates Delegates to pre-populate the object.
- * @return GenericConfig
*/
- public function createConfig($data = null, array $delegates = null)
+ public function createConfig($data = null, ?array $delegates = null): \Charcoal\Config\GenericConfig
{
return new GenericConfig($data, $delegates);
}
/**
* Asserts that the object implements ConfigurableInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testConfigurableInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testConfigurableInterface(): void
{
$this->assertInstanceOf(ConfigurableInterface::class, $this->obj);
$this->assertInstanceOf(ConfigInterface::class, $this->obj->createConfig());
@@ -93,13 +88,7 @@ public function testConfigurableInterface()
// Test SetConfig
// =========================================================================
-
- /**
- * @covers ::createConfig()
- * @covers ::setConfig()
- * @return void
- */
- public function testSetConfigWithString()
+ public function testSetConfigWithString(): void
{
$path = $this->getPathToFixture('pass/valid.json');
$that = $this->obj->setConfig($path);
@@ -111,8 +100,6 @@ public function testSetConfigWithString()
}
/**
- * @covers ::createConfig()
- * @covers ::setConfig()
* @return ConfigurableInterface
*/
public function testSetConfigWithArray()
@@ -126,12 +113,7 @@ public function testSetConfigWithArray()
return $this->obj;
}
- /**
- * @covers ::createConfig()
- * @covers ::setConfig()
- * @return void
- */
- public function testSetConfigWithConfigInstance()
+ public function testSetConfigWithConfigInstance(): void
{
$this->obj->setConfig($this->cfg);
@@ -140,11 +122,7 @@ public function testSetConfigWithConfigInstance()
$this->assertArraySubsets($this->data, $cfg->data());
}
- /**
- * @covers ::setConfig()
- * @return void
- */
- public function testSetConfigWithInvalidData()
+ public function testSetConfigWithInvalidData(): void
{
$this->expectExceptionMessage('Configset must be an associative array, a file path, or an instance of Charcoal\Config\ConfigInterface');
$this->expectException(InvalidArgumentException::class);
@@ -157,107 +135,79 @@ public function testSetConfigWithInvalidData()
// Test GetConfig
// =========================================================================
-
/**
* Asserts that the object will create a new Config
* if one has not been assigned to object.
- *
- * @covers ::createConfig()
- * @covers ::config()
- * @return void
*/
- public function testGetConfigCreatesConfig()
+ public function testGetConfigCreatesConfig(): void
{
$cfg = $this->obj->config();
$this->assertInstanceOf(GenericConfig::class, $cfg);
}
/**
- * @covers ::config()
- * @depends testSetConfigWithArray
- *
* @param ConfigurableInterface $obj The ConfigurableInterface implementation to test.
- * @return void
*/
- public function testGetConfigReturnsConfigOnNullKey(ConfigurableInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetConfigWithArray')]
+ public function testGetConfigReturnsConfigOnNullKey(ConfigurableInterface $obj): void
{
- $cfg = $obj->config(null);
+ $cfg = $obj->config();
$this->assertInstanceOf(GenericConfig::class, $cfg);
}
/**
- * @covers ::config()
- * @depends testSetConfigWithArray
- *
* @param ConfigurableInterface $obj The ConfigurableInterface implementation to test.
- * @return void
*/
- public function testGetConfigReturnsValueOnKey(ConfigurableInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetConfigWithArray')]
+ public function testGetConfigReturnsValueOnKey(ConfigurableInterface $obj): void
{
$this->assertEquals($this->data['name'], $obj->config('name'));
}
/**
- * @covers ::config()
- * @depends testSetConfigWithArray
- *
* @param ConfigurableInterface $obj The ConfigurableInterface implementation to test.
- * @return void
*/
- public function testGetConfigReturnsNullOnNonexistentKey(ConfigurableInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetConfigWithArray')]
+ public function testGetConfigReturnsNullOnNonexistentKey(ConfigurableInterface $obj): void
{
$this->assertNull($obj->config('charset'));
}
/**
- * @covers ::config()
- * @depends testSetConfigWithArray
- *
* @param ConfigurableInterface $obj The ConfigurableInterface implementation to test.
- * @return void
*/
- public function testGetConfigReturnsDefaultValueOnNonexistentKey(ConfigurableInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetConfigWithArray')]
+ public function testGetConfigReturnsDefaultValueOnNonexistentKey(ConfigurableInterface $obj): void
{
$val = $obj->config('charset', 'utf8mb4');
$this->assertEquals('utf8mb4', $val);
}
/**
- * @covers ::config()
- * @depends testSetConfigWithArray
- *
* @param ConfigurableInterface $obj The ConfigurableInterface implementation to test.
- * @return void
*/
- public function testGetConfigReturnsFallbackClosureOnNonexistentKey(ConfigurableInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetConfigWithArray')]
+ public function testGetConfigReturnsFallbackClosureOnNonexistentKey(ConfigurableInterface $obj): void
{
- $val = $obj->config('charset', function () {
- return 'utf8mb4';
- });
+ $val = $obj->config('charset', fn(): string => 'utf8mb4');
$this->assertEquals('utf8mb4', $val);
}
/**
- * @covers ::config()
- * @depends testSetConfigWithArray
- *
* @param ConfigurableInterface $obj The ConfigurableInterface implementation to test.
- * @return void
*/
- public function testGetConfigReturnsFallbackMethodOnNonexistentKey(ConfigurableInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetConfigWithArray')]
+ public function testGetConfigReturnsFallbackMethodOnNonexistentKey(ConfigurableInterface $obj): void
{
- $val = $obj->config('charset', [ $this, 'getName' ]);
+ $val = $obj->config('charset', [ $this, 'name' ]);
$this->assertEquals('testGetConfigReturnsFallbackMethodOnNonexistentKey', $val);
}
/**
- * @covers ::config()
- * @depends testSetConfigWithArray
- *
* @param ConfigurableInterface $obj The ConfigurableInterface implementation to test.
- * @return void
*/
- public function testGetConfigReturnsFallbackFunctionOnNonexistentKey(ConfigurableInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetConfigWithArray')]
+ public function testGetConfigReturnsFallbackFunctionOnNonexistentKey(ConfigurableInterface $obj): void
{
$val = $obj->config('charset', 'getcwd');
$this->assertEquals('getcwd', $val);
diff --git a/packages/config/tests/Charcoal/Config/Mixin/DelegatesAwareTest.php b/packages/config/tests/Charcoal/Config/Mixin/DelegatesAwareTest.php
index 47ea0704a..af17c6939 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/DelegatesAwareTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/DelegatesAwareTest.php
@@ -11,9 +11,13 @@
/**
* Test DelegatesAwareTrait
- *
- * @coversDefaultClass \Charcoal\Config\DelegatesAwareTrait
*/
+#[\PHPUnit\Framework\Attributes\CoversTrait(\Charcoal\Config\DelegatesAwareTrait::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\DelegatesAwareTrait::class, 'setDelegates()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\DelegatesAwareTrait::class, 'addDelegate()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\DelegatesAwareTrait::class, 'prependDelegate()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\DelegatesAwareTrait::class, 'hasInDelegates()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\DelegatesAwareTrait::class, 'getInDelegates()')]
class DelegatesAwareTest extends AbstractTestCase
{
/**
@@ -28,8 +32,6 @@ class DelegatesAwareTest extends AbstractTestCase
/**
* Create a DelegateEntity instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -72,20 +74,17 @@ protected function setUp(): void
* Create a DelegateEntity instance.
*
* @param array $data Data to pre-populate the object.
- * @return DelegateEntity
*/
- public function createObject(array $data = null)
+ public function createObject(?array $data = null): \Charcoal\Tests\Config\Mock\DelegateEntity
{
return new DelegateEntity($data);
}
/**
* Asserts that the object implements DelegatesAwareInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testDelegatesAwareInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testDelegatesAwareInterface(): void
{
$this->assertInstanceOf(DelegatesAwareInterface::class, $this->obj);
}
@@ -94,25 +93,16 @@ public function testDelegatesAwareInterface()
// Test Delegate Collecting
// =========================================================================
-
/**
* Asserts that the separator is disabled by default.
- *
- * @coversNothing
- * @return void
*/
- public function testDefaultDelegatesCollection()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testDefaultDelegatesCollection(): void
{
$this->assertEmpty($this->obj->delegates());
}
- /**
- * @covers ::setDelegates()
- * @covers ::addDelegate()
- * @covers ::prependDelegate()
- * @return void
- */
- public function testSetDelegates()
+ public function testSetDelegates(): void
{
$obj = $this->obj;
@@ -134,10 +124,10 @@ public function testSetDelegates()
}
/**
- * @coversNothing
- * @doesNotPerformAssertions
* @return DelegateEntity
*/
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ #[\PHPUnit\Framework\Attributes\DoesNotPerformAssertions]
public function testSetNestedDelegates()
{
$this->delegates[4]->addDelegate($this->delegates[2]);
@@ -155,28 +145,22 @@ public function testSetNestedDelegates()
// Test HasInDelegates
// =========================================================================
-
/**
- * @covers ::hasInDelegates()
- * @depends testSetNestedDelegates
*
* @see self::$delegates[1]['bubble']
* @param DelegatesAwareInterface $obj The DelegatesAwareInterface implementation to test.
- * @return void
*/
- public function testHasInDelegatesReturnsTrueOnDelegatedKey(DelegatesAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetNestedDelegates')]
+ public function testHasInDelegatesReturnsTrueOnDelegatedKey(DelegatesAwareInterface $obj): void
{
$this->assertTrue($obj->hasInDelegates('bubble'));
}
/**
- * @covers ::hasInDelegates()
- * @depends testSetNestedDelegates
- *
* @param DelegatesAwareInterface $obj The DelegatesAwareInterface implementation to test.
- * @return void
*/
- public function testHasInDelegatesReturnsFalseOnNonexistentKey(DelegatesAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetNestedDelegates')]
+ public function testHasInDelegatesReturnsFalseOnNonexistentKey(DelegatesAwareInterface $obj): void
{
$this->assertFalse($obj->hasInDelegates('use_error_handler'));
}
@@ -186,16 +170,13 @@ public function testHasInDelegatesReturnsFalseOnNonexistentKey(DelegatesAwareInt
// Test GetInDelegates
// =========================================================================
-
/**
- * @covers ::getInDelegates()
- * @depends testSetNestedDelegates
*
* @see self::$delegates[2]['level']
* @param DelegatesAwareInterface $obj The DelegatesAwareInterface implementation to test.
- * @return void
*/
- public function testGetInDelegatesReturnsValueOnDelegatedKey(DelegatesAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetNestedDelegates')]
+ public function testGetInDelegatesReturnsValueOnDelegatedKey(DelegatesAwareInterface $obj): void
{
$this->assertEquals(
$this->delegates[2]['level'],
@@ -204,13 +185,10 @@ public function testGetInDelegatesReturnsValueOnDelegatedKey(DelegatesAwareInter
}
/**
- * @covers ::getInDelegates()
- * @depends testSetNestedDelegates
- *
* @param DelegatesAwareInterface $obj The DelegatesAwareInterface implementation to test.
- * @return void
*/
- public function testGetInDelegatesReturnsNullOnNonexistentKey(DelegatesAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetNestedDelegates')]
+ public function testGetInDelegatesReturnsNullOnNonexistentKey(DelegatesAwareInterface $obj): void
{
$this->assertNull($obj->getInDelegates('use_error_handler'));
}
diff --git a/packages/config/tests/Charcoal/Config/Mixin/FileAwareTest.php b/packages/config/tests/Charcoal/Config/Mixin/FileAwareTest.php
index a943300fa..196bd2e02 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/FileAwareTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/FileAwareTest.php
@@ -10,58 +10,44 @@
/**
* Test FileAwareTrait
- *
- * @coversDefaultClass \Charcoal\Config\FileAwareTrait
*/
+#[\PHPUnit\Framework\Attributes\CoversTrait(\Charcoal\Config\FileAwareTrait::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\FileAwareTrait::class, 'loadFile()')]
class FileAwareTest extends AbstractFileLoaderTestCase
{
/**
* Asserts that the object implements FileAwareInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testFileAwareInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testFileAwareInterface(): void
{
$this->assertInstanceOf(FileAwareInterface::class, $this->obj);
}
- /**
- * @covers ::loadFile()
- * @return void
- */
- public function testLoadWithUnsupportedFormat()
+ public function testLoadWithUnsupportedFormat(): void
{
$this->expectExceptionMessageMatches('/^Unsupported file format for ".+?"; must be one of ".+?"$/');
$this->expectException(InvalidArgumentException::class);
$path = $this->getPathToFixture('fail/unsupported.txt');
- $data = $this->obj->loadFile($path);
+ $this->obj->loadFile($path);
}
- /**
- * @covers ::loadFile()
- * @return void
- */
- public function testLoadWithInvalidPath()
+ public function testLoadWithInvalidPath(): void
{
$this->expectExceptionMessageMatches('/^File ".+?" does not exist$/');
$this->expectException(InvalidArgumentException::class);
$path = $this->getPathToFixture('fail/missing.ini');
- $data = $this->obj->loadFile($path);
+ $this->obj->loadFile($path);
}
- /**
- * @covers ::loadFile()
- * @return void
- */
- public function testLoadWithInvalidType()
+ public function testLoadWithInvalidType(): void
{
$this->expectExceptionMessage('File must be a string');
$this->expectException(InvalidArgumentException::class);
$path = null;
- $data = $this->obj->loadFile($path);
+ $this->obj->loadFile($path);
}
}
diff --git a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/AbstractFileLoaderTestCase.php b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/AbstractFileLoaderTestCase.php
index 57953c525..6ac87a944 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/AbstractFileLoaderTestCase.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/AbstractFileLoaderTestCase.php
@@ -21,8 +21,6 @@ abstract class AbstractFileLoaderTestCase extends AbstractTestCase
/**
* Create a FileLoader instance.
- *
- * @return void
*/
protected function setUp(): void
{
diff --git a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/IniFileLoaderTest.php b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/IniFileLoaderTest.php
index 37406e840..f189a37d8 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/IniFileLoaderTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/IniFileLoaderTest.php
@@ -1,5 +1,7 @@
getPathToFixture('pass/valid1.ini');
$data = $this->obj->loadFile($path);
@@ -42,10 +41,8 @@ public function testLoadFile()
* Asserts that the File Loader does NOT support key-paths in INI config files.
*
* @see \Charcoal\Tests\Config\Config\ConfigFileAwareTest::testLoadIniFileWithDelimitedData
- * @covers ::loadIniFile()
- * @return void
*/
- public function testLoadFileWithDelimitedData()
+ public function testLoadFileWithDelimitedData(): void
{
$path = $this->getPathToFixture('pass/valid2.ini');
$data = $this->obj->loadFile($path);
@@ -64,11 +61,8 @@ public function testLoadFileWithDelimitedData()
/**
* Asserts that an empty file is silently ignored.
- *
- * @covers ::loadIniFile()
- * @return void
*/
- public function testLoadEmptyFile()
+ public function testLoadEmptyFile(): void
{
$path = $this->getPathToFixture('pass/empty.ini');
$data = $this->obj->loadFile($path);
@@ -78,28 +72,22 @@ public function testLoadEmptyFile()
/**
* Asserts that a broken file is NOT ignored.
- *
- * @covers ::loadIniFile()
- * @return void
*/
- public function testLoadMalformedFile()
+ public function testLoadMalformedFile(): void
{
$this->expectExceptionMessageMatches('/^INI file ".+?" is empty or invalid$/');
$this->expectException(UnexpectedValueException::class);
// phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
$path = $this->getPathToFixture('fail/malformed.ini');
- $data = @$this->obj->loadFile($path);
+ @$this->obj->loadFile($path);
// phpcs:enable
}
/**
* Asserts that an unparsable file is silently ignored.
- *
- * @covers ::loadIniFile()
- * @return void
*/
- public function testLoadUnparsableFile()
+ public function testLoadUnparsableFile(): void
{
// phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
$path = $this->getPathToFixture('pass/unparsable.ini');
diff --git a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/JsonFileLoaderTest.php b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/JsonFileLoaderTest.php
index 3443b4699..2376d8f71 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/JsonFileLoaderTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/JsonFileLoaderTest.php
@@ -1,5 +1,7 @@
getPathToFixture('pass/valid.json');
$data = $this->obj->loadFile($path);
@@ -40,11 +39,8 @@ public function testLoadFile()
/**
* Asserts that an empty file is silently ignored.
- *
- * @covers ::loadJsonFile()
- * @return void
*/
- public function testLoadEmptyFile()
+ public function testLoadEmptyFile(): void
{
$path = $this->getPathToFixture('pass/empty.json');
$data = $this->obj->loadFile($path);
@@ -54,18 +50,15 @@ public function testLoadEmptyFile()
/**
* Asserts that a broken file is NOT ignored.
- *
- * @covers ::loadJsonFile()
- * @return void
*/
- public function testLoadMalformedFile()
+ public function testLoadMalformedFile(): void
{
$this->expectExceptionMessageMatches('/^JSON file ".+?" could not be parsed: .+$/');
$this->expectException(UnexpectedValueException::class);
// phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
$path = $this->getPathToFixture('fail/malformed.json');
- $data = @$this->obj->loadFile($path);
+ @$this->obj->loadFile($path);
// phpcs:enable
}
}
diff --git a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/PhpFileLoaderTest.php b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/PhpFileLoaderTest.php
index 0dd110db7..499a7fe35 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/PhpFileLoaderTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/PhpFileLoaderTest.php
@@ -1,5 +1,7 @@
getPathToFixture('pass/valid1.php');
$data = $this->obj->loadFile($path);
@@ -40,11 +39,8 @@ public function testLoadFile()
/**
* Asserts that the scope of PHP config files is bound to the File Loader.
- *
- * @covers ::loadPhpFile()
- * @return void
*/
- public function testLoadFileThatMutatesContext()
+ public function testLoadFileThatMutatesContext(): void
{
$path = $this->getPathToFixture('pass/valid3.php');
$data = $this->obj->loadFile($path);
@@ -55,11 +51,8 @@ public function testLoadFileThatMutatesContext()
/**
* Asserts that an empty file is silently ignored.
- *
- * @covers ::loadPhpFile()
- * @return void
*/
- public function testLoadEmptyFile()
+ public function testLoadEmptyFile(): void
{
$path = $this->getPathToFixture('pass/empty.php');
$data = $this->obj->loadFile($path);
@@ -69,34 +62,28 @@ public function testLoadEmptyFile()
/**
* Asserts that a broken file is NOT ignored.
- *
- * @requires PHP >= 7.0
- * @covers ::loadPhpFile()
- * @return void
*/
- public function testLoadMalformedFileInPhp7()
+ #[\PHPUnit\Framework\Attributes\RequiresPhp('>=8.1.0')]
+ public function testLoadMalformedFile(): void
{
$this->expectExceptionMessageMatches('/^PHP file ".+?" could not be parsed: .+$/');
$this->expectException(UnexpectedValueException::class);
// phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
$path = $this->getPathToFixture('fail/malformed.php');
- $data = $this->obj->loadFile($path);
+ $this->obj->loadFile($path);
// phpcs:enable
}
/**
* Asserts that an exception thrown within the file is caught.
- *
- * @covers ::loadPhpFile()
- * @return void
*/
- public function testLoadExceptionalFile()
+ public function testLoadExceptionalFile(): void
{
$this->expectExceptionMessageMatches('/^PHP file ".+?" could not be parsed: Thrown Exception$/');
$this->expectException(UnexpectedValueException::class);
$path = $this->getPathToFixture('fail/exception.php');
- $data = $this->obj->loadFile($path);
+ $this->obj->loadFile($path);
}
}
diff --git a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/YamlFileLoaderTest.php b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/YamlFileLoaderTest.php
index 9c7de1d6c..f5083a826 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/FileLoader/YamlFileLoaderTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/FileLoader/YamlFileLoaderTest.php
@@ -12,19 +12,16 @@
/**
* Test {@see FileAwareTrait::loadYamlFile() YAML File Loading}
- *
- * @coversDefaultClass \Charcoal\Config\FileAwareTrait
*/
+#[\PHPUnit\Framework\Attributes\CoversTrait(\Charcoal\Config\FileAwareTrait::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\FileAwareTrait::class, 'loadYamlFile()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\FileAwareTrait::class, 'loadFile()')]
class YamlFileLoaderTest extends AbstractFileLoaderTestCase
{
/**
* Asserts that the File Loader supports '.yml' YAML config files.
- *
- * @covers ::loadYamlFile()
- * @covers ::loadFile()
- * @return void
*/
- public function testLoadFileWithYmlExtension()
+ public function testLoadFileWithYmlExtension(): void
{
$path = $this->getPathToFixture('pass/valid1.yml');
$data = $this->obj->loadFile($path);
@@ -43,12 +40,8 @@ public function testLoadFileWithYmlExtension()
/**
* Asserts that the File Loader supports '.yaml' YAML config files.
- *
- * @covers ::loadYamlFile()
- * @covers ::loadFile()
- * @return void
*/
- public function testLoadFileWithYamlExtension()
+ public function testLoadFileWithYamlExtension(): void
{
$path = $this->getPathToFixture('pass/valid2.yaml');
$data = $this->obj->loadFile($path);
@@ -67,19 +60,15 @@ public function testLoadFileWithYamlExtension()
/**
* Asserts that the File Loader throws an exception if the YAML Parser is unavailable.
- *
- * @runInSeparateProcess
- * @preserveGlobalState disabled
- * @covers ::loadYamlFile()
- * @return void
*/
- public function testLoadFileWithNoYamlParser()
+ #[\PHPUnit\Framework\Attributes\PreserveGlobalState(false)]
+ #[\PHPUnit\Framework\Attributes\RunInSeparateProcess]
+ public function testLoadFileWithNoYamlParser(): void
{
- if (class_exists('Symfony\Component\Yaml\Parser', false)) {
+ if (class_exists(\Symfony\Component\Yaml\Parser::class, false)) {
$this->markTestSkipped(
'The Symfony YAML component was loaded before the test could run'
);
- return;
}
$this->expectExceptionMessage('YAML format requires the Symfony YAML component');
@@ -88,16 +77,13 @@ public function testLoadFileWithNoYamlParser()
$this->disableSymfonyYamlComponent();
$path = $this->getPathToFixture('pass/valid1.yml');
- $data = $this->obj->loadFile($path);
+ $this->obj->loadFile($path);
}
/**
* Asserts that an empty file is silently ignored.
- *
- * @covers ::loadYamlFile()
- * @return void
*/
- public function testLoadEmptyFile()
+ public function testLoadEmptyFile(): void
{
$path = $this->getPathToFixture('pass/empty.yml');
$data = $this->obj->loadFile($path);
@@ -107,25 +93,20 @@ public function testLoadEmptyFile()
/**
* Asserts that a broken file is NOT ignored.
- *
- * @covers ::loadYamlFile()
- * @return void
*/
- public function testLoadMalformedFile()
+ public function testLoadMalformedFile(): void
{
$this->expectExceptionMessageMatches('/^YAML file ".+?" could not be parsed: .+$/');
$this->expectException(UnexpectedValueException::class);
$path = $this->getPathToFixture('pass/malformed.yml');
- $data = $this->obj->loadFile($path);
+ $this->obj->loadFile($path);
}
/**
* Remove the "symfony/yaml" package from Composer's search paths.
- *
- * @return void
*/
- public function disableSymfonyYamlComponent()
+ public function disableSymfonyYamlComponent(): void
{
// phpcs:disable Squiz.PHP.GlobalKeyword.NotAllowed
global $autoloader;
@@ -133,18 +114,16 @@ public function disableSymfonyYamlComponent()
// If PSR-0/4 autoloading was optimized
$classMap = $autoloader->getClassMap();
- if (isset($classMap['Symfony\\Component\\Yaml\\Parser'])) {
+ if (isset($classMap[\Symfony\Component\Yaml\Parser::class])) {
$refClassMap = new ReflectionProperty($autoloader, 'classMap');
- $refClassMap->setAccessible(true);
- unset($classMap['Symfony\\Component\\Yaml\\Parser']);
+ unset($classMap[\Symfony\Component\Yaml\Parser::class]);
$refClassMap->setValue($autoloader, $classMap);
}
$prefixesPsr4 = $autoloader->getPrefixesPsr4();
if (isset($prefixesPsr4['Symfony\\Component\\Yaml\\'])) {
$refPrefixesPsr4 = new ReflectionProperty($autoloader, 'prefixDirsPsr4');
- $refPrefixesPsr4->setAccessible(true);
unset($prefixesPsr4['Symfony\\Component\\Yaml\\']);
$refPrefixesPsr4->setValue($autoloader, $prefixesPsr4);
@@ -153,10 +132,8 @@ public function disableSymfonyYamlComponent()
/**
* Add the "symfony/yaml" package from Composer's search paths.
- *
- * @return void
*/
- public function enableSymfonyYamlComponent()
+ public function enableSymfonyYamlComponent(): void
{
// phpcs:disable Squiz.PHP.GlobalKeyword.NotAllowed
global $autoloader;
@@ -164,27 +141,25 @@ public function enableSymfonyYamlComponent()
// If PSR-0/4 autoloading was optimized
$classMap = $autoloader->getClassMap();
- if (!isset($classMap['Symfony\\Component\\Yaml\\Parser'])) {
+ if (!isset($classMap[\Symfony\Component\Yaml\Parser::class])) {
$refClassMap = new ReflectionProperty($autoloader, 'classMap');
- $refClassMap->setAccessible(true);
$refClassLoader = $refClassMap->getDeclaringClass();
$classLoaderPath = $refClassLoader->getFileName();
- $vendorDir = dirname(dirname($classLoaderPath));
- $prefixesPsr4['Symfony\\Component\\Yaml\\Parser'] = [ $vendorDir.'/symfony/yaml/Parser.php' ];
+ $vendorDir = dirname($classLoaderPath, 2);
+ $prefixesPsr4[\Symfony\Component\Yaml\Parser::class] = [ $vendorDir.'/symfony/yaml/Parser.php' ];
$refClassMap->setValue($autoloader, $prefixesPsr4);
}
$prefixesPsr4 = $autoloader->getPrefixesPsr4();
if (!isset($prefixesPsr4['Symfony\\Component\\Yaml\\'])) {
$refPrefixesPsr4 = new ReflectionProperty($autoloader, 'prefixDirsPsr4');
- $refPrefixesPsr4->setAccessible(true);
$refClassLoader = $refPrefixesPsr4->getDeclaringClass();
$classLoaderPath = $refClassLoader->getFileName();
- $vendorDir = dirname(dirname($classLoaderPath));
+ $vendorDir = dirname($classLoaderPath, 2);
$prefixesPsr4['Symfony\\Component\\Yaml\\'] = [ $vendorDir.'/symfony/yaml' ];
$refPrefixesPsr4->setValue($autoloader, $prefixesPsr4);
}
diff --git a/packages/config/tests/Charcoal/Config/Mixin/SeparatorAwareTest.php b/packages/config/tests/Charcoal/Config/Mixin/SeparatorAwareTest.php
index 5bfce4750..31bf44b82 100644
--- a/packages/config/tests/Charcoal/Config/Mixin/SeparatorAwareTest.php
+++ b/packages/config/tests/Charcoal/Config/Mixin/SeparatorAwareTest.php
@@ -9,12 +9,17 @@
use Charcoal\Config\SeparatorAwareInterface;
use Charcoal\Config\SeparatorAwareTrait;
use InvalidArgumentException;
+use ValueError;
/**
* Test SeparatorAwareTrait
- *
- * @coversDefaultClass \Charcoal\Config\SeparatorAwareTrait
*/
+#[\PHPUnit\Framework\Attributes\CoversTrait(\Charcoal\Config\SeparatorAwareTrait::class)]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\SeparatorAwareTrait::class, 'separator()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\SeparatorAwareTrait::class, 'setSeparator()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\SeparatorAwareTrait::class, 'hasWithSeparator()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\SeparatorAwareTrait::class, 'getWithSeparator()')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Config\SeparatorAwareTrait::class, 'setWithSeparator()')]
class SeparatorAwareTest extends AbstractTestCase
{
use AssertionsTrait;
@@ -31,8 +36,6 @@ class SeparatorAwareTest extends AbstractTestCase
/**
* Create a TreeEntity instance.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -66,20 +69,17 @@ protected function setUp(): void
* Create a TreeEntity instance.
*
* @param array $data Data to pre-populate the object.
- * @return TreeEntity
*/
- public function createObject(array $data = null)
+ public function createObject(?array $data = null): \Charcoal\Tests\Config\Mock\TreeEntity
{
return new TreeEntity($data);
}
/**
* Asserts that the object implements SeparatorAwareInterface.
- *
- * @coversNothing
- * @return void
*/
- public function testSeparatorAwareInterface()
+ #[\PHPUnit\Framework\Attributes\CoversNothing]
+ public function testSeparatorAwareInterface(): void
{
$this->assertInstanceOf(SeparatorAwareInterface::class, $this->obj);
}
@@ -88,21 +88,15 @@ public function testSeparatorAwareInterface()
// Test Seperator Token
// =========================================================================
-
/**
* Asserts that the separator is disabled by default.
- *
- * @covers ::separator()
- * @return void
*/
- public function testDefaultSeparatorIsEmptyString()
+ public function testDefaultSeparatorIsEmptyString(): void
{
$this->assertEmpty($this->obj->separator());
}
/**
- * @covers ::setSeparator()
- * @covers ::separator()
* @return TreeEntity
*/
public function testSetSeparator()
@@ -116,12 +110,7 @@ public function testSetSeparator()
return $obj;
}
- /**
- * @covers ::setSeparator()
- * @covers ::separator()
- * @return void
- */
- public function testMutatedSeparator()
+ public function testMutatedSeparator(): void
{
$obj = $this->obj;
@@ -132,12 +121,7 @@ public function testMutatedSeparator()
);
}
- /**
- * @covers ::setSeparator()
- * @covers ::separator()
- * @return void
- */
- public function testEmptySeparator()
+ public function testEmptySeparator(): void
{
$obj = $this->obj;
@@ -145,11 +129,7 @@ public function testEmptySeparator()
$this->assertEquals('', $obj->separator());
}
- /**
- * @covers ::setSeparator()
- * @return void
- */
- public function testSetSeparatorWithInvalidType()
+ public function testSetSeparatorWithInvalidType(): void
{
$this->expectExceptionMessage('Separator must be a string');
$this->expectException(InvalidArgumentException::class);
@@ -157,11 +137,7 @@ public function testSetSeparatorWithInvalidType()
$this->obj->setSeparator(1);
}
- /**
- * @covers ::setSeparator()
- * @return void
- */
- public function testSetSeparatorWithInvalidToken()
+ public function testSetSeparatorWithInvalidToken(): void
{
$this->expectExceptionMessage('Separator must be one-character, or empty');
$this->expectException(InvalidArgumentException::class);
@@ -173,127 +149,83 @@ public function testSetSeparatorWithInvalidToken()
// Test HasWithSeparator
// =========================================================================
-
/**
- * @covers ::hasWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsTrueOnHasEndKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsTrueOnHasEndKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertTrue($obj->hasWithSeparator('connections.default.driver'));
}
/**
- * @covers ::hasWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsTrueOnHasMidKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsTrueOnHasMidKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertTrue($obj->hasWithSeparator('connections.default'));
}
/**
- * @covers ::hasWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsTrueOnHasBaseKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsTrueOnHasBaseKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertTrue($obj->hasWithSeparator('connections'));
}
/**
- * @covers ::hasWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsFalseOnHasEndKeyPathToNullValue(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsFalseOnHasEndKeyPathToNullValue(SeparatorAwareInterface $obj): void
{
$this->assertFalse($obj->hasWithSeparator('connections.customer.unix_socket'));
}
/**
- * @covers ::hasWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsFalseOnHasNonexistentEndKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsFalseOnHasNonexistentEndKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertFalse($obj->hasWithSeparator('connections.default.server_version'));
}
/**
- * @covers ::hasWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsFalseOnHasNonexistentMidKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsFalseOnHasNonexistentMidKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertFalse($obj->hasWithSeparator('connections.analytics.host'));
}
/**
- * @covers ::hasWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsFalseOnHasNonexistentBaseKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsFalseOnHasNonexistentBaseKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertFalse($obj->hasWithSeparator('logging'));
}
- /**
- * @used-by self::testHasWithSeparatorWithoutDelimiterInPhp7()
- * @used-by self::testHasWithSeparatorWithoutDelimiterInPhp5()
- *
- * @covers ::hasWithSeparator()
- * @return void
- */
- public function delegatedTestHasWithSeparatorWithoutDelimiter()
+ public function testHasWithSeparatorWithoutDelimiter(): void
{
+ $this->expectException(ValueError::class);
$this->obj->hasWithSeparator('connections.default.host');
}
- /**
- * @requires PHP >= 7.0
- * @return void
- */
- public function testHasWithSeparatorWithoutDelimiterInPhp7()
- {
- $this->expectError();
-
- $this->delegatedTestHasWithSeparatorWithoutDelimiter();
- }
-
-
// Test GetWithSeparator
// =========================================================================
-
/**
- * @covers ::getWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsValueOnGetEndKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsValueOnGetEndKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertEquals(
$this->connections['default']['driver'],
@@ -302,13 +234,10 @@ public function testObjReturnsValueOnGetEndKeyPath(SeparatorAwareInterface $obj)
}
/**
- * @covers ::getWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsValueOnGetMidKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsValueOnGetMidKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertEquals(
$this->connections['default'],
@@ -317,13 +246,10 @@ public function testObjReturnsValueOnGetMidKeyPath(SeparatorAwareInterface $obj)
}
/**
- * @covers ::getWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsValueOnGetBaseKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsValueOnGetBaseKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertEquals(
$this->connections,
@@ -332,88 +258,54 @@ public function testObjReturnsValueOnGetBaseKeyPath(SeparatorAwareInterface $obj
}
/**
- * @covers ::getWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsNullOnGetEndKeyPathToNullValue(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsNullOnGetEndKeyPathToNullValue(SeparatorAwareInterface $obj): void
{
$this->assertNull($obj->getWithSeparator('connections.customer.unix_socket'));
}
/**
- * @covers ::getWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsNullOnGetNonexistentEndKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsNullOnGetNonexistentEndKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertNull($obj->getWithSeparator('connections.default.server_version'));
}
/**
- * @covers ::getWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsNullOnGetNonexistentMidKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsNullOnGetNonexistentMidKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertNull($obj->getWithSeparator('connections.analytics.host'));
}
/**
- * @covers ::getWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReturnsNullOnGetNonexistentBaseKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReturnsNullOnGetNonexistentBaseKeyPath(SeparatorAwareInterface $obj): void
{
$this->assertNull($obj->getWithSeparator('logging'));
}
- /**
- * @used-by self::testGetWithSeparatorWithoutDelimiterInPhp7()
- * @used-by self::testGetWithSeparatorWithoutDelimiterInPhp5()
- *
- * @covers ::getWithSeparator()
- * @return void
- */
- public function delegatedTestGetWithSeparatorWithoutDelimiter()
+ public function testGetWithSeparatorWithoutDelimiter(): void
{
+ $this->expectException(ValueError::class);
$this->obj->getWithSeparator('connections.default.host');
}
- /**
- * @requires PHP >= 7.0
- * @return void
- */
- public function testGetWithSeparatorWithoutDelimiterInPhp7()
- {
- $this->expectError();
-
- $this->delegatedTestGetWithSeparatorWithoutDelimiter();
- }
-
-
// Test SetWithSeparator
// =========================================================================
-
/**
- * @covers ::setWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReplacesValueRecursivelyOnSetKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReplacesValueRecursivelyOnSetKeyPath(SeparatorAwareInterface $obj): void
{
$obj->setWithSeparator('keywords', [ 'php', 'framework', 'charcoal', 'config' ]);
$obj->setWithSeparator('keywords', [ 1 => 'library', 4 => 'component' ]);
@@ -430,78 +322,60 @@ public function testObjReplacesValueRecursivelyOnSetKeyPath(SeparatorAwareInterf
}
/**
- * @covers ::setWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReplacesValueOnSetEndKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReplacesValueOnSetEndKeyPath(SeparatorAwareInterface $obj): void
{
$obj->setWithSeparator('connections.default.driver', 'pdo_sqlite');
$this->assertEquals('pdo_sqlite', $obj->get('connections.default.driver'));
}
/**
- * @covers ::setWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReplacesValueOnSetMidKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReplacesValueOnSetMidKeyPath(SeparatorAwareInterface $obj): void
{
$obj->setWithSeparator('connections.default', [ 'dbname' => 'otherdatabase' ]);
$this->assertEquals('otherdatabase', $obj->get('connections.default.dbname'));
}
/**
- * @covers ::setWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjReplacesValueOnSetBaseKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjReplacesValueOnSetBaseKeyPath(SeparatorAwareInterface $obj): void
{
$obj->setWithSeparator('connections', [ 'default' => [ 'host' => 'web.otherplace.tld' ] ]);
$this->assertEquals('web.otherplace.tld', $obj->get('connections.default.host'));
}
/**
- * @covers ::setWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjAddsValueOnSetNonexistentEndKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjAddsValueOnSetNonexistentEndKeyPath(SeparatorAwareInterface $obj): void
{
$obj->setWithSeparator('connections.default.server_version', '5.7');
$this->assertEquals('5.7', $obj->get('connections.default.server_version'));
}
/**
- * @covers ::setWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjAddsValueOnSetNonexistentMidKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjAddsValueOnSetNonexistentMidKeyPath(SeparatorAwareInterface $obj): void
{
$obj->setWithSeparator('connections.analytics', [ 'driver' => 'pdo_pgsql' ]);
$this->assertEquals('pdo_pgsql', $obj->get('connections.analytics.driver'));
}
/**
- * @covers ::setWithSeparator()
- * @depends testSetSeparator
- *
* @param SeparatorAwareInterface $obj The SeparatorAwareInterface implementation to test.
- * @return void
*/
- public function testObjAddsValueOnSetNonexistentBaseKeyPath(SeparatorAwareInterface $obj)
+ #[\PHPUnit\Framework\Attributes\Depends('testSetSeparator')]
+ public function testObjAddsValueOnSetNonexistentBaseKeyPath(SeparatorAwareInterface $obj): void
{
$obj->setWithSeparator('logging', [ 'level' => 'debug' ]);
$this->assertTrue($obj->has('logging.level'));
@@ -511,26 +385,9 @@ public function testObjAddsValueOnSetNonexistentBaseKeyPath(SeparatorAwareInterf
);
}
- /**
- * @used-by self::testSetWithSeparatorWithoutDelimiterInPhp7()
- * @used-by self::testSetWithSeparatorWithoutDelimiterInPhp5()
- *
- * @covers ::setWithSeparator()
- * @return void
- */
- public function delegatedTestSetWithSeparatorWithoutDelimiter()
+ public function testSetWithSeparatorWithoutDelimiter(): void
{
+ $this->expectException(ValueError::class);
$this->obj->setWithSeparator('connections.default.server_version', '5.7');
}
-
- /**
- * @requires PHP >= 7.0
- * @return void
- */
- public function testSetWithSeparatorWithoutDelimiterInPhp7()
- {
- $this->expectError();
-
- $this->delegatedTestSetWithSeparatorWithoutDelimiter();
- }
}
diff --git a/packages/config/tests/Charcoal/Config/Mock/ConfigurableObject.php b/packages/config/tests/Charcoal/Config/Mock/ConfigurableObject.php
index 876aa3583..9d0d53df4 100644
--- a/packages/config/tests/Charcoal/Config/Mock/ConfigurableObject.php
+++ b/packages/config/tests/Charcoal/Config/Mock/ConfigurableObject.php
@@ -1,5 +1,7 @@
{$key}();
+ } elseif (isset($this->{$key})) {
+ return $this->{$key};
} else {
- if (isset($this->{$key})) {
- return $this->{$key};
- } else {
- return $this->getInDelegates($key);
- }
+ return $this->getInDelegates($key);
}
}
}
diff --git a/packages/config/tests/Charcoal/Config/Mock/Entity.php b/packages/config/tests/Charcoal/Config/Mock/Entity.php
index 7b84adfb9..d783597f8 100644
--- a/packages/config/tests/Charcoal/Config/Mock/Entity.php
+++ b/packages/config/tests/Charcoal/Config/Mock/Entity.php
@@ -1,5 +1,7 @@
setData($data);
}
}
diff --git a/packages/config/tests/Charcoal/Config/Mock/FileLoader.php b/packages/config/tests/Charcoal/Config/Mock/FileLoader.php
index 2da06b397..d6c07c419 100644
--- a/packages/config/tests/Charcoal/Config/Mock/FileLoader.php
+++ b/packages/config/tests/Charcoal/Config/Mock/FileLoader.php
@@ -1,5 +1,7 @@
-3,
diff --git a/packages/config/tests/Charcoal/Config/Mock/MacroEntity.php b/packages/config/tests/Charcoal/Config/Mock/MacroEntity.php
index e5b55cd60..24a5d29f8 100644
--- a/packages/config/tests/Charcoal/Config/Mock/MacroEntity.php
+++ b/packages/config/tests/Charcoal/Config/Mock/MacroEntity.php
@@ -1,5 +1,7 @@
foo;
}
diff --git a/packages/config/tests/Charcoal/Config/Mock/TreeEntity.php b/packages/config/tests/Charcoal/Config/Mock/TreeEntity.php
index 7761a7bc6..b49aa22bf 100644
--- a/packages/config/tests/Charcoal/Config/Mock/TreeEntity.php
+++ b/packages/config/tests/Charcoal/Config/Mock/TreeEntity.php
@@ -26,7 +26,8 @@ class TreeEntity extends Entity implements SeparatorAwareInterface
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
* @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise.
*/
- public function offsetExists($key)
+ #[\Override]
+ public function offsetExists($key): bool
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -63,12 +64,7 @@ public function offsetExists($key)
return ($this->{$key}() !== null);
}
// -- END DEPRECATED
-
- if (isset($this->{$key})) {
- return true;
- }
-
- return false;
+ return isset($this->{$key});
}
/**
@@ -78,7 +74,8 @@ public function offsetExists($key)
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
* @return mixed Value of the requested $key on success, NULL if the $key is not set.
*/
- public function offsetGet($key)
+ #[\Override]
+ public function offsetGet($key): mixed
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
@@ -114,13 +111,8 @@ public function offsetGet($key)
if ($this->mutatorCache[$key]) {
return $this->{$key}();
}
- // -- END DEPRECATED
-
- if (isset($this->{$key})) {
- return $this->{$key};
- }
- return null;
+ return $this->{$key} ?? null;
}
/**
@@ -129,9 +121,9 @@ public function offsetGet($key)
* @param string $key The data key to assign $value to.
* @param mixed $value The data value to assign to $key.
* @throws InvalidArgumentException If the $key is not a string or is a numeric value.
- * @return void
*/
- public function offsetSet($key, $value)
+ #[\Override]
+ public function offsetSet($key, $value): void
{
if (is_numeric($key)) {
throw new InvalidArgumentException(
diff --git a/packages/config/tests/Charcoal/FixturesTrait.php b/packages/config/tests/Charcoal/FixturesTrait.php
index d296ee5cf..7168625b3 100644
--- a/packages/config/tests/Charcoal/FixturesTrait.php
+++ b/packages/config/tests/Charcoal/FixturesTrait.php
@@ -13,7 +13,7 @@ trait FixturesTrait
* @param string $file The file path relative to the Fixture directory.
* @return string The file path to the fixture relative to the base directory.
*/
- public function getPathToFixture($file)
+ public function getPathToFixture($file): string
{
return __DIR__.'/../../tests/Charcoal/Config/Fixture/'.ltrim($file, '/');
}
diff --git a/packages/config/tests/bootstrap.php b/packages/config/tests/bootstrap.php
index a79f4b20d..70ded9041 100644
--- a/packages/config/tests/bootstrap.php
+++ b/packages/config/tests/bootstrap.php
@@ -1,6 +1,8 @@
-
->
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
-
-
+
+ ./src/Charcoal
-
-
+
+
+
+
+
+
+
+
-
+
-
-
-
-
diff --git a/packages/core/src/Charcoal/Loader/CollectionLoader.php b/packages/core/src/Charcoal/Loader/CollectionLoader.php
index 119096d59..c99909efe 100644
--- a/packages/core/src/Charcoal/Loader/CollectionLoader.php
+++ b/packages/core/src/Charcoal/Loader/CollectionLoader.php
@@ -26,6 +26,7 @@
/**
* Object Collection Loader
*/
+#[\AllowDynamicProperties]
class CollectionLoader implements
FilterCollectionInterface,
OrderCollectionInterface,
@@ -107,9 +108,8 @@ public function __construct(array $data)
* Set an object model factory.
*
* @param FactoryInterface $factory The model factory, to create objects.
- * @return self
*/
- public function setFactory(FactoryInterface $factory)
+ public function setFactory(FactoryInterface $factory): static
{
$this->factory = $factory;
@@ -126,7 +126,7 @@ protected function factory()
{
if ($this->factory === null) {
throw new RuntimeException(
- sprintf('Model Factory is not defined for "%s"', get_class($this))
+ sprintf('Model Factory is not defined for "%s"', static::class)
);
}
@@ -140,8 +140,7 @@ protected function factory()
*/
public function createModel()
{
- $obj = $this->factory()->create($this->modelClass());
- return $obj;
+ return $this->factory()->create($this->modelClass());
}
/**
@@ -152,17 +151,15 @@ public function createModel()
*/
protected function createModelFromData(array $data)
{
- $obj = $this->factory()->create($this->dynamicModelClass($data));
- return $obj;
+ return $this->factory()->create($this->dynamicModelClass($data));
}
/**
* Set the loader settings.
*
* @param array $data Data to assign to the loader.
- * @return self
*/
- public function setData(array $data)
+ public function setData(array $data): static
{
foreach ($data as $key => $val) {
$setter = $this->setter($key);
@@ -195,9 +192,8 @@ public function source()
* Set the source to load objects from.
*
* @param SourceInterface $source A data source.
- * @return self
*/
- public function setSource(SourceInterface $source)
+ public function setSource(SourceInterface $source): static
{
$source->reset();
@@ -208,10 +204,8 @@ public function setSource(SourceInterface $source)
/**
* Reset everything but the model.
- *
- * @return self
*/
- public function reset()
+ public function reset(): static
{
if ($this->source) {
$this->source()->reset();
@@ -240,12 +234,10 @@ public function model()
/**
* Determine if the loader has an object model.
- *
- * @return boolean
*/
- public function hasModel()
+ public function hasModel(): bool
{
- return !!$this->model;
+ return (bool)$this->model;
}
/**
@@ -253,9 +245,8 @@ public function hasModel()
*
* @param string|ModelInterface $model An object model.
* @throws InvalidArgumentException If the given argument is not a model.
- * @return self
*/
- public function setModel($model)
+ public function setModel($model): static
{
if (is_string($model)) {
$model = $this->factory()->get($model);
@@ -279,12 +270,10 @@ public function setModel($model)
/**
* Retrieve the model class.
- *
- * @return string
*/
- public function modelClass()
+ public function modelClass(): string
{
- return get_class($this->model());
+ return $this->model()::class;
}
/**
@@ -313,20 +302,17 @@ public function dynamicTypeField()
/**
* Determine if the model has a dynamic object type.
- *
- * @return boolean
*/
- public function hasDynamicTypeField()
+ public function hasDynamicTypeField(): bool
{
- return !!$this->dynamicTypeField;
+ return (bool)$this->dynamicTypeField;
}
/**
* @param string $field The field to use for dynamic object type.
* @throws InvalidArgumentException If the field is not a string.
- * @return self
*/
- public function setDynamicTypeField($field)
+ public function setDynamicTypeField($field): static
{
if (!is_string($field)) {
throw new InvalidArgumentException(
@@ -353,9 +339,8 @@ public function properties()
* Alias of {@see SourceInterface::setProperties()}
*
* @param array $properties An array of property identifiers.
- * @return self
*/
- public function setProperties(array $properties)
+ public function setProperties(array $properties): static
{
$this->source()->setProperties($properties);
@@ -366,9 +351,8 @@ public function setProperties(array $properties)
* Alias of {@see SourceInterface::addProperty()}
*
* @param string $property A property identifier.
- * @return self
*/
- public function addProperty($property)
+ public function addProperty($property): static
{
$this->source()->addProperty($property);
@@ -380,9 +364,8 @@ public function addProperty($property)
*
* @param array $keywords An array of keywords and properties.
* Expected format: `[ "search query", [ "field names…" ] ]`.
- * @return self
*/
- public function setKeywords(array $keywords)
+ public function setKeywords(array $keywords): static
{
foreach ($keywords as $query) {
$keyword = $query[0];
@@ -398,9 +381,8 @@ public function setKeywords(array $keywords)
*
* @param string $keyword A value to match among $properties.
* @param array $properties One or more of properties to search amongst.
- * @return self
*/
- public function addKeyword($keyword, array $properties = null)
+ public function addKeyword(string $keyword, ?array $properties = null): static
{
if ($properties === null) {
$properties = [];
@@ -443,9 +425,8 @@ public function hasFilters()
* Alias of {@see SourceInterface::setFilters()}
*
* @param array $filters An array of filters.
- * @return self
*/
- public function setFilters(array $filters)
+ public function setFilters(array $filters): static
{
$this->source()->setFilters($filters);
return $this;
@@ -455,9 +436,8 @@ public function setFilters(array $filters)
* Alias of {@see SourceInterface::addFilters()}
*
* @param array $filters An array of filters.
- * @return self
*/
- public function addFilters(array $filters)
+ public function addFilters(array $filters): static
{
foreach ($filters as $f) {
$this->addFilter($f);
@@ -474,9 +454,8 @@ public function addFilters(array $filters)
* @param mixed $value Optional value for the property to compare against.
* Only used if the first argument is a string.
* @param array $options Optional extra settings to apply on the filter.
- * @return self
*/
- public function addFilter($param, $value = null, array $options = null)
+ public function addFilter($param, $value = null, ?array $options = null): static
{
$this->source()->addFilter($param, $value, $options);
return $this;
@@ -506,9 +485,8 @@ public function hasOrders()
* Alias of {@see SourceInterface::setOrders()}
*
* @param array $orders An array of orders.
- * @return self
*/
- public function setOrders(array $orders)
+ public function setOrders(array $orders): static
{
$this->source()->setOrders($orders);
return $this;
@@ -518,9 +496,8 @@ public function setOrders(array $orders)
* Alias of {@see SourceInterface::addOrders()}
*
* @param array $orders An array of orders.
- * @return self
*/
- public function addOrders(array $orders)
+ public function addOrders(array $orders): static
{
foreach ($orders as $o) {
$this->addOrder($o);
@@ -537,9 +514,8 @@ public function addOrders(array $orders)
* @param string $mode Optional sorting mode.
* Defaults to ascending if a property is provided.
* @param array $options Optional extra settings to apply on the order.
- * @return self
*/
- public function addOrder($param, $mode = 'asc', array $options = null)
+ public function addOrder($param, $mode = 'asc', ?array $options = null): static
{
$this->source()->addOrder($param, $mode, $options);
return $this;
@@ -559,9 +535,8 @@ public function pagination()
* Alias of {@see SourceInterface::setPagination()}
*
* @param mixed $param An associative array of pagination settings.
- * @return self
*/
- public function setPagination($param)
+ public function setPagination($param): static
{
$this->source()->setPagination($param);
@@ -582,9 +557,8 @@ public function page()
* Alias of {@see PaginationInterface::pagination()}
*
* @param integer $page A page number.
- * @return self
*/
- public function setPage($page)
+ public function setPage($page): static
{
$this->pagination()->setPage($page);
@@ -605,9 +579,8 @@ public function numPerPage()
* Alias of {@see PaginationInterface::setNumPerPage()}
*
* @param integer $num The number of items to display per page.
- * @return self
*/
- public function setNumPerPage($num)
+ public function setNumPerPage($num): static
{
$this->pagination()->setNumPerPage($num);
@@ -618,9 +591,8 @@ public function setNumPerPage($num)
* Set the callback routine applied to every object added to the collection.
*
* @param callable $callback The callback routine.
- * @return self
*/
- public function setCallback(callable $callback)
+ public function setCallback(callable $callback): static
{
$this->callback = $callback;
@@ -647,7 +619,7 @@ public function callback()
* @throws Exception If the database connection fails.
* @return ModelInterface[]|ArrayAccess
*/
- public function load($ident = null, callable $callback = null, callable $before = null)
+ public function load($ident = null, ?callable $callback = null, ?callable $before = null): \ArrayAccess|array
{
// Unused.
unset($ident);
@@ -661,9 +633,8 @@ public function load($ident = null, callable $callback = null, callable $before
* Get the total number of items for this collection query.
*
* @throws RuntimeException If the database connection fails.
- * @return integer
*/
- public function loadCount()
+ public function loadCount(): int
{
$query = $this->source()->sqlLoadCount();
@@ -707,7 +678,7 @@ public function loadCount()
* @throws InvalidArgumentException If the SQL string/set is invalid.
* @return ModelInterface[]|ArrayAccess
*/
- public function loadFromQuery($query, callable $callback = null, callable $before = null)
+ public function loadFromQuery($query, ?callable $callback = null, ?callable $before = null): \ArrayAccess|array
{
$db = $this->source()->db();
@@ -723,14 +694,14 @@ public function loadFromQuery($query, callable $callback = null, callable $befor
$sth = $db->prepare($query);
$sth->execute();
} elseif (is_array($query)) {
- list($query, $binds, $types) = array_pad($query, 3, []);
+ [$query, $binds, $types] = array_pad($query, 3, []);
$sth = $this->source()->dbQuery($query, $binds, $types);
} else {
throw new InvalidArgumentException(sprintf(
'The SQL query must be a string or an array: ' .
'[ string $query, array $binds, array $dataTypes ]; ' .
'received %s',
- is_object($query) ? get_class($query) : $query
+ is_object($query) ? $query::class : $query
));
}
@@ -751,7 +722,7 @@ public function loadFromQuery($query, callable $callback = null, callable $befor
* @param callable|null $after Process each entity after applying raw data.
* @return ModelInterface[]|ArrayAccess
*/
- protected function processCollection($results, callable $before = null, callable $after = null)
+ protected function processCollection($results, ?callable $before = null, ?callable $after = null): \ArrayAccess|array
{
$collection = $this->createCollection();
foreach ($results as $objData) {
@@ -773,7 +744,7 @@ protected function processCollection($results, callable $before = null, callable
* @param callable|null $after Process each entity after applying raw data.
* @return ModelInterface|ArrayAccess|null
*/
- protected function processModel($objData, callable $before = null, callable $after = null)
+ protected function processModel(array $objData, ?callable $before = null, ?callable $after = null)
{
$obj = $this->createModelFromData($objData);
@@ -794,9 +765,8 @@ protected function processModel($objData, callable $before = null, callable $aft
* Create a collection class or array.
*
* @throws RuntimeException If the collection class is invalid.
- * @return array|ArrayAccess
*/
- public function createCollection()
+ public function createCollection(): array|\ArrayAccess
{
$collectClass = $this->collectionClass();
if ($collectClass === 'array') {
@@ -817,9 +787,7 @@ public function createCollection()
));
}
- $collection = new $collectClass();
-
- return $collection;
+ return new $collectClass();
}
/**
@@ -827,9 +795,8 @@ public function createCollection()
*
* @param string $className The class name of the collection.
* @throws InvalidArgumentException If the class name is not a string.
- * @return self
*/
- public function setCollectionClass($className)
+ public function setCollectionClass($className): static
{
if (!is_string($className)) {
throw new InvalidArgumentException(
@@ -858,7 +825,7 @@ public function collectionClass()
* @param string $key The key to get the getter from.
* @return string The getter method name, for a given key.
*/
- protected function getter($key)
+ protected function getter($key): string
{
$getter = $key;
return $this->camelize($getter);
@@ -870,7 +837,7 @@ protected function getter($key)
* @param string $key The key to get the setter from.
* @return string The setter method name, for a given key.
*/
- protected function setter($key)
+ protected function setter(string $key): string
{
$setter = 'set_' . $key;
return $this->camelize($setter);
@@ -882,8 +849,8 @@ protected function setter($key)
* @param string $str The snake_case string to camelize.
* @return string The camelcase'd string.
*/
- protected function camelize($str)
+ protected function camelize($str): string
{
- return lcfirst(implode('', array_map('ucfirst', explode('_', $str))));
+ return lcfirst(implode('', array_map(ucfirst(...), explode('_', $str))));
}
}
diff --git a/packages/core/src/Charcoal/Loader/CollectionLoaderAwareTrait.php b/packages/core/src/Charcoal/Loader/CollectionLoaderAwareTrait.php
index 770f9d5fd..989f42127 100644
--- a/packages/core/src/Charcoal/Loader/CollectionLoaderAwareTrait.php
+++ b/packages/core/src/Charcoal/Loader/CollectionLoaderAwareTrait.php
@@ -24,11 +24,12 @@ trait CollectionLoaderAwareTrait
* Set a model collection loader.
*
* @param CollectionLoader $loader The model collection loader.
- * @return void
*/
- protected function setCollectionLoader(CollectionLoader $loader)
+ protected function setCollectionLoader(CollectionLoader $loader): static
{
$this->collectionLoader = $loader;
+
+ return $this;
}
/**
@@ -37,12 +38,12 @@ protected function setCollectionLoader(CollectionLoader $loader)
* @throws RuntimeException If the collection loader is missing.
* @return CollectionLoader
*/
- public function collectionLoader()
+ public function collectionLoader(): \Charcoal\Loader\CollectionLoader
{
if (!isset($this->collectionLoader)) {
throw new RuntimeException(sprintf(
'Collection Loader is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
diff --git a/packages/core/src/Charcoal/Loader/CollectionLoaderFactoryTrait.php b/packages/core/src/Charcoal/Loader/CollectionLoaderFactoryTrait.php
index f256bd609..0643e1d6d 100644
--- a/packages/core/src/Charcoal/Loader/CollectionLoaderFactoryTrait.php
+++ b/packages/core/src/Charcoal/Loader/CollectionLoaderFactoryTrait.php
@@ -42,7 +42,7 @@ public function collectionLoaderFactory()
if (!isset($this->collectionLoaderFactory)) {
throw new RuntimeException(sprintf(
'Collection Loader Factory is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
@@ -56,7 +56,7 @@ public function collectionLoaderFactory()
* @param callable|null $callback Optional. Called at creation.
* @return CollectionLoader
*/
- public function createCollectionLoaderWith(array $args = null, callable $callback = null)
+ public function createCollectionLoaderWith(?array $args = null, ?callable $callback = null)
{
$factory = $this->collectionLoaderFactory();
diff --git a/packages/core/src/Charcoal/Loader/LazyCollectionLoader.php b/packages/core/src/Charcoal/Loader/LazyCollectionLoader.php
index caa54cba7..f6696db75 100644
--- a/packages/core/src/Charcoal/Loader/LazyCollectionLoader.php
+++ b/packages/core/src/Charcoal/Loader/LazyCollectionLoader.php
@@ -1,5 +1,7 @@
processModel($objData, $before, $after);
diff --git a/packages/core/src/Charcoal/Model/AbstractModel.php b/packages/core/src/Charcoal/Model/AbstractModel.php
index 15c4e88c4..dc76a9dd6 100644
--- a/packages/core/src/Charcoal/Model/AbstractModel.php
+++ b/packages/core/src/Charcoal/Model/AbstractModel.php
@@ -65,7 +65,7 @@ abstract class AbstractModel extends AbstractEntity implements
/**
* @param array $data Dependencies.
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
// LoggerAwareInterface dependencies
$this->setLogger($data['logger']);
@@ -107,7 +107,8 @@ public function __construct(array $data = null)
* for retrieving a subset of data.
* @return array
*/
- public function data(array $properties = null)
+ #[\Override]
+ public function data(?array $properties = null)
{
$data = [];
$properties = $this->properties($properties);
@@ -128,6 +129,7 @@ public function data(array $properties = null)
* @return self
* @see AbstractEntity::setData()
*/
+ #[\Override]
public function setData(array $data)
{
$data = $this->setIdFromData($data);
@@ -183,11 +185,7 @@ public function mergeData(array $data)
$property = $this->p($propIdent);
if ($property['l10n'] && is_array($val)) {
$currentValue = json_decode(json_encode($this[$propIdent]), true);
- if (is_array($currentValue)) {
- $this[$propIdent] = array_merge($currentValue, $val);
- } else {
- $this[$propIdent] = $val;
- }
+ $this[$propIdent] = is_array($currentValue) ? array_merge($currentValue, $val) : $val;
} else {
$this[$propIdent] = $val;
}
@@ -238,20 +236,18 @@ public function setFlatData(array $flatData)
public function setPropertyDataFromFlatData(array $flatData)
{
$flatData = $this->setIdFromData($flatData);
-
- $propData = [];
$properties = $this->properties();
foreach ($properties as $propertyIdent => $property) {
$fieldValues = [];
$fieldNames = $property->fieldNames();
foreach ($fieldNames as $fieldName) {
- if (array_key_exists($fieldName, $flatData)) {
+ if (array_key_exists((string)$fieldName, $flatData)) {
$fieldValues[$fieldName] = $flatData[$fieldName];
unset($flatData[$fieldName]);
}
}
- if ($fieldValues) {
+ if ($fieldValues !== []) {
$this[$propertyIdent] = $property->parseFromFlatData($fieldValues);
}
}
@@ -268,7 +264,7 @@ public function setPropertyDataFromFlatData(array $flatData)
* for retrieving a subset of data.
* @return array
*/
- public function flatData(array $properties = null)
+ public function flatData(?array $properties = null)
{
$flatData = [];
$properties = $this->properties($properties);
@@ -299,7 +295,7 @@ public function propertyValue($propertyIdent)
* @param array $properties Optional array of properties to save. If null, use all object's properties.
* @return boolean
*/
- public function saveProperties(array $properties = null)
+ public function saveProperties(?array $properties = null)
{
if ($properties === null) {
$properties = array_keys($this->metadata()->properties());
@@ -335,7 +331,7 @@ public function saveProperties(array $properties = null)
* @throws PDOException If the PDO query fails.
* @return string The matching language.
*/
- public function loadFromL10n($key, $value, array $langs)
+ public function loadFromL10n(string $key, $value, array $langs)
{
$binds = [
'ident' => $value,
@@ -366,9 +362,9 @@ public function loadFromL10n($key, $value, array $langs)
if ($sth === false) {
throw new PDOException(sprintf(
'Could not load model [%s] for localized column "%s" [%s]',
- get_class($this),
+ static::class,
$fieldName,
- (is_object($value) ? get_class($value) : (is_string($value) ? $value : gettype($value)))
+ (is_object($value) ? $value::class : (is_string($value) ? $value : gettype($value)))
));
}
@@ -376,9 +372,9 @@ public function loadFromL10n($key, $value, array $langs)
if (!$data || !isset($data['_lang'])) {
throw new PDOException(sprintf(
'Unable to retrieve model [%s] data for localized column "%s" [%s]',
- get_class($this),
+ static::class,
$fieldName,
- (is_object($value) ? get_class($value) : (is_string($value) ? $value : gettype($value)))
+ (is_object($value) ? $value::class : (is_string($value) ? $value : gettype($value)))
));
}
@@ -446,7 +442,7 @@ protected function preSave()
* @see StorableTrait::preUpdate()
* @return boolean
*/
- protected function preUpdate(array $properties = null)
+ protected function preUpdate(?array $properties = null)
{
return $this->saveProperties($properties);
}
@@ -488,11 +484,11 @@ protected function createSource()
if (!$sourceConfig) {
throw new UnexpectedValueException(sprintf(
'Can not create source for model [%s]: Invalid metadata (can not load source\'s configuration)',
- get_class($this)
+ static::class
));
}
- $type = isset($sourceConfig['type']) ? $sourceConfig['type'] : self::DEFAULT_SOURCE_TYPE;
+ $type = ($sourceConfig['type'] ?? self::DEFAULT_SOURCE_TYPE);
$source = $this->sourceFactory()->create($type);
$source->setModel($this);
@@ -508,8 +504,7 @@ protected function createSource()
*/
protected function createValidator()
{
- $validator = new ModelValidator($this);
- return $validator;
+ return new ModelValidator($this);
}
/**
@@ -533,9 +528,8 @@ protected function setDependencies(Container $container)
*/
public static function objType()
{
- $class = get_called_class();
+ $class = static::class;
$ident = preg_replace('/([a-z])([A-Z])/', '$1-$2', $class);
- $ident = strtolower(str_replace('\\', '/', $ident));
- return $ident;
+ return strtolower(str_replace('\\', '/', $ident));
}
}
diff --git a/packages/core/src/Charcoal/Model/Collection.php b/packages/core/src/Charcoal/Model/Collection.php
index f05a22173..922843144 100644
--- a/packages/core/src/Charcoal/Model/Collection.php
+++ b/packages/core/src/Charcoal/Model/Collection.php
@@ -40,7 +40,6 @@ class Collection implements CollectionInterface
* Create a new collection.
*
* @param array|Traversable|null $objs Array of objects to pre-populate this collection.
- * @return void
*/
public function __construct($objs = null)
{
@@ -54,7 +53,7 @@ public function __construct($objs = null)
*
* @return object|null Returns the first object, or NULL if the collection is empty.
*/
- public function first()
+ public function first(): ?object
{
if (empty($this->objects)) {
return null;
@@ -68,7 +67,7 @@ public function first()
*
* @return object|null Returns the last object, or NULL if the collection is empty.
*/
- public function last()
+ public function last(): ?object
{
if (empty($this->objects)) {
return null;
@@ -79,15 +78,13 @@ public function last()
// Satisfies CollectionInterface
// =============================================================================================
-
/**
* Merge the collection with the given objects.
*
* @param array|Traversable $objs Array of objects to append to this collection.
* @throws InvalidArgumentException If the given array contains an unacceptable value.
- * @return self
*/
- public function merge($objs)
+ public function merge($objs): static
{
$objs = $this->asArray($objs);
@@ -96,7 +93,7 @@ public function merge($objs)
throw new InvalidArgumentException(
sprintf(
'Must be an array of models, contains %s',
- (is_object($obj) ? get_class($obj) : gettype($obj))
+ (get_debug_type($obj))
)
);
}
@@ -113,15 +110,14 @@ public function merge($objs)
*
* @param object $obj An acceptable object.
* @throws InvalidArgumentException If the given object is not acceptable.
- * @return self
*/
- public function add($obj)
+ public function add($obj): static
{
if (!$this->isAcceptable($obj)) {
throw new InvalidArgumentException(
sprintf(
'Must be a model, received %s',
- (is_object($obj) ? get_class($obj) : gettype($obj))
+ (get_debug_type($obj))
)
);
}
@@ -155,15 +151,14 @@ public function get($key)
* Determine if an object exists in the collection by key.
*
* @param mixed $key The primary key to lookup.
- * @return boolean
*/
- public function has($key)
+ public function has($key): bool
{
if ($this->isAcceptable($key)) {
$key = $this->modelKey($key);
}
- return array_key_exists($key, $this->objects);
+ return array_key_exists((string)$key, $this->objects);
}
/**
@@ -171,9 +166,8 @@ public function has($key)
*
* @param mixed $key The object primary key to remove.
* @throws InvalidArgumentException If the given key is not acceptable.
- * @return self
*/
- public function remove($key)
+ public function remove($key): static
{
if ($this->isAcceptable($key)) {
$key = $this->modelKey($key);
@@ -186,10 +180,8 @@ public function remove($key)
/**
* Remove all objects from collection.
- *
- * @return self
*/
- public function clear()
+ public function clear(): static
{
$this->objects = [];
@@ -211,7 +203,7 @@ public function all()
*
* @return object[] A sequential array of objects.
*/
- public function values()
+ public function values(): array
{
return array_values($this->objects);
}
@@ -221,22 +213,20 @@ public function values()
*
* @return array A sequential array of keys.
*/
- public function keys()
+ public function keys(): array
{
return array_keys($this->objects);
}
// Satisfies ArrayAccess
// =============================================================================================
-
/**
* Alias of {@see CollectionInterface::has()}.
*
* @see \ArrayAccess
* @param mixed $offset The object primary key or array offset.
- * @return boolean
*/
- public function offsetExists($offset)
+ public function offsetExists($offset): bool
{
if (is_int($offset)) {
$offset = $this->resolveOffset($offset);
@@ -255,7 +245,7 @@ public function offsetExists($offset)
* @param mixed $offset The object primary key or array offset.
* @return mixed Returns the requested object or NULL if not in the collection.
*/
- public function offsetGet($offset)
+ public function offsetGet($offset): mixed
{
if (is_int($offset)) {
$offset = $this->resolveOffset($offset);
@@ -275,9 +265,8 @@ public function offsetGet($offset)
* @param mixed $offset The object primary key or array offset.
* @param mixed $value The object.
* @throws LogicException Attempts to assign an offset.
- * @return void
*/
- public function offsetSet($offset, $value)
+ public function offsetSet($offset, $value): void
{
if ($offset === null) {
$this->add($value);
@@ -293,9 +282,8 @@ public function offsetSet($offset, $value)
*
* @see \ArrayAccess
* @param mixed $offset The object primary key or array offset.
- * @return void
*/
- public function offsetUnset($offset)
+ public function offsetUnset($offset): void
{
if (is_int($offset)) {
$offset = $this->resolveOffset($offset);
@@ -319,10 +307,8 @@ public function offsetUnset($offset)
*/
protected function resolveOffset($offset)
{
- if (is_int($offset)) {
- if ($offset < 0) {
- $offset = ($this->count() - abs($offset));
- }
+ if (is_int($offset) && $offset < 0) {
+ $offset = ($this->count() - abs($offset));
}
return $offset;
@@ -330,28 +316,24 @@ protected function resolveOffset($offset)
// Satisfies Countable
// =============================================================================================
-
/**
* Get number of objects in collection
*
* @see \Countable
- * @return integer
*/
- public function count()
+ public function count(): int
{
return count($this->objects);
}
// Satisfies IteratorAggregate
// =============================================================================================
-
/**
* Retrieve an external iterator.
*
* @see \IteratorAggregate
- * @return \ArrayIterator
*/
- public function getIterator()
+ public function getIterator(): \ArrayIterator
{
return new ArrayIterator($this->objects);
}
@@ -360,24 +342,22 @@ public function getIterator()
* Retrieve a cached iterator.
*
* @param integer $flags Bitmask of flags.
- * @return \CachingIterator
*/
- public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING)
+ public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING): \CachingIterator
{
return new CachingIterator($this->getIterator(), $flags);
}
// Satisfies backwards-compatibility
// =============================================================================================
-
/**
* Retrieve the array offset from the given key.
*
- * @deprecated
* @param mixed $key The primary key to retrieve the offset from.
* @return integer Returns an array offset.
*/
- public function pos($key)
+ #[\Deprecated]
+ public function pos($key): int|false
{
trigger_error('Collection::pos() is deprecated', E_USER_DEPRECATED);
@@ -387,11 +367,11 @@ public function pos($key)
/**
* Alias of {@see self::values()}
*
- * @deprecated
* @todo Trigger deprecation error.
* @return object[]
*/
- public function objects()
+ #[\Deprecated]
+ public function objects(): array
{
return $this->values();
}
@@ -399,26 +379,24 @@ public function objects()
/**
* Alias of {@see self::all()}.
*
- * @deprecated
* @todo Trigger deprecation error.
* @return object[]
*/
+ #[\Deprecated]
public function map()
{
return $this->all();
}
// =============================================================================================
-
/**
* Determine if the given value is acceptable for the collection.
*
* Note: Practical for specialized collections extending the base collection.
*
* @param mixed $value The value being vetted.
- * @return boolean
*/
- public function isAcceptable($value)
+ public function isAcceptable($value): bool
{
return ($value instanceof ModelInterface);
}
@@ -438,7 +416,7 @@ protected function modelKey($obj)
throw new InvalidArgumentException(
sprintf(
'Must be a model, received %s',
- (is_object($obj) ? get_class($obj) : gettype($obj))
+ (get_debug_type($obj))
)
);
}
@@ -448,10 +426,8 @@ protected function modelKey($obj)
/**
* Determine if the collection is empty or not.
- *
- * @return boolean
*/
- public function isEmpty()
+ public function isEmpty(): bool
{
return empty($this->objects);
}
@@ -460,10 +436,8 @@ public function isEmpty()
* Get a base collection instance from this collection.
*
* Note: Practical for extended classes.
- *
- * @return Collection
*/
- public function toBase()
+ public function toBase(): self
{
return new self($this);
}
diff --git a/packages/core/src/Charcoal/Model/CollectionInterface.php b/packages/core/src/Charcoal/Model/CollectionInterface.php
index 245394c30..19b538c4f 100644
--- a/packages/core/src/Charcoal/Model/CollectionInterface.php
+++ b/packages/core/src/Charcoal/Model/CollectionInterface.php
@@ -1,5 +1,7 @@
metadataLoader) {
throw new RuntimeException(
- sprintf('Metadata loader was not set for "%s"', get_class($this))
+ sprintf('Metadata loader was not set for "%s"', $this::class)
);
}
return $this->metadataLoader;
@@ -160,13 +160,10 @@ protected function metadataLoader()
* Generate a metadata identifier from this object's class name (FQN).
*
* Converts the short class name and converts it from camelCase to kebab-case.
- *
- * @return string
*/
- protected function generateMetadataIdent()
+ protected function generateMetadataIdent(): string
{
$ident = preg_replace('/([a-z])([A-Z])/', '$1-$2', static::class);
- $ident = strtolower(str_replace('\\', '/', $ident));
- return $ident;
+ return strtolower(str_replace('\\', '/', $ident));
}
}
diff --git a/packages/core/src/Charcoal/Model/MetadataInterface.php b/packages/core/src/Charcoal/Model/MetadataInterface.php
index 9f60dde0c..6e2c973f9 100644
--- a/packages/core/src/Charcoal/Model/MetadataInterface.php
+++ b/packages/core/src/Charcoal/Model/MetadataInterface.php
@@ -1,5 +1,7 @@
metadataLoader)) {
throw new RuntimeException(sprintf(
'Metadata Loader is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
@@ -58,9 +58,8 @@ public function metadataLoader()
protected function loadMetadata($metadataIdent)
{
$metadataLoader = $this->metadataLoader();
- $metadata = $metadataLoader->load($metadataIdent, $this->createMetadata());
- return $metadata;
+ return $metadataLoader->load($metadataIdent, $this->createMetadata());
}
/**
diff --git a/packages/core/src/Charcoal/Model/Model.php b/packages/core/src/Charcoal/Model/Model.php
index 59dc94c17..cde44b635 100644
--- a/packages/core/src/Charcoal/Model/Model.php
+++ b/packages/core/src/Charcoal/Model/Model.php
@@ -7,6 +7,8 @@
* @author Mathieu Ducharme
*/
+declare(strict_types=1);
+
namespace Charcoal\Model;
// From 'charcoal-core'
diff --git a/packages/core/src/Charcoal/Model/ModelFactoryTrait.php b/packages/core/src/Charcoal/Model/ModelFactoryTrait.php
index 78251ce21..7d0b6ef2f 100644
--- a/packages/core/src/Charcoal/Model/ModelFactoryTrait.php
+++ b/packages/core/src/Charcoal/Model/ModelFactoryTrait.php
@@ -43,7 +43,7 @@ public function modelFactory()
if (!isset($this->modelFactory)) {
throw new RuntimeException(sprintf(
'Model Factory is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
diff --git a/packages/core/src/Charcoal/Model/ModelInterface.php b/packages/core/src/Charcoal/Model/ModelInterface.php
index 01c133a7f..f4b60f818 100644
--- a/packages/core/src/Charcoal/Model/ModelInterface.php
+++ b/packages/core/src/Charcoal/Model/ModelInterface.php
@@ -1,5 +1,7 @@
modelLoaderBuilder)) {
throw new RuntimeException(sprintf(
'Model Factory is not defined for [%s]',
- get_class($this)
+ $this::class
));
}
@@ -72,7 +72,7 @@ protected function modelLoader($objType, $objKey = null)
if (!is_string($objType)) {
throw new InvalidArgumentException(sprintf(
'The object type must be a string, received %s',
- is_object($objType) ? get_class($objType) : gettype($objType)
+ get_debug_type($objType)
));
}
@@ -82,7 +82,7 @@ protected function modelLoader($objType, $objKey = null)
} elseif (!is_string($key)) {
throw new InvalidArgumentException(sprintf(
'The object property key must be a string, received %s',
- is_object($key) ? get_class($key) : gettype($key)
+ get_debug_type($key)
));
}
diff --git a/packages/core/src/Charcoal/Model/ModelMetadata.php b/packages/core/src/Charcoal/Model/ModelMetadata.php
index 696a22f1a..64e72e2af 100644
--- a/packages/core/src/Charcoal/Model/ModelMetadata.php
+++ b/packages/core/src/Charcoal/Model/ModelMetadata.php
@@ -13,10 +13,8 @@ class ModelMetadata extends AbstractMetadata
{
/**
* The metadata identifier.
- *
- * @var string
*/
- private $ident;
+ private ?string $ident = null;
/**
* The model's sources.
@@ -27,26 +25,23 @@ class ModelMetadata extends AbstractMetadata
/**
* The model's default source.
- *
- * @var string
*/
- private $defaultSource;
+ private ?string $defaultSource = null;
/**
* Set the metadata identifier.
*
* @param string $ident The metadata identifier.
* @throws InvalidArgumentException If identifier is not a string.
- * @return self
*/
- public function setIdent($ident)
+ public function setIdent($ident): static
{
if (!is_string($ident)) {
throw new InvalidArgumentException(
sprintf(
'[%s] Identifier must be a string; received %s',
- get_called_class(),
- (is_object($ident) ? get_class($ident) : gettype($ident))
+ static::class,
+ (get_debug_type($ident))
)
);
}
@@ -61,16 +56,15 @@ public function setIdent($ident)
*
* @return string
*/
- public function ident()
+ public function ident(): ?string
{
return $this->ident;
}
/**
* @param array $sources The available sources for this model.
- * @return self
*/
- public function setSources(array $sources)
+ public function setSources(array $sources): static
{
foreach ($sources as $sourceIdent => $source) {
$this->addSource($sourceIdent, $source);
@@ -89,9 +83,8 @@ public function sources()
/**
* @param string $sourceIdent The source identifier.
* @param mixed $source The source data.
- * @return self
*/
- public function addSource($sourceIdent, $source)
+ public function addSource($sourceIdent, $source): static
{
$this->sources[$sourceIdent] = $source;
return $this;
@@ -113,9 +106,8 @@ public function source($sourceIdent)
/**
* @param string $defaultSource The default source identifier.
* @throws InvalidArgumentException If the argument is not a string.
- * @return self
*/
- public function setDefaultSource($defaultSource)
+ public function setDefaultSource($defaultSource): static
{
if (!is_string($defaultSource)) {
throw new InvalidArgumentException(
@@ -129,7 +121,7 @@ public function setDefaultSource($defaultSource)
/**
* @return string
*/
- public function defaultSource()
+ public function defaultSource(): ?string
{
return $this->defaultSource;
}
diff --git a/packages/core/src/Charcoal/Model/Service/MetadataConfig.php b/packages/core/src/Charcoal/Model/Service/MetadataConfig.php
index 446dc61bf..429d2049d 100644
--- a/packages/core/src/Charcoal/Model/Service/MetadataConfig.php
+++ b/packages/core/src/Charcoal/Model/Service/MetadataConfig.php
@@ -15,17 +15,13 @@ class MetadataConfig extends AbstractConfig
{
/**
* Metadata search paths.
- *
- * @var array
*/
- private $paths = [];
+ private array $paths = [];
/**
* The PSR-6 caching service or cache identifier(s) to use.
- *
- * @var mixed
*/
- private $cache = true;
+ private array|bool|null|object $cache = true;
/**
* Retrieve the default values.
@@ -34,7 +30,8 @@ class MetadataConfig extends AbstractConfig
* @return mixed An associative array if $key is NULL.
* If $key is specified, the value of that data key if it exists, NULL on failure.
*/
- public function defaults($key = null)
+ #[\Override]
+ public function defaults($key = null): array|true|null
{
$data = [
'paths' => [],
@@ -42,7 +39,7 @@ public function defaults($key = null)
];
if ($key) {
- return isset($data[$key]) ? $data[$key] : null;
+ return ($data[$key] ?? null);
}
return $data;
@@ -53,9 +50,9 @@ public function defaults($key = null)
*
* @see \Charcoal\Config\AbstractConfig::merge()
* @param array|Traversable $data The data to merge.
- * @return self
*/
- public function merge($data)
+ #[\Override]
+ public function merge($data): static
{
foreach ($data as $key => $val) {
if ($key === 'paths') {
@@ -70,19 +67,15 @@ public function merge($data)
return $this;
}
- /**
- * @return array
- */
- public function paths()
+ public function paths(): array
{
return $this->paths;
}
/**
* @param string[] $paths One or more search paths.
- * @return self
*/
- public function setPaths(array $paths)
+ public function setPaths(array $paths): static
{
$this->paths = [];
$this->addPaths($paths);
@@ -91,9 +84,8 @@ public function setPaths(array $paths)
/**
* @param string[] $paths One or more search paths.
- * @return self
*/
- public function addPaths(array $paths)
+ public function addPaths(array $paths): static
{
foreach ($paths as $path) {
$this->addPath($path);
@@ -104,9 +96,8 @@ public function addPaths(array $paths)
/**
* @param string $path A directory path.
* @throws InvalidArgumentException If the path is not a string.
- * @return self
*/
- public function addPath($path)
+ public function addPath($path): static
{
if (!is_string($path)) {
throw new InvalidArgumentException(
@@ -117,12 +108,9 @@ public function addPath($path)
return $this;
}
- /**
- * @return mixed
- */
- public function cache()
+ public function cache(): bool|object|array
{
- return isset($this->cache) ? $this->cache : false;
+ return ($this->cache ?? false);
}
/**
@@ -137,9 +125,8 @@ public function cache()
* - a {@see \Psr\Cache\CacheItemPoolInterface PSR-6 caching service},
* that instance will be used by the {@see \Charcoal\Model\Service\MetadataLoader}.
* @throws InvalidArgumentException If the cache option is invalid.
- * @return self
*/
- public function setCache($cache)
+ public function setCache($cache): static
{
if ($cache === null) {
$this->cache = $this->defaults('cache');
diff --git a/packages/core/src/Charcoal/Model/Service/MetadataLoader.php b/packages/core/src/Charcoal/Model/Service/MetadataLoader.php
index e424665ff..da23aa015 100644
--- a/packages/core/src/Charcoal/Model/Service/MetadataLoader.php
+++ b/packages/core/src/Charcoal/Model/Service/MetadataLoader.php
@@ -29,10 +29,8 @@ final class MetadataLoader implements LoggerAwareInterface
/**
* The PSR-6 caching service.
- *
- * @var CacheItemPoolInterface
*/
- private $cachePool;
+ private \Psr\Cache\CacheItemPoolInterface $cachePool;
/**
* The cache of metadata instances, indexed by metadata identifier.
@@ -43,10 +41,8 @@ final class MetadataLoader implements LoggerAwareInterface
/**
* The cache of class/interface lineages.
- *
- * @var array
*/
- private static $lineageCache = [];
+ private static array $lineageCache = [];
/**
* The cache of snake-cased words.
@@ -57,24 +53,18 @@ final class MetadataLoader implements LoggerAwareInterface
/**
* The cache of camel-cased words.
- *
- * @var array
*/
- private static $camelCache = [];
+ private static array $camelCache = [];
/**
* The base path to prepend to any relative paths to search in.
- *
- * @var string
*/
- private $basePath = '';
+ private string $basePath = '';
/**
* The paths to search in.
- *
- * @var array
*/
- private $paths = [];
+ private array $paths = [];
/**
* Return new MetadataLoader object.
@@ -89,9 +79,8 @@ final class MetadataLoader implements LoggerAwareInterface
* - `base_path`
*
* @param array $data The loader's dependencies.
- * @return void
*/
- public function __construct(array $data = null)
+ public function __construct(?array $data = null)
{
$this->setLogger($data['logger']);
$this->setCachePool($data['cache']);
@@ -121,16 +110,16 @@ public function __construct(array $data = null)
* as an array or an instance of {@see MetadataInterface}.
* See $metadata for more details.
*/
- public function load($ident, $metadata = [], array $idents = null)
+ public function load($ident, $metadata = [], ?array $idents = null)
{
if (!is_string($ident)) {
throw new InvalidArgumentException(sprintf(
'Metadata identifier must be a string, received %s',
- is_object($ident) ? get_class($ident) : gettype($ident)
+ get_debug_type($ident)
));
}
- if (strpos($ident, '\\') !== false) {
+ if (str_contains($ident, '\\')) {
$ident = $this->metaKeyFromClassName($ident);
}
@@ -139,12 +128,12 @@ public function load($ident, $metadata = [], array $idents = null)
throw new InvalidArgumentException(sprintf(
'Metadata object must be a class name or instance of %s, received %s',
MetadataInterface::class,
- is_object($metadata) ? get_class($metadata) : gettype($metadata)
+ get_debug_type($metadata)
));
}
- if (isset(static::$metadataCache[$ident])) {
- $cachedMetadata = static::$metadataCache[$ident];
+ if (isset(self::$metadataCache[$ident])) {
+ $cachedMetadata = self::$metadataCache[$ident];
if (is_object($targetMetadata)) {
return $targetMetadata->merge($cachedMetadata);
@@ -165,7 +154,7 @@ public function load($ident, $metadata = [], array $idents = null)
$targetMetadata = new $metadataType();
$targetMetadata->setData($data);
- static::$metadataCache[$ident] = $targetMetadata;
+ self::$metadataCache[$ident] = $targetMetadata;
return $targetMetadata;
}
@@ -175,9 +164,8 @@ public function load($ident, $metadata = [], array $idents = null)
*
* @param string $ident The metadata identifier to load.
* @throws InvalidArgumentException If the identifier is not a string.
- * @return array
*/
- public function loadMetadataByKey($ident)
+ public function loadMetadataByKey($ident): array
{
if (!is_string($ident)) {
throw new InvalidArgumentException(
@@ -201,9 +189,8 @@ public function loadMetadataByKey($ident)
* Fetch the metadata for the given identifiers.
*
* @param array $idents One or more metadata identifiers to load.
- * @return array
*/
- public function loadMetadataByKeys(array $idents)
+ public function loadMetadataByKeys(array $idents): array
{
$metadata = [];
foreach ($idents as $metaKey) {
@@ -222,14 +209,14 @@ public function loadMetadataByKeys(array $idents)
* @param string $ident The FQCN (in snake-case) to load the hierarchy from.
* @return array
*/
- private function hierarchy($ident)
+ private function hierarchy(string $ident)
{
if (!is_string($ident)) {
return [];
}
- if (isset(static::$lineageCache[$ident])) {
- return static::$lineageCache[$ident];
+ if (isset(self::$lineageCache[$ident])) {
+ return self::$lineageCache[$ident];
}
$classname = $this->classNameFromMetaKey($ident);
@@ -254,8 +241,8 @@ private function classLineage($class, $ident = null)
$ident = $this->metaKeyFromClassName($class);
}
- if (isset(static::$lineageCache[$ident])) {
- return static::$lineageCache[$ident];
+ if (isset(self::$lineageCache[$ident])) {
+ return self::$lineageCache[$ident];
}
$class = $this->classNameFromMetaKey($ident);
@@ -280,7 +267,7 @@ private function classLineage($class, $ident = null)
$hierarchy = array_keys($hierarchy);
- static::$lineageCache[$ident] = $hierarchy;
+ self::$lineageCache[$ident] = $hierarchy;
return $hierarchy;
}
@@ -293,7 +280,7 @@ private function classLineage($class, $ident = null)
* and these metadata identifiers are loaded instead.
* @return array The data associated with the metadata identifier.
*/
- private function loadMetadataFromCache($ident, array $idents = null)
+ private function loadMetadataFromCache($ident, ?array $idents = null)
{
$cacheKey = $this->cacheKeyFromMetaKey($ident);
$cacheItem = $this->cachePool()->getItem($cacheKey);
@@ -310,12 +297,7 @@ private function loadMetadataFromCache($ident, array $idents = null)
return $metadata;
} else {
- if (empty($idents)) {
- $metadata = $this->loadMetadataByKey($ident);
- } else {
- $metadata = $this->loadMetadataByKeys($idents);
- }
-
+ $metadata = $idents === null || $idents === [] ? $this->loadMetadataByKey($ident) : $this->loadMetadataByKeys($idents);
$cacheItem->set($metadata);
$this->cachePool()->save($cacheItem);
}
@@ -346,14 +328,14 @@ private function loadMetadataFromSource($ident)
* @throws UnexpectedValueException If the file cannot be loaded.
* @return array|null An associative array on success, NULL on failure.
*/
- private function loadFile($path)
+ private function loadFile(string $path)
{
if (file_exists($path)) {
return $this->loadJsonFile($path);
}
$dirs = $this->paths();
- if (empty($dirs)) {
+ if ($dirs === []) {
return null;
}
@@ -366,7 +348,7 @@ private function loadFile($path)
}
}
- if (empty($data)) {
+ if ($data === []) {
return null;
}
@@ -380,7 +362,7 @@ private function loadFile($path)
* @throws UnexpectedValueException If the file can not correctly be parsed into an array.
* @return array An associative array on success.
*/
- private function loadJsonFile($path)
+ private function loadJsonFile(string $path)
{
$data = json_decode(file_get_contents($path), true);
if (json_last_error() !== JSON_ERROR_NONE) {
@@ -403,9 +385,8 @@ private function loadJsonFile($path)
* Generate a store key.
*
* @param string|string[] $ident The metadata identifier(s) to convert.
- * @return string
*/
- public function serializeMetaKey($ident)
+ public function serializeMetaKey($ident): string
{
if (is_array($ident)) {
sort($ident);
@@ -423,8 +404,7 @@ public function serializeMetaKey($ident)
*/
public function cacheKeyFromMetaKey($ident)
{
- $cacheKey = 'metadata/' . str_replace('/', '.', $ident);
- return $cacheKey;
+ return 'metadata/' . str_replace('/', '.', $ident);
}
/**
@@ -436,9 +416,8 @@ public function cacheKeyFromMetaKey($ident)
private function filePathFromMetaKey($ident)
{
$filename = str_replace('\\', '.', $ident);
- $filename .= '.json';
- return $filename;
+ return $filename . '.json';
}
/**
@@ -451,15 +430,15 @@ private function classNameFromMetaKey($ident)
{
$key = $ident;
- if (isset(static::$camelCache[$key])) {
- return static::$camelCache[$key];
+ if (isset(self::$camelCache[$key])) {
+ return self::$camelCache[$key];
}
// Change "foo-bar" to "fooBar"
$parts = explode('-', $ident);
array_walk(
$parts,
- function (&$i) {
+ function (&$i): void {
$i = ucfirst($i);
}
);
@@ -471,14 +450,14 @@ function (&$i) {
array_walk(
$parts,
- function (&$i) {
+ function (&$i): void {
$i = ucfirst($i);
}
);
$classname = trim(implode('\\', $parts), '\\');
- static::$camelCache[$key] = $classname;
- static::$snakeCache[$classname] = $key;
+ self::$camelCache[$key] = $classname;
+ self::$snakeCache[$classname] = $key;
return $classname;
}
@@ -493,16 +472,16 @@ private function metaKeyFromClassName($class)
{
$key = trim($class, '\\');
- if (isset(static::$snakeCache[$key])) {
- return static::$snakeCache[$key];
+ if (isset(self::$snakeCache[$key])) {
+ return self::$snakeCache[$key];
}
- $ident = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $class));
+ $ident = strtolower((string)preg_replace('/([a-z])([A-Z])/', '$1-$2', $class));
$ident = str_replace('\\', '/', strtolower($ident));
$ident = ltrim($ident, '/');
- static::$snakeCache[$key] = $ident;
- static::$camelCache[$ident] = $key;
+ self::$snakeCache[$key] = $ident;
+ self::$camelCache[$ident] = $key;
return $ident;
}
@@ -515,9 +494,8 @@ private function metaKeyFromClassName($class)
* @param mixed $metadata The metadata type or container to validate.
* @param string|null $type If provided, then it is filled with the resolved metadata type.
* @param mixed|null $bag If provided, then it is filled with the resolved metadata container.
- * @return boolean
*/
- private function validateMetadataContainer($metadata, &$type = null, &$bag = null)
+ private function validateMetadataContainer($metadata, &$type = null, &$bag = null): bool
{
// If variables are provided, clear existing values.
$type = null;
@@ -531,7 +509,7 @@ private function validateMetadataContainer($metadata, &$type = null, &$bag = nul
if (is_a($metadata, MetadataInterface::class, true)) {
if (is_object($metadata)) {
- $type = get_class($metadata);
+ $type = $metadata::class;
$bag = $metadata;
return true;
}
@@ -549,9 +527,8 @@ private function validateMetadataContainer($metadata, &$type = null, &$bag = nul
*
* @param string $basePath The base path to use.
* @throws InvalidArgumentException If the base path parameter is not a string.
- * @return void
*/
- private function setBasePath($basePath)
+ private function setBasePath($basePath): void
{
if (!is_string($basePath)) {
throw new InvalidArgumentException(
@@ -565,10 +542,8 @@ private function setBasePath($basePath)
/**
* Retrieve the base path for relative search paths.
- *
- * @return string
*/
- private function basePath()
+ private function basePath(): string
{
return $this->basePath;
}
@@ -577,9 +552,8 @@ private function basePath()
* Assign many search paths.
*
* @param string[] $paths One or more search paths.
- * @return void
*/
- private function setPaths(array $paths)
+ private function setPaths(array $paths): void
{
$this->paths = [];
$this->addPaths($paths);
@@ -590,7 +564,7 @@ private function setPaths(array $paths)
*
* @return string[]
*/
- private function paths()
+ private function paths(): array
{
return $this->paths;
}
@@ -599,9 +573,8 @@ private function paths()
* Append many search paths.
*
* @param string[] $paths One or more search paths.
- * @return self
*/
- private function addPaths(array $paths)
+ private function addPaths(array $paths): self
{
foreach ($paths as $path) {
$this->addPath($path);
@@ -614,9 +587,8 @@ private function addPaths(array $paths)
* Append a search path.
*
* @param string $path A directory path.
- * @return self
*/
- private function addPath($path)
+ private function addPath($path): self
{
$path = $this->resolvePath($path);
@@ -632,9 +604,8 @@ private function addPath($path)
*
* @param string $path The path to resolve.
* @throws InvalidArgumentException If the path is invalid.
- * @return string
*/
- private function resolvePath($path)
+ private function resolvePath($path): string
{
if (!is_string($path)) {
throw new InvalidArgumentException(
@@ -645,7 +616,7 @@ private function resolvePath($path)
$basePath = $this->basePath();
$path = trim($path, '/\\');
- if ($basePath && strpos($path, $basePath) === false) {
+ if ($basePath && !str_contains($path, $basePath)) {
$path = $basePath . DIRECTORY_SEPARATOR . $path;
}
@@ -656,9 +627,8 @@ private function resolvePath($path)
* Validate a resolved path.
*
* @param string $path The path to validate.
- * @return string
*/
- private function validatePath($path)
+ private function validatePath(string $path): bool
{
return is_dir($path);
}
@@ -667,19 +637,16 @@ private function validatePath($path)
* Set the cache service.
*
* @param CacheItemPoolInterface $cache A PSR-6 compliant cache pool instance.
- * @return void
*/
- private function setCachePool(CacheItemPoolInterface $cache)
+ private function setCachePool(CacheItemPoolInterface $cache): void
{
$this->cachePool = $cache;
}
/**
* Retrieve the cache service.
- *
- * @return CacheItemPoolInterface
*/
- private function cachePool()
+ private function cachePool(): \Psr\Cache\CacheItemPoolInterface
{
return $this->cachePool;
}
diff --git a/packages/core/src/Charcoal/Model/Service/ModelBuilder.php b/packages/core/src/Charcoal/Model/Service/ModelBuilder.php
index d23fc9afc..667d238a1 100644
--- a/packages/core/src/Charcoal/Model/Service/ModelBuilder.php
+++ b/packages/core/src/Charcoal/Model/Service/ModelBuilder.php
@@ -14,22 +14,13 @@
*/
final class ModelBuilder
{
- public const DEFAULT_SOURCE_TYPE = 'database';
+ public const string DEFAULT_SOURCE_TYPE = 'database';
- /**
- * @var FactoryInterface
- */
- private $factory;
+ private \Charcoal\Factory\FactoryInterface $factory;
- /**
- * @var MetadataLoader
- */
- private $metadataLoader;
+ private \Charcoal\Model\Service\MetadataLoader $metadataLoader;
- /**
- * @var FactoryInterface
- */
- private $sourceFactory;
+ private \Charcoal\Factory\FactoryInterface $sourceFactory;
/**
* @param array $data Constructor dependencies.
@@ -84,27 +75,24 @@ public function __invoke($objType, $metadataIdent = null, $sourceIdent = null)
/**
* @param FactoryInterface $factory The factory to use to create models.
- * @return void
*/
- private function setFactory(FactoryInterface $factory)
+ private function setFactory(FactoryInterface $factory): void
{
$this->factory = $factory;
}
/**
* @param MetadataLoader $loader The loader instance, used to load metadata.
- * @return void
*/
- private function setMetadataLoader(MetadataLoader $loader)
+ private function setMetadataLoader(MetadataLoader $loader): void
{
$this->metadataLoader = $loader;
}
/**
* @param FactoryInterface $factory The factory to use to create models.
- * @return void
*/
- private function setSourceFactory(FactoryInterface $factory)
+ private function setSourceFactory(FactoryInterface $factory): void
{
$this->sourceFactory = $factory;
}
@@ -118,7 +106,7 @@ private function setSourceFactory(FactoryInterface $factory)
*/
private function createMetadata($objType, $metadataIdent = null)
{
- $metadataIdent = ($metadataIdent !== null) ? $metadataIdent : $objType;
+ $metadataIdent ??= $objType;
return $this->metadataLoader->load($metadataIdent, ModelMetadata::class);
}
@@ -139,11 +127,11 @@ private function createSource(ModelMetadata $metadata, $sourceIdent = null)
if (!$sourceConfig) {
throw new UnexpectedValueException(
- sprintf('Can not create %s source: "%s" is not defined in metadata.', get_class($this), $sourceIdent)
+ sprintf('Can not create %s source: "%s" is not defined in metadata.', self::class, $sourceIdent)
);
}
- $sourceType = isset($sourceConfig['type']) ? $sourceConfig['type'] : self::DEFAULT_SOURCE_TYPE;
+ $sourceType = ($sourceConfig['type'] ?? self::DEFAULT_SOURCE_TYPE);
$source = $this->sourceFactory->create($sourceType);
$source->setData($sourceConfig);
diff --git a/packages/core/src/Charcoal/Model/Service/ModelLoader.php b/packages/core/src/Charcoal/Model/Service/ModelLoader.php
index 3e776aa24..342803078 100644
--- a/packages/core/src/Charcoal/Model/Service/ModelLoader.php
+++ b/packages/core/src/Charcoal/Model/Service/ModelLoader.php
@@ -42,17 +42,13 @@ final class ModelLoader implements ArrayAccess
/**
* The model factory.
- *
- * @var FactoryInterface
*/
- private $factory;
+ private \Charcoal\Factory\FactoryInterface $factory;
/**
* The PSR-6 caching service.
- *
- * @var CacheItemPoolInterface
*/
- private $cachePool;
+ private \Psr\Cache\CacheItemPoolInterface $cachePool;
/**
* Construct a Model Loader with the dependencies
@@ -90,7 +86,7 @@ public function __construct(array $data)
* @param mixed $args Unused; Method arguments.
* @return ModelInterface
*/
- public function __call($ident, $args = null)
+ public function __call(string $ident, ?array $args = null)
{
unset($args);
@@ -103,7 +99,7 @@ public function __call($ident, $args = null)
* @param string|integer $ident The object identifier to load.
* @return ModelInterface
*/
- public function __get($ident)
+ public function __get(string $ident): mixed
{
return $this->load($ident);
}
@@ -115,7 +111,7 @@ public function __get($ident)
* @param string $ident The object identifier to lookup.
* @return boolean
*/
- public function __isset($ident)
+ public function __isset(string $ident)
{
return true;
}
@@ -127,7 +123,7 @@ public function __isset($ident)
* @throws LogicException This method should never be called.
* @return void
*/
- public function __unset($ident)
+ public function __unset(string $ident)
{
throw new LogicException(
'Can not unset value on a loader'
@@ -136,16 +132,14 @@ public function __unset($ident)
// Satisfies ArrayAccess
// =============================================================================================
-
/**
* Determine if an object exists by its key.
*
* @todo Needs implementation
* @see ArrayAccess::offsetExists
* @param string $ident The object identifier to lookup.
- * @return boolean
*/
- public function offsetExists($ident)
+ public function offsetExists($ident): bool
{
return true;
}
@@ -157,7 +151,7 @@ public function offsetExists($ident)
* @param string|integer $ident The object identifier to load.
* @return ModelInterface
*/
- public function offsetGet($ident)
+ public function offsetGet($ident): ModelInterface
{
return $this->load($ident);
}
@@ -169,9 +163,8 @@ public function offsetGet($ident)
* @param string|integer $ident The $object identifier.
* @param mixed $obj The object to add.
* @throws LogicException This method should never be called.
- * @return void
*/
- public function offsetSet($ident, $obj)
+ public function offsetSet($ident, $obj): never
{
throw new LogicException(
'Can not set value on a loader'
@@ -184,9 +177,8 @@ public function offsetSet($ident, $obj)
* @see ArrayAccess::offsetUnset()
* @param string|integer $ident The object identifier to remove.
* @throws LogicException This method should never be called.
- * @return void
*/
- public function offsetUnset($ident)
+ public function offsetUnset($ident): never
{
throw new LogicException(
'Can not unset value on a loader'
@@ -215,14 +207,11 @@ public function load($ident, $useCache = true, $reloadObj = false)
$cacheKey = $this->cacheKey($ident);
$cacheItem = $this->cachePool->getItem($cacheKey);
- if (!$reloadObj) {
- if ($cacheItem->isHit()) {
- $data = $cacheItem->get();
- $obj = $this->factory->create($this->objType);
- $obj->setData($data);
-
- return $obj;
- }
+ if (!$reloadObj && $cacheItem->isHit()) {
+ $data = $cacheItem->get();
+ $obj = $this->factory->create($this->objType);
+ $obj->setData($data);
+ return $obj;
}
$obj = $this->loadFromSource($ident);
@@ -264,9 +253,7 @@ private function cacheKey($ident)
$this->setObjKey($model->key());
}
- $cacheKey = 'object/' . str_replace('/', '.', $this->objType . '.' . $this->objKey . '.' . $ident);
-
- return $cacheKey;
+ return 'object/' . str_replace('/', '.', $this->objType . '.' . $this->objKey . '.' . $ident);
}
/**
@@ -276,9 +263,8 @@ private function cacheKey($ident)
*
* @param string $objType The object type to load with this loader.
* @throws InvalidArgumentException If the object type is not a string.
- * @return self
*/
- private function setObjType($objType)
+ private function setObjType($objType): self
{
if (!is_string($objType)) {
throw new InvalidArgumentException(
@@ -287,7 +273,7 @@ private function setObjType($objType)
}
$objType = preg_replace('/([a-z])([A-Z])/', '$1-$2', $objType);
- $objType = strtolower(str_replace('\\', '/', trim($objType, '\\/')));
+ $objType = strtolower(str_replace('\\', '/', trim((string)$objType, '\\/')));
$this->objType = $objType;
return $this;
@@ -298,9 +284,8 @@ private function setObjType($objType)
*
* @param string $objKey The object key to use for laoding.
* @throws InvalidArgumentException If the object key is not a string.
- * @return self
*/
- private function setObjKey($objKey)
+ private function setObjKey($objKey): self
{
if (empty($objKey) && !is_numeric($objKey)) {
$this->objKey = null;
@@ -321,9 +306,8 @@ private function setObjKey($objKey)
* Set the model factory.
*
* @param FactoryInterface $factory The factory to create models.
- * @return self
*/
- private function setFactory(FactoryInterface $factory)
+ private function setFactory(FactoryInterface $factory): self
{
$this->factory = $factory;
return $this;
@@ -333,9 +317,8 @@ private function setFactory(FactoryInterface $factory)
* Set the cache pool handler.
*
* @param CacheItemPoolInterface $cachePool A PSR-6 compatible cache pool.
- * @return self
*/
- private function setCachePool(CacheItemPoolInterface $cachePool)
+ private function setCachePool(CacheItemPoolInterface $cachePool): self
{
$this->cachePool = $cachePool;
return $this;
diff --git a/packages/core/src/Charcoal/Model/Service/ModelLoaderBuilder.php b/packages/core/src/Charcoal/Model/Service/ModelLoaderBuilder.php
index b1c66116c..d4f34fd84 100644
--- a/packages/core/src/Charcoal/Model/Service/ModelLoaderBuilder.php
+++ b/packages/core/src/Charcoal/Model/Service/ModelLoaderBuilder.php
@@ -16,15 +16,9 @@
*/
final class ModelLoaderBuilder
{
- /**
- * @var FactoryInterface
- */
- private $factory;
+ private \Charcoal\Factory\FactoryInterface $factory;
- /**
- * @var CacheItemPoolInterface
- */
- private $cachePool;
+ private \Psr\Cache\CacheItemPoolInterface $cachePool;
/**
* @param array $data Builder dependencies.
@@ -38,9 +32,8 @@ public function __construct(array $data)
/**
* @param string $objType The object type of the ModelLoader.
* @param string $objKey Optional object key, to set on the ModelLoader.
- * @return ModelLoader
*/
- public function build($objType, $objKey = null)
+ public function build($objType, $objKey = null): \Charcoal\Model\Service\ModelLoader
{
return new ModelLoader([
'factory' => $this->factory,
@@ -55,27 +48,24 @@ public function build($objType, $objKey = null)
*
* @param string $objType The object type of the ModelLoader.
* @param string $objKey Optional object key, to set on the ModelLoader.
- * @return ModelLoader
*/
- public function __invoke($objType, $objKey = null)
+ public function __invoke($objType, $objKey = null): \Charcoal\Model\Service\ModelLoader
{
return $this->build($objType, $objKey);
}
/**
* @param FactoryInterface $factory The factory to use to create models.
- * @return void
*/
- private function setFactory(FactoryInterface $factory)
+ private function setFactory(FactoryInterface $factory): void
{
$this->factory = $factory;
}
/**
* @param CacheItemPoolInterface $cachePool The PSR-6 compliant cache pool.
- * @return void
*/
- private function setCachePool(CacheItemPoolInterface $cachePool)
+ private function setCachePool(CacheItemPoolInterface $cachePool): void
{
$this->cachePool = $cachePool;
}
diff --git a/packages/core/src/Charcoal/Model/ServiceProvider/ModelServiceProvider.php b/packages/core/src/Charcoal/Model/ServiceProvider/ModelServiceProvider.php
index 3212f075b..aa52bc186 100644
--- a/packages/core/src/Charcoal/Model/ServiceProvider/ModelServiceProvider.php
+++ b/packages/core/src/Charcoal/Model/ServiceProvider/ModelServiceProvider.php
@@ -48,9 +48,8 @@ class ModelServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container A Pimple DI container.
- * @return void
*/
- public function register(Container $container)
+ public function register(Container $container): void
{
$this->registerModelDependencies($container);
$this->registerMetadataDependencies($container);
@@ -68,35 +67,29 @@ protected function registerBuilderDependencies(Container $container)
* @param Container $container A Pimple DI container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['model/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => ModelInterface::class,
- 'arguments' => [ $container['model/dependencies'] ]
- ]);
- };
+ $container['model/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => ModelInterface::class,
+ 'arguments' => [ $container['model/dependencies'] ]
+ ]));
/**
* @param Container $container A Pimple DI container.
* @return ModelBuilder
*/
- $container['model/builder'] = function (Container $container) {
- return new ModelBuilder([
- 'factory' => $container['model/factory'],
- 'metadata_loader' => $container['metadata/loader'],
- 'source_factory' => $container['source/factory']
- ]);
- };
+ $container['model/builder'] = (fn(Container $container): \Charcoal\Model\Service\ModelBuilder => new ModelBuilder([
+ 'factory' => $container['model/factory'],
+ 'metadata_loader' => $container['metadata/loader'],
+ 'source_factory' => $container['source/factory']
+ ]));
/**
* @param Container $container A Pimple DI container.
* @return ModelLoaderBuilder
*/
- $container['model/loader/builder'] = function (Container $container) {
- return new ModelLoaderBuilder([
- 'factory' => $container['model/factory'],
- 'cache' => $container['cache']
- ]);
- };
+ $container['model/loader/builder'] = (fn(Container $container): \Charcoal\Model\Service\ModelLoaderBuilder => new ModelLoaderBuilder([
+ 'factory' => $container['model/factory'],
+ 'cache' => $container['cache']
+ ]));
}
/**
@@ -112,9 +105,7 @@ protected function registerCollectionDependencies(Container $container)
* @param Container $container A Pimple DI container.
* @return \ArrayAccess|\Traversable
*/
- $container['model/collection'] = $container->factory(function (Container $container) {
- return new $container['model/collection/class']();
- });
+ $container['model/collection'] = $container->factory(fn(Container $container): object => new $container['model/collection/class']());
/**
* @param Container $container A Pimple DI container.
@@ -129,16 +120,14 @@ protected function registerCollectionDependencies(Container $container)
* @param Container $container A Pimple DI container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['model/collection/loader/factory'] = function (Container $container) {
- return new Factory([
- 'default_class' => CollectionLoader::class,
- 'arguments' => [[
- 'logger' => $container['logger'],
- 'factory' => $container['model/factory'],
- 'collection' => $container['model/collection/class']
- ]]
- ]);
- };
+ $container['model/collection/loader/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'default_class' => CollectionLoader::class,
+ 'arguments' => [[
+ 'logger' => $container['logger'],
+ 'factory' => $container['model/factory'],
+ 'collection' => $container['model/collection/class']
+ ]]
+ ]));
}
/**
@@ -153,16 +142,14 @@ protected function registerModelDependencies(Container $container)
* @param Container $container A Pimple DI container.
* @return array The model dependencies array.
*/
- $container['model/dependencies'] = function (Container $container) {
- return [
- 'container' => $container,
- 'logger' => $container['logger'],
- 'view' => $container['view'],
- 'property_factory' => $container['property/factory'],
- 'metadata_loader' => $container['metadata/loader'],
- 'source_factory' => $container['source/factory']
- ];
- };
+ $container['model/dependencies'] = (fn(Container $container): array => [
+ 'container' => $container,
+ 'logger' => $container['logger'],
+ 'view' => $container['view'],
+ 'property_factory' => $container['property/factory'],
+ 'metadata_loader' => $container['metadata/loader'],
+ 'source_factory' => $container['source/factory']
+ ]);
}
// The property factory might be already set from elsewhere; defines it if not.
@@ -171,22 +158,20 @@ protected function registerModelDependencies(Container $container)
* @param Container $container A Pimple DI container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['property/factory'] = function (Container $container) {
- return new Factory([
- 'base_class' => PropertyInterface::class,
- 'default_class' => GenericProperty::class,
- 'resolver_options' => [
- 'prefix' => '\\Charcoal\\Property\\',
- 'suffix' => 'Property'
- ],
- 'arguments' => [[
- 'container' => $container,
- 'database' => $container['database'],
- 'logger' => $container['logger'],
- 'translator' => $container['translator']
- ]]
- ]);
- };
+ $container['property/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'base_class' => PropertyInterface::class,
+ 'default_class' => GenericProperty::class,
+ 'resolver_options' => [
+ 'prefix' => '\\Charcoal\\Property\\',
+ 'suffix' => 'Property'
+ ],
+ 'arguments' => [[
+ 'container' => $container,
+ 'database' => $container['database'],
+ 'logger' => $container['logger'],
+ 'translator' => $container['translator']
+ ]]
+ ]));
}
if (!isset($container['source/factory'])) {
@@ -194,19 +179,17 @@ protected function registerModelDependencies(Container $container)
* @param Container $container A Pimple DI container.
* @return \Charcoal\Factory\FactoryInterface
*/
- $container['source/factory'] = function (Container $container) {
- return new Factory([
- 'map' => [
- 'database' => DatabaseSource::class
- ],
- 'base_class' => SourceInterface::class,
- 'arguments' => [[
- 'logger' => $container['logger'],
- 'cache' => $container['cache'],
- 'pdo' => $container['database']
- ]]
- ]);
- };
+ $container['source/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'map' => [
+ 'database' => DatabaseSource::class
+ ],
+ 'base_class' => SourceInterface::class,
+ 'arguments' => [[
+ 'logger' => $container['logger'],
+ 'cache' => $container['cache'],
+ 'pdo' => $container['database']
+ ]]
+ ]));
}
}
@@ -223,9 +206,9 @@ protected function registerMetadataDependencies(Container $container)
* @param Container $container Pimple DI container.
* @return MetadataConfig
*/
- $container['metadata/config'] = function (Container $container) {
- $appConfig = isset($container['config']) ? $container['config'] : [];
- $metaConfig = isset($appConfig['metadata']) ? $appConfig['metadata'] : null;
+ $container['metadata/config'] = function (Container $container): \Charcoal\Model\Service\MetadataConfig {
+ $appConfig = ($container['config'] ?? []);
+ $metaConfig = ($appConfig['metadata'] ?? null);
$metaConfig = new MetadataConfig($metaConfig);
if (isset($container['module/classes'])) {
@@ -234,7 +217,7 @@ protected function registerMetadataDependencies(Container $container)
$modules = $container['module/classes'];
foreach ($modules as $module) {
if (defined(sprintf('%s::APP_CONFIG', $module))) {
- $configPath = ltrim($module::APP_CONFIG, '/');
+ $configPath = ltrim((string)$module::APP_CONFIG, '/');
$configPath = $basePath . DIRECTORY_SEPARATOR . $configPath;
$configData = $metaConfig->loadFile($configPath);
@@ -247,7 +230,7 @@ protected function registerMetadataDependencies(Container $container)
};
}
- if (!empty($extraPaths)) {
+ if ($extraPaths !== []) {
$metaConfig->addPaths($extraPaths);
}
}
@@ -288,7 +271,7 @@ protected function registerMetadataDependencies(Container $container)
* @param Container $container A Pimple DI container.
* @return MetadataLoader
*/
- $container['metadata/loader'] = function (Container $container) {
+ $container['metadata/loader'] = function (Container $container): \Charcoal\Model\Service\MetadataLoader {
$appConfig = $container['config'];
$metaConfig = $container['metadata/config'];
diff --git a/packages/core/src/Charcoal/Source/AbstractExpression.php b/packages/core/src/Charcoal/Source/AbstractExpression.php
index fe6b88a61..5b48a0ffa 100644
--- a/packages/core/src/Charcoal/Source/AbstractExpression.php
+++ b/packages/core/src/Charcoal/Source/AbstractExpression.php
@@ -71,7 +71,7 @@ abstract public function data();
*/
public function setActive($active)
{
- $this->active = !!$active;
+ $this->active = (bool)$active;
return $this;
}
@@ -183,7 +183,7 @@ public static function quoteIdentifier($identifier, $tableName = null)
if (!is_string($identifier)) {
throw new InvalidArgumentException(sprintf(
'Field Name must be a string, received %s',
- is_object($identifier) ? get_class($identifier) : gettype($identifier)
+ get_debug_type($identifier)
));
}
@@ -191,7 +191,7 @@ public static function quoteIdentifier($identifier, $tableName = null)
if (!is_string($tableName)) {
throw new InvalidArgumentException(sprintf(
'Table Name must be a string, received %s',
- is_object($tableName) ? get_class($tableName) : gettype($tableName)
+ get_debug_type($tableName)
));
}
@@ -201,11 +201,7 @@ public static function quoteIdentifier($identifier, $tableName = null)
);
}
- if ($identifier === '*') {
- $template = '%1$s.*';
- } else {
- $template = '%1$s.`%2$s`';
- }
+ $template = $identifier === '*' ? '%1$s.*' : '%1$s.`%2$s`';
return sprintf($template, $tableName, $identifier);
}
@@ -255,9 +251,9 @@ public static function isCallable($value)
* @uses self::diffValues()
* @return array An associative array containing only mutated values.
*/
- public function jsonSerialize()
+ public function jsonSerialize(): array
{
- return array_udiff_assoc($this->data(), $this->defaultData(), [ $this, 'diffValues' ]);
+ return array_udiff_assoc($this->data(), $this->defaultData(), $this->diffValues(...));
}
/**
@@ -276,9 +272,8 @@ public function serialize()
*
* @see Serializable
* @param string $data The serialized data.
- * @return void
*/
- public function unserialize($data)
+ public function unserialize($data): void
{
$data = unserialize($data);
$this->setData($data);
diff --git a/packages/core/src/Charcoal/Source/AbstractSource.php b/packages/core/src/Charcoal/Source/AbstractSource.php
index b5e1dab1e..a980076ca 100644
--- a/packages/core/src/Charcoal/Source/AbstractSource.php
+++ b/packages/core/src/Charcoal/Source/AbstractSource.php
@@ -29,6 +29,7 @@
/**
* Data Storage Source Handler.
*/
+#[\AllowDynamicProperties]
abstract class AbstractSource implements
SourceInterface,
ConfigurableInterface,
@@ -227,7 +228,6 @@ protected function resolvePropertyName($property)
* - as 3 parameters: `property`, `value` and `options`
* - `addFilter('foo', 42, ['operator' => '<=']);`
*
- * @deprecated 0.3 To be replaced with FilterCollectionTrait::addFilter()
*
* @uses self::parseFilterWithModel()
* @uses FilterCollectionTrait::processFilter()
@@ -239,8 +239,10 @@ protected function resolvePropertyName($property)
* @param array $options Optional extra settings to apply on the filter.
* @throws InvalidArgumentException If the $param argument is invalid.
* @return self
+ *
*/
- public function addFilter($param, $value = null, array $options = null)
+ #![\Deprecated(message: '0.3 To be replaced with FilterCollectionTrait::addFilter()')
+ public function addFilter($param, $value = null, ?array $options = null)
{
if (is_string($param) && $value !== null) {
$expr = $this->createFilter();
@@ -292,7 +294,7 @@ protected function parseFilterWithModel(FilterInterface $filter)
}
if ($filter instanceof FilterCollectionInterface) {
- $filter->traverseFilters(function (FilterInterface $expr) {
+ $filter->traverseFilters(function (FilterInterface $expr): void {
$this->parseFilterWithModel($expr);
});
}
@@ -308,7 +310,7 @@ protected function parseFilterWithModel(FilterInterface $filter)
* @param array $data Optional expression data.
* @return FilterInterface A new filter expression object.
*/
- protected function createFilter(array $data = null)
+ protected function createFilter(?array $data = null)
{
$filter = new Filter();
if ($data !== null) {
@@ -320,7 +322,6 @@ protected function createFilter(array $data = null)
/**
* Append a query order on the source.
*
- * @deprecated 0.3 To be replaced with OrderCollectionTrait::addOrder()
*
* @uses self::parseOrderWithModel()
* @uses OrderCollectionTrait::processOrder()
@@ -333,7 +334,8 @@ protected function createFilter(array $data = null)
* @throws InvalidArgumentException If the $param argument is invalid.
* @return self
*/
- public function addOrder($param, $mode = 'asc', array $options = null)
+ #![\Deprecated(message: '0.3 To be replaced with OrderCollectionTrait::addOrder()')]
+ public function addOrder($param, $mode = 'asc', ?array $options = null)
{
if (is_string($param) && $mode !== null) {
$expr = $this->createOrder();
@@ -380,7 +382,7 @@ protected function parseOrderWithModel(OrderInterface $order)
}
if ($order instanceof OrderCollectionInterface) {
- $order->traverseOrders(function (OrderInterface $expr) {
+ $order->traverseOrders(function (OrderInterface $expr): void {
$this->parseOrderWithModel($expr);
});
}
@@ -395,7 +397,7 @@ protected function parseOrderWithModel(OrderInterface $order)
* @param array $data Optional expression data.
* @return OrderInterface
*/
- protected function createOrder(array $data = null)
+ protected function createOrder(?array $data = null)
{
$order = new Order();
if ($data !== null) {
@@ -467,7 +469,7 @@ public function pagination()
* @param array $data Optional clause data.
* @return PaginationInterface
*/
- protected function createPagination(array $data = null)
+ protected function createPagination(?array $data = null)
{
$pagination = new Pagination();
if ($data !== null) {
@@ -529,10 +531,9 @@ public function numPerPage()
* @param array $data Optional data.
* @return SourceConfig
*/
- public function createConfig(array $data = null)
+ public function createConfig(?array $data = null)
{
- $config = new SourceConfig($data);
- return $config;
+ return new SourceConfig($data);
}
/**
@@ -542,7 +543,7 @@ public function createConfig(array $data = null)
* @param StorableInterface $item Optional item to load into.
* @return StorableInterface
*/
- abstract public function loadItem($ident, StorableInterface $item = null);
+ abstract public function loadItem($ident, ?StorableInterface $item = null);
/**
* Load items for the given model.
@@ -550,7 +551,7 @@ abstract public function loadItem($ident, StorableInterface $item = null);
* @param StorableInterface|null $item Optional model.
* @return StorableInterface[]
*/
- abstract public function loadItems(StorableInterface $item = null);
+ abstract public function loadItems(?StorableInterface $item = null);
/**
* Save an item (create a new row) in storage.
@@ -568,7 +569,7 @@ abstract public function saveItem(StorableInterface $item);
* @param array $properties The list of properties to update, if not all.
* @return boolean TRUE if the item was updated, otherwise FALSE.
*/
- abstract public function updateItem(StorableInterface $item, array $properties = null);
+ abstract public function updateItem(StorableInterface $item, ?array $properties = null);
/**
* Delete an item from storage.
@@ -577,7 +578,7 @@ abstract public function updateItem(StorableInterface $item, array $properties =
* @throws UnexpectedValueException If the item does not have an ID.
* @return boolean TRUE if the item was deleted, otherwise FALSE.
*/
- abstract public function deleteItem(StorableInterface $item = null);
+ abstract public function deleteItem(?StorableInterface $item = null);
/**
* Allow an object to define how the key getter are called.
@@ -597,7 +598,7 @@ protected function getter($key)
* @param string $key The key to get the setter from.
* @return string The setter method name, for a given key.
*/
- protected function setter($key)
+ protected function setter(string $key)
{
$setter = 'set_' . $key;
return $this->camelize($setter);
@@ -611,7 +612,7 @@ protected function setter($key)
*/
protected function camelize($str)
{
- return lcfirst(implode('', array_map('ucfirst', explode('_', $str))));
+ return lcfirst(implode('', array_map(ucfirst(...), explode('_', $str))));
}
/**
@@ -620,7 +621,7 @@ protected function camelize($str)
protected function getModelClassForException()
{
if ($this->hasModel()) {
- return get_class($this->model());
+ return $this->model()::class;
}
return 'Unknown Model';
diff --git a/packages/core/src/Charcoal/Source/Database/DatabaseExpression.php b/packages/core/src/Charcoal/Source/Database/DatabaseExpression.php
index c58ff74bd..5526333a7 100644
--- a/packages/core/src/Charcoal/Source/Database/DatabaseExpression.php
+++ b/packages/core/src/Charcoal/Source/Database/DatabaseExpression.php
@@ -1,5 +1,7 @@
operator(), [ '!', 'NOT' ]);
}
@@ -88,9 +87,8 @@ public function isNegating()
*
* @param string[] $conditions The list of conditions to compile.
* @param string|null $conjunction The condition separator.
- * @return string
*/
- protected function compileConditions(array $conditions, $conjunction = null)
+ protected function compileConditions(array $conditions, $conjunction = null): string
{
if (count($conditions) === 1) {
return $conditions[0];
@@ -124,9 +122,8 @@ protected function byCondition()
* Retrieve the correctly parenthesized and nested WHERE conditions.
*
* @throws UnexpectedValueException If the custom condition is empty.
- * @return string
*/
- protected function byFilters()
+ protected function byFilters(): string
{
if (!$this->hasFilters()) {
throw new UnexpectedValueException(
@@ -140,7 +137,7 @@ protected function byFilters()
$filter = $filter->sql();
}
- if ($filter && strlen($filter) > 0) {
+ if ($filter && (string)$filter !== '') {
$conditions[] = $filter;
}
}
@@ -153,12 +150,11 @@ protected function byFilters()
*
* @todo Values are often not quoted.
* @throws UnexpectedValueException If any required property, function, operator, or value is empty.
- * @return string
*/
- protected function byPredicate()
+ protected function byPredicate(): string
{
$fields = $this->fieldIdentifiers();
- if (empty($fields)) {
+ if ($fields === []) {
throw new UnexpectedValueException(
'Property is required.'
);
@@ -169,11 +165,7 @@ protected function byPredicate()
$operator = $this->operator();
$function = $this->func();
foreach ($fields as $fieldName) {
- if ($function !== null) {
- $target = sprintf('%1$s(%2$s)', $function, $fieldName);
- } else {
- $target = $fieldName;
- }
+ $target = $function !== null ? sprintf('%1$s(%2$s)', $function, $fieldName) : $fieldName;
switch ($operator) {
case 'FIND_IN_SET':
diff --git a/packages/core/src/Charcoal/Source/Database/DatabaseOrder.php b/packages/core/src/Charcoal/Source/Database/DatabaseOrder.php
index c587e600a..9b1ce2ee3 100644
--- a/packages/core/src/Charcoal/Source/Database/DatabaseOrder.php
+++ b/packages/core/src/Charcoal/Source/Database/DatabaseOrder.php
@@ -29,10 +29,9 @@ class DatabaseOrder extends Order implements
/**
* Retrieve the default values for sorting.
- *
- * @return array
*/
- public function defaultData()
+ #[\Override]
+ public function defaultData(): array
{
$defaults = parent::defaultData();
$defaults['table'] = DatabaseSource::DEFAULT_TABLE_ALIAS;
@@ -77,10 +76,8 @@ public function sql()
/**
* Retrieve the ORDER BY clause for the {@see self::MODE_RANDOM} mode.
- *
- * @return string
*/
- protected function byRandom()
+ protected function byRandom(): string
{
return 'RAND()';
}
@@ -89,12 +86,11 @@ protected function byRandom()
* Generate the ORDER BY clause(s) for the direction mode.
*
* @throws UnexpectedValueException If any required property is empty.
- * @return string
*/
- protected function byProperty()
+ protected function byProperty(): string
{
$fields = $this->fieldIdentifiers();
- if (empty($fields)) {
+ if ($fields === []) {
throw new UnexpectedValueException(
'Property is required.'
);
@@ -127,19 +123,18 @@ protected function byCondition()
* Retrieve the ORDER BY clause for the {@see self::MODE_VALUES} mode.
*
* @throws UnexpectedValueException If any required property or values is empty.
- * @return string
*/
- protected function byValues()
+ protected function byValues(): string
{
$fields = $this->fieldIdentifiers();
- if (empty($fields)) {
+ if ($fields === []) {
throw new UnexpectedValueException(
'Property is required.'
);
}
$values = $this->prepareValues($this->values());
- if (empty($values)) {
+ if ($values === []) {
throw new UnexpectedValueException(sprintf(
'Value can not be empty on fields: %s',
implode(', ', $fields)
@@ -164,7 +159,7 @@ protected function byValues()
* @param mixed $values The value to be normalized.
* @return array Returns a collection of parsed values.
*/
- public function prepareValues($values)
+ public function prepareValues($values): array
{
if (empty($values)) {
return [];
@@ -174,9 +169,8 @@ public function prepareValues($values)
$values = (array)$values;
}
- $values = array_filter($values, 'is_scalar');
- $values = array_map('self::quoteValue', $values);
+ $values = array_filter($values, is_scalar(...));
- return $values;
+ return array_map(self::quoteValue(...), $values);
}
}
diff --git a/packages/core/src/Charcoal/Source/Database/DatabasePagination.php b/packages/core/src/Charcoal/Source/Database/DatabasePagination.php
index 34af33a3f..6b9993a7e 100644
--- a/packages/core/src/Charcoal/Source/Database/DatabasePagination.php
+++ b/packages/core/src/Charcoal/Source/Database/DatabasePagination.php
@@ -1,5 +1,7 @@
active() && $this->hasLimit()) {
$limit = $this->limit();
@@ -31,10 +33,8 @@ public function sql()
/**
* Determine if the expression has a number per page.
- *
- * @return boolean
*/
- public function hasLimit()
+ public function hasLimit(): bool
{
return ($this->limit() > 0);
}
@@ -51,10 +51,8 @@ public function limit()
/**
* Retrieve the offset from the page number and count.
- *
- * @return integer
*/
- public function offset()
+ public function offset(): int
{
$page = $this->page();
$limit = $this->numPerPage();
diff --git a/packages/core/src/Charcoal/Source/DatabaseSource.php b/packages/core/src/Charcoal/Source/DatabaseSource.php
index 1c27b0ef9..934af45bc 100644
--- a/packages/core/src/Charcoal/Source/DatabaseSource.php
+++ b/packages/core/src/Charcoal/Source/DatabaseSource.php
@@ -22,6 +22,7 @@
/**
* Database Source Handler, through PDO.
*/
+#[\AllowDynamicProperties]
class DatabaseSource extends AbstractSource implements
DatabaseSourceInterface
{
@@ -32,6 +33,8 @@ class DatabaseSource extends AbstractSource implements
public const MYSQL_DRIVER_NAME = 'mysql';
public const SQLITE_DRIVER_NAME = 'sqlite';
+ protected array $tableExistsCache = [];
+
/**
* The database connector.
*
@@ -41,10 +44,8 @@ class DatabaseSource extends AbstractSource implements
/**
* The {@see self::$model}'s table name.
- *
- * @var string
*/
- private $table;
+ private ?string $table = null;
/**
* Create a new database handler.
@@ -80,9 +81,8 @@ public function db()
*
* @param string $table The source table.
* @throws InvalidArgumentException If argument is not a string or alphanumeric/underscore.
- * @return self
*/
- public function setTable($table)
+ public function setTable($table): static
{
if (!is_string($table)) {
throw new InvalidArgumentException(sprintf(
@@ -97,7 +97,7 @@ public function setTable($table)
* are valid table names; Although SQL can support more,
* there's really no reason to.
*/
- if (!preg_match('/[A-Za-z0-9_]/', $table)) {
+ if (!preg_match('/\w/', $table)) {
throw new InvalidArgumentException(sprintf(
'[%s] Database table name "%s" is invalid: must be alphanumeric / underscore',
$this->getModelClassForException(),
@@ -111,21 +111,18 @@ public function setTable($table)
/**
* Determine if a table is assigned.
- *
- * @return boolean
*/
- public function hasTable()
+ public function hasTable(): bool
{
- return !empty($this->table);
+ return !in_array($this->table, [null, '', '0'], true);
}
/**
* Get the database's current table.
*
* @throws RuntimeException If the table was not set.
- * @return string
*/
- public function table()
+ public function table(): string
{
if ($this->table === null) {
throw new RuntimeException(sprintf(
@@ -141,7 +138,7 @@ public function table()
*
* @return boolean TRUE if the table was created, otherwise FALSE.
*/
- public function createTable()
+ public function createTable(): bool
{
if ($this->tableExists() === true) {
return true;
@@ -178,7 +175,7 @@ public function createTable()
/** @todo Add indexes for all defined list constraints (yea... tough job...) */
if ($driver === self::MYSQL_DRIVER_NAME) {
$engine = 'InnoDB';
- $query .= ') ENGINE=' . $engine . ' DEFAULT CHARSET=utf8 COMMENT="' . addslashes($metadata['name']) . '";';
+ $query .= ') ENGINE=' . $engine . ' DEFAULT CHARSET=utf8 COMMENT="' . addslashes((string)$metadata['name']) . '";';
} else {
$query .= ');';
}
@@ -196,7 +193,7 @@ public function createTable()
*
* @return boolean TRUE if the table was altered, otherwise FALSE.
*/
- public function alterTable()
+ public function alterTable(): bool
{
if ($this->tableExists() === false) {
return false;
@@ -209,7 +206,7 @@ public function alterTable()
foreach ($fields as $field) {
$ident = $field->ident();
- if (!array_key_exists($ident, $cols)) {
+ if (!array_key_exists((string)$ident, $cols)) {
$fieldSql = $field->sql();
if ($fieldSql) {
// The key does not exist at all.
@@ -226,30 +223,27 @@ public function alterTable()
// The key exists. Validate.
$col = $cols[$ident];
$alter = true;
- if (strtolower($col['Type']) !== strtolower($field->sqlType())) {
+ if (strtolower((string)$col['Type']) !== strtolower($field->sqlType())) {
$alter = true;
}
- if ((strtolower($col['Null']) !== 'no') !== $field->allowNull()) {
+ if ((strtolower((string)$col['Null']) !== 'no') !== $field->allowNull()) {
$alter = true;
}
if ($col['Default'] !== $field->defaultVal()) {
$alter = true;
}
-
- if ($alter === true) {
- $fieldSql = $field->sql();
- if ($fieldSql) {
- $query = 'ALTER TABLE `' . $table . '` CHANGE `' . $ident . '` ' . $fieldSql;
- $this->logger->debug($query);
- $dbh->query($query);
- } else {
- $this->logger->warning('Empty column definition.', [
- 'table' => $table,
- 'field' => $ident,
- ]);
- }
+ $fieldSql = $field->sql();
+ if ($fieldSql) {
+ $query = 'ALTER TABLE `' . $table . '` CHANGE `' . $ident . '` ' . $fieldSql;
+ $this->logger->debug($query);
+ $dbh->query($query);
+ } else {
+ $this->logger->warning('Empty column definition.', [
+ 'table' => $table,
+ 'field' => $ident,
+ ]);
}
}
}
@@ -264,11 +258,11 @@ public function alterTable()
*/
public function tableExists()
{
- $dbh = $this->db();
+ $this->db();
$table = $this->table();
- if (isset($dbh->tableExists, $dbh->tableExists[$table])) {
- return $dbh->tableExists[$table];
+ if (isset($this->tableExistsCache[$table])) {
+ return $this->tableExistsCache[$table];
}
$exists = $this->performTableExists();
@@ -282,7 +276,7 @@ public function tableExists()
*
* @return boolean TRUE if the table exists, otherwise FALSE.
*/
- protected function performTableExists()
+ protected function performTableExists(): bool
{
$dbh = $this->db();
$table = $this->table();
@@ -309,14 +303,9 @@ protected function performTableExists()
*/
protected function setTableExists($exists = true)
{
- $dbh = $this->db();
$table = $this->table();
- if (!isset($dbh->tableExists)) {
- $dbh->tableExists = [];
- }
-
- $dbh->tableExists[$table] = $exists;
+ $this->tableExistsCache[$table] = $exists;
}
/**
@@ -345,9 +334,9 @@ public function tableStructure()
// Normalize SQLite's result (PRAGMA) with mysql's (SHOW COLUMNS)
$struct[$col['name']] = [
'Type' => $col['type'],
- 'Null' => !!$col['notnull'] ? 'NO' : 'YES',
+ 'Null' => $col['notnull'] ? 'NO' : 'YES',
'Default' => $col['dflt_value'],
- 'Key' => !!$col['pk'] ? 'PRI' : '',
+ 'Key' => $col['pk'] ? 'PRI' : '',
'Extra' => '',
];
}
@@ -362,7 +351,7 @@ public function tableStructure()
*
* @return boolean TRUE if the table has no data, otherwise FALSE.
*/
- public function tableIsEmpty()
+ public function tableIsEmpty(): bool
{
$table = $this->table();
$query = sprintf('SELECT NULL FROM `%s` LIMIT 1', $table);
@@ -380,7 +369,7 @@ public function tableIsEmpty()
* If NULL, retrieve all (from metadata).
* @return PropertyField[]
*/
- private function getModelFields(ModelInterface $model, $properties = null)
+ private function getModelFields(ModelInterface $model, ?array $properties = null): array
{
if ($properties === null) {
// No custom properties; use all (from model metadata)
@@ -398,7 +387,7 @@ private function getModelFields(ModelInterface $model, $properties = null)
}
$val = $model->propertyValue($propertyIdent);
- foreach ($prop->fields($val) as $fieldIdent => $field) {
+ foreach ($prop->fields($val) as $field) {
$fields[$field->ident()] = $field;
}
}
@@ -413,7 +402,7 @@ private function getModelFields(ModelInterface $model, $properties = null)
* @param StorableInterface $item Optional item to load into.
* @return StorableInterface
*/
- public function loadItem($ident, StorableInterface $item = null)
+ public function loadItem($ident, ?StorableInterface $item = null)
{
$key = $this->model()->key();
@@ -429,12 +418,12 @@ public function loadItem($ident, StorableInterface $item = null)
* @throws \Exception If the query fails.
* @return StorableInterface
*/
- public function loadItemFromKey($key, $ident, StorableInterface $item = null)
+ public function loadItemFromKey($key, $ident, ?StorableInterface $item = null)
{
- if ($item !== null) {
+ if ($item instanceof \Charcoal\Source\StorableInterface) {
$this->setModel($item);
} else {
- $class = get_class($this->model());
+ $class = $this->model()::class;
$item = new $class();
}
@@ -472,12 +461,12 @@ public function loadItemFromKey($key, $ident, StorableInterface $item = null)
* @throws PDOException If there is a query error.
* @return StorableInterface
*/
- public function loadItemFromQuery($query, array $binds = [], StorableInterface $item = null)
+ public function loadItemFromQuery($query, array $binds = [], ?StorableInterface $item = null): object
{
- if ($item !== null) {
+ if ($item instanceof \Charcoal\Source\StorableInterface) {
$this->setModel($item);
} else {
- $class = get_class($this->model());
+ $class = $this->model()::class;
$item = new $class();
}
@@ -508,9 +497,9 @@ public function loadItemFromQuery($query, array $binds = [], StorableInterface $
* @param StorableInterface|null $item Optional model.
* @return StorableInterface[]
*/
- public function loadItems(StorableInterface $item = null)
+ public function loadItems(?StorableInterface $item = null): array
{
- if ($item !== null) {
+ if ($item instanceof \Charcoal\Source\StorableInterface) {
$this->setModel($item);
}
@@ -526,9 +515,9 @@ public function loadItems(StorableInterface $item = null)
* @param StorableInterface|null $item Model Item.
* @return StorableInterface[]
*/
- public function loadItemsFromQuery($query, array $binds = [], StorableInterface $item = null)
+ public function loadItemsFromQuery($query, array $binds = [], ?StorableInterface $item = null): array
{
- if ($item !== null) {
+ if ($item instanceof \Charcoal\Source\StorableInterface) {
$this->setModel($item);
}
@@ -541,14 +530,14 @@ public function loadItemsFromQuery($query, array $binds = [], StorableInterface
$sth = $dbh->prepare($query);
// @todo Binds
- if (!empty($binds)) {
+ if ($binds !== []) {
unset($binds);
}
$sth->execute();
$sth->setFetchMode(PDO::FETCH_ASSOC);
- $className = get_class($model);
+ $className = $model::class;
while ($objData = $sth->fetch()) {
$obj = new $className();
$obj->setFlatData($objData);
@@ -572,9 +561,7 @@ public function saveItem(StorableInterface $item)
$this->createTable();
}
- if ($item !== null) {
- $this->setModel($item);
- }
+ $this->setModel($item);
$model = $this->model();
$table = $this->table();
$struct = array_keys($this->tableStructure());
@@ -609,12 +596,10 @@ public function saveItem(StorableInterface $item)
'[%s] Could not save item',
$this->getModelClassForException()
));
+ } elseif ($model->id()) {
+ return $model->id();
} else {
- if ($model->id()) {
- return $model->id();
- } else {
- return $this->db()->lastInsertId();
- }
+ return $this->db()->lastInsertId();
}
}
@@ -625,11 +610,9 @@ public function saveItem(StorableInterface $item)
* @param array $properties The list of properties to update, if not all.
* @return boolean TRUE if the item was updated, otherwise FALSE.
*/
- public function updateItem(StorableInterface $item, array $properties = null)
+ public function updateItem(StorableInterface $item, ?array $properties = null): bool
{
- if ($item !== null) {
- $this->setModel($item);
- }
+ $this->setModel($item);
$model = $this->model();
$table = $this->table();
$struct = array_keys($this->tableStructure());
@@ -651,7 +634,7 @@ public function updateItem(StorableInterface $item, array $properties = null)
$this->logger->warning(
sprintf('Field "%s" not in table structure', $key),
[
- 'model' => get_class($model),
+ 'model' => $model::class,
'table' => $table,
'field' => $key,
]
@@ -659,11 +642,11 @@ public function updateItem(StorableInterface $item, array $properties = null)
}
}
- if (empty($updates)) {
+ if ($updates === []) {
$this->logger->warning(
'Could not update items. No valid fields were set or available in database table.',
[
- 'model' => get_class($model),
+ 'model' => $model::class,
'table' => $table,
'properties' => $properties,
'structure' => $struct
@@ -704,9 +687,9 @@ public function updateItem(StorableInterface $item, array $properties = null)
* @throws UnexpectedValueException If the item does not have an ID.
* @return boolean TRUE if the item was deleted, otherwise FALSE.
*/
- public function deleteItem(StorableInterface $item = null)
+ public function deleteItem(?StorableInterface $item = null): bool
{
- if ($item !== null) {
+ if ($item instanceof \Charcoal\Source\StorableInterface) {
$this->setModel($item);
}
@@ -798,17 +781,15 @@ public function dbPrepare($query, array $binds = [], array $types = [])
return false;
}
- if (!empty($binds)) {
- foreach ($binds as $key => $val) {
- if ($binds[$key] === null) {
- $types[$key] = PDO::PARAM_NULL;
- } elseif (!is_scalar($binds[$key])) {
- $binds[$key] = json_encode($binds[$key]);
- }
- $type = (isset($types[$key]) ? $types[$key] : PDO::PARAM_STR);
- $param = ':' . $key;
- $sth->bindParam($param, $binds[$key], $type);
+ foreach (array_keys($binds) as $key) {
+ if ($binds[$key] === null) {
+ $types[$key] = PDO::PARAM_NULL;
+ } elseif (!is_scalar($binds[$key])) {
+ $binds[$key] = json_encode($binds[$key]);
}
+ $type = ($types[$key] ?? PDO::PARAM_STR);
+ $param = ':' . $key;
+ $sth->bindParam($param, $binds[$key], $type);
}
return $sth;
@@ -818,9 +799,8 @@ public function dbPrepare($query, array $binds = [], array $types = [])
* Compile the SELECT statement for fetching one or more objects.
*
* @throws UnexpectedValueException If the source does not have a table defined.
- * @return string
*/
- public function sqlLoad()
+ public function sqlLoad(): string
{
if (!$this->hasTable()) {
throw new UnexpectedValueException(sprintf(
@@ -834,18 +814,15 @@ public function sqlLoad()
$filters = $this->sqlFilters();
$orders = $this->sqlOrders();
$limits = $this->sqlPagination();
-
- $query = 'SELECT ' . $selects . ' FROM ' . $tables . $filters . $orders . $limits;
- return $query;
+ return 'SELECT ' . $selects . ' FROM ' . $tables . $filters . $orders . $limits;
}
/**
* Compile the SELECT statement for fetching the number of objects.
*
* @throws UnexpectedValueException If the source does not have a table defined.
- * @return string
*/
- public function sqlLoadCount()
+ public function sqlLoadCount(): string
{
if (!$this->hasTable()) {
throw new UnexpectedValueException(sprintf(
@@ -856,18 +833,15 @@ public function sqlLoadCount()
$tables = $this->sqlFrom();
$filters = $this->sqlFilters();
-
- $query = 'SELECT COUNT(*) FROM ' . $tables . $filters;
- return $query;
+ return 'SELECT COUNT(*) FROM ' . $tables . $filters;
}
/**
* Compile the SELECT clause.
*
* @throws UnexpectedValueException If the clause has no selectable fields.
- * @return string
*/
- public function sqlSelect()
+ public function sqlSelect(): string
{
$properties = $this->properties();
if (empty($properties)) {
@@ -879,25 +853,22 @@ public function sqlSelect()
$parts[] = Expression::quoteIdentifier($key, self::DEFAULT_TABLE_ALIAS);
}
- if (empty($parts)) {
+ if ($parts === []) {
throw new UnexpectedValueException(sprintf(
'[%s] Can not get SQL SELECT clause; no valid properties',
$this->getModelClassForException()
));
}
- $clause = implode(', ', $parts);
-
- return $clause;
+ return implode(', ', $parts);
}
/**
* Compile the FROM clause.
*
* @throws UnexpectedValueException If the source does not have a table defined.
- * @return string
*/
- public function sqlFrom()
+ public function sqlFrom(): string
{
if (!$this->hasTable()) {
throw new UnexpectedValueException(sprintf(
@@ -927,7 +898,7 @@ public function sqlFilters()
]);
$sql = $criteria->sql();
- if ($sql && strlen($sql) > 0) {
+ if ($sql && (string)$sql !== '') {
$sql = ' WHERE ' . $sql;
}
@@ -936,10 +907,8 @@ public function sqlFilters()
/**
* Compile the ORDER BY clause.
- *
- * @return string
*/
- public function sqlOrders()
+ public function sqlOrders(): string
{
if (!$this->hasOrders()) {
return '';
@@ -952,12 +921,12 @@ public function sqlOrders()
}
$sql = $order->sql();
- if ($sql && strlen($sql) > 0) {
+ if ($sql && (string)$sql !== '') {
$parts[] = $sql;
}
}
- if (empty($parts)) {
+ if ($parts === []) {
return '';
}
@@ -966,10 +935,8 @@ public function sqlOrders()
/**
* Compile the LIMIT clause.
- *
- * @return string
*/
- public function sqlPagination()
+ public function sqlPagination(): string
{
$pager = $this->pagination();
if (!$pager instanceof DatabasePagination) {
@@ -977,7 +944,7 @@ public function sqlPagination()
}
$sql = $pager->sql();
- if ($sql && strlen($sql) > 0) {
+ if ($sql && $sql !== '') {
$sql = ' ' . $sql;
}
@@ -988,9 +955,9 @@ public function sqlPagination()
* Create a new filter expression.
*
* @param array $data Optional expression data.
- * @return DatabaseFilter
*/
- protected function createFilter(array $data = null)
+ #[\Override]
+ protected function createFilter(?array $data = null): \Charcoal\Source\Database\DatabaseFilter
{
$filter = new DatabaseFilter();
if ($data !== null) {
@@ -1003,9 +970,9 @@ protected function createFilter(array $data = null)
* Create a new order expression.
*
* @param array $data Optional expression data.
- * @return DatabaseOrder
*/
- protected function createOrder(array $data = null)
+ #[\Override]
+ protected function createOrder(?array $data = null): \Charcoal\Source\Database\DatabaseOrder
{
$order = new DatabaseOrder();
if ($data !== null) {
@@ -1018,9 +985,9 @@ protected function createOrder(array $data = null)
* Create a new pagination clause.
*
* @param array $data Optional clause data.
- * @return DatabasePagination
*/
- protected function createPagination(array $data = null)
+ #[\Override]
+ protected function createPagination(?array $data = null): \Charcoal\Source\Database\DatabasePagination
{
$pagination = new DatabasePagination();
if ($data !== null) {
@@ -1034,11 +1001,10 @@ protected function createPagination(array $data = null)
*
* @see \Charcoal\Config\ConfigurableTrait
* @param array $data Optional data.
- * @return DatabaseSourceConfig
*/
- public function createConfig(array $data = null)
+ #[\Override]
+ public function createConfig(?array $data = null): \Charcoal\Source\DatabaseSourceConfig
{
- $config = new DatabaseSourceConfig($data);
- return $config;
+ return new DatabaseSourceConfig($data);
}
}
diff --git a/packages/core/src/Charcoal/Source/DatabaseSourceConfig.php b/packages/core/src/Charcoal/Source/DatabaseSourceConfig.php
index 6cfe1042c..da6aeb336 100644
--- a/packages/core/src/Charcoal/Source/DatabaseSourceConfig.php
+++ b/packages/core/src/Charcoal/Source/DatabaseSourceConfig.php
@@ -1,5 +1,7 @@
'mysql',
@@ -61,9 +43,9 @@ public function defaults()
*
* @param string $type The database type.
* @throws InvalidArgumentException If parameter is not a string.
- * @return self
*/
- public function setType($type)
+ #[\Override]
+ public function setType($type): static
{
if (!is_string($type)) {
throw new InvalidArgumentException(
@@ -79,7 +61,8 @@ public function setType($type)
*
* @return string
*/
- public function type()
+ #[\Override]
+ public function type(): ?string
{
return $this->type;
}
@@ -89,9 +72,8 @@ public function type()
*
* @param string $hostname The database server hostname.
* @throws InvalidArgumentException If hostname is not a string.
- * @return self
*/
- public function setHostname($hostname)
+ public function setHostname($hostname): static
{
if (!is_string($hostname)) {
throw new InvalidArgumentException(
@@ -107,7 +89,7 @@ public function setHostname($hostname)
*
* @return string
*/
- public function hostname()
+ public function hostname(): ?string
{
return $this->hostname;
}
@@ -117,9 +99,8 @@ public function hostname()
*
* @param string $username The username.
* @throws InvalidArgumentException If username is not a string.
- * @return self
*/
- public function setUsername($username)
+ public function setUsername($username): static
{
if (!is_string($username)) {
throw new InvalidArgumentException(
@@ -135,7 +116,7 @@ public function setUsername($username)
*
* @return string
*/
- public function username()
+ public function username(): ?string
{
return $this->username;
}
@@ -145,9 +126,8 @@ public function username()
*
* @param string $password The password.
* @throws InvalidArgumentException If password is not a string.
- * @return self
*/
- public function setPassword($password)
+ public function setPassword($password): static
{
if (!is_string($password)) {
throw new InvalidArgumentException(
@@ -163,7 +143,7 @@ public function setPassword($password)
*
* @return string
*/
- public function password()
+ public function password(): ?string
{
return $this->password;
}
@@ -173,9 +153,8 @@ public function password()
*
* @param string $database The database name.
* @throws InvalidArgumentException If database is not a string.
- * @return self
*/
- public function setDatabase($database)
+ public function setDatabase($database): static
{
if (!is_string($database)) {
throw new InvalidArgumentException(
@@ -191,7 +170,7 @@ public function setDatabase($database)
*
* @return string
*/
- public function database()
+ public function database(): ?string
{
return $this->database;
}
@@ -200,11 +179,10 @@ public function database()
* Set whether to disable UTF-8 compatibility or not.
*
* @param boolean $disableUtf8 The disable flag.
- * @return self
*/
- public function setDisableUtf8($disableUtf8)
+ public function setDisableUtf8($disableUtf8): static
{
- $this->disableUtf8 = !!$disableUtf8;
+ $this->disableUtf8 = (bool)$disableUtf8;
return $this;
}
@@ -213,7 +191,7 @@ public function setDisableUtf8($disableUtf8)
*
* @return boolean
*/
- public function disableUtf8()
+ public function disableUtf8(): ?bool
{
return $this->disableUtf8;
}
diff --git a/packages/core/src/Charcoal/Source/DatabaseSourceInterface.php b/packages/core/src/Charcoal/Source/DatabaseSourceInterface.php
index 182b87f02..987748c9d 100644
--- a/packages/core/src/Charcoal/Source/DatabaseSourceInterface.php
+++ b/packages/core/src/Charcoal/Source/DatabaseSourceInterface.php
@@ -1,5 +1,7 @@
$data The expression data;
* as an associative array.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -44,7 +44,7 @@ public function setData(array $data)
*
* @return array An associative array.
*/
- public function defaultData()
+ public function defaultData(): array
{
return [
'condition' => null,
@@ -58,7 +58,7 @@ public function defaultData()
*
* @return array An associative array.
*/
- public function data()
+ public function data(): array
{
return [
'condition' => $this->condition(),
@@ -72,9 +72,8 @@ public function data()
*
* @param string|null $condition The custom query expression.
* @throws InvalidArgumentException If the parameter is not a valid string expression.
- * @return self
*/
- public function setCondition($condition)
+ public function setCondition($condition): static
{
if ($condition === null) {
$this->condition = $condition;
@@ -98,10 +97,8 @@ public function setCondition($condition)
/**
* Determine if the expression has a custom condition.
- *
- * @return boolean
*/
- public function hasCondition()
+ public function hasCondition(): bool
{
return !(empty($this->condition) && !is_numeric($this->condition));
}
diff --git a/packages/core/src/Charcoal/Source/ExpressionFieldInterface.php b/packages/core/src/Charcoal/Source/ExpressionFieldInterface.php
index 665bf7440..3694c3b3f 100644
--- a/packages/core/src/Charcoal/Source/ExpressionFieldInterface.php
+++ b/packages/core/src/Charcoal/Source/ExpressionFieldInterface.php
@@ -1,5 +1,7 @@
property);
}
@@ -130,10 +128,8 @@ public function setTable($table)
/**
* Determine if a table is assigned.
- *
- * @return boolean
*/
- public function hasTable()
+ public function hasTable(): bool
{
return !empty($this->table);
}
@@ -212,7 +208,7 @@ public function fieldName()
*
* @return string[]
*/
- public function fieldIdentifiers()
+ public function fieldIdentifiers(): array
{
$identifiers = [];
$tableName = $this->table();
@@ -243,7 +239,7 @@ public function fieldIdentifier()
* @param string $value The string to snakeize.
* @return string The snake_case string.
*/
- protected function snakeize($value)
+ protected function snakeize($value): string
{
$key = $value;
@@ -251,7 +247,7 @@ protected function snakeize($value)
return static::$snakeCache[$key];
}
- $value = strtolower(preg_replace('/(?filters);
}
@@ -72,9 +71,9 @@ public function count()
*
* @param array $data The expression data;
* as an associative array.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -174,7 +173,8 @@ public function setData(array $data)
*
* @return array An associative array.
*/
- public function defaultData()
+ #[\Override]
+ public function defaultData(): array
{
return [
'property' => null,
@@ -195,7 +195,8 @@ public function defaultData()
*
* @return array An associative array.
*/
- public function data()
+ #[\Override]
+ public function data(): array
{
return [
'property' => $this->property(),
@@ -215,9 +216,8 @@ public function data()
* Set the value used for comparison.
*
* @param mixed $value The value on the right side of the comparison.
- * @return self
*/
- public function setValue($value)
+ public function setValue($value): static
{
$this->value = $this::parseValue($value);
return $this;
@@ -238,9 +238,8 @@ public function value()
*
* @param string $operator The comparison operator.
* @throws InvalidArgumentException If the parameter is not a valid operator.
- * @return self
*/
- public function setOperator($operator)
+ public function setOperator($operator): static
{
if (!is_string($operator)) {
throw new InvalidArgumentException(
@@ -262,10 +261,8 @@ public function setOperator($operator)
/**
* Retrieve the operator used for comparing field and value.
- *
- * @return string
*/
- public function operator()
+ public function operator(): string
{
return strtoupper($this->operator);
}
@@ -275,9 +272,8 @@ public function operator()
*
* @param string $func The function name to invoke on the field.
* @throws InvalidArgumentException If the parameter is not a valid function.
- * @return self
*/
- public function setFunc($func)
+ public function setFunc($func): static
{
if ($func === null) {
$this->func = $func;
@@ -317,9 +313,8 @@ public function func()
*
* @param string $conjunction The separator to use.
* @throws InvalidArgumentException If the parameter is not a valid conjunction.
- * @return self
*/
- public function setConjunction($conjunction)
+ public function setConjunction($conjunction): static
{
if (!is_string($conjunction)) {
throw new InvalidArgumentException(
@@ -354,7 +349,7 @@ public function conjunction()
*
* @return string[]
*/
- protected function validOperators()
+ protected function validOperators(): array
{
return [
'!', 'NOT',
@@ -376,7 +371,7 @@ protected function validOperators()
*
* @return string[]
*/
- protected function validFunc()
+ protected function validFunc(): array
{
return [
'ABS',
@@ -410,7 +405,7 @@ protected function validFunc()
*
* @return string[] List of separators (case sensitive).
*/
- protected function validConjunctions()
+ protected function validConjunctions(): array
{
return [
'AND', '&&',
@@ -424,9 +419,8 @@ protected function validConjunctions()
*
* @see FilterCollectionTrait::createFilter()
* @param array $data Optional expression data.
- * @return self
*/
- protected function createFilter(array $data = null)
+ protected function createFilter(?array $data = null): static
{
$filter = new static();
if ($data !== null) {
@@ -448,8 +442,6 @@ public function traverse(callable $callable)
/**
* Clone this expression and its subtree of expressions.
- *
- * @return void
*/
public function __clone()
{
diff --git a/packages/core/src/Charcoal/Source/FilterCollectionInterface.php b/packages/core/src/Charcoal/Source/FilterCollectionInterface.php
index c0f9d330e..c81437713 100644
--- a/packages/core/src/Charcoal/Source/FilterCollectionInterface.php
+++ b/packages/core/src/Charcoal/Source/FilterCollectionInterface.php
@@ -1,5 +1,7 @@
filters);
}
@@ -165,5 +163,5 @@ public function traverseFilters(callable $callable)
* @param array $data Optional expression data.
* @return FilterInterface A new filter expression object.
*/
- abstract protected function createFilter(array $data = null);
+ abstract protected function createFilter(?array $data = null);
}
diff --git a/packages/core/src/Charcoal/Source/FilterInterface.php b/packages/core/src/Charcoal/Source/FilterInterface.php
index bc132ddc2..bc618ba87 100644
--- a/packages/core/src/Charcoal/Source/FilterInterface.php
+++ b/packages/core/src/Charcoal/Source/FilterInterface.php
@@ -1,5 +1,7 @@
model !== null);
}
diff --git a/packages/core/src/Charcoal/Source/Order.php b/packages/core/src/Charcoal/Source/Order.php
index afd1876a6..06771dd19 100644
--- a/packages/core/src/Charcoal/Source/Order.php
+++ b/packages/core/src/Charcoal/Source/Order.php
@@ -60,9 +60,9 @@ class Order extends Expression implements
*
* @param array $data The expression data;
* as an associative array.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -114,10 +114,8 @@ public function setData(array $data)
}
}
- if (isset($data['condition']) || isset($data['string'])) {
- if (!isset($data['mode'])) {
- $this->setMode(self::MODE_CUSTOM);
- }
+ if ((isset($data['condition']) || isset($data['string'])) && !isset($data['mode'])) {
+ $this->setMode(self::MODE_CUSTOM);
}
return $this;
@@ -128,7 +126,8 @@ public function setData(array $data)
*
* @return array An associative array.
*/
- public function defaultData()
+ #[\Override]
+ public function defaultData(): array
{
return [
'property' => null,
@@ -147,7 +146,8 @@ public function defaultData()
*
* @return array An associative array.
*/
- public function data()
+ #[\Override]
+ public function data(): array
{
return [
'property' => $this->property(),
@@ -166,9 +166,8 @@ public function data()
*
* @param string|null $mode The sorting mode.
* @throws InvalidArgumentException If the mode is not a string or invalid.
- * @return self
*/
- public function setMode($mode)
+ public function setMode($mode): static
{
if ($mode === null) {
$this->mode = $mode;
@@ -213,9 +212,8 @@ public function mode()
*
* @param string|null $direction The direction to sort on.
* @throws InvalidArgumentException If the direction is not a string.
- * @return self
*/
- public function setDirection($direction)
+ public function setDirection($direction): static
{
if ($direction === null) {
$this->direction = $direction;
@@ -253,9 +251,8 @@ public function direction()
* - is a string, the string will be split by ",".
* - is an array, the values will be used as is.
* - any other data type throws an exception.
- * @return self
*/
- public function setValues($values)
+ public function setValues($values): static
{
if ($values === null) {
$this->values = $values;
@@ -269,11 +266,11 @@ public function setValues($values)
);
}
- $values = array_map('trim', explode(',', $values));
+ $values = array_map(trim(...), explode(',', $values));
}
if (is_array($values)) {
- if (empty($values)) {
+ if ($values === []) {
throw new InvalidArgumentException(
'Array values can not be empty.'
);
@@ -285,16 +282,14 @@ public function setValues($values)
throw new InvalidArgumentException(sprintf(
'Order Values must be an array or comma-delimited string, received %s',
- is_object($values) ? get_class($values) : gettype($values)
+ get_debug_type($values)
));
}
/**
* Determine if the Order expression has values.
- *
- * @return boolean
*/
- public function hasValues()
+ public function hasValues(): bool
{
return !empty($this->values);
}
@@ -311,10 +306,8 @@ public function values()
/**
* Retrieve the supported sorting modes.
- *
- * @return array
*/
- protected function validModes()
+ protected function validModes(): array
{
return [
self::MODE_DESC,
diff --git a/packages/core/src/Charcoal/Source/OrderCollectionInterface.php b/packages/core/src/Charcoal/Source/OrderCollectionInterface.php
index 9f8abf25c..b737427da 100644
--- a/packages/core/src/Charcoal/Source/OrderCollectionInterface.php
+++ b/packages/core/src/Charcoal/Source/OrderCollectionInterface.php
@@ -1,5 +1,7 @@
orders);
}
@@ -165,5 +163,5 @@ public function traverseOrders(callable $callable)
* @param array $data Optional expression data.
* @return OrderInterface A new order expression object.
*/
- abstract protected function createOrder(array $data = null);
+ abstract protected function createOrder(?array $data = null);
}
diff --git a/packages/core/src/Charcoal/Source/OrderInterface.php b/packages/core/src/Charcoal/Source/OrderInterface.php
index d49ab383e..b57ba3ffe 100644
--- a/packages/core/src/Charcoal/Source/OrderInterface.php
+++ b/packages/core/src/Charcoal/Source/OrderInterface.php
@@ -1,5 +1,7 @@
$data The expression data;
* as an associative array.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -63,7 +63,7 @@ public function setData(array $data)
*
* @return array An associative array.
*/
- public function defaultData()
+ public function defaultData(): array
{
return [
'page' => self::DEFAULT_PAGE,
@@ -78,7 +78,7 @@ public function defaultData()
*
* @return array An associative array.
*/
- public function data()
+ public function data(): array
{
return [
'page' => $this->page(),
@@ -94,9 +94,8 @@ public function data()
* @param integer $page The current page.
* Pages should start at 1.
* @throws InvalidArgumentException If the parameter is not numeric or < 0.
- * @return self
*/
- public function setPage($page)
+ public function setPage($page): static
{
if (!is_numeric($page)) {
throw new InvalidArgumentException(
@@ -133,9 +132,8 @@ public function page()
* @param integer $count The number of results to return, per page.
* Use 0 to request all results.
* @throws InvalidArgumentException If the parameter is not numeric or < 0.
- * @return self
*/
- public function setNumPerPage($count)
+ public function setNumPerPage($count): static
{
if (!is_numeric($count)) {
throw new InvalidArgumentException(
@@ -166,10 +164,8 @@ public function numPerPage()
/**
* Retrieve the pagination's lowest possible index.
- *
- * @return integer
*/
- public function first()
+ public function first(): int
{
$page = $this->page();
$limit = $this->numPerPage();
@@ -184,7 +180,7 @@ public function first()
*
* @return integer
*/
- public function last()
+ public function last(): float|int|array
{
$first = $this->first();
$limit = $this->numPerPage();
diff --git a/packages/core/src/Charcoal/Source/PaginationInterface.php b/packages/core/src/Charcoal/Source/PaginationInterface.php
index f90fdb9a9..d6dcfb324 100644
--- a/packages/core/src/Charcoal/Source/PaginationInterface.php
+++ b/packages/core/src/Charcoal/Source/PaginationInterface.php
@@ -1,5 +1,7 @@
''
@@ -29,9 +26,8 @@ public function defaults()
/**
* @param string $type The type of source.
* @throws InvalidArgumentException If parameter is not a string.
- * @return self
*/
- public function setType($type)
+ public function setType($type): static
{
if (!is_string($type)) {
throw new InvalidArgumentException(
@@ -45,7 +41,7 @@ public function setType($type)
/**
* @return string
*/
- public function type()
+ public function type(): ?string
{
return $this->type;
}
diff --git a/packages/core/src/Charcoal/Source/SourceInterface.php b/packages/core/src/Charcoal/Source/SourceInterface.php
index 5d566e29a..c73e251ab 100644
--- a/packages/core/src/Charcoal/Source/SourceInterface.php
+++ b/packages/core/src/Charcoal/Source/SourceInterface.php
@@ -1,5 +1,7 @@
preSave();
if ($pre === false) {
@@ -229,7 +229,7 @@ final public function save()
'Can not save object "%s:%s"; cancelled by %s::preSave()',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -240,7 +240,7 @@ final public function save()
'Can not save object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
} else {
@@ -253,7 +253,7 @@ final public function save()
'Saved object "%s:%s" but %s::postSave() failed',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -267,7 +267,7 @@ final public function save()
* @param string[] $keys If provided, only update the properties specified.
* @return boolean TRUE on success.
*/
- final public function update(array $keys = null)
+ final public function update(?array $keys = null): bool
{
$pre = $this->preUpdate($keys);
if ($pre === false) {
@@ -275,7 +275,7 @@ final public function update(array $keys = null)
'Can not update object "%s:%s"; cancelled by %s::preUpdate()',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -286,7 +286,7 @@ final public function update(array $keys = null)
'Can not update object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -297,7 +297,7 @@ final public function update(array $keys = null)
'Updated object "%s:%s" but %s::postUpdate() failed',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -310,7 +310,7 @@ final public function update(array $keys = null)
*
* @return boolean TRUE on success.
*/
- final public function delete()
+ final public function delete(): bool
{
$pre = $this->preDelete();
if ($pre === false) {
@@ -318,7 +318,7 @@ final public function delete()
'Can not delete object "%s:%s"; cancelled by %s::preDelete()',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -329,7 +329,7 @@ final public function delete()
'Can not delete object "%s:%s"; repository failed for %s',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -340,7 +340,7 @@ final public function delete()
'Deleted object "%s:%s" but %s::postDelete() failed',
$this->objType(),
$this->id(),
- get_called_class()
+ static::class
));
return false;
}
@@ -370,7 +370,7 @@ protected function sourceFactory()
{
if (!isset($this->sourceFactory)) {
throw new RuntimeException(
- sprintf('Source factory is not set for "%s"', get_class($this))
+ sprintf('Source factory is not set for "%s"', $this::class)
);
}
return $this->sourceFactory;
@@ -381,7 +381,7 @@ protected function sourceFactory()
*
* @return boolean TRUE to proceed with creation; FALSE to stop creation.
*/
- protected function preSave()
+ protected function preSave(): bool
{
return true;
}
@@ -391,7 +391,7 @@ protected function preSave()
*
* @return boolean TRUE to indicate object was created.
*/
- protected function postSave()
+ protected function postSave(): bool
{
return true;
}
@@ -402,7 +402,7 @@ protected function postSave()
* @param string[] $keys Optional list of properties to update.
* @return boolean TRUE to proceed with update; FALSE to stop update.
*/
- protected function preUpdate(array $keys = null)
+ protected function preUpdate(?array $keys = null): bool
{
return true;
}
@@ -413,7 +413,7 @@ protected function preUpdate(array $keys = null)
* @param string[] $keys Optional list of properties to update.
* @return boolean TRUE to indicate object was updated.
*/
- protected function postUpdate(array $keys = null)
+ protected function postUpdate(?array $keys = null): bool
{
return true;
}
@@ -423,7 +423,7 @@ protected function postUpdate(array $keys = null)
*
* @return boolean TRUE to proceed with deletion; FALSE to stop deletion.
*/
- protected function preDelete()
+ protected function preDelete(): bool
{
return true;
}
@@ -433,7 +433,7 @@ protected function preDelete()
*
* @return boolean TRUE to indicate object was deleted.
*/
- protected function postDelete()
+ protected function postDelete(): bool
{
return true;
}
diff --git a/packages/core/src/Charcoal/Validator/AbstractValidator.php b/packages/core/src/Charcoal/Validator/AbstractValidator.php
index be98ede35..6bea5c507 100644
--- a/packages/core/src/Charcoal/Validator/AbstractValidator.php
+++ b/packages/core/src/Charcoal/Validator/AbstractValidator.php
@@ -15,15 +15,10 @@
*/
abstract class AbstractValidator implements ValidatorInterface
{
- /**
- * @var ValidatableInterface
- */
- protected $model;
-
/**
* @var ValidatorResult[] $results
*/
- private $results = [];
+ private array $results = [];
/**
* Holds a list of all camelized strings.
@@ -35,9 +30,8 @@ abstract class AbstractValidator implements ValidatorInterface
/**
* @param ValidatableInterface $model The object to validate.
*/
- public function __construct(ValidatableInterface $model)
+ public function __construct(protected \Charcoal\Validator\ValidatableInterface $model)
{
- $this->model = $model;
}
/**
@@ -80,7 +74,7 @@ public function log($level, $msg, $ident = null)
{
$this->addResult(
[
- 'ident' => (($ident !== null) ? $ident : ''),
+ 'ident' => ($ident ?? ''),
'level' => $level,
'message' => $msg
]
@@ -160,7 +154,7 @@ public function merge(ValidatorInterface $v, $prefix = null)
{
$allResults = $v->results();
- foreach ($allResults as $level => $resultset) {
+ foreach ($allResults as $resultset) {
foreach ($resultset as $result) {
if ($prefix !== null) {
$result->setIdent($prefix . '.' . $result->ident());
@@ -185,8 +179,8 @@ final protected function camelize($value)
return static::$camelCache[$key];
}
- if (strpos($value, '_') !== false) {
- $value = implode('', array_map('ucfirst', explode('_', $value)));
+ if (str_contains($value, '_')) {
+ $value = implode('', array_map(ucfirst(...), explode('_', $value)));
}
static::$camelCache[$key] = lcfirst($value);
diff --git a/packages/core/src/Charcoal/Validator/ValidatableInterface.php b/packages/core/src/Charcoal/Validator/ValidatableInterface.php
index 09791b9f2..aa0f525e3 100644
--- a/packages/core/src/Charcoal/Validator/ValidatableInterface.php
+++ b/packages/core/src/Charcoal/Validator/ValidatableInterface.php
@@ -1,5 +1,7 @@
setValidator($v);
}
diff --git a/packages/core/src/Charcoal/Validator/ValidatorInterface.php b/packages/core/src/Charcoal/Validator/ValidatorInterface.php
index a500e19ce..726400766 100644
--- a/packages/core/src/Charcoal/Validator/ValidatorInterface.php
+++ b/packages/core/src/Charcoal/Validator/ValidatorInterface.php
@@ -1,5 +1,7 @@
setIdent($data['ident']);
@@ -69,9 +58,8 @@ public function setData(array $data)
/**
* @param string $ident The result identigier.
* @throws InvalidArgumentException If parameter is not valid.
- * @return ValidatorResult
*/
- public function setIdent($ident)
+ public function setIdent($ident): static
{
if (!is_string($ident)) {
throw new InvalidArgumentException(
@@ -85,7 +73,7 @@ public function setIdent($ident)
/**
* @return string
*/
- public function ident()
+ public function ident(): ?string
{
return $this->ident;
}
@@ -93,9 +81,8 @@ public function ident()
/**
* @param string $level The validation level ('notice', 'warning' or 'error').
* @throws InvalidArgumentException If parameter is not a valid level.
- * @return ValidatorResult
*/
- public function setLevel($level)
+ public function setLevel($level): static
{
if (!is_string($level)) {
throw new InvalidArgumentException(
@@ -114,7 +101,7 @@ public function setLevel($level)
/**
* @return string
*/
- public function level()
+ public function level(): ?string
{
return $this->level;
}
@@ -122,9 +109,8 @@ public function level()
/**
* @param string $message The validation message.
* @throws InvalidArgumentException If parameter is not valid.
- * @return ValidatorResult
*/
- public function setMessage($message)
+ public function setMessage($message): static
{
if (!is_string($message)) {
throw new InvalidArgumentException(
@@ -138,7 +124,7 @@ public function setMessage($message)
/**
* @return string
*/
- public function message()
+ public function message(): ?string
{
return $this->message;
}
@@ -146,9 +132,8 @@ public function message()
/**
* @param string|DateTime $ts The datetime value.
* @throws InvalidArgumentException If parameter is not valid "datetime".
- * @return ValidatorResult
*/
- public function setTs($ts)
+ public function setTs($ts): static
{
if (is_string($ts)) {
$ts = new DateTime($ts);
@@ -165,7 +150,7 @@ public function setTs($ts)
/**
* @return DateTime
*/
- public function ts()
+ public function ts(): \DateTimeInterface
{
return $this->ts;
}
diff --git a/packages/core/tests/Charcoal/AbstractTestCase.php b/packages/core/tests/Charcoal/AbstractTestCase.php
index 59ba12ea0..80f1772c4 100644
--- a/packages/core/tests/Charcoal/AbstractTestCase.php
+++ b/packages/core/tests/Charcoal/AbstractTestCase.php
@@ -1,5 +1,7 @@
assertCount(count($expected), $haystack, $message);
$this->assertEquals($expected, $haystack, $message);
@@ -27,9 +26,8 @@ public function assertArrayEquals(array $expected, array $haystack, $message = '
* @param array $expected The expected haystack.
* @param array $haystack The actual haystack.
* @param string $message The error to report.
- * @return void
*/
- public function assertArrayContains(array $expected, array $haystack, $message = '')
+ public function assertArrayContains(array $expected, array $haystack, $message = ''): void
{
foreach ($expected as $item) {
$this->assertContains($item, $haystack, $message);
@@ -42,9 +40,8 @@ public function assertArrayContains(array $expected, array $haystack, $message =
* @param array $expected The expected haystack.
* @param array $haystack The actual haystack.
* @param string $message The error to report.
- * @return void
*/
- public function assertArrayHasKeys(array $expected, array $haystack, $message = '')
+ public function assertArrayHasKeys(array $expected, array $haystack, $message = ''): void
{
foreach ($expected as $item) {
$this->assertArrayHasKey($item, $haystack, $message);
@@ -58,14 +55,13 @@ public function assertArrayHasKeys(array $expected, array $haystack, $message =
* @param array $haystack The actual haystack.
* @param boolean $strict Whether to check for object identity.
* @param string $message The error to report.
- * @return void
*/
public function assertArraySubsets(
array $expected,
array $haystack,
$strict = false,
$message = ''
- ) {
+ ): void {
foreach ($expected as $key => $val) {
$this->assertArraySubset([ $key => $val ], $haystack, $strict, $message);
}
diff --git a/packages/core/tests/Charcoal/CoreContainerIntegrationTrait.php b/packages/core/tests/Charcoal/CoreContainerIntegrationTrait.php
index 57ce03768..9b6c79600 100644
--- a/packages/core/tests/Charcoal/CoreContainerIntegrationTrait.php
+++ b/packages/core/tests/Charcoal/CoreContainerIntegrationTrait.php
@@ -50,10 +50,9 @@ protected function getContainerProvider()
}
/**
- * @return void
* @see CoreContainerProvider
*/
- private function setupContainer()
+ private function setupContainer(): void
{
$provider = new CoreContainerProvider();
$container = new Container();
diff --git a/packages/core/tests/Charcoal/CoreContainerProvider.php b/packages/core/tests/Charcoal/CoreContainerProvider.php
index 6de374c33..70a8b4f97 100644
--- a/packages/core/tests/Charcoal/CoreContainerProvider.php
+++ b/packages/core/tests/Charcoal/CoreContainerProvider.php
@@ -44,9 +44,8 @@ class CoreContainerProvider
* Register the unit tests required services.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerBaseServices(Container $container)
+ public function registerBaseServices(Container $container): void
{
$this->registerConfig($container);
$this->registerSource($container);
@@ -58,15 +57,12 @@ public function registerBaseServices(Container $container)
* Setup the application configset.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerConfig(Container $container)
+ public function registerConfig(Container $container): void
{
- $container['config'] = function () {
- return new AppConfig([
- 'base_path' => realpath(__DIR__ . '/../../..')
- ]);
- };
+ $container['config'] = (fn(): \Charcoal\App\AppConfig => new AppConfig([
+ 'base_path' => realpath(__DIR__ . '/../../..')
+ ]));
}
/**
@@ -75,11 +71,10 @@ public function registerConfig(Container $container)
* Note: Uses SQLite to create a database in memory.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerSource(Container $container)
+ public function registerSource(Container $container): void
{
- $container['database'] = function () {
+ $container['database'] = function (): \PDO {
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
@@ -90,60 +85,48 @@ public function registerSource(Container $container)
* Setup the application's logging interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerLogger(Container $container)
+ public function registerLogger(Container $container): void
{
- $container['logger'] = function () {
- return new NullLogger();
- };
+ $container['logger'] = (fn(): \Psr\Log\NullLogger => new NullLogger());
}
/**
* Setup the application's caching interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerCache(Container $container)
+ public function registerCache(Container $container): void
{
- $container['cache'] = function () {
- return new Pool();
- };
+ $container['cache'] = (fn(): \Stash\Pool => new Pool());
}
/**
* Setup the application's translator service.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerTranslator(Container $container)
+ public function registerTranslator(Container $container): void
{
- $container['locales/manager'] = function () {
- return new LocalesManager([
- 'locales' => [
- 'en' => [ 'locale' => 'en-US' ]
- ]
- ]);
- };
+ $container['locales/manager'] = (fn(): \Charcoal\Translator\LocalesManager => new LocalesManager([
+ 'locales' => [
+ 'en' => [ 'locale' => 'en-US' ]
+ ]
+ ]));
- $container['translator'] = function (Container $container) {
- return new Translator([
- 'manager' => $container['locales/manager']
- ]);
- };
+ $container['translator'] = (fn(Container $container): \Charcoal\Translator\Translator => new Translator([
+ 'manager' => $container['locales/manager']
+ ]));
}
/**
* Setup the application's translator service.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerMultilingualTranslator(Container $container)
+ public function registerMultilingualTranslator(Container $container): void
{
- $container['locales/manager'] = function () {
+ $container['locales/manager'] = function (): \Charcoal\Translator\LocalesManager {
$manager = new LocalesManager([
'locales' => [
'en' => [
@@ -178,7 +161,7 @@ public function registerMultilingualTranslator(Container $container)
return $manager;
};
- $container['translator'] = function (Container $container) {
+ $container['translator'] = function (Container $container): \Charcoal\Translator\Translator {
$translator = new Translator([
'manager' => $container['locales/manager']
]);
@@ -198,106 +181,91 @@ public function registerMultilingualTranslator(Container $container)
* Setup the framework's metadata loader interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerMetadataLoader(Container $container)
+ public function registerMetadataLoader(Container $container): void
{
- $container['metadata/loader'] = function (Container $container) {
- return new MetadataLoader([
- 'cache' => $container['cache'],
- 'logger' => $container['logger'],
- 'base_path' => $container['config']['base_path'],
- 'paths' => [
- 'metadata',
- // Standalone
- 'vendor/charcoal/property/metadata',
- // Monorepo
- '/../property/metadata'
- ]
- ]);
- };
+ $container['metadata/loader'] = (fn(Container $container): \Charcoal\Model\Service\MetadataLoader => new MetadataLoader([
+ 'cache' => $container['cache'],
+ 'logger' => $container['logger'],
+ 'base_path' => $container['config']['base_path'],
+ 'paths' => [
+ 'metadata',
+ // Standalone
+ 'vendor/charcoal/property/metadata',
+ // Monorepo
+ '/../property/metadata'
+ ]
+ ]));
}
/**
* Setup the framework's data source factory.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerSourceFactory(Container $container)
+ public function registerSourceFactory(Container $container): void
{
- $container['source/factory'] = function (Container $container) {
- return new Factory([
- 'map' => [
- 'database' => DatabaseSource::class
- ],
- 'arguments' => [[
- 'logger' => $container['logger'],
- 'cache' => $container['cache'],
- 'pdo' => $container['database']
- ]]
- ]);
- };
+ $container['source/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'map' => [
+ 'database' => DatabaseSource::class
+ ],
+ 'arguments' => [[
+ 'logger' => $container['logger'],
+ 'cache' => $container['cache'],
+ 'pdo' => $container['database']
+ ]]
+ ]));
}
/**
* Setup the framework's model factory.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerModelFactory(Container $container)
+ public function registerModelFactory(Container $container): void
{
- $container['model/factory'] = function (Container $container) {
- return new Factory([
- 'arguments' => [[
- 'container' => $container,
- 'logger' => $container['logger'],
- 'metadata_loader' => $container['metadata/loader'],
- 'source_factory' => $container['source/factory'],
- 'property_factory' => $container['property/factory']
- ]]
- ]);
- };
+ $container['model/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'arguments' => [[
+ 'container' => $container,
+ 'logger' => $container['logger'],
+ 'metadata_loader' => $container['metadata/loader'],
+ 'source_factory' => $container['source/factory'],
+ 'property_factory' => $container['property/factory']
+ ]]
+ ]));
}
/**
* Setup the framework's property factory.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerPropertyFactory(Container $container)
+ public function registerPropertyFactory(Container $container): void
{
- $container['property/factory'] = function (Container $container) {
- return new Factory([
- 'resolver_options' => [
- 'prefix' => '\\Charcoal\\Property\\',
- 'suffix' => 'Property'
- ],
- 'arguments' => [[
- 'container' => $container,
- 'database' => $container['database'],
- 'logger' => $container['logger'],
- 'translator' => $container['translator']
- ]]
- ]);
- };
+ $container['property/factory'] = (fn(Container $container): \Charcoal\Factory\GenericFactory => new Factory([
+ 'resolver_options' => [
+ 'prefix' => '\\Charcoal\\Property\\',
+ 'suffix' => 'Property'
+ ],
+ 'arguments' => [[
+ 'container' => $container,
+ 'database' => $container['database'],
+ 'logger' => $container['logger'],
+ 'translator' => $container['translator']
+ ]]
+ ]));
}
/**
* Setup the framework's collection loader interface.
*
* @param Container $container A DI container.
- * @return void
*/
- public function registerModelCollectionLoader(Container $container)
+ public function registerModelCollectionLoader(Container $container): void
{
- $container['model/collection/loader'] = function (Container $container) {
- return new CollectionLoader([
- 'logger' => $container['logger'],
- 'cache' => $container['cache']
- ]);
- };
+ $container['model/collection/loader'] = (fn(Container $container): \Charcoal\Loader\CollectionLoader => new CollectionLoader([
+ 'logger' => $container['logger'],
+ 'cache' => $container['cache']
+ ]));
}
}
diff --git a/packages/core/tests/Charcoal/Loader/CollectionLoaderTest.php b/packages/core/tests/Charcoal/Loader/CollectionLoaderTest.php
index 11b110546..ca9c8e74e 100644
--- a/packages/core/tests/Charcoal/Loader/CollectionLoaderTest.php
+++ b/packages/core/tests/Charcoal/Loader/CollectionLoaderTest.php
@@ -20,27 +20,18 @@
use Charcoal\Tests\CoreContainerIntegrationTrait;
use Charcoal\Tests\ReflectionsTrait;
-/**
- *
- */
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Loader\CollectionLoader::class, 'camelize')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Loader\CollectionLoader::class, 'getter')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Loader\CollectionLoader::class, 'setter')]
class CollectionLoaderTest extends AbstractTestCase
{
use CoreContainerIntegrationTrait;
use ReflectionsTrait;
- /**
- * @var CollectionLoader
- */
- private $loader;
+ private \Charcoal\Loader\CollectionLoader $loader;
- /**
- * @var Model
- */
- private $model;
+ private \Charcoal\Model\Model $model;
- /**
- * @return void
- */
protected function setUp(): void
{
$this->model = $this->createModel();
@@ -49,10 +40,7 @@ protected function setUp(): void
$this->loader = $this->createCollectionLoader();
}
- /**
- * @return CollectionLoader
- */
- public function createCollectionLoader()
+ public function createCollectionLoader(): \Charcoal\Loader\CollectionLoader
{
$container = $this->getContainer();
@@ -63,18 +51,13 @@ public function createCollectionLoader()
]]
]);
- $loader = new CollectionLoader([
+ return new CollectionLoader([
'logger' => $container['logger'],
'factory' => $factory,
]);
-
- return $loader;
}
- /**
- * @return Model
- */
- public function createModel()
+ public function createModel(): \Charcoal\Model\Model
{
$container = $this->getContainer();
@@ -117,10 +100,7 @@ public function createModel()
return $model;
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$loader = $this->loader;
$loader->setModel($this->model);
@@ -134,30 +114,21 @@ public function testSetData()
$this->assertEquals([ 'id', 'test' ], $loader->properties());
}
- /**
- * @return void
- */
- public function testSetDataIsChainable()
+ public function testSetDataIsChainable(): void
{
$loader = $this->loader;
$ret = $loader->setData([]);
$this->assertSame($ret, $loader);
}
- /**
- * @return void
- */
- public function testDefaultCollection()
+ public function testDefaultCollection(): void
{
$loader = $this->loader;
$collection = $loader->createCollection();
$this->assertInstanceOf(Collection::class, $collection);
}
- /**
- * @return void
- */
- public function testCustomCollectionClass()
+ public function testCustomCollectionClass(): void
{
$loader = $this->loader;
@@ -177,10 +148,7 @@ public function testCustomCollectionClass()
$this->assertInternalType('array', $collection);
}
- /**
- * @return void
- */
- public function testAll()
+ public function testAll(): void
{
$loader = $this->loader;
$loader->setModel($this->model)
@@ -194,7 +162,7 @@ public function testAll()
$this->assertTrue($loader->hasModel());
- $collection = $loader->load();
+ $loader->load();
$this->assertEquals(1, 1);
@@ -204,13 +172,8 @@ public function testAll()
/**
* Test camelization.
*
- * @covers \Charcoal\Loader\CollectionLoader::camelize
- * @covers \Charcoal\Loader\CollectionLoader::getter
- * @covers \Charcoal\Loader\CollectionLoader::setter
- *
- * @return void
*/
- public function testCamelize()
+ public function testCamelize(): void
{
$loader = $this->loader;
diff --git a/packages/core/tests/Charcoal/Mock/BadStorableMock.php b/packages/core/tests/Charcoal/Mock/BadStorableMock.php
index 40765d358..fced583e3 100644
--- a/packages/core/tests/Charcoal/Mock/BadStorableMock.php
+++ b/packages/core/tests/Charcoal/Mock/BadStorableMock.php
@@ -1,5 +1,7 @@
fail;
}
@@ -70,7 +71,8 @@ protected function preSave()
* @see StorableTrait::postSave()
* @return boolean TRUE to indicate object was created.
*/
- protected function postSave()
+ #[\Override]
+ protected function postSave(): bool
{
return !$this->fail;
}
@@ -82,7 +84,8 @@ protected function postSave()
* @param string[] $keys Optional list of properties to update.
* @return boolean TRUE to proceed with update; FALSE to stop update.
*/
- protected function preUpdate(array $keys = null)
+ #[\Override]
+ protected function preUpdate(?array $keys = null): bool
{
return $this->fail;
}
@@ -94,7 +97,8 @@ protected function preUpdate(array $keys = null)
* @param string[] $keys Optional list of properties to update.
* @return boolean TRUE to indicate object was updated.
*/
- protected function postUpdate(array $keys = null)
+ #[\Override]
+ protected function postUpdate(?array $keys = null): bool
{
return !$this->fail;
}
@@ -105,7 +109,8 @@ protected function postUpdate(array $keys = null)
* @see StorableTrait::preDelete()
* @return boolean TRUE to proceed with deletion; FALSE to stop deletion.
*/
- protected function preDelete()
+ #[\Override]
+ protected function preDelete(): bool
{
return $this->fail;
}
@@ -116,7 +121,8 @@ protected function preDelete()
* @see StorableTrait::postDelete()
* @return boolean TRUE to indicate object was deleted.
*/
- protected function postDelete()
+ #[\Override]
+ protected function postDelete(): bool
{
return !$this->fail;
}
diff --git a/packages/core/tests/Charcoal/Mock/FilterCollectionClass.php b/packages/core/tests/Charcoal/Mock/FilterCollectionClass.php
index b7bbac07b..a6b15238c 100644
--- a/packages/core/tests/Charcoal/Mock/FilterCollectionClass.php
+++ b/packages/core/tests/Charcoal/Mock/FilterCollectionClass.php
@@ -23,7 +23,7 @@ class FilterCollectionClass implements
* @param array $data Optional expression data.
* @return FilterInterface
*/
- protected function createFilter(array $data = null)
+ protected function createFilter(?array $data = null): \Charcoal\Source\Filter
{
$filter = new Filter();
if ($data !== null) {
diff --git a/packages/core/tests/Charcoal/Mock/GenericModel.php b/packages/core/tests/Charcoal/Mock/GenericModel.php
index 64e28d826..584f4b326 100644
--- a/packages/core/tests/Charcoal/Mock/GenericModel.php
+++ b/packages/core/tests/Charcoal/Mock/GenericModel.php
@@ -1,5 +1,7 @@
[
@@ -55,9 +57,8 @@ public function __construct(array $data = null)
/**
* @param mixed $name The name of the model.
- * @return self
*/
- public function setName($name)
+ public function setName($name): static
{
$this->name = $name;
return $this;
@@ -71,10 +72,7 @@ public function name()
return $this->name;
}
- /**
- * @return string
- */
- public function icon()
+ public function icon(): string
{
return '';
}
diff --git a/packages/core/tests/Charcoal/Mock/MockModule.php b/packages/core/tests/Charcoal/Mock/MockModule.php
index e9c7f93da..cebde9ac0 100644
--- a/packages/core/tests/Charcoal/Mock/MockModule.php
+++ b/packages/core/tests/Charcoal/Mock/MockModule.php
@@ -1,5 +1,7 @@
$data The expression data;
* as an associative array.
- * @return self
*/
- public function setData(array $data)
+ #[\Override]
+ public function setData(array $data): static
{
parent::setData($data);
@@ -40,7 +40,8 @@ public function setData(array $data)
*
* @return array An associative array.
*/
- public function defaultData()
+ #[\Override]
+ public function defaultData(): array
{
return [
'property' => null,
@@ -60,7 +61,8 @@ public function defaultData()
*
* @return array An associative array.
*/
- public function data()
+ #[\Override]
+ public function data(): array
{
return [
'property' => $this->property(),
@@ -80,9 +82,8 @@ public function data()
*
* @see OrderCollectionTrait::createOrder()
* @param array $data Optional expression data.
- * @return self
*/
- protected function createOrder(array $data = null)
+ protected function createOrder(?array $data = null): static
{
$order = new static();
if ($data !== null) {
@@ -104,8 +105,6 @@ public function traverse(callable $callable)
/**
* Clone this expression and its subtree of expressions.
- *
- * @return void
*/
public function __clone()
{
diff --git a/packages/core/tests/Charcoal/Mock/SourceMock.php b/packages/core/tests/Charcoal/Mock/SourceMock.php
index c423156ae..b17ff8e66 100644
--- a/packages/core/tests/Charcoal/Mock/SourceMock.php
+++ b/packages/core/tests/Charcoal/Mock/SourceMock.php
@@ -1,5 +1,7 @@
$this->logger
@@ -75,7 +70,7 @@ protected function createSource()
* @param mixed $offset The offset to check for.
* @return boolean Returns TRUE on success or FALSE on failure.
*/
- public function offsetExists($offset)
+ public function offsetExists($offset): bool
{
return isset($this->data[$offset]);
}
@@ -88,7 +83,7 @@ public function offsetExists($offset)
*/
public function offsetGet($offset)
{
- return isset($this->data[$offset]) ? $this->data[$offset] : null;
+ return $this->data[$offset] ?? null;
}
/**
@@ -96,9 +91,8 @@ public function offsetGet($offset)
*
* @param mixed $offset The offset to assign the value to.
* @param mixed $value The value to set.
- * @return void
*/
- public function offsetSet($offset, $value)
+ public function offsetSet($offset, $value): void
{
if ($offset === null) {
$this->data[] = $value;
@@ -111,9 +105,8 @@ public function offsetSet($offset, $value)
* Unset an offset.
*
* @param mixed $offset The offset to unset.
- * @return void
*/
- public function offsetUnset($offset)
+ public function offsetUnset($offset): void
{
unset($this->data[$offset]);
}
diff --git a/packages/core/tests/Charcoal/Mock/ValidatableClass.php b/packages/core/tests/Charcoal/Mock/ValidatableClass.php
index 142032f8a..a2004ff0b 100644
--- a/packages/core/tests/Charcoal/Mock/ValidatableClass.php
+++ b/packages/core/tests/Charcoal/Mock/ValidatableClass.php
@@ -20,9 +20,8 @@ class ValidatableClass implements ValidatableInterface
/**
* @param array|null $data Validator data.
- * @return ValidatorClass
*/
- public function createValidator(array $data = null)
+ public function createValidator(?array $data = null): \Charcoal\Tests\Mock\ValidatorClass
{
$v = new ValidatorClass();
if ($data !== null) {
diff --git a/packages/core/tests/Charcoal/Mock/ValidatorClass.php b/packages/core/tests/Charcoal/Mock/ValidatorClass.php
index cae083a0d..43d7d2373 100644
--- a/packages/core/tests/Charcoal/Mock/ValidatorClass.php
+++ b/packages/core/tests/Charcoal/Mock/ValidatorClass.php
@@ -1,5 +1,7 @@
obj = $this->getMockForAbstractClass(AbstractMetadata::class);
+ $this->obj = new class () extends AbstractMetadata {};
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->merge([
@@ -39,10 +33,7 @@ public function testSetData()
$this->assertEquals('bar', $obj->foo);
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetExists()
+ public function testArrayAccessOffsetExists(): void
{
$obj = $this->obj;
$this->assertFalse(isset($obj['x']));
diff --git a/packages/core/tests/Charcoal/Model/CollectionTest.php b/packages/core/tests/Charcoal/Model/CollectionTest.php
index 9ef435593..f13ccda9d 100644
--- a/packages/core/tests/Charcoal/Model/CollectionTest.php
+++ b/packages/core/tests/Charcoal/Model/CollectionTest.php
@@ -41,9 +41,6 @@ class CollectionTest extends AbstractTestCase
*/
protected $map;
- /**
- * @return void
- */
protected function setUp(): void
{
$this->map = [
@@ -66,97 +63,66 @@ protected function setUp(): void
// Test \Charcoal\Model\CollectionInterface
// =============================================================================================
-
- /**
- * @return void
- */
- public function testCollectionIsConstructed()
+ public function testCollectionIsConstructed(): void
{
$c = new Collection;
$this->assertSame([], $c->all());
- $c = new Collection(null);
+ $c = new Collection();
$this->assertSame([], $c->all());
}
- /**
- * @return void
- */
- public function testConstructMethodWithAcceptableData()
+ public function testConstructMethodWithAcceptableData(): void
{
[$o1] = $this->arr;
$c = new Collection($o1);
$this->assertSame([ self::OBJ_1 => $o1 ], $c->all());
}
- /**
- * @return void
- */
- public function testConstructMethodWithUnacceptableData()
+ public function testConstructMethodWithUnacceptableData(): void
{
$this->expectException(InvalidArgumentException::class);
- $c = new Collection('foo');
+ new Collection('foo');
}
- /**
- * @return void
- */
- public function testConstructMethodFromArray()
+ public function testConstructMethodFromArray(): void
{
$c = new Collection($this->arr);
$this->assertEquals($this->map, $c->all());
}
- /**
- * @return void
- */
- public function testConstructMethodFromTraversable()
+ public function testConstructMethodFromTraversable(): void
{
$c = new Collection(new ArrayObject($this->arr));
$this->assertEquals($this->map, $c->all());
}
- /**
- * @return void
- */
- public function testConstructMethodFromCollection()
+ public function testConstructMethodFromCollection(): void
{
$c = new Collection(new Collection($this->arr));
$this->assertEquals($this->map, $c->all());
}
- /**
- * @return void
- */
- public function testValues()
+ public function testValues(): void
{
$c = new Collection($this->arr);
$this->assertEquals($this->arr, $c->values());
}
- /**
- * @return void
- */
- public function testKeys()
+ public function testKeys(): void
{
$c = new Collection($this->arr);
$this->assertEquals(array_keys($this->map), $c->keys());
}
- /**
- * @return void
- */
- public function testBaseCollection()
+ public function testBaseCollection(): void
{
$c = new Collection($this->arr);
$this->assertInstanceOf(Collection::class, $c->toBase());
}
- /**
- * @return void
- */
- public function testEmptyCollection()
+ public function testEmptyCollection(): void
{
$c = new Collection;
@@ -165,10 +131,7 @@ public function testEmptyCollection()
$this->assertEquals(null, $c->last());
}
- /**
- * @return void
- */
- public function testFirstItemInCollection()
+ public function testFirstItemInCollection(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
$c = new Collection($this->arr);
@@ -176,10 +139,7 @@ public function testFirstItemInCollection()
$this->assertEquals($o1, $c->first());
}
- /**
- * @return void
- */
- public function testLastItemInCollection()
+ public function testLastItemInCollection(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
$c = new Collection($this->arr);
@@ -187,16 +147,12 @@ public function testLastItemInCollection()
$this->assertEquals($o5, $c->last());
}
- /**
- * @return void
- */
- public function testArrayableItems()
+ public function testArrayableItems(): void
{
$c = new Collection;
$class = new ReflectionClass($c);
$method = $class->getMethod('asArray');
- $method->setAccessible(true);
$items = new Collection($this->arr);
$array = $method->invokeArgs($c, [ $items ]);
@@ -211,10 +167,7 @@ public function testArrayableItems()
$this->assertSame($this->arr, $array);
}
- /**
- * @return void
- */
- public function testRemoveKey()
+ public function testRemoveKey(): void
{
[$o1] = $this->arr;
@@ -227,30 +180,21 @@ public function testRemoveKey()
$this->assertFalse(isset($c[self::OBJ_1]));
}
- /**
- * @return void
- */
- public function testAddAcceptableData()
+ public function testAddAcceptableData(): void
{
[$o1] = $this->arr;
$c = new Collection;
$this->assertSame([ $o1->id() => $o1 ], $c->add($o1)->all());
}
- /**
- * @return void
- */
- public function testAddUnacceptableData()
+ public function testAddUnacceptableData(): void
{
$this->expectException(InvalidArgumentException::class);
$c = new Collection;
$c->add('foo');
}
- /**
- * @return void
- */
- public function testGet()
+ public function testGet(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
$c = new Collection($this->arr);
@@ -258,10 +202,7 @@ public function testGet()
$this->assertSame($o1, $c->get($o1));
}
- /**
- * @return void
- */
- public function testHas()
+ public function testHas(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
$c = new Collection($this->arr);
@@ -270,28 +211,19 @@ public function testHas()
$this->assertFalse($c->offsetExists('missing'));
}
- /**
- * @return void
- */
- public function testClear()
+ public function testClear(): void
{
$c = new Collection($this->arr);
$this->assertSame([], $c->clear()->all());
}
- /**
- * @return void
- */
- public function testMergeNull()
+ public function testMergeNull(): void
{
$c = new Collection($this->arr);
$this->assertEquals($this->map, $c->merge(null)->all());
}
- /**
- * @return void
- */
- public function testMergeArray()
+ public function testMergeArray(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
$c = new Collection([ $o1, $o2, $o3, $o4 ]);
@@ -299,10 +231,7 @@ public function testMergeArray()
$this->assertEquals($this->map, $c->merge([ $o5 ])->all());
}
- /**
- * @return void
- */
- public function testMergeCollection()
+ public function testMergeCollection(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
$c1 = new Collection([ $o1, $o2, $o3, $o4 ]);
@@ -313,11 +242,7 @@ public function testMergeCollection()
// Test \IteratorAggregate
// =============================================================================================
-
- /**
- * @return void
- */
- public function testIterable()
+ public function testIterable(): void
{
$c = new Collection($this->arr);
@@ -326,10 +251,7 @@ public function testIterable()
$this->assertEquals($this->map, $i->getArrayCopy());
}
- /**
- * @return void
- */
- public function testCachingIterator()
+ public function testCachingIterator(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
$c = new Collection($this->arr);
@@ -353,11 +275,7 @@ public function testCachingIterator()
// Test \Countable
// =============================================================================================
-
- /**
- * @return void
- */
- public function testCountable()
+ public function testCountable(): void
{
$c = new Collection($this->arr);
$this->assertCount(count($this->arr), $c);
@@ -365,11 +283,7 @@ public function testCountable()
// Test \ArrayAccess
// =============================================================================================
-
- /**
- * @return void
- */
- public function testArrayAccess()
+ public function testArrayAccess(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
@@ -390,10 +304,7 @@ public function testArrayAccess()
$this->assertEquals($o4, $c[-1]);
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetExists()
+ public function testArrayAccessOffsetExists(): void
{
$c = new Collection($this->arr);
$this->assertTrue($c->offsetExists(0));
@@ -401,10 +312,7 @@ public function testArrayAccessOffsetExists()
$this->assertFalse($c->offsetExists(5));
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetGet()
+ public function testArrayAccessOffsetGet(): void
{
[$o1, $o2] = $this->arr;
@@ -413,10 +321,7 @@ public function testArrayAccessOffsetGet()
$this->assertEquals($o2, $c->offsetGet(1));
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetGetWithNegativeOffset()
+ public function testArrayAccessOffsetGetWithNegativeOffset(): void
{
[$o1, $o2, $o3, $o4, $o5] = $this->arr;
@@ -426,19 +331,13 @@ public function testArrayAccessOffsetGetWithNegativeOffset()
$this->assertEquals($o3, $c->offsetGet(-1));
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetGetOnNonExist()
+ public function testArrayAccessOffsetGetOnNonExist(): void
{
$c = new Collection($this->arr);
$this->assertEquals(null, $c->offsetGet(10));
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetSet()
+ public function testArrayAccessOffsetSet(): void
{
[$o1, $o2] = $this->arr;
$c = new Collection($o1);
@@ -447,11 +346,7 @@ public function testArrayAccessOffsetSet()
$this->assertEquals($o2, $c[1]);
}
- /**
- *
- * @return void
- */
- public function testArrayAccessOffsetSetWithOffset()
+ public function testArrayAccessOffsetSetWithOffset(): void
{
$this->expectException(LogicException::class);
[$o1] = $this->arr;
@@ -460,11 +355,7 @@ public function testArrayAccessOffsetSetWithOffset()
$c->offsetSet(1, $o1);
}
- /**
- *
- * @return void
- */
- public function testArrayAccessOffsetSetWithKey()
+ public function testArrayAccessOffsetSetWithKey(): void
{
$this->expectException(LogicException::class);
[$o1] = $this->arr;
@@ -473,10 +364,7 @@ public function testArrayAccessOffsetSetWithKey()
$c->offsetSet(self::OBJ_1, $o1);
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetUnset()
+ public function testArrayAccessOffsetUnset(): void
{
$c = new Collection($this->arr);
@@ -484,10 +372,7 @@ public function testArrayAccessOffsetUnset()
$this->assertEquals(null, $c[self::OBJ_2]);
}
- /**
- * @return void
- */
- public function testArrayAccessOffsetUnsetWithKey()
+ public function testArrayAccessOffsetUnsetWithKey(): void
{
$c = new Collection($this->arr);
diff --git a/packages/core/tests/Charcoal/Model/ModelMetadataTest.php b/packages/core/tests/Charcoal/Model/ModelMetadataTest.php
index 0af4aefce..61f8e1372 100644
--- a/packages/core/tests/Charcoal/Model/ModelMetadataTest.php
+++ b/packages/core/tests/Charcoal/Model/ModelMetadataTest.php
@@ -13,23 +13,14 @@
*/
class ModelMetadataTest extends AbstractTestCase
{
- /**
- * @var ModelMetadata
- */
- private $obj;
-
- /**
- * @return void
- */
+ private \Charcoal\Model\ModelMetadata $obj;
+
protected function setUp(): void
{
$this->obj = new ModelMetadata();
}
- /**
- * @return void
- */
- public function testSetIdent()
+ public function testSetIdent(): void
{
$ret = $this->obj->setIdent('foo');
$this->assertSame($ret, $this->obj);
@@ -39,10 +30,7 @@ public function testSetIdent()
$this->obj->setIdent(false);
}
- /**
- * @return void
- */
- public function testArrayAccessGet()
+ public function testArrayAccessGet(): void
{
$obj = $this->obj;
$obj->foo = 'bar';
@@ -50,10 +38,7 @@ public function testArrayAccessGet()
$this->assertEquals($obj->foo, $obj['foo']);
}
- /**
- * @return void
- */
- public function testArrayAccessSet()
+ public function testArrayAccessSet(): void
{
$obj = $this->obj;
$obj['foo'] = 'bar';
@@ -61,25 +46,19 @@ public function testArrayAccessSet()
$this->assertEquals($obj->foo, $obj['foo']);
}
- /**
- * @return void
- */
- public function testArrayAccessUnset()
+ public function testArrayAccessUnset(): void
{
$obj = $this->obj;
- $this->assertObjectNotHasAttribute('foo', $obj);
+ $this->assertFalse(property_exists($obj, 'foo'));
$obj['foo'] = 'bar';
- $this->assertObjectHasAttribute('foo', $obj);
+ $this->assertTrue(property_exists($obj, 'foo'));
unset($obj['foo']);
//$this->assertObjectNotHasAttribute('foo', $obj);
}
- /**
- * @return void
- */
- public function testMerge()
+ public function testMerge(): void
{
$data = [
'foo' => 'bar',
@@ -93,10 +72,7 @@ public function testMerge()
$this->assertEquals($obj->bar, 'foo');
}
- /**
- * @return void
- */
- public function testMergeIsChainable()
+ public function testMergeIsChainable(): void
{
$obj = $this->obj;
$ret = $obj->merge([]);
diff --git a/packages/core/tests/Charcoal/Model/ModelTest.php b/packages/core/tests/Charcoal/Model/ModelTest.php
index dad743937..42eddb2a8 100644
--- a/packages/core/tests/Charcoal/Model/ModelTest.php
+++ b/packages/core/tests/Charcoal/Model/ModelTest.php
@@ -24,10 +24,8 @@ class ModelTest extends AbstractTestCase
/**
* Retrieve the model's mock metadata.
- *
- * @return array
*/
- private function getModelMetadata()
+ private function getModelMetadata(): array
{
return [
'properties' => [
@@ -75,10 +73,8 @@ private function createModel()
/**
* Drop the SQL table.
- *
- * @return void
*/
- private function dropTable()
+ private function dropTable(): void
{
$container = $this->getContainer();
@@ -87,10 +83,8 @@ private function dropTable()
/**
* Retrieve the model's mock object data.
- *
- * @return array
*/
- private function getHuxleyData()
+ private function getHuxleyData(): array
{
return [
'id' => 1,
@@ -104,7 +98,7 @@ private function getHuxleyData()
*
* @return integer The saved object ID.
*/
- private function saveHuxley()
+ private function saveHuxley(): bool
{
$obj = $this->obj;
$obj->setData($this->getHuxleyData());
@@ -116,8 +110,6 @@ private function saveHuxley()
* Set up the test.
*
* Create the SQL table for the test, dropping any existing table.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -130,17 +122,12 @@ protected function setUp(): void
* Tear down the test.
*
* Drop any existing SQL table.
- *
- * @return void
*/
protected function tearDown(): void {
$this->dropTable();
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$obj = $this->obj;
@@ -148,10 +135,7 @@ public function testConstructor()
$this->assertInstanceOf(ModelInterface::class, $obj);
}
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([ 'name' => 'Orwell' ]);
@@ -160,10 +144,7 @@ public function testSetData()
$this->assertEquals('Orwell', $obj->name);
}
- /**
- * @return void
- */
- public function testSetFlatData()
+ public function testSetFlatData(): void
{
$obj = $this->obj;
$ret = $obj->setFlatData([ 'name' => 'Clarke' ]);
@@ -172,22 +153,16 @@ public function testSetFlatData()
$this->assertEquals('Clarke', $obj->name);
}
- /**
- * @return void
- */
- public function testSave()
+ public function testSave(): void
{
$ret = $this->saveHuxley();
$this->assertEquals(1, $ret);
}
- /**
- * @return void
- */
- public function testLoad()
+ public function testLoad(): void
{
- $ret = $this->saveHuxley();
+ $this->saveHuxley();
$obj1 = $this->createModel();
$obj1->load(1);
@@ -195,10 +170,7 @@ public function testLoad()
$this->assertEquals($this->getHuxleyData(), $obj1->data());
}
- /**
- * @return void
- */
- public function testUpdate()
+ public function testUpdate(): void
{
$ret = $this->saveHuxley();
@@ -226,10 +198,7 @@ public function testUpdate()
$this->assertEquals('Screenwriter', $obj2['role']);
}
- /**
- * @return void
- */
- public function testDelete()
+ public function testDelete(): void
{
$ret = $this->saveHuxley();
@@ -242,19 +211,15 @@ public function testDelete()
$this->assertEquals(null, $obj1['id']);
}
- /**
- * @return void
- */
- public function testSerializeUnserialize()
+ public function testSerializeUnserialize(): void
{
$obj = $this->obj;
$data = $this->getHuxleyData();
$obj->setData($data);
-
$serialized = serialize($obj);
$this->assertEquals(
- 'C:20:"Charcoal\Model\Model":69:{a:3:{s:2:"id";i:1;s:4:"name";s:6:"Huxley";s:4:"role";s:8:"Novelist";}}',
+ 'O:20:"Charcoal\Model\Model":3:{s:2:"id";i:1;s:4:"name";s:6:"Huxley";s:4:"role";s:8:"Novelist";}',
serialize($obj)
);
@@ -265,10 +230,7 @@ public function testSerializeUnserialize()
$this->assertEquals('Huxley', $obj2['name']);
}
- /**
- * @return void
- */
- public function testJsonSerialize()
+ public function testJsonSerialize(): void
{
$obj = $this->obj;
$data = $this->getHuxleyData();
diff --git a/packages/core/tests/Charcoal/Model/ModelValidatorTest.php b/packages/core/tests/Charcoal/Model/ModelValidatorTest.php
index 9fd4736e7..d8d88e5f9 100644
--- a/packages/core/tests/Charcoal/Model/ModelValidatorTest.php
+++ b/packages/core/tests/Charcoal/Model/ModelValidatorTest.php
@@ -1,5 +1,7 @@
getContainer();
@@ -31,20 +30,14 @@ protected function model()
]);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$model = $this->model();
$obj = new ModelValidator($model);
$this->assertInstanceOf(ModelValidator::class, $obj);
}
- /**
- * @return void
- */
- public function testValidateModel()
+ public function testValidateModel(): void
{
$model = $this->model();
$model->setMetadata([
diff --git a/packages/core/tests/Charcoal/Model/Service/MetadataLoaderTest.php b/packages/core/tests/Charcoal/Model/Service/MetadataLoaderTest.php
index fd02a4cae..e8198d818 100644
--- a/packages/core/tests/Charcoal/Model/Service/MetadataLoaderTest.php
+++ b/packages/core/tests/Charcoal/Model/Service/MetadataLoaderTest.php
@@ -1,5 +1,7 @@
getContainer();
@@ -33,10 +32,7 @@ protected function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testLoadData()
+ public function testLoadData(): void
{
$this->assertInstanceOf(MetadataLoader::class, $this->obj);
//$ret = $this->obj->load('test', $this->);
diff --git a/packages/core/tests/Charcoal/Model/Service/ModelLoaderBuilderTest.php b/packages/core/tests/Charcoal/Model/Service/ModelLoaderBuilderTest.php
index fd973062a..0648993fc 100644
--- a/packages/core/tests/Charcoal/Model/Service/ModelLoaderBuilderTest.php
+++ b/packages/core/tests/Charcoal/Model/Service/ModelLoaderBuilderTest.php
@@ -24,9 +24,6 @@ class ModelLoaderBuilderTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
protected function setUp(): void
{
$container = $this->getContainer();
@@ -52,19 +49,13 @@ protected function setUp(): void
]);
}
- /**
- * @return void
- */
- public function testBuild()
+ public function testBuild(): void
{
$ret = $this->obj->build(GenericModel::class, 'name');
$this->assertInstanceOf(ModelLoader::class, $ret);
}
- /**
- * @return void
- */
- public function testInvokable()
+ public function testInvokable(): void
{
$builder = $this->obj;
$ret = $builder(GenericModel::class);
diff --git a/packages/core/tests/Charcoal/Model/Service/ModelLoaderTest.php b/packages/core/tests/Charcoal/Model/Service/ModelLoaderTest.php
index 3390e30a0..5553c5fab 100644
--- a/packages/core/tests/Charcoal/Model/Service/ModelLoaderTest.php
+++ b/packages/core/tests/Charcoal/Model/Service/ModelLoaderTest.php
@@ -1,5 +1,7 @@
expectException(Exception::class);
$this->obj->load('foobar');
diff --git a/packages/core/tests/Charcoal/Model/ServiceProvider/ModelServiceProviderTest.php b/packages/core/tests/Charcoal/Model/ServiceProvider/ModelServiceProviderTest.php
index d2e5704a2..915f47222 100644
--- a/packages/core/tests/Charcoal/Model/ServiceProvider/ModelServiceProviderTest.php
+++ b/packages/core/tests/Charcoal/Model/ServiceProvider/ModelServiceProviderTest.php
@@ -51,9 +51,6 @@ class ModelServiceProviderTest extends AbstractTestCase
public $obj;
- /**
- * @return void
- */
protected function setUp(): void
{
$this->obj = new ModelServiceProvider();
@@ -70,9 +67,8 @@ protected function setUp(): void
* - view
*
* @todo Use ContainerIntegrationTrait?
- * @return Container
*/
- private function container()
+ private function container(): \Pimple\Container
{
$container = new Container();
@@ -117,10 +113,7 @@ private function container()
return $container;
}
- /**
- * @return void
- */
- public function testFactories()
+ public function testFactories(): void
{
$container = $this->container();
@@ -136,10 +129,7 @@ public function testFactories()
$this->assertInstanceOf(FactoryInterface::class, $container['source/factory']);
}
- /**
- * @return void
- */
- public function testRegisterSetsModelBuilder()
+ public function testRegisterSetsModelBuilder(): void
{
$container = $this->container();
$this->obj->register($container);
@@ -148,10 +138,7 @@ public function testRegisterSetsModelBuilder()
$this->assertInstanceOf(ModelBuilder::class, $container['model/builder']);
}
- /**
- * @return void
- */
- public function testRegisterSetsModelLoaderBuilder()
+ public function testRegisterSetsModelLoaderBuilder(): void
{
$container = $this->container();
$this->obj->register($container);
@@ -160,10 +147,7 @@ public function testRegisterSetsModelLoaderBuilder()
$this->assertInstanceOf(ModelLoaderBuilder::class, $container['model/loader/builder']);
}
- /**
- * @return void
- */
- public function testRegisterSetsMetadataLoader()
+ public function testRegisterSetsMetadataLoader(): void
{
$container = $this->container();
$this->obj->register($container);
@@ -172,17 +156,14 @@ public function testRegisterSetsMetadataLoader()
$this->assertInstanceOf(MetadataLoader::class, $container['metadata/loader']);
}
- /**
- * @return void
- */
- public function testExtraMetadataPaths()
+ public function testExtraMetadataPaths(): void
{
$container = new Container([
'config' => [
- 'base_path' => dirname(dirname(dirname(dirname(__DIR__)))),
+ 'base_path' => dirname(__DIR__, 4),
],
'module/classes' => [
- 'Charcoal\\Tests\\Mock\\MockModule',
+ \Charcoal\Tests\Mock\MockModule::class,
],
]);
diff --git a/packages/core/tests/Charcoal/ReflectionsTrait.php b/packages/core/tests/Charcoal/ReflectionsTrait.php
index 3a63ff2b1..047d2c172 100644
--- a/packages/core/tests/Charcoal/ReflectionsTrait.php
+++ b/packages/core/tests/Charcoal/ReflectionsTrait.php
@@ -18,13 +18,10 @@ trait ReflectionsTrait
*
* @param mixed $class The class name or object that contains the method.
* @param string $name The method name to reflect.
- * @return ReflectionMethod
*/
- public function getMethod($class, $name)
+ public function getMethod($class, $name): \ReflectionMethod
{
- $reflected = new ReflectionMethod($class, $name);
- $reflected->setAccessible(true);
- return $reflected;
+ return new ReflectionMethod($class, $name);
}
/**
@@ -38,7 +35,7 @@ public function getMethod($class, $name)
public function callMethod($object, $name, array $args = [])
{
$method = $this->getMethod($object, $name);
- if (empty($args)) {
+ if ($args === []) {
return $method->invoke($object);
} else {
return $method->invokeArgs($object, $args);
@@ -65,13 +62,10 @@ public function callMethodWith($object, $name, ...$args)
*
* @param mixed $class The class name or object that contains the property.
* @param string $name The property name to reflect.
- * @return ReflectionProperty
*/
- public function getProperty($class, $name)
+ public function getProperty($class, $name): \ReflectionProperty
{
- $reflected = new ReflectionProperty($class, $name);
- $reflected->setAccessible(true);
- return $reflected;
+ return new ReflectionProperty($class, $name);
}
/**
@@ -92,9 +86,8 @@ public function getPropertyValue($object, $name)
* @param mixed $object The object to access.
* @param string $name The property name to affect.
* @param mixed $value The new value.
- * @return void
*/
- public function setPropertyValue($object, $name, $value)
+ public function setPropertyValue($object, $name, $value): void
{
$this->getProperty($object, $name)->setValue($object, $value);
}
diff --git a/packages/core/tests/Charcoal/Source/AbstractExpressionTest.php b/packages/core/tests/Charcoal/Source/AbstractExpressionTest.php
index a82b15ba5..95bf86449 100644
--- a/packages/core/tests/Charcoal/Source/AbstractExpressionTest.php
+++ b/packages/core/tests/Charcoal/Source/AbstractExpressionTest.php
@@ -2,6 +2,7 @@
namespace Charcoal\Tests\Source;
+use Charcoal\Property\DateTimeProperty;
use stdClass;
use DateTime;
use InvalidArgumentException;
@@ -27,7 +28,16 @@ class AbstractExpressionTest extends AbstractTestCase
*/
final protected function createExpression()
{
- return $this->getMockForAbstractClass(AbstractExpression::class);
+ return new class () extends AbstractExpression
+ {
+ public function defaultData()
+ {
+ }
+
+ public function data()
+ {
+ }
+ };
}
/**
@@ -37,10 +47,8 @@ final protected function createExpression()
* 1. Default state
* 2. Mutated state
* 3. Chainable method
- *
- * @return void
*/
- public function testName()
+ public function testName(): void
{
$obj = $this->createExpression();
@@ -57,10 +65,8 @@ public function testName()
/**
* Test "name" property with invalid value.
- *
- * @return void
*/
- public function testNameWithInvalidValue()
+ public function testNameWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setName(0);
@@ -74,10 +80,8 @@ public function testNameWithInvalidValue()
* 2. Mutated state
* 3. Chainable method
* 4. Cast value to boolean
- *
- * @return void
*/
- public function testActive()
+ public function testActive(): void
{
$obj = $this->createExpression();
@@ -102,16 +106,19 @@ public function testActive()
/**
* Test value parsing.
*
- * @dataProvider provideParsableValues
*
* @param mixed $value The value to test.
* @param mixed $expected The expected result.
- * @return void
*/
- public function testParseValue($value, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideParsableValues')]
+ public function testParseValue($value, int|string|bool|null $expected): void
{
$obj = $this->createExpression();
+ if ($value instanceof \Closure) {
+ $value = $value->call($this);
+ }
+
$this->assertEquals($expected, $obj::parseValue($value));
}
@@ -119,14 +126,16 @@ public function testParseValue($value, $expected)
* Provide data for value parsing.
*
* @used-by self::testParseValue()
- * @return array
*/
- public function provideParsableValues()
+ public static function provideParsableValues(): array
{
- $container = $this->getContainer();
+ $prop = function () {
+ $container = $this->getContainer();
+ return $container['property/factory']
+ ->create('date-time')
+ ->setVal('13 July 2004');
+ };
- $prop = $container['property/factory']->create('date-time');
- $prop->setVal('13 July 2004');
$time = new DateTime('8 June 1995');
return [
@@ -144,13 +153,12 @@ public function provideParsableValues()
/**
* Test value quoting.
*
- * @dataProvider provideQuotableValues
*
* @param mixed $value The value to test.
* @param mixed $expected The expected result.
- * @return void
*/
- public function testQuoteValue($value, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideQuotableValues')]
+ public function testQuoteValue(int|string|bool|\stdClass|array|null $value, int|string|\stdClass|array|null $expected): void
{
$obj = $this->createExpression();
@@ -161,9 +169,8 @@ public function testQuoteValue($value, $expected)
* Provide data for value quoting.
*
* @used-by self::testQuoteValue()
- * @return array
*/
- public function provideQuotableValues()
+ public static function provideQuotableValues(): array
{
$obj = new stdClass();
@@ -182,14 +189,13 @@ public function provideQuotableValues()
/**
* Test field quoting.
*
- * @dataProvider provideQuotableIdentifiers
*
* @param mixed $fieldName The field name.
* @param mixed $tableName The table name.
* @param mixed $expected The expected identifier.
- * @return void
*/
- public function testQuoteIdentifier($fieldName, $tableName, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideQuotableIdentifiers')]
+ public function testQuoteIdentifier(?string $fieldName, ?string $tableName, string $expected): void
{
$obj = $this->createExpression();
@@ -200,9 +206,8 @@ public function testQuoteIdentifier($fieldName, $tableName, $expected)
* Provide data for field quoting.
*
* @used-by self::testQuoteIdentifier()
- * @return array
*/
- public function provideQuotableIdentifiers()
+ public static function provideQuotableIdentifiers(): array
{
return [
[ null, null, '' ],
@@ -216,10 +221,8 @@ public function provideQuotableIdentifiers()
/**
* Test field quoting with invalid field name.
- *
- * @return void
*/
- public function testQuoteIdentifierWithInvalidFieldName()
+ public function testQuoteIdentifierWithInvalidFieldName(): void
{
$this->expectException(InvalidArgumentException::class);
$obj = $this->createExpression();
@@ -228,10 +231,8 @@ public function testQuoteIdentifierWithInvalidFieldName()
/**
* Test field quoting with blank table name.
- *
- * @return void
*/
- public function testQuoteIdentifierWithBlankTableName()
+ public function testQuoteIdentifierWithBlankTableName(): void
{
$this->expectException(InvalidArgumentException::class);
$obj = $this->createExpression();
@@ -240,10 +241,8 @@ public function testQuoteIdentifierWithBlankTableName()
/**
* Test field quoting with invalid table name.
- *
- * @return void
*/
- public function testQuoteIdentifierWithInvalidTableName()
+ public function testQuoteIdentifierWithInvalidTableName(): void
{
$this->expectException(InvalidArgumentException::class);
$obj = $this->createExpression();
@@ -253,14 +252,13 @@ public function testQuoteIdentifierWithInvalidTableName()
/**
* Test value differentiation.
*
- * @dataProvider provideDiffValues
*
* @param mixed $a The custom value.
* @param mixed $b The default value.
* @param mixed $expected The expected result.
- * @return void
*/
- public function testDiffValues($a, $b, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideDiffValues')]
+ public function testDiffValues(int $a, int|string $b, int $expected): void
{
$obj = $this->createExpression();
@@ -271,9 +269,8 @@ public function testDiffValues($a, $b, $expected)
* Provide data for value differentiation.
*
* @used-by self::testDiffValues()
- * @return array
*/
- public function provideDiffValues()
+ public static function provideDiffValues(): array
{
return [
'Same Type' => [ 5, 5, 0 ],
@@ -284,13 +281,12 @@ public function provideDiffValues()
/**
* Test callable detection.
*
- * @dataProvider provideCallableValues
*
* @param mixed $value The value to test.
* @param mixed $expected The expected result.
- * @return void
*/
- public function testIsCallable($value, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideCallableValues')]
+ public function testIsCallable(string|\Closure|null $value, bool $expected): void
{
$obj = $this->createExpression();
@@ -301,14 +297,13 @@ public function testIsCallable($value, $expected)
* Provide data for callable detection.
*
* @used-by self::testIsCallable()
- * @return array
*/
- public function provideCallableValues()
+ public static function provideCallableValues(): array
{
return [
'Null Type' => [ null, false ],
'String Type' => [ 'strval', false ],
- 'Closure' => [ function () {
+ 'Closure' => [ function (): void {
}, true ],
];
}
diff --git a/packages/core/tests/Charcoal/Source/AbstractSourceTest.php b/packages/core/tests/Charcoal/Source/AbstractSourceTest.php
index 744c195a0..d24924f51 100644
--- a/packages/core/tests/Charcoal/Source/AbstractSourceTest.php
+++ b/packages/core/tests/Charcoal/Source/AbstractSourceTest.php
@@ -2,6 +2,8 @@
namespace Charcoal\Tests\Source;
+use Charcoal\Source\StorableInterface;
+use Charcoal\Source\UnexpectedValueException;
use RuntimeException;
use InvalidArgumentException;
@@ -34,6 +36,25 @@
/**
* Test {@see AbstractSource} and {@see SourceInterface}.
*/
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'setProperties')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'addProperties')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'resolvePropertyName')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'hasProperties')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'addProperty')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'removeProperty')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'addFilter')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'parseFilterWithModel')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'createFilter')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'addOrder')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'parseOrderWithModel')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'createOrder')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'pagination')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'hasPagination')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'setPagination')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'createPagination')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'camelize')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'getter')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\AbstractSource::class, 'setter')]
class AbstractSourceTest extends AbstractTestCase
{
use AssertionsTrait;
@@ -49,16 +70,20 @@ class AbstractSourceTest extends AbstractTestCase
/**
* Setup the test.
- *
- * @return void
*/
protected function setUp(): void
{
$container = $this->getContainer();
- $this->obj = $this->getMockForAbstractClass(AbstractSource::class, [[
+ $this->obj = new class ([
'logger' => $container['logger']
- ]]);
+ ]) extends AbstractSource {
+ public function loadItem($ident, ?StorableInterface $item = null) {}
+ public function loadItems(?StorableInterface $item = null) {}
+ public function saveItem(StorableInterface $item) {}
+ public function updateItem(StorableInterface $item, ?array $properties = null) {}
+ public function deleteItem(?StorableInterface $item = null) {}
+ };
}
/**
@@ -83,10 +108,8 @@ final public function createProperty()
* - clear the filters
* - clear the orders
* - @todo clear the pagination
- *
- * @return void
*/
- public function testReset()
+ public function testReset(): void
{
$obj = $this->obj;
$filter = $this->createFilter();
@@ -114,10 +137,8 @@ public function testReset()
* Assert that the `setData` method:
* - is chainable
* - set the data (properties, filters, orders & pagination)
- *
- * @return void
*/
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -137,10 +158,8 @@ public function testSetData()
* Assert that the `setModel` method:
* - is chainable
* - set the model (retrievable with the `model` method)
- *
- * @return void
*/
- public function testSetModel()
+ public function testSetModel(): void
{
$container = $this->getContainer();
@@ -159,10 +178,7 @@ public function testSetModel()
$this->assertSame($model, $obj->model());
}
- /**
- * @return void
- */
- public function testModelWithoutSetThrowsException()
+ public function testModelWithoutSetThrowsException(): void
{
$obj = $this->obj;
$this->expectException(RuntimeException::class);
@@ -175,13 +191,8 @@ public function testModelWithoutSetThrowsException()
* - set the properties
* - reset the properties, when called again
*
- * @covers \Charcoal\Source\AbstractSource::setProperties
- * @covers \Charcoal\Source\AbstractSource::addProperties
- * @covers \Charcoal\Source\AbstractSource::resolvePropertyName
- *
- * @return void
*/
- public function testSetProperties()
+ public function testSetProperties(): void
{
$obj = $this->obj;
$ret = $obj->setProperties([ 'foo' ]);
@@ -199,11 +210,8 @@ public function testSetProperties()
* 1. Empty; Default state
* 2. Populated; Mutated state
*
- * @covers \Charcoal\Source\AbstractSource::hasProperties
- *
- * @return void
*/
- public function testHasProperties()
+ public function testHasProperties(): void
{
$obj = $this->obj;
@@ -218,12 +226,8 @@ public function testHasProperties()
/**
* Test property collection appending.
*
- * @covers \Charcoal\Source\AbstractSource::addProperty
- * @covers \Charcoal\Source\AbstractSource::resolvePropertyName
- *
- * @return void
*/
- public function testAddProperty()
+ public function testAddProperty(): void
{
$obj = $this->obj;
$this->assertEquals([], $obj->properties());
@@ -238,12 +242,8 @@ public function testAddProperty()
/**
* Test property collection appending.
*
- * @covers \Charcoal\Source\AbstractSource::removeProperty
- * @covers \Charcoal\Source\AbstractSource::resolvePropertyName
- *
- * @return void
*/
- public function testRemoveProperty()
+ public function testRemoveProperty(): void
{
$obj = $this->obj;
$obj->setProperties([ 'foo', 'bar', 'qux' ]);
@@ -256,11 +256,8 @@ public function testRemoveProperty()
/**
* Test failure when appending an invalid property name.
*
- * @covers \Charcoal\Source\AbstractSource::resolvePropertyName
- *
- * @return void
*/
- public function testInvalidPropertyNameResolution()
+ public function testInvalidPropertyNameResolution(): void
{
$obj = $this->obj;
$this->expectException(InvalidArgumentException::class);
@@ -270,11 +267,8 @@ public function testInvalidPropertyNameResolution()
/**
* Test failure when appending an blank property name.
*
- * @covers \Charcoal\Source\AbstractSource::resolvePropertyName
- *
- * @return void
*/
- public function testBlankPropertyNameResolution()
+ public function testBlankPropertyNameResolution(): void
{
$obj = $this->obj;
$this->expectException(InvalidArgumentException::class);
@@ -284,11 +278,8 @@ public function testBlankPropertyNameResolution()
/**
* Test failure when appending a unnamed property object.
*
- * @covers \Charcoal\Source\AbstractSource::resolvePropertyName
- *
- * @return void
*/
- public function testAnonymousPropertyNameResolution()
+ public function testAnonymousPropertyNameResolution(): void
{
$obj = $this->obj;
$prop = $this->createProperty()->setIdent('');
@@ -299,11 +290,8 @@ public function testAnonymousPropertyNameResolution()
/**
* Test appending a named property object.
*
- * @covers \Charcoal\Source\AbstractSource::resolvePropertyName
- *
- * @return void
*/
- public function testNamedPropertyNameResolution()
+ public function testNamedPropertyNameResolution(): void
{
$obj = $this->obj;
$prop = $this->createProperty();
@@ -329,11 +317,8 @@ public function testNamedPropertyNameResolution()
* an Expression object with given extra data is returned
* 6. Chainable method
*
- * @covers \Charcoal\Source\AbstractSource::addFilter
- *
- * @return void
*/
- public function testAddFilter()
+ public function testAddFilter(): void
{
$obj = $this->obj;
@@ -394,11 +379,8 @@ public function testAddFilter()
* 3. If a tree of expressions is passed, the source will traverse
* all expressions.
*
- * @covers \Charcoal\Source\AbstractSource::parseFilterWithModel
- *
- * @return void
*/
- public function testParseFilterWithModel()
+ public function testParseFilterWithModel(): void
{
$model = $this->createModel();
$source = $this->obj;
@@ -438,11 +420,8 @@ public function testParseFilterWithModel()
* 2. Instance of {@see Filter}
*
* @see \Charcoal\Tests\Source\FilterTest::testCreateFilter
- * @covers \Charcoal\Source\AbstractSource::createFilter
- *
- * @return void
*/
- public function testCreateFilter()
+ public function testCreateFilter(): void
{
$result = $this->callMethodWith($this->obj, 'createFilter', [ 'name' => 'foo' ]);
$this->assertInstanceOf(Filter::class, $result);
@@ -467,11 +446,8 @@ public function testCreateFilter()
* an Expression object with given extra data is returned
* 6. Chainable method
*
- * @covers \Charcoal\Source\AbstractSource::addOrder
- *
- * @return void
*/
- public function testAddOrder()
+ public function testAddOrder(): void
{
$obj = $this->obj;
@@ -530,11 +506,8 @@ public function testAddOrder()
* 2. If a tree of expressions is passed, the source will traverse
* all expressions.
*
- * @covers \Charcoal\Source\AbstractSource::parseOrderWithModel
- *
- * @return void
*/
- public function testParseOrderWithModel()
+ public function testParseOrderWithModel(): void
{
$model = $this->createModel();
$source = $this->obj;
@@ -567,11 +540,8 @@ public function testParseOrderWithModel()
* 1. Instance of {@see ExpressionInterface}
* 2. Instance of {@see Order}
*
- * @covers \Charcoal\Source\AbstractSource::createOrder
- *
- * @return void
*/
- public function testCreateOrder()
+ public function testCreateOrder(): void
{
$result = $this->callMethodWith($this->obj, 'createOrder', [ 'name' => 'foo' ]);
$this->assertInstanceOf(Order::class, $result);
@@ -586,12 +556,8 @@ public function testCreateOrder()
* 1. Default state is NULL
* 2. Create paginator if state is NULL
*
- * @covers \Charcoal\Source\AbstractSource::pagination
- * @covers \Charcoal\Source\AbstractSource::hasPagination
- *
- * @return void
*/
- public function testGetPagination()
+ public function testGetPagination(): void
{
/** 1. Default state is NULL */
$this->assertFalse($this->obj->hasPagination());
@@ -612,11 +578,8 @@ public function testGetPagination()
* 4. Accepts up to two numeric arguments
* 5. Chainable method
*
- * @covers \Charcoal\Source\AbstractSource::setPagination
- *
- * @return void
*/
- public function testSetPagination()
+ public function testSetPagination(): void
{
$obj = $this->obj;
@@ -653,11 +616,8 @@ public function testSetPagination()
/**
* Test the failure when assigning an invalid pagination expression.
*
- * @covers \Charcoal\Source\AbstractSource::setPagination
- *
- * @return void
*/
- public function testProcessExpressionWithInvalidValue()
+ public function testProcessExpressionWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->setPagination(false);
@@ -670,11 +630,8 @@ public function testProcessExpressionWithInvalidValue()
* 1. Instance of {@see ExpressionInterface}
* 2. Instance of {@see PaginationInterface}
*
- * @covers \Charcoal\Source\AbstractSource::createPagination
- *
- * @return void
*/
- public function testCreatePagination()
+ public function testCreatePagination(): void
{
$result = $this->callMethodWith($this->obj, 'createPagination', [ 'name' => 'foo' ]);
$this->assertInstanceOf(Pagination::class, $result);
@@ -682,10 +639,7 @@ public function testCreatePagination()
$this->assertEquals('foo', $result->name());
}
- /**
- * @return void
- */
- public function testSetPage()
+ public function testSetPage(): void
{
$obj = $this->obj;
$this->assertEquals(1, $obj->page());
@@ -698,10 +652,7 @@ public function testSetPage()
$obj->setPage('foo');
}
- /**
- * @return void
- */
- public function testNumPerPage()
+ public function testNumPerPage(): void
{
$obj = $this->obj;
$this->assertEquals(Pagination::DEFAULT_COUNT, $obj->numPerPage());
@@ -713,10 +664,7 @@ public function testNumPerPage()
$obj->setNumPerPage('foobar');
}
- /**
- * @return void
- */
- public function testCreateConfig()
+ public function testCreateConfig(): void
{
$obj = $this->obj;
$config = $obj->createConfig([ 'type' => 'foo' ]);
@@ -727,13 +675,8 @@ public function testCreateConfig()
/**
* Test camelization.
*
- * @covers \Charcoal\Source\AbstractSource::camelize
- * @covers \Charcoal\Source\AbstractSource::getter
- * @covers \Charcoal\Source\AbstractSource::setter
- *
- * @return void
*/
- public function testCamelize()
+ public function testCamelize(): void
{
$obj = $this->obj;
@@ -748,9 +691,8 @@ public function testCamelize()
* Create a query filter expression, for testing.
*
* @param array $data Optional expression data.
- * @return Filter
*/
- final public function createFilter(array $data = null)
+ final public function createFilter(?array $data = null): \Charcoal\Source\Filter
{
$expr = new Filter();
if ($data !== null) {
@@ -763,9 +705,8 @@ final public function createFilter(array $data = null)
* Create query sorting expression, for testing.
*
* @param array $data Optional expression data.
- * @return Order
*/
- final public function createOrder(array $data = null)
+ final public function createOrder(?array $data = null): \Charcoal\Source\Order
{
$expr = new Order();
if ($data !== null) {
@@ -778,9 +719,8 @@ final public function createOrder(array $data = null)
* Create query pagination expression, for testing.
*
* @param array $data Optional expression data.
- * @return Pagination
*/
- final public function createPagination(array $data = null)
+ final public function createPagination(?array $data = null): \Charcoal\Source\Pagination
{
$expr = new Pagination();
if ($data !== null) {
@@ -806,10 +746,8 @@ final protected function createModel()
/**
* Retrieve the model's mock metadata.
- *
- * @return array
*/
- final protected function getModelMetadata()
+ final protected function getModelMetadata(): array
{
return [
'properties' => [
diff --git a/packages/core/tests/Charcoal/Source/Database/DatabaseExpressionTest.php b/packages/core/tests/Charcoal/Source/Database/DatabaseExpressionTest.php
index 083ff6141..f7f34bccd 100644
--- a/packages/core/tests/Charcoal/Source/Database/DatabaseExpressionTest.php
+++ b/packages/core/tests/Charcoal/Source/Database/DatabaseExpressionTest.php
@@ -21,20 +21,16 @@ class DatabaseExpressionTest extends AbstractTestCase
/**
* Create expression for testing.
- *
- * @return DatabaseExpression
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Database\DatabaseExpression
{
return new DatabaseExpression();
}
/**
* Test influence of "active" property on SQL compilation.
- *
- * @return void
*/
- public function testInactiveExpression()
+ public function testInactiveExpression(): void
{
$obj = $this->createExpression();
$obj->setCondition(' /* xyzzy */ ');
@@ -48,10 +44,8 @@ public function testInactiveExpression()
/**
* Test "condition" property.
- *
- * @return void
*/
- public function testCustomSql()
+ public function testCustomSql(): void
{
$obj = $this->createExpression();
@@ -61,10 +55,8 @@ public function testCustomSql()
/**
* Test invalid custom SQL.
- *
- * @return void
*/
- public function testCustomSqlWithoutQuery()
+ public function testCustomSqlWithoutQuery(): void
{
$obj = $this->createExpression();
diff --git a/packages/core/tests/Charcoal/Source/Database/DatabaseFilterTest.php b/packages/core/tests/Charcoal/Source/Database/DatabaseFilterTest.php
index 9e4e0b543..050fe478d 100644
--- a/packages/core/tests/Charcoal/Source/Database/DatabaseFilterTest.php
+++ b/packages/core/tests/Charcoal/Source/Database/DatabaseFilterTest.php
@@ -21,6 +21,7 @@
/**
* Test {@see DatabaseFilter}.
*/
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\Database\DatabaseFilter::class, 'isNegating')]
class DatabaseFilterTest extends AbstractTestCase
{
use CoreContainerIntegrationTrait;
@@ -29,10 +30,8 @@ class DatabaseFilterTest extends AbstractTestCase
/**
* Create expression for testing.
- *
- * @return DatabaseFilter
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Database\DatabaseFilter
{
return new DatabaseFilter();
}
@@ -56,10 +55,8 @@ final public function createProperty()
* Test default table name for default data values.
*
* @see \Charcoal\Tests\Source\Database\DatabaseOrderTest::testDefaultValues()
- *
- * @return void
*/
- public function testDefaultValues()
+ public function testDefaultValues(): void
{
$obj = $this->createExpression();
@@ -71,10 +68,8 @@ public function testDefaultValues()
/**
* Test influence of "active" property on SQL compilation.
- *
- * @return void
*/
- public function testInactiveExpression()
+ public function testInactiveExpression(): void
{
$obj = $this->createExpression();
$obj->setProperty('foo')->setValue('Charcoal');
@@ -94,11 +89,8 @@ public function testInactiveExpression()
* 2. Negatable Operators
* 3. Ignored Operators
*
- * @covers \Charcoal\Source\Database\DatabaseFilter::isNegating
- *
- * @return void
*/
- public function testNegation()
+ public function testNegation(): void
{
$obj = $this->createExpression();
@@ -119,10 +111,8 @@ public function testNegation()
/**
* Test SQL without conditions.
- *
- * @return void
*/
- public function testBlankSql()
+ public function testBlankSql(): void
{
$obj = $this->createExpression();
@@ -131,10 +121,8 @@ public function testBlankSql()
/**
* Test invalid SQL predicate.
- *
- * @return void
*/
- public function testSqlWithoutPredicate()
+ public function testSqlWithoutPredicate(): void
{
$obj = $this->createExpression();
@@ -147,13 +135,12 @@ public function testSqlWithoutPredicate()
/**
* Test nested filters.
*
- * @dataProvider providedNestedExpressions
*
* @param array $conditions The expressions to define.
* @param string $expected The expected compiled SQL string.
- * @return void
*/
- public function testNestedSql(array $conditions, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('providedNestedExpressions')]
+ public function testNestedSql(array $conditions, $expected): void
{
$obj = $this->createExpression();
$obj->addFilters($conditions);
@@ -165,13 +152,12 @@ public function testNestedSql(array $conditions, $expected)
*
* @example [ [ , ] ]
* @used-by self::testNestedSql()
- * @return array
*/
- public function providedNestedExpressions()
+ public static function providedNestedExpressions(): array
{
return [
- 'One Level' => $this->nestedExpressionsDataset1(),
- 'Two Levels' => $this->nestedExpressionsDataset2(),
+ 'One Level' => self::nestedExpressionsDataset1(),
+ 'Two Levels' => self::nestedExpressionsDataset2(),
];
}
@@ -179,9 +165,8 @@ public function providedNestedExpressions()
* Dataset #1 for testing nested expressions.
*
* @used-by self::providedNestedExpressions()
- * @return array
*/
- protected function nestedExpressionsDataset1()
+ protected static function nestedExpressionsDataset1(): array
{
$time = new DateTime('3 days ago');
@@ -213,9 +198,8 @@ protected function nestedExpressionsDataset1()
* Dataset #2 for testing nested expressions.
*
* @used-by self::providedNestedExpressions()
- * @return array
*/
- protected function nestedExpressionsDataset2()
+ protected static function nestedExpressionsDataset2(): array
{
$time = date('Y-m-d');
@@ -265,10 +249,8 @@ protected function nestedExpressionsDataset2()
/**
* Test nested filters has precedence over other features.
- *
- * @return void
*/
- public function testNestedSqlPrecedence()
+ public function testNestedSqlPrecedence(): void
{
$obj = $this->createExpression();
@@ -282,10 +264,8 @@ public function testNestedSqlPrecedence()
/**
* Test invalid SQL nested filters.
- *
- * @return void
*/
- public function testSqlWithoutNestedExpressions()
+ public function testSqlWithoutNestedExpressions(): void
{
$obj = $this->createExpression();
@@ -297,10 +277,8 @@ public function testSqlWithoutNestedExpressions()
/**
* Test "condition" property with and without placeholders.
- *
- * @return void
*/
- public function testCustomSql()
+ public function testCustomSql(): void
{
$obj = $this->createExpression();
@@ -310,10 +288,8 @@ public function testCustomSql()
/**
* Test the negation of the "condition" property with the "operator" property.
- *
- * @return void
*/
- public function testCustomSqlNegation()
+ public function testCustomSqlNegation(): void
{
$obj = $this->createExpression();
@@ -323,10 +299,8 @@ public function testCustomSqlNegation()
/**
* Test "condition" property has precedence over other features.
- *
- * @return void
*/
- public function testCustomSqlPrecedence()
+ public function testCustomSqlPrecedence(): void
{
$obj = $this->createExpression();
@@ -340,10 +314,8 @@ public function testCustomSqlPrecedence()
/**
* Test invalid custom SQL.
- *
- * @return void
*/
- public function testCustomSqlWithoutQuery()
+ public function testCustomSqlWithoutQuery(): void
{
$obj = $this->createExpression();
@@ -355,10 +327,8 @@ public function testCustomSqlWithoutQuery()
/**
* Test condition compilation.
- *
- * @return void
*/
- public function testCompileConditions()
+ public function testCompileConditions(): void
{
$obj = $this->createExpression();
@@ -369,10 +339,8 @@ public function testCompileConditions()
/**
* Test basic SQL operator without a value.
- *
- * @return void
*/
- public function testSqlOperatorWithoutValue()
+ public function testSqlOperatorWithoutValue(): void
{
$obj = $this->createExpression();
@@ -388,12 +356,11 @@ public function testSqlOperatorWithoutValue()
/**
* Test comparison SQL operators.
*
- * @dataProvider provideComparisonOperators
*
* @param string $operator A SQL operator.
- * @return void
*/
- public function testSqlComparisonOperators($operator)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideComparisonOperators')]
+ public function testSqlComparisonOperators(string $operator): void
{
$obj = $this->createExpression();
$obj->setData([
@@ -408,12 +375,11 @@ public function testSqlComparisonOperators($operator)
/**
* Test condition-style SQL operators ("value" is ignored).
*
- * @dataProvider provideConditionalOperators
*
* @param string $operator A SQL operator.
- * @return void
*/
- public function testSqlConditionalOperators($operator)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideConditionalOperators')]
+ public function testSqlConditionalOperators(string $operator): void
{
$obj = $this->createExpression();
$obj->setData([
@@ -428,12 +394,11 @@ public function testSqlConditionalOperators($operator)
/**
* Test NOT-style SQL operators ("value" is ignored).
*
- * @dataProvider provideNegationOperators
*
* @param string $operator A SQL operator.
- * @return void
*/
- public function testSqlNegationOperators($operator)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideNegationOperators')]
+ public function testSqlNegationOperators(string $operator): void
{
$obj = $this->createExpression();
$obj->setData([
@@ -448,14 +413,13 @@ public function testSqlNegationOperators($operator)
/**
* Test list-based SQL operators.
*
- * @dataProvider provideSetOperators
*
* @param string $operator A SQL operator.
* @param string $delimiter The set's delimiter.
* @param string $expected The expected result.
- * @return void
*/
- public function testSqlSetOperators($operator, $delimiter, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideSetOperators')]
+ public function testSqlSetOperators(string $operator, string $delimiter, string $expected): void
{
$obj = $this->createExpression();
@@ -475,14 +439,13 @@ public function testSqlSetOperators($operator, $delimiter, $expected)
/**
* Test list-based SQL operator without a value.
*
- * @dataProvider provideSetOperators
*
* @param string $operator A SQL operator.
* @param string $delimiter The set's delimiter.
* @param string $expected Unused; The expected result.
- * @return void
*/
- public function testSqlSetOperatorsWithoutValue($operator, $delimiter, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideSetOperators')]
+ public function testSqlSetOperatorsWithoutValue(string $operator, string $delimiter, string $expected): void
{
$obj = $this->createExpression();
@@ -497,10 +460,8 @@ public function testSqlSetOperatorsWithoutValue($operator, $delimiter, $expected
/**
* Test SQL function.
- *
- * @return void
*/
- public function testSqlFunction()
+ public function testSqlFunction(): void
{
$obj = $this->createExpression();
$obj->setData([
@@ -515,10 +476,8 @@ public function testSqlFunction()
/**
* Test SQL condition with multiple field names.
- *
- * @return void
*/
- public function testSqlFields()
+ public function testSqlFields(): void
{
$container = $this->getContainer();
@@ -543,9 +502,8 @@ public function testSqlFields()
* Provide data for simple operators.
*
* @used-by self::testSqlComparisonOperators()
- * @return array
*/
- public function provideComparisonOperators()
+ public static function provideComparisonOperators(): array
{
return [
[ '=' ], [ '!=' ],
@@ -559,9 +517,8 @@ public function provideComparisonOperators()
* Provide data for sets-style operators.
*
* @used-by self::testSqlSetOperators()
- * @return array
*/
- public function provideSetOperators()
+ public static function provideSetOperators(): array
{
return [
'FIND_IN_SET' => [ 'FIND_IN_SET', ',', 'FIND_IN_SET(\'%2$s\', %1$s)' ],
@@ -574,9 +531,8 @@ public function provideSetOperators()
* Provide data for condition-style operators.
*
* @used-by self::testSqlConditionalOperators()
- * @return array
*/
- public function provideConditionalOperators()
+ public static function provideConditionalOperators(): array
{
return [
[ 'IS NULL' ], [ 'IS NOT NULL' ],
@@ -590,9 +546,8 @@ public function provideConditionalOperators()
* Provide data for logical NOT operators.
*
* @used-by self::testSqlNegationOperators()
- * @return array
*/
- public function provideNegationOperators()
+ public static function provideNegationOperators(): array
{
return [
[ '!' ],
diff --git a/packages/core/tests/Charcoal/Source/Database/DatabaseOrderTest.php b/packages/core/tests/Charcoal/Source/Database/DatabaseOrderTest.php
index f0c502fe1..f24263e71 100644
--- a/packages/core/tests/Charcoal/Source/Database/DatabaseOrderTest.php
+++ b/packages/core/tests/Charcoal/Source/Database/DatabaseOrderTest.php
@@ -23,10 +23,8 @@ class DatabaseOrderTest extends AbstractTestCase
/**
* Create expression for testing.
- *
- * @return DatabaseOrder
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Database\DatabaseOrder
{
return new DatabaseOrder();
}
@@ -35,10 +33,8 @@ final protected function createExpression()
* Test default table name for default data values.
*
* @see \Charcoal\Tests\Source\Database\DatabaseFilterTest::testDefaultValues()
- *
- * @return void
*/
- public function testDefaultValues()
+ public function testDefaultValues(): void
{
$obj = $this->createExpression();
@@ -50,10 +46,8 @@ public function testDefaultValues()
/**
* Test influence of "active" property on SQL compilation.
- *
- * @return void
*/
- public function testInactiveExpression()
+ public function testInactiveExpression(): void
{
$obj = $this->createExpression();
$obj->setMode('asc')->setProperty('foo');
@@ -67,10 +61,8 @@ public function testInactiveExpression()
/**
* Test SQL without a mode.
- *
- * @return void
*/
- public function testBlankSql()
+ public function testBlankSql(): void
{
$obj = $this->createExpression();
@@ -80,10 +72,8 @@ public function testBlankSql()
/**
* Test SQL with custom mode and placeholders.
- *
- * @return void
*/
- public function testSqlCustomMode()
+ public function testSqlCustomMode(): void
{
$obj = $this->createExpression();
@@ -94,10 +84,8 @@ public function testSqlCustomMode()
/**
* Test that "custom" and "values" mode have precedence over other features
* when the mode is undefined.
- *
- * @return void
*/
- public function testSqlModeResolutionAndPrecedence()
+ public function testSqlModeResolutionAndPrecedence(): void
{
$obj = $this->createExpression();
@@ -114,10 +102,8 @@ public function testSqlModeResolutionAndPrecedence()
/**
* Test SQL with random mode.
- *
- * @return void
*/
- public function testSqlRandomMode()
+ public function testSqlRandomMode(): void
{
$obj = $this->createExpression();
@@ -128,13 +114,12 @@ public function testSqlRandomMode()
/**
* Test SQL with direction mode.
*
- * @dataProvider provideSqlDirectionMode
*
* @param mixed $mode The directional mode to set.
* @param mixed $expected The expected SQL direction.
- * @return void
*/
- public function testSqlDirectionMode($mode, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideSqlDirectionMode')]
+ public function testSqlDirectionMode(string $mode, string $expected): void
{
$obj = $this->createExpression();
@@ -149,9 +134,8 @@ public function testSqlDirectionMode($mode, $expected)
* Provide data for selecting directional ordering.
*
* @used-by self::testSqlDirectionMode()
- * @return array
*/
- public function provideSqlDirectionMode()
+ public static function provideSqlDirectionMode(): array
{
return [
[ 'asc', 'ASC' ],
@@ -161,10 +145,8 @@ public function provideSqlDirectionMode()
/**
* Test direction mode without property.
- *
- * @return void
*/
- public function testSqlDirectionModeWithoutProperty()
+ public function testSqlDirectionModeWithoutProperty(): void
{
$obj = $this->createExpression();
@@ -174,10 +156,8 @@ public function testSqlDirectionModeWithoutProperty()
/**
* Test SQL with values mode.
- *
- * @return void
*/
- public function testSqlValuesMode()
+ public function testSqlValuesMode(): void
{
$obj = $this->createExpression();
$obj->setMode('values')
@@ -189,10 +169,8 @@ public function testSqlValuesMode()
/**
* Test values mode without property.
- *
- * @return void
*/
- public function testSqlValuesModeWithoutProperty()
+ public function testSqlValuesModeWithoutProperty(): void
{
$obj = $this->createExpression();
@@ -204,10 +182,8 @@ public function testSqlValuesModeWithoutProperty()
/**
* Test values mode without values.
- *
- * @return void
*/
- public function testSqlValuesModeWithoutValues()
+ public function testSqlValuesModeWithoutValues(): void
{
$obj = $this->createExpression();
@@ -219,10 +195,8 @@ public function testSqlValuesModeWithoutValues()
/**
* Test invalid custom SQL.
- *
- * @return void
*/
- public function testSqlCustomModeWithoutQuery()
+ public function testSqlCustomModeWithoutQuery(): void
{
$obj = $this->createExpression();
@@ -234,10 +208,8 @@ public function testSqlCustomModeWithoutQuery()
/**
* Test invalid property SQL.
- *
- * @return void
*/
- public function testSqlWithoutModeWithoutProperty()
+ public function testSqlWithoutModeWithoutProperty(): void
{
$obj = $this->createExpression();
@@ -249,10 +221,8 @@ public function testSqlWithoutModeWithoutProperty()
/**
* Test helper methods.
- *
- * @return void
*/
- public function testPrepareValues()
+ public function testPrepareValues(): void
{
$obj = $this->createExpression();
diff --git a/packages/core/tests/Charcoal/Source/Database/DatabasePaginationTest.php b/packages/core/tests/Charcoal/Source/Database/DatabasePaginationTest.php
index 1314f565b..f97d5fb88 100644
--- a/packages/core/tests/Charcoal/Source/Database/DatabasePaginationTest.php
+++ b/packages/core/tests/Charcoal/Source/Database/DatabasePaginationTest.php
@@ -21,20 +21,16 @@ class DatabasePaginationTest extends AbstractTestCase
/**
* Create expression for testing.
- *
- * @return DatabasePagination
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Database\DatabasePagination
{
return new DatabasePagination();
}
/**
* Test influence of "active" property on SQL compilation.
- *
- * @return void
*/
- public function testInactiveExpression()
+ public function testInactiveExpression(): void
{
$obj = $this->createExpression();
$obj->setNumPerPage(10);
@@ -48,10 +44,8 @@ public function testInactiveExpression()
/**
* Test "page" property without "num_per_page".
- *
- * @return void
*/
- public function testSqlOffsetWithoutLimit()
+ public function testSqlOffsetWithoutLimit(): void
{
$obj = $this->createExpression();
@@ -64,10 +58,8 @@ public function testSqlOffsetWithoutLimit()
/**
* Test "page" property with "num_per_page".
- *
- * @return void
*/
- public function testSqlOffsetWithLimit()
+ public function testSqlOffsetWithLimit(): void
{
$obj = $this->createExpression();
@@ -83,10 +75,8 @@ public function testSqlOffsetWithLimit()
/**
* Test "num_per_page" property without "page".
- *
- * @return void
*/
- public function testSqlLimitWithoutOffset()
+ public function testSqlLimitWithoutOffset(): void
{
$obj = $this->createExpression();
@@ -99,10 +89,8 @@ public function testSqlLimitWithoutOffset()
/**
* Test helper methods.
- *
- * @return void
*/
- public function testUtilities()
+ public function testUtilities(): void
{
$obj = $this->createExpression();
diff --git a/packages/core/tests/Charcoal/Source/DatabaseExpressionTestTrait.php b/packages/core/tests/Charcoal/Source/DatabaseExpressionTestTrait.php
index f9f24b0f0..d5661ffca 100644
--- a/packages/core/tests/Charcoal/Source/DatabaseExpressionTestTrait.php
+++ b/packages/core/tests/Charcoal/Source/DatabaseExpressionTestTrait.php
@@ -35,10 +35,8 @@ abstract public function testInactiveExpression();
*
* Assertions:
* 1. Implements {@see ExpressionInterface}
- *
- * @return void
*/
- public function testConstruct()
+ public function testConstruct(): void
{
$obj = $this->createExpression();
diff --git a/packages/core/tests/Charcoal/Source/DatabaseSourceConfigTest.php b/packages/core/tests/Charcoal/Source/DatabaseSourceConfigTest.php
index 8890b86a2..9f74a4141 100644
--- a/packages/core/tests/Charcoal/Source/DatabaseSourceConfigTest.php
+++ b/packages/core/tests/Charcoal/Source/DatabaseSourceConfigTest.php
@@ -13,10 +13,7 @@
*/
class DatabaseSourceConfigTest extends AbstractTestCase
{
- /**
- * @return void
- */
- public function testDefaultData()
+ public function testDefaultData(): void
{
$obj = new DatabaseSourceConfig();
$defaults = $obj->defaults();
@@ -26,20 +23,14 @@ public function testDefaultData()
$this->assertEquals($obj->hostname(), $defaults['hostname']);
}
- /**
- * @return void
- */
- public function testMerge()
+ public function testMerge(): void
{
$obj = new DatabaseSourceConfig();
$ret = $obj->merge([]);
$this->assertSame($ret, $obj);
}
- /**
- * @return void
- */
- public function testSetHostname()
+ public function testSetHostname(): void
{
$obj = new DatabaseSourceConfig();
$this->assertEquals('localhost', $obj->hostname());
@@ -51,10 +42,7 @@ public function testSetHostname()
$obj->setHostname(false);
}
- /**
- * @return void
- */
- public function testSetUsername()
+ public function testSetUsername(): void
{
$obj = new DatabaseSourceConfig();
$this->assertEquals(null, $obj->username());
@@ -66,10 +54,7 @@ public function testSetUsername()
$obj->setUsername(false);
}
- /**
- * @return void
- */
- public function testSetPassword()
+ public function testSetPassword(): void
{
$obj = new DatabaseSourceConfig();
$this->assertEquals('', $obj->password());
@@ -81,10 +66,7 @@ public function testSetPassword()
$obj->setPassword(false);
}
- /**
- * @return void
- */
- public function testSetDatabase()
+ public function testSetDatabase(): void
{
$obj = new DatabaseSourceConfig();
$this->assertEquals(null, $obj->database());
@@ -96,10 +78,7 @@ public function testSetDatabase()
$obj->setDatabase(false);
}
- /**
- * @return void
- */
- public function testSetDisableUtf8()
+ public function testSetDisableUtf8(): void
{
$obj = new DatabaseSourceConfig();
$this->assertEquals(false, $obj->disableUtf8());
diff --git a/packages/core/tests/Charcoal/Source/DatabaseSourceTest.php b/packages/core/tests/Charcoal/Source/DatabaseSourceTest.php
index 213989c22..d95f6fb98 100644
--- a/packages/core/tests/Charcoal/Source/DatabaseSourceTest.php
+++ b/packages/core/tests/Charcoal/Source/DatabaseSourceTest.php
@@ -1,5 +1,7 @@
getContainer();
diff --git a/packages/core/tests/Charcoal/Source/DatabaseTestModel.php b/packages/core/tests/Charcoal/Source/DatabaseTestModel.php
index e52ed51e6..1548f4804 100644
--- a/packages/core/tests/Charcoal/Source/DatabaseTestModel.php
+++ b/packages/core/tests/Charcoal/Source/DatabaseTestModel.php
@@ -1,5 +1,7 @@
getMockForTrait(ExpressionFieldTrait::class);
-
- return $obj;
+ return new class implements ExpressionFieldInterface {
+ use ExpressionFieldTrait;
+ };
}
/**
@@ -69,10 +67,8 @@ final public function createProperty()
* 3. Chainable method
* 4. Accepts Property
* 5. Accepts NULL
- *
- * @return void
*/
- public function testProperty()
+ public function testProperty(): void
{
$obj = $this->createField();
@@ -100,10 +96,8 @@ public function testProperty()
/**
* Test the "property" determiner.
- *
- * @return void
*/
- public function testHasProperty()
+ public function testHasProperty(): void
{
$obj = $this->createField();
$this->assertFalse($obj->hasProperty());
@@ -114,10 +108,8 @@ public function testHasProperty()
/**
* Test "property" property with blank value.
- *
- * @return void
*/
- public function testPropertyWithBlankValue()
+ public function testPropertyWithBlankValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createField()->setProperty('');
@@ -125,10 +117,8 @@ public function testPropertyWithBlankValue()
/**
* Test "property" property with invalid property.
- *
- * @return void
*/
- public function testPropertyWithInvalidProperty()
+ public function testPropertyWithInvalidProperty(): void
{
$container = $this->getContainer();
$property = $container['property/factory']->create('generic');
@@ -139,10 +129,8 @@ public function testPropertyWithInvalidProperty()
/**
* Test "property" property with invalid value.
- *
- * @return void
*/
- public function testPropertyWithInvalidValue()
+ public function testPropertyWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createField()->setProperty([]);
@@ -156,10 +144,8 @@ public function testPropertyWithInvalidValue()
* 2. Mutated state
* 3. Chainable method
* 4. Accepts NULL
- *
- * @return void
*/
- public function testTable()
+ public function testTable(): void
{
$obj = $this->createField();
@@ -181,10 +167,8 @@ public function testTable()
/**
* Test the "table" determiner.
- *
- * @return void
*/
- public function testHasTable()
+ public function testHasTable(): void
{
$obj = $this->createField();
$this->assertFalse($obj->hasTable());
@@ -195,10 +179,8 @@ public function testHasTable()
/**
* Test "table" property with blank value.
- *
- * @return void
*/
- public function testTableWithBlankValue()
+ public function testTableWithBlankValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createField()->setTable('');
@@ -206,10 +188,8 @@ public function testTableWithBlankValue()
/**
* Test "table" property with invalid value.
- *
- * @return void
*/
- public function testTableWithInvalidValue()
+ public function testTableWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createField()->setTable([]);
@@ -222,10 +202,8 @@ public function testTableWithInvalidValue()
* 1. Default state
* 2. With column name
* 3. With property instance
- *
- * @return void
*/
- public function testFieldNames()
+ public function testFieldNames(): void
{
$obj = $this->createField();
@@ -252,10 +230,8 @@ public function testFieldNames()
* 1. Default state
* 2. With column name
* 3. With property instance
- *
- * @return void
*/
- public function testFieldName()
+ public function testFieldName(): void
{
$obj = $this->createField();
@@ -282,10 +258,8 @@ public function testFieldName()
* 1. Default state
* 2. With column name
* 3. With table name
- *
- * @return void
*/
- public function testFieldIdentifiers()
+ public function testFieldIdentifiers(): void
{
$obj = $this->createField();
@@ -310,10 +284,8 @@ public function testFieldIdentifiers()
* 1. Default state
* 2. With column name
* 3. With table name
- *
- * @return void
*/
- public function testFieldIdentifier()
+ public function testFieldIdentifier(): void
{
$obj = $this->createField();
diff --git a/packages/core/tests/Charcoal/Source/ExpressionTest.php b/packages/core/tests/Charcoal/Source/ExpressionTest.php
index a486017e5..5f3e9c6b2 100644
--- a/packages/core/tests/Charcoal/Source/ExpressionTest.php
+++ b/packages/core/tests/Charcoal/Source/ExpressionTest.php
@@ -21,10 +21,8 @@ class ExpressionTest extends AbstractTestCase
/**
* Create expression for testing.
- *
- * @return Expression
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Expression
{
return new Expression();
}
@@ -33,9 +31,8 @@ final protected function createExpression()
* Provide data for value parsing.
*
* @used-by ExpressionTestTrait::testDefaultValues()
- * @return array
*/
- final public function provideDefaultValues()
+ final public static function provideDefaultValues(): array
{
return [
'condition' => [ 'condition', null ],
@@ -54,10 +51,8 @@ final public function provideDefaultValues()
* 4. Trimmed value
* 5. Accepts NULL
* 6. Swaps blank string for NULL
- *
- * @return void
*/
- public function testConditionExpression()
+ public function testConditionExpression(): void
{
$obj = $this->createExpression();
@@ -87,10 +82,8 @@ public function testConditionExpression()
/**
* Test the conditional check of "condition".
- *
- * @return void
*/
- public function testHasConditionExpression()
+ public function testHasConditionExpression(): void
{
$obj = $this->createExpression();
@@ -99,16 +92,14 @@ public function testHasConditionExpression()
$obj->setCondition(' ');
$this->assertFalse($obj->hasCondition());
- $that = $obj->setCondition('1 = 1');
+ $obj->setCondition('1 = 1');
$this->assertTrue($obj->hasCondition());
}
/**
* Test "condition" property with invalid value.
- *
- * @return void
*/
- public function testConditionExpressionWithInvalidValue()
+ public function testConditionExpressionWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setCondition([]);
@@ -120,10 +111,8 @@ public function testConditionExpressionWithInvalidValue()
* Assertions:
* 1. Mutate all options
* 2. Partially mutated state
- *
- * @return void
*/
- public function testData()
+ public function testData(): void
{
/** 1. Mutate all options */
$mutation = [
diff --git a/packages/core/tests/Charcoal/Source/ExpressionTestFieldTrait.php b/packages/core/tests/Charcoal/Source/ExpressionTestFieldTrait.php
index 9207605d8..f4d11d6ee 100644
--- a/packages/core/tests/Charcoal/Source/ExpressionTestFieldTrait.php
+++ b/packages/core/tests/Charcoal/Source/ExpressionTestFieldTrait.php
@@ -6,6 +6,8 @@
use Charcoal\Source\ExpressionInterface;
use Charcoal\Source\ExpressionFieldInterface;
use Charcoal\Source\ExpressionFieldTrait;
+use Charcoal\Source\Filter;
+use Charcoal\Source\Order;
/**
* Shared tests for implementations of {@see ExpressionFieldTrait}
@@ -15,10 +17,8 @@ trait ExpressionTestFieldTrait
{
/**
* Test deprecated "table_name" property.
- *
- * @return void
*/
- public function testDeprecatedTableNameExpression()
+ public function testDeprecatedTableNameExpression(): void
{
$obj = $this->createExpression();
@@ -28,24 +28,17 @@ public function testDeprecatedTableNameExpression()
/**
* Test "table_name" property deprecation notice.
- *
- * @used-by self::testDeprecatedTableNameErrorInPhp7()
- *
- * @return void
- */
- public function delegatedTestDeprecatedTableNameError()
- {
- $this->createExpression()->setData([ 'table_name' => 'foobar' ]);
- }
-
- /**
- * @requires PHP >= 7.0
- * @return void
*/
- public function testDeprecatedTableNameErrorInPhp7()
+ public function testDeprecatedTableNameError(): void
{
- $this->expectDeprecation();
- $this->delegatedTestDeprecatedTableNameError();
+ $expression = $this->createExpression();
+ $message = match (get_class($expression)) {
+ Filter::class => 'Filter expression option "table_name" is deprecated in favour of "table": foobar',
+ Order::class => 'Sort expression option "table_name" is deprecated in favour of "table": foobar',
+ default => 'Expression option "table_name" is deprecated in favour of "table": foobar',
+ };
+ $this->expectUserDeprecationMessage($message);
+ $expression->setData([ 'table_name' => 'foobar' ]);
}
/**
@@ -53,16 +46,15 @@ public function testDeprecatedTableNameErrorInPhp7()
*
* @param ExpressionFieldInterface $obj The expression to test.
* @param array|null $expected The expected data subset.
- * @return void
*/
- public function assertStructHasFieldData(ExpressionFieldInterface $obj, array $expected = null)
+ public function assertStructHasFieldData(ExpressionFieldInterface $obj, ?array $expected = null): void
{
- if (empty($expected)) {
+ if ($expected === null || $expected === []) {
$expected = [
'property' => 'col',
'table' => 'tbl',
];
- $obj->setData($mutation);
+ $obj->setData($expected);
}
$data = $obj->data();
diff --git a/packages/core/tests/Charcoal/Source/ExpressionTestTrait.php b/packages/core/tests/Charcoal/Source/ExpressionTestTrait.php
index 5356bcaaa..84a77e1a3 100644
--- a/packages/core/tests/Charcoal/Source/ExpressionTestTrait.php
+++ b/packages/core/tests/Charcoal/Source/ExpressionTestTrait.php
@@ -12,7 +12,7 @@
* Shared tests for implementations of {@see AbstractExpression}
* and {@see ExpressionInterface}.
*/
-trait ExpressionTestTrait
+trait ExpressionTestTrait
{
/**
* @return \Pimple\Container
@@ -33,17 +33,15 @@ abstract protected function createExpression();
* @used-by self::testDefaultValues()
* @return array
*/
- abstract public function provideDefaultValues();
+ abstract public static function provideDefaultValues();
/**
* Test new instance.
*
* Assertions:
* 1. Implements {@see ExpressionInterface}
- *
- * @return void
*/
- final public function testConstruct()
+ final public function testConstruct(): void
{
$obj = $this->createExpression();
@@ -56,10 +54,8 @@ final public function testConstruct()
*
* Assertions:
* 1. Getter returns an array
- *
- * @return void
*/
- final public function testDefaultValuesMethod()
+ final public function testDefaultValuesMethod(): void
{
$obj = $this->createExpression();
@@ -74,9 +70,9 @@ final public function testDefaultValuesMethod()
*
* @param mixed $key The data key test.
* @param mixed $expected The expected data value.
- * @return void
*/
- final public function testDefaultValues($key, $expected)
+ #[\PHPUnit\Framework\Attributes\DataProvider('provideDefaultValues')]
+ final public function testDefaultValues($key, $expected): void
{
$obj = $this->createExpression();
$data = $obj->defaultData();
@@ -91,10 +87,8 @@ final public function testDefaultValues($key, $expected)
* Assertions:
* 1. Getter returns an array
* 2. Setter is chainable
- *
- * @return void
*/
- final public function testDataMethod()
+ final public function testDataMethod(): void
{
$obj = $this->createExpression();
@@ -108,10 +102,8 @@ final public function testDataMethod()
/**
* Test data structure with default state.
- *
- * @return void
*/
- final public function testDefaultData()
+ final public function testDefaultData(): void
{
$obj = $this->createExpression();
$this->assertEquals($obj->defaultData(), $obj->data());
@@ -122,16 +114,15 @@ final public function testDefaultData()
*
* @param ExpressionInterface $obj The expression to test.
* @param array|null $expected The expected data subset.
- * @return void
*/
- final public function assertStructHasBasicData(ExpressionInterface $obj, array $expected = null)
+ final public function assertStructHasBasicData(ExpressionInterface $obj, ?array $expected = null): void
{
- if (empty($expected)) {
+ if ($expected === null || $expected === []) {
$expected = [
'active' => false,
'name' => 'foo',
];
- $obj->setData($mutation);
+ $obj->setData($expected);
}
$data = $obj->data();
@@ -151,10 +142,8 @@ final public function assertStructHasBasicData(ExpressionInterface $obj, array $
* Assertions:
* 1. Serialization from default state
* 2. Serialization from mutated state
- *
- * @return void
*/
- public function testJsonSerializable()
+ public function testJsonSerializable(): void
{
$obj = $this->createExpression();
@@ -181,16 +170,14 @@ public function testJsonSerializable()
* Assertions:
* 1. Serialization from default state
* 2. Serialization from mutated state
- *
- * @return void
*/
- public function testSerializable()
+ public function testSerializable(): void
{
$obj = $this->createExpression();
/** 1. Serialization from default state */
$that = unserialize(serialize($obj));
- $this->assertInstanceOf(get_class($obj), $that);
+ $this->assertInstanceOf($obj::class, $that);
$this->assertEquals($obj, $that);
$this->assertTrue($that->active());
$this->assertNull($that->name());
@@ -202,7 +189,7 @@ public function testSerializable()
];
$obj->setData($mutation);
$that = unserialize(serialize($obj));
- $this->assertInstanceOf(get_class($obj), $that);
+ $this->assertInstanceOf($obj::class, $that);
$this->assertEquals($obj, $that);
$this->assertFalse($that->active());
$this->assertEquals('foo', $that->name());
diff --git a/packages/core/tests/Charcoal/Source/FilterCollectionTraitTest.php b/packages/core/tests/Charcoal/Source/FilterCollectionTraitTest.php
index 6993a1028..6c4c470c1 100644
--- a/packages/core/tests/Charcoal/Source/FilterCollectionTraitTest.php
+++ b/packages/core/tests/Charcoal/Source/FilterCollectionTraitTest.php
@@ -20,6 +20,14 @@
/**
* Test {@see FilterCollectionTrait} and {@see FilterCollectionInterface}.
*/
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'createFilter')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'filters')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'hasFilters')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'setFilters')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'addFilters')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'addFilter')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'processFilter')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\FilterCollectionTrait::class, 'traverseFilters')]
class FilterCollectionTraitTest extends AbstractTestCase
{
use AssertionsTrait;
@@ -28,10 +36,8 @@ class FilterCollectionTraitTest extends AbstractTestCase
/**
* Create mock object for testing.
- *
- * @return FilterCollectionClass
*/
- final public function createCollector()
+ final public function createCollector(): \Charcoal\Tests\Mock\FilterCollectionClass
{
return new FilterCollectionClass();
}
@@ -40,9 +46,8 @@ final public function createCollector()
* Create expression for testing.
*
* @param array $data Optional expression data.
- * @return Filter
*/
- final protected function createExpression(array $data = null)
+ final protected function createExpression(?array $data = null): \Charcoal\Source\Filter
{
$expr = new Filter();
if ($data !== null) {
@@ -58,11 +63,8 @@ final protected function createExpression(array $data = null)
* 1. Instance of {@see ExpressionInterface}
* 2. Instance of {@see FilterInterface}
*
- * @covers \Charcoal\Source\FilterCollectionTrait::createFilter
- *
- * @return void
*/
- public function testCreateExpression()
+ public function testCreateExpression(): void
{
$obj = $this->createCollector();
@@ -78,11 +80,8 @@ public function testCreateExpression()
* 1. Empty; Default state
* 2. Populated; Mutated state
*
- * @covers \Charcoal\Source\FilterCollectionTrait::filters
- *
- * @return void
*/
- public function testGetExpressions()
+ public function testGetExpressions(): void
{
$obj = $this->createCollector();
@@ -103,11 +102,8 @@ public function testGetExpressions()
* 1. Empty; Default state
* 2. Populated; Mutated state
*
- * @covers \Charcoal\Source\FilterCollectionTrait::hasFilters
- *
- * @return void
*/
- public function testHasExpressions()
+ public function testHasExpressions(): void
{
$obj = $this->createCollector();
@@ -126,11 +122,8 @@ public function testHasExpressions()
* 1. Replaces expressions with a new collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\FilterCollectionTrait::setFilters
- *
- * @return void
*/
- public function testSetExpressions()
+ public function testSetExpressions(): void
{
$obj = $this->createCollector();
$exp1 = $this->createExpression();
@@ -157,11 +150,8 @@ public function testSetExpressions()
* 1. Appends an array of items to the internal collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\FilterCollectionTrait::addFilters
- *
- * @return void
*/
- public function testAddExpressions()
+ public function testAddExpressions(): void
{
$obj = $this->createCollector();
$exp1 = $this->createExpression();
@@ -184,11 +174,8 @@ public function testAddExpressions()
/**
* Test the mass addition of expressions with names.
*
- * @covers \Charcoal\Source\FilterCollectionTrait::addFilters
- *
- * @return void
*/
- public function testAddExpressionsMap()
+ public function testAddExpressionsMap(): void
{
$obj = $this->createCollector();
$map = [
@@ -216,11 +203,8 @@ public function testAddExpressionsMap()
* 1. Appends one item to the internal collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\FilterCollectionTrait::addFilter
- *
- * @return void
*/
- public function testAddExpression()
+ public function testAddExpression(): void
{
$obj = $this->createCollector();
$expr = $this->createExpression();
@@ -251,11 +235,8 @@ public function testAddExpression()
* 4. If an instance of {@see FilterInterface} is provided,
* the Expression object is used as is.
*
- * @covers \Charcoal\Source\FilterCollectionTrait::processFilter
- *
- * @return void
*/
- public function testProcessExpression()
+ public function testProcessExpression(): void
{
$obj = $this->createCollector();
@@ -275,9 +256,7 @@ public function testProcessExpression()
$this->assertArrayContains($struct, $result->data());
/** 3. Closure */
- $lambda = function (FilterInterface $expr, FilterCollectionInterface $tested) use ($struct) {
- return $expr->setData($struct);
- };
+ $lambda = (fn(FilterInterface $expr, FilterCollectionInterface $tested) => $expr->setData($struct));
$result = $this->callMethodWith($obj, 'processFilter', $lambda);
$this->assertInstanceOf(FilterInterface::class, $result);
$this->assertArrayContains($struct, $result->data());
@@ -291,11 +270,8 @@ public function testProcessExpression()
/**
* Test the failure when parsing an invalid expression.
*
- * @covers \Charcoal\Source\FilterCollectionTrait::processFilter
- *
- * @return void
*/
- public function testProcessExpressionWithInvalidValue()
+ public function testProcessExpressionWithInvalidValue(): void
{
$obj = $this->createCollector();
@@ -310,11 +286,8 @@ public function testProcessExpressionWithInvalidValue()
* 1. Applies callback to internal collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\FilterCollectionTrait::traverseFilters
- *
- * @return void
*/
- public function testTraverseExpressions()
+ public function testTraverseExpressions(): void
{
$obj = $this->createCollector();
$exp1 = $this->createExpression();
@@ -327,7 +300,7 @@ public function testTraverseExpressions()
/** 1. Traverse internal collection */
$obj->addFilters([ $exp1, $exp4 ]);
- $that = $obj->traverseFilters(function (FilterInterface $exp) {
+ $that = $obj->traverseFilters(function (FilterInterface $exp): void {
$exp->setProperty('foo');
});
diff --git a/packages/core/tests/Charcoal/Source/FilterTest.php b/packages/core/tests/Charcoal/Source/FilterTest.php
index 61acabdea..cd0fc37aa 100644
--- a/packages/core/tests/Charcoal/Source/FilterTest.php
+++ b/packages/core/tests/Charcoal/Source/FilterTest.php
@@ -17,6 +17,9 @@
/**
* Test {@see Filter} and {@see FilterInterface}.
*/
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\Filter::class, '__clone')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\Filter::class, 'count')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\Filter::class, 'createFilter')]
class FilterTest extends AbstractTestCase
{
use CoreContainerIntegrationTrait;
@@ -29,7 +32,7 @@ class FilterTest extends AbstractTestCase
*
* @return Order
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Filter
{
return new Filter();
}
@@ -39,10 +42,8 @@ final protected function createExpression()
*
* Assertions:
* 1. Implements {@see FilterInterface}
- *
- * @return void
*/
- public function testFilterConstruct()
+ public function testFilterConstruct(): void
{
$obj = $this->createExpression();
@@ -53,11 +54,8 @@ public function testFilterConstruct()
/**
* Test deep cloning of expression trees.
*
- * @covers \Charcoal\Source\Filter::__clone
- *
- * @return void
*/
- public function testDeepCloning()
+ public function testDeepCloning(): void
{
$obj = $this->createExpression();
$obj->addFilters([
@@ -88,9 +86,8 @@ public function testDeepCloning()
* Provide data for value parsing.
*
* @used-by ExpressionTestTrait::testDefaultValues()
- * @return array
*/
- final public function provideDefaultValues()
+ final public static function provideDefaultValues(): array
{
return [
'property' => [ 'property', null ],
@@ -116,10 +113,8 @@ final public function provideDefaultValues()
*
* Note: {@see Filter::value()} uses {@see \Charcoal\Source\AbstractExpression::parseValue()}.
* Tests for `parseValue()` are performed in {@see ExpressionTestTrait::testParseValue()}.
- *
- * @return void
*/
- public function testValue()
+ public function testValue(): void
{
$obj = $this->createExpression();
@@ -137,10 +132,8 @@ public function testValue()
/**
* Test deprecated "val" property.
- *
- * @return void
*/
- public function testDeprecatedValExpression()
+ public function testDeprecatedValExpression(): void
{
$obj = $this->createExpression();
@@ -150,29 +143,13 @@ public function testDeprecatedValExpression()
/**
* Test "val" property deprecation notice.
- *
- * @used-by self::testDeprecatedValErrorInPhp7()
- *
- * @return void
*/
- public function delegatedTestDeprecatedValError()
+ public function testDeprecatedValError(): void
{
+ $this->expectUserDeprecationMessage('Filter expression option "val" is deprecated in favour of "value": qux');
$this->createExpression()->setData([ 'val' => 'qux' ]);
}
- /**
- *
- *
- * @requires PHP >= 7.0
- * @return void
- */
- public function testDeprecatedValErrorInPhp7()
- {
- $this->expectDeprecation();
- $this->delegatedTestDeprecatedValError();
- }
-
-
/**
* Test the "operator" property.
*
@@ -181,10 +158,8 @@ public function testDeprecatedValErrorInPhp7()
* 2. Mutated state
* 3. Chainable method
* 4. Accepts mixed case
- *
- * @return void
*/
- public function testOperator()
+ public function testOperator(): void
{
$obj = $this->createExpression();
@@ -206,10 +181,8 @@ public function testOperator()
/**
* Test "operator" property with unsupported operator.
- *
- * @return void
*/
- public function testOperatorWithUnsupportedOperator()
+ public function testOperatorWithUnsupportedOperator(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setOperator('foo');
@@ -217,10 +190,8 @@ public function testOperatorWithUnsupportedOperator()
/**
* Test "operator" property with invalid value.
- *
- * @return void
*/
- public function testOperatorWithInvalidValue()
+ public function testOperatorWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setOperator(42);
@@ -235,10 +206,8 @@ public function testOperatorWithInvalidValue()
* 3. Chainable method
* 4. Accepts mixed case
* 5. Accepts NULL
- *
- * @return void
*/
- public function testFunc()
+ public function testFunc(): void
{
$obj = $this->createExpression();
@@ -264,10 +233,8 @@ public function testFunc()
/**
* Test "func" property with unsupported func.
- *
- * @return void
*/
- public function testFuncWithUnsupportedFunction()
+ public function testFuncWithUnsupportedFunction(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setFunc('xyzzy');
@@ -275,10 +242,8 @@ public function testFuncWithUnsupportedFunction()
/**
* Test "func" property with invalid value.
- *
- * @return void
*/
- public function testFuncWithInvalidValue()
+ public function testFuncWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setFunc(33);
@@ -292,10 +257,8 @@ public function testFuncWithInvalidValue()
* 2. Mutated state
* 3. Chainable method
* 4. Accepts mixed case
- *
- * @return void
*/
- public function testConjunction()
+ public function testConjunction(): void
{
$obj = $this->createExpression();
@@ -317,10 +280,8 @@ public function testConjunction()
/**
* Test "conjunction" property with unsupported conjunction.
- *
- * @return void
*/
- public function testConjunctionWithUnsupportedConjunction()
+ public function testConjunctionWithUnsupportedConjunction(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setConjunction('qux');
@@ -328,10 +289,8 @@ public function testConjunctionWithUnsupportedConjunction()
/**
* Test "conjunction" property with invalid value.
- *
- * @return void
*/
- public function testConjunctionWithInvalidValue()
+ public function testConjunctionWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setConjunction(11);
@@ -339,10 +298,8 @@ public function testConjunctionWithInvalidValue()
/**
* Test deprecated "operand" property.
- *
- * @return void
*/
- public function testDeprecatedOperandExpression()
+ public function testDeprecatedOperandExpression(): void
{
$obj = $this->createExpression();
@@ -352,28 +309,13 @@ public function testDeprecatedOperandExpression()
/**
* Test "operand" property deprecation notice.
- *
- * @used-by self::testDeprecatedOperandErrorInPhp7()
- *
- * @return void
*/
- public function delegatedTestDeprecatedOperandError()
+ public function testDeprecatedOperandError(): void
{
+ $this->expectUserDeprecationMessage('Query expression option "operand" is deprecated in favour of "conjunction": XOR');
$this->createExpression()->setData([ 'operand' => 'XOR' ]);
}
- /**
- *
- *
- * @requires PHP >= 7.0
- * @return void
- */
- public function testDeprecatedOperandErrorInPhp7()
- {
- $this->expectDeprecation();
- $this->delegatedTestDeprecatedOperandError();
- }
-
/**
* Test implementation of {@see Countable}.
*
@@ -381,11 +323,8 @@ public function testDeprecatedOperandErrorInPhp7()
* 1. Default state
* 2. Mutated state
*
- * @covers \Charcoal\Source\Filter::count
- *
- * @return void
*/
- public function testCount()
+ public function testCount(): void
{
$obj = $this->createExpression();
@@ -405,11 +344,8 @@ public function testCount()
* 2. Instance of {@see Filter}
*
* @see \Charcoal\Tests\Source\AbstractSourceTest::testCreateFilter
- * @covers \Charcoal\Source\Filter::createFilter
- *
- * @return void
*/
- public function testCreateFilter()
+ public function testCreateFilter(): void
{
$obj = $this->createExpression();
@@ -426,10 +362,8 @@ public function testCreateFilter()
* 1. Mutate all options
* 2. Partially mutated state
* 3. Mutation via aliases
- *
- * @return void
*/
- public function testData()
+ public function testData(): void
{
/** 1. Mutate all options */
$exp1 = $this->createExpression();
@@ -514,10 +448,8 @@ public function testData()
* Test deprecated "string" property.
*
* @see OrderTest::testDeprecatedStringExpression()
- *
- * @return void
*/
- public function testDeprecatedStringExpression()
+ public function testDeprecatedStringExpression(): void
{
$obj = $this->createExpression();
@@ -529,23 +461,10 @@ public function testDeprecatedStringExpression()
* Test "string" property deprecation notice.
*
* @see OrderTest::testDeprecatedStringError()
- *
- * @used-by self::testDeprecatedStringErrorInPhp7()
- *
- * @return void
*/
- public function delegatedTestDeprecatedStringError()
+ public function testDeprecatedStringError(): void
{
+ $this->expectUserDeprecationMessage('Filter expression option "string" is deprecated in favour of "condition": 1 = 1');
$this->createExpression()->setData([ 'string' => '1 = 1' ]);
}
-
- /**
- * @requires PHP >= 7.0
- * @return void
- */
- public function testDeprecatedStringErrorInPhp7()
- {
- $this->expectDeprecation();
- $this->delegatedTestDeprecatedStringError();
- }
}
diff --git a/packages/core/tests/Charcoal/Source/OrderCollectionTraitTest.php b/packages/core/tests/Charcoal/Source/OrderCollectionTraitTest.php
index fa2c91048..5dfc2bbc6 100644
--- a/packages/core/tests/Charcoal/Source/OrderCollectionTraitTest.php
+++ b/packages/core/tests/Charcoal/Source/OrderCollectionTraitTest.php
@@ -21,6 +21,14 @@
/**
* Test {@see OrderCollectionTrait} and {@see OrderCollectionInterface}.
*/
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'createOrder')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'orders')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'hasOrders')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'setOrders')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'addOrders')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'addOrder')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'processOrder')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\OrderCollectionTrait::class, 'traverseOrders')]
class OrderCollectionTraitTest extends AbstractTestCase
{
use AssertionsTrait;
@@ -29,10 +37,8 @@ class OrderCollectionTraitTest extends AbstractTestCase
/**
* Create mock object for testing.
- *
- * @return OrderCollectionClass
*/
- final public function createCollector()
+ final public function createCollector(): \Charcoal\Tests\Mock\OrderCollectionClass
{
return new OrderCollectionClass();
}
@@ -41,9 +47,8 @@ final public function createCollector()
* Create expression for testing.
*
* @param array $data Optional expression data.
- * @return Order
*/
- final protected function createExpression(array $data = null)
+ final protected function createExpression(?array $data = null): \Charcoal\Source\Order
{
$expr = new Order();
if ($data !== null) {
@@ -59,11 +64,8 @@ final protected function createExpression(array $data = null)
* 1. Instance of {@see ExpressionInterface}
* 2. Instance of {@see OrderInterface}
*
- * @covers \Charcoal\Source\OrderCollectionTrait::createOrder
- *
- * @return void
*/
- public function testCreateExpression()
+ public function testCreateExpression(): void
{
$obj = $this->createCollector();
@@ -79,11 +81,8 @@ public function testCreateExpression()
* 1. Empty; Default state
* 2. Populated; Mutated state
*
- * @covers \Charcoal\Source\OrderCollectionTrait::orders
- *
- * @return void
*/
- public function testGetExpressions()
+ public function testGetExpressions(): void
{
$obj = $this->createCollector();
@@ -104,11 +103,8 @@ public function testGetExpressions()
* 1. Empty; Default state
* 2. Populated; Mutated state
*
- * @covers \Charcoal\Source\OrderCollectionTrait::hasOrders
- *
- * @return void
*/
- public function testHasExpressions()
+ public function testHasExpressions(): void
{
$obj = $this->createCollector();
@@ -127,11 +123,8 @@ public function testHasExpressions()
* 1. Replaces expressions with a new collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\OrderCollectionTrait::setOrders
- *
- * @return void
*/
- public function testSetExpressions()
+ public function testSetExpressions(): void
{
$obj = $this->createCollector();
$exp1 = $this->createExpression();
@@ -158,11 +151,8 @@ public function testSetExpressions()
* 1. Appends an array of items to the internal collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\OrderCollectionTrait::addOrders
- *
- * @return void
*/
- public function testAddExpressions()
+ public function testAddExpressions(): void
{
$obj = $this->createCollector();
$exp1 = $this->createExpression();
@@ -185,11 +175,8 @@ public function testAddExpressions()
/**
* Test the mass addition of expressions with names.
*
- * @covers \Charcoal\Source\OrderCollectionTrait::addOrders
- *
- * @return void
*/
- public function testAddExpressionsMap()
+ public function testAddExpressionsMap(): void
{
$obj = $this->createCollector();
$map = [
@@ -217,11 +204,8 @@ public function testAddExpressionsMap()
* 1. Appends one item to the internal collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\OrderCollectionTrait::addOrder
- *
- * @return void
*/
- public function testAddExpression()
+ public function testAddExpression(): void
{
$obj = $this->createCollector();
$expr = $this->createExpression();
@@ -252,11 +236,8 @@ public function testAddExpression()
* 4. If an instance of {@see OrderInterface} is provided,
* the Expression object is used as is.
*
- * @covers \Charcoal\Source\OrderCollectionTrait::processOrder
- *
- * @return void
*/
- public function testProcessExpression()
+ public function testProcessExpression(): void
{
$obj = $this->createCollector();
@@ -276,9 +257,7 @@ public function testProcessExpression()
$this->assertArrayContains($struct, $result->data());
/** 3. Closure */
- $lambda = function (OrderInterface $expr, OrderCollectionInterface $tested) use ($struct) {
- return $expr->setData($struct);
- };
+ $lambda = (fn(OrderInterface $expr, OrderCollectionInterface $tested) => $expr->setData($struct));
$result = $this->callMethodWith($obj, 'processOrder', $lambda);
$this->assertInstanceOf(OrderInterface::class, $result);
$this->assertArrayContains($struct, $result->data());
@@ -292,11 +271,8 @@ public function testProcessExpression()
/**
* Test the failure when parsing an invalid expression.
*
- * @covers \Charcoal\Source\OrderCollectionTrait::processOrder
- *
- * @return void
*/
- public function testProcessExpressionWithInvalidValue()
+ public function testProcessExpressionWithInvalidValue(): void
{
$obj = $this->createCollector();
@@ -311,11 +287,8 @@ public function testProcessExpressionWithInvalidValue()
* 1. Replaces expressions with a new collection
* 2. Chainable method
*
- * @covers \Charcoal\Source\OrderCollectionTrait::traverseOrders
- *
- * @return void
*/
- public function testTraverseExpressions()
+ public function testTraverseExpressions(): void
{
$obj = $this->createCollector();
$exp1 = new OrderTree();
@@ -329,7 +302,7 @@ public function testTraverseExpressions()
$obj->addOrders([ $exp1 ]);
$i = 0;
- $that = $obj->traverseOrders(function (OrderInterface $exp) use (&$i) {
+ $that = $obj->traverseOrders(function (OrderInterface $exp) use (&$i): void {
$i++;
$exp->setProperty('foo');
});
diff --git a/packages/core/tests/Charcoal/Source/OrderTest.php b/packages/core/tests/Charcoal/Source/OrderTest.php
index 3274bfcb8..38d86ec17 100644
--- a/packages/core/tests/Charcoal/Source/OrderTest.php
+++ b/packages/core/tests/Charcoal/Source/OrderTest.php
@@ -23,10 +23,8 @@ class OrderTest extends AbstractTestCase
/**
* Create expression for testing.
- *
- * @return Order
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Order
{
return new Order();
}
@@ -36,10 +34,8 @@ final protected function createExpression()
*
* Assertions:
* 1. Implements {@see OrderInterface}
- *
- * @return void
*/
- public function testOrderConstruct()
+ public function testOrderConstruct(): void
{
$obj = $this->createExpression();
@@ -51,9 +47,8 @@ public function testOrderConstruct()
* Provide data for value parsing.
*
* @used-by ExpressionTestTrait::testDefaultValues()
- * @return array
*/
- final public function provideDefaultValues()
+ final public static function provideDefaultValues(): array
{
return [
'property' => [ 'property', null ],
@@ -76,10 +71,8 @@ final public function provideDefaultValues()
* 3. Chainable method
* 4. Accepts NULL
* 5. Unsupported direction sets DESC
- *
- * @return void
*/
- public function testDirection()
+ public function testDirection(): void
{
$obj = $this->createExpression();
@@ -98,16 +91,14 @@ public function testDirection()
$this->assertNull($obj->direction());
/** 5. Unsupported Direction */
- $that = $obj->setDirection('foo');
+ $obj->setDirection('foo');
$this->assertEquals('DESC', $obj->direction());
}
/**
* Test "direction" property with invalid value.
- *
- * @return void
*/
- public function testDirectionWithInvalidValue()
+ public function testDirectionWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setDirection(0);
@@ -122,10 +113,8 @@ public function testDirectionWithInvalidValue()
* 3. Chainable method
* 4. Accepts mixed case
* 5. Accepts NULL
- *
- * @return void
*/
- public function testMode()
+ public function testMode(): void
{
$obj = $this->createExpression();
@@ -151,10 +140,8 @@ public function testMode()
/**
* Test "direction" property when selecting a direction "mode".
- *
- * @return void
*/
- public function testDirectionMode()
+ public function testDirectionMode(): void
{
$obj = $this->createExpression();
@@ -172,10 +159,8 @@ public function testDirectionMode()
/**
* Test "mode" property with unsupported mode.
- *
- * @return void
*/
- public function testModeWithUnsupportedMode()
+ public function testModeWithUnsupportedMode(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setMode('foobar');
@@ -183,10 +168,8 @@ public function testModeWithUnsupportedMode()
/**
* Test "mode" property with invalid value.
- *
- * @return void
*/
- public function testModeWithInvalidValue()
+ public function testModeWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setMode([]);
@@ -200,10 +183,8 @@ public function testModeWithInvalidValue()
* 2. Mutated state
* 3. Chainable method
* 4. Accepts NULL
- *
- * @return void
*/
- public function testValues()
+ public function testValues(): void
{
$obj = $this->createExpression();
@@ -233,10 +214,8 @@ public function testValues()
/**
* Test "mode" property with blank string.
- *
- * @return void
*/
- public function testValuesWithBlankValue()
+ public function testValuesWithBlankValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setValues('');
@@ -244,10 +223,8 @@ public function testValuesWithBlankValue()
/**
* Test "mode" property with blank string.
- *
- * @return void
*/
- public function testValuesWithEmptyArray()
+ public function testValuesWithEmptyArray(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setValues([]);
@@ -255,10 +232,8 @@ public function testValuesWithEmptyArray()
/**
* Test "mode" property with invalid value.
- *
- * @return void
*/
- public function testValuesWithInvalidValue()
+ public function testValuesWithInvalidValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->createExpression()->setValues(42);
@@ -271,10 +246,8 @@ public function testValuesWithInvalidValue()
* 1. Mutate all options
* 2. Partially mutated state
* 3. Auto-set mode from "condition"
- *
- * @return void
*/
- public function testData()
+ public function testData(): void
{
/** 1. Mutate all options */
$values = [ 'foo', 'baz', 'qux' ];
@@ -342,10 +315,8 @@ public function testData()
* Test deprecated "string" property.
*
* @see FilterTest::testDeprecatedStringExpression()
- *
- * @return void
*/
- public function testDeprecatedStringExpression()
+ public function testDeprecatedStringExpression(): void
{
$obj = $this->createExpression();
@@ -357,25 +328,10 @@ public function testDeprecatedStringExpression()
* Test "string" property deprecation notice.
*
* @see FilterTest::testDeprecatedStringError()
- *
- * @used-by self::testDeprecatedStringErrorInPhp7()
- *
- * @return void
*/
- public function delegatedTestDeprecatedStringError()
+ public function testDeprecatedStringError(): void
{
+ $this->expectUserDeprecationMessage('Sort expression option "string" is deprecated in favour of "condition": 1 = 1');
$this->createExpression()->setData([ 'string' => '1 = 1' ]);
}
-
- /**
- *
- *
- * @requires PHP >= 7.0
- * @return void
- */
- public function testDeprecatedStringErrorInPhp7()
- {
- $this->expectDeprecation();
- $this->delegatedTestDeprecatedStringError();
- }
}
diff --git a/packages/core/tests/Charcoal/Source/PaginationTest.php b/packages/core/tests/Charcoal/Source/PaginationTest.php
index 8f75981ba..f57c42afc 100644
--- a/packages/core/tests/Charcoal/Source/PaginationTest.php
+++ b/packages/core/tests/Charcoal/Source/PaginationTest.php
@@ -21,10 +21,8 @@ class PaginationTest extends AbstractTestCase
/**
* Create expression for testing.
- *
- * @return Pagination
*/
- final protected function createExpression()
+ final protected function createExpression(): \Charcoal\Source\Pagination
{
return new Pagination();
}
@@ -34,10 +32,8 @@ final protected function createExpression()
*
* Assertions:
* 1. Implements {@see PaginationInterface}
- *
- * @return void
*/
- public function testPaginationConstruct()
+ public function testPaginationConstruct(): void
{
$obj = $this->createExpression();
@@ -49,9 +45,8 @@ public function testPaginationConstruct()
* Provide data for value parsing.
*
* @used-by ExpressionTestTrait::testDefaultValues()
- * @return array
*/
- final public function provideDefaultValues()
+ final public static function provideDefaultValues(): array
{
return [
'page num' => [ 'page', 1 ],
@@ -70,10 +65,8 @@ final public function provideDefaultValues()
* 3. Chainable method
* 4. Accepts float
* 5. Swaps zero for one
- *
- * @return void
*/
- public function testPageNum()
+ public function testPageNum(): void
{
$obj = $this->createExpression();
@@ -99,10 +92,8 @@ public function testPageNum()
/**
* Test "page" property with negative value.
- *
- * @return void
*/
- public function testPageNumWithNegativeValue()
+ public function testPageNumWithNegativeValue(): void
{
$obj = $this->createExpression();
@@ -112,10 +103,8 @@ public function testPageNumWithNegativeValue()
/**
* Test "page" property with invalid value.
- *
- * @return void
*/
- public function testPageNumWithInvalidValue()
+ public function testPageNumWithInvalidValue(): void
{
$obj = $this->createExpression();
@@ -131,10 +120,8 @@ public function testPageNumWithInvalidValue()
* 2. Mutated state
* 3. Chainable method
* 4. Accepts float
- *
- * @return void
*/
- public function testNumPerPage()
+ public function testNumPerPage(): void
{
$obj = $this->createExpression();
@@ -156,10 +143,8 @@ public function testNumPerPage()
/**
* Test "num_per_page" property with negative value.
- *
- * @return void
*/
- public function testNumPerPageWithNegativeValue()
+ public function testNumPerPageWithNegativeValue(): void
{
$obj = $this->createExpression();
@@ -169,10 +154,8 @@ public function testNumPerPageWithNegativeValue()
/**
* Test "num_per_page" property with invalid value.
- *
- * @return void
*/
- public function testNumPerPageWithInvalidValue()
+ public function testNumPerPageWithInvalidValue(): void
{
$obj = $this->createExpression();
@@ -187,10 +170,8 @@ public function testNumPerPageWithInvalidValue()
* 1. Mutate all options
* 2. Partially mutated state
* 3. Mutation via aliases
- *
- * @return void
*/
- public function testData()
+ public function testData(): void
{
/** 1. Mutate all options */
$mutation = [
@@ -244,10 +225,8 @@ public function testData()
/**
* Test lowest possible index.
- *
- * @return void
*/
- public function testFirst()
+ public function testFirst(): void
{
$obj = $this->createExpression();
@@ -262,10 +241,8 @@ public function testFirst()
/**
* Test highest possible index.
- *
- * @return void
*/
- public function testLast()
+ public function testLast(): void
{
$obj = $this->createExpression();
diff --git a/packages/core/tests/Charcoal/Source/SourceConfigTest.php b/packages/core/tests/Charcoal/Source/SourceConfigTest.php
index f84c5653e..78bc901e6 100644
--- a/packages/core/tests/Charcoal/Source/SourceConfigTest.php
+++ b/packages/core/tests/Charcoal/Source/SourceConfigTest.php
@@ -13,10 +13,7 @@
*/
class SourceConfigTest extends AbstractTestCase
{
- /**
- * @return void
- */
- public function testDefaultData()
+ public function testDefaultData(): void
{
$obj = new SourceConfig();
$defaults = $obj->defaults();
@@ -24,10 +21,7 @@ public function testDefaultData()
$this->assertEquals($obj->type(), $defaults['type']);
}
- /**
- * @return void
- */
- public function testSetType()
+ public function testSetType(): void
{
$obj = new SourceConfig();
$ret = $obj->setType('foo');
diff --git a/packages/core/tests/Charcoal/Source/StorableTraitTest.php b/packages/core/tests/Charcoal/Source/StorableTraitTest.php
index 83ae6750d..270adafbd 100644
--- a/packages/core/tests/Charcoal/Source/StorableTraitTest.php
+++ b/packages/core/tests/Charcoal/Source/StorableTraitTest.php
@@ -25,6 +25,24 @@
/**
* Test {@see StorableTrait} and {@see StorableInterface}.
*/
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'setKey')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'key')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'setId')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'id')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'setSourceFactory')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'sourceFactory')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'createSource')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'setSource')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'source')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'save')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'preSave')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'postSave')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'update')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'preUpdate')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'postUpdate')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'delete')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'preDelete')]
+#[\PHPUnit\Framework\Attributes\CoversMethod(\Charcoal\Source\StorableTrait::class, 'postDelete')]
class StorableTraitTest extends AbstractTestCase
{
use ReflectionsTrait;
@@ -38,8 +56,6 @@ class StorableTraitTest extends AbstractTestCase
/**
* Setup the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -48,10 +64,8 @@ protected function setUp(): void
/**
* Create datasource repository for testing.
- *
- * @return SourceMock
*/
- final protected function createSource()
+ final protected function createSource(): \Charcoal\Tests\Mock\SourceMock
{
return new SourceMock([
'logger' => new NullLogger()
@@ -66,12 +80,8 @@ final protected function createSource()
* 2. Mutated state
* 3. Chainable method
*
- * @covers \Charcoal\Source\StorableTrait::setKey
- * @covers \Charcoal\Source\StorableTrait::key
- *
- * @return void
*/
- public function testKey()
+ public function testKey(): void
{
$obj = $this->obj;
@@ -89,11 +99,8 @@ public function testKey()
/**
* Test for invalid data type when assigning a primary object key.
*
- * @covers \Charcoal\Source\StorableTrait::setKey
- *
- * @return void
*/
- public function testKeyWithInvalidDataType()
+ public function testKeyWithInvalidDataType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->setKey(null);
@@ -102,11 +109,8 @@ public function testKeyWithInvalidDataType()
/**
* Test for invalid character set when assigning a primary object key.
*
- * @covers \Charcoal\Source\StorableTrait::setKey
- *
- * @return void
*/
- public function testKeyWithInvalidCharacters()
+ public function testKeyWithInvalidCharacters(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->setKey('foo-bar');
@@ -120,12 +124,8 @@ public function testKeyWithInvalidCharacters()
* 2. Mutated state
* 3. Chainable method
*
- * @covers \Charcoal\Source\StorableTrait::setId
- * @covers \Charcoal\Source\StorableTrait::id
- *
- * @return void
*/
- public function testId()
+ public function testId(): void
{
$obj = $this->obj;
@@ -149,11 +149,8 @@ public function testId()
/**
* Test for invalid data type when assigning a unique object ID.
*
- * @covers \Charcoal\Source\StorableTrait::setId
- *
- * @return void
*/
- public function testIdWithInvalidDataType()
+ public function testIdWithInvalidDataType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->obj->setId(null);
@@ -162,12 +159,8 @@ public function testIdWithInvalidDataType()
/**
* Test the unique object ID with an alternate primary key.
*
- * @covers \Charcoal\Source\StorableTrait::setId
- * @covers \Charcoal\Source\StorableTrait::id
- *
- * @return void
*/
- public function testAltId()
+ public function testAltId(): void
{
$obj = $this->obj;
@@ -180,12 +173,8 @@ public function testAltId()
/**
* Test repository factory.
*
- * @covers \Charcoal\Source\StorableTrait::setSourceFactory
- * @covers \Charcoal\Source\StorableTrait::sourceFactory
- *
- * @return void
*/
- public function testSourceFactory()
+ public function testSourceFactory(): void
{
$obj = $this->obj;
@@ -203,11 +192,8 @@ public function testSourceFactory()
/**
* Test for missing repository factory.
*
- * @covers \Charcoal\Source\StorableTrait::sourceFactory
- *
- * @return void
*/
- public function testMissingSourceFactory()
+ public function testMissingSourceFactory(): void
{
$this->expectException(RuntimeException::class);
$this->callMethod($this->obj, 'sourceFactory');
@@ -223,13 +209,8 @@ public function testMissingSourceFactory()
* 4. Storable can create a repository
* 5. Chainable method
*
- * @covers \Charcoal\Source\StorableTrait::createSource
- * @covers \Charcoal\Source\StorableTrait::setSource
- * @covers \Charcoal\Source\StorableTrait::source
- *
- * @return void
*/
- public function testSource()
+ public function testSource(): void
{
$obj = $this->obj;
@@ -262,13 +243,8 @@ public function testSource()
* 2. Fail Early
* 3. Fail Late
*
- * @covers \Charcoal\Source\StorableTrait::save
- * @covers \Charcoal\Source\StorableTrait::preSave
- * @covers \Charcoal\Source\StorableTrait::postSave
- *
- * @return void
*/
- public function testSave()
+ public function testSave(): void
{
$src = $this->createSource();
@@ -296,13 +272,8 @@ public function testSave()
* 2. Fail Early
* 3. Fail Late
*
- * @covers \Charcoal\Source\StorableTrait::update
- * @covers \Charcoal\Source\StorableTrait::preUpdate
- * @covers \Charcoal\Source\StorableTrait::postUpdate
- *
- * @return void
*/
- public function testUpdate()
+ public function testUpdate(): void
{
$src = $this->createSource();
@@ -330,13 +301,8 @@ public function testUpdate()
* 2. Fail Early
* 3. Fail Late
*
- * @covers \Charcoal\Source\StorableTrait::delete
- * @covers \Charcoal\Source\StorableTrait::preDelete
- * @covers \Charcoal\Source\StorableTrait::postDelete
- *
- * @return void
*/
- public function testDelete()
+ public function testDelete(): void
{
$src = $this->createSource();
diff --git a/packages/core/tests/Charcoal/Validator/ValidatableTraitTest.php b/packages/core/tests/Charcoal/Validator/ValidatableTraitTest.php
index 4116f8ae4..0601dc331 100644
--- a/packages/core/tests/Charcoal/Validator/ValidatableTraitTest.php
+++ b/packages/core/tests/Charcoal/Validator/ValidatableTraitTest.php
@@ -16,18 +16,12 @@ class ValidatableTraitTest extends AbstractTestCase
*/
public $obj;
- /**
- * @return void
- */
protected function setUp(): void
{
$this->obj = new ValidatableClass();
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$obj = $this->obj;
$this->assertInstanceOf(ValidatableClass::class, $obj);
diff --git a/packages/core/tests/Charcoal/Validator/ValidatorResultTest.php b/packages/core/tests/Charcoal/Validator/ValidatorResultTest.php
index c15badce4..957449c73 100644
--- a/packages/core/tests/Charcoal/Validator/ValidatorResultTest.php
+++ b/packages/core/tests/Charcoal/Validator/ValidatorResultTest.php
@@ -13,20 +13,14 @@
*/
class ValidatorResultTest extends AbstractTestCase
{
- /**
- * @return void
- */
- public function testSetData()
+ public function testSetData(): void
{
$obj = new ValidatorResult();
$ret = $obj->setData([]);
$this->assertSame($ret, $obj);
}
- /**
- * @return void
- */
- public function testSetIdent()
+ public function testSetIdent(): void
{
$obj = new ValidatorResult();
$this->assertEquals(null, $obj->ident());
@@ -39,10 +33,7 @@ public function testSetIdent()
$obj->setIdent(false);
}
- /**
- * @return void
- */
- public function testSetLevel()
+ public function testSetLevel(): void
{
$obj = new ValidatorResult();
$this->assertEquals(null, $obj->level());
@@ -55,20 +46,14 @@ public function testSetLevel()
$obj->setLevel(false);
}
- /**
- * @return void
- */
- public function testSetLevelWithInvalidLevelsThrowException()
+ public function testSetLevelWithInvalidLevelsThrowException(): void
{
$obj = new ValidatorResult();
$this->expectException(InvalidArgumentException::class);
$obj->setLevel('foo');
}
- /**
- * @return void
- */
- public function testSetMessage()
+ public function testSetMessage(): void
{
$obj = new ValidatorResult();
$this->assertEquals('', $obj->message());
@@ -81,10 +66,7 @@ public function testSetMessage()
$obj->setMessage(false);
}
- /**
- * @return void
- */
- public function testSetTs()
+ public function testSetTs(): void
{
$obj = new ValidatorResult();
$ret = $obj->setTs('2015-01-01 00:00:00');
diff --git a/packages/core/tests/Charcoal/Validator/ValidatorTest.php b/packages/core/tests/Charcoal/Validator/ValidatorTest.php
index 687dd3dc9..4aa900fd9 100644
--- a/packages/core/tests/Charcoal/Validator/ValidatorTest.php
+++ b/packages/core/tests/Charcoal/Validator/ValidatorTest.php
@@ -26,28 +26,19 @@ class ValidatorTest extends AbstractTestCase
*/
public $model;
- /**
- * @return void
- */
protected function setUp(): void
{
$this->model = new ValidatableClass();
$this->obj = new ValidatorClass($this->model);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$obj = $this->obj;
- $this->assertInstanceOf('\Charcoal\Validator\AbstractValidator', $obj);
+ $this->assertInstanceOf(\Charcoal\Validator\AbstractValidator::class, $obj);
}
- /**
- * @return void
- */
- public function testError()
+ public function testError(): void
{
$obj = $this->obj;
$ret = $obj->error('foo');
@@ -55,10 +46,7 @@ public function testError()
// var_dump($obj->errorResults());
}
- /**
- * @return void
- */
- public function testWarning()
+ public function testWarning(): void
{
$obj = $this->obj;
$ret = $obj->warning('foo');
@@ -66,10 +54,7 @@ public function testWarning()
// var_dump($obj->warningResults());
}
- /**
- * @return void
- */
- public function testNotice()
+ public function testNotice(): void
{
$obj = $this->obj;
$ret = $obj->notice('foo');
@@ -77,10 +62,7 @@ public function testNotice()
// var_dump($obj->noticeResults());
}
- /**
- * @return void
- */
- public function testAddResult()
+ public function testAddResult(): void
{
$result = [
'ident' => 'bar',
@@ -100,11 +82,8 @@ public function testAddResult()
$obj->addResult(false);
}
- /**
- * @group time-sensitive
- * @return void
- */
- public function testResults()
+ #[\PHPUnit\Framework\Attributes\Group('time-sensitive')]
+ public function testResults(): void
{
$result = [
'ident' => 'bar',
@@ -128,10 +107,7 @@ public function testResults()
$this->assertEquals([ ValidatorClass::ERROR => [ $expectedResult ] ], $actualResult);
}
- /**
- * @return void
- */
- public function testErrorResults()
+ public function testErrorResults(): void
{
$result1 = [
'ident' => 'bar',
@@ -161,10 +137,7 @@ public function testErrorResults()
$this->assertEquals([ $expectedResult ], $actualResult);
}
- /**
- * @return void
- */
- public function testWarningResults()
+ public function testWarningResults(): void
{
$result1 = [
'ident' => 'bar',
@@ -194,10 +167,7 @@ public function testWarningResults()
$this->assertEquals([ $expectedResult ], $actualResult);
}
- /**
- * @return void
- */
- public function testNoticeResults()
+ public function testNoticeResults(): void
{
$result1 = [
'ident' => 'bar',
@@ -227,10 +197,7 @@ public function testNoticeResults()
$this->assertEquals([ $expectedResult ], $actualResult);
}
- /**
- * @return void
- */
- public function testMerge()
+ public function testMerge(): void
{
$result1 = [
'ident' => 'bar',
diff --git a/packages/core/tests/bootstrap.php b/packages/core/tests/bootstrap.php
new file mode 100644
index 000000000..90929e3b5
--- /dev/null
+++ b/packages/core/tests/bootstrap.php
@@ -0,0 +1,14 @@
+
-
- >
+ cacheDirectory=".phpunit.cache"
+ backupStaticProperties="false"
+ failOnWarning="false"
+ failOnPhpunitWarning="false"
+ failOnNotice="false"
+ failOnDeprecation="false">
./tests/Charcoal
-
-
+
+ ./src/Charcoal
-
-
+
+
+
+
+
+
+
+
-
+
-
-
-
-
diff --git a/packages/email/src/Charcoal/Email/Api/V1/LinkAction.php b/packages/email/src/Charcoal/Email/Api/V1/LinkAction.php
index c0d2cc1fd..0a347ee66 100644
--- a/packages/email/src/Charcoal/Email/Api/V1/LinkAction.php
+++ b/packages/email/src/Charcoal/Email/Api/V1/LinkAction.php
@@ -19,37 +19,18 @@
*/
class LinkAction
{
- /**
- * @var string
- */
- private $linkId;
-
- /**
- * @var Tracker
- */
- private $tracker;
-
- /**
- * @var FactoryInterface
- */
- private $modelFactory;
-
/**
* @param string $linkId Link ID.
* @param Tracker $tracker Tracker service.
* @param FactoryInterface $modelFactory Model factory, to create Link objects.
*/
- public function __construct(string $linkId, Tracker $tracker, FactoryInterface $modelFactory)
+ public function __construct(private readonly string $linkId, private readonly Tracker $tracker, private readonly FactoryInterface $modelFactory)
{
- $this->linkId = $linkId;
- $this->tracker = $tracker;
- $this->modelFactory = $modelFactory;
}
/**
* @param Request $request PSR-7 Request.
* @param Response $response PSR-7 Response.
- * @return Response
*/
public function __invoke(Request $request, Response $response): Response
{
diff --git a/packages/email/src/Charcoal/Email/Api/V1/OpenAction.php b/packages/email/src/Charcoal/Email/Api/V1/OpenAction.php
index 96b45f563..7c1fbcc92 100644
--- a/packages/email/src/Charcoal/Email/Api/V1/OpenAction.php
+++ b/packages/email/src/Charcoal/Email/Api/V1/OpenAction.php
@@ -17,30 +17,17 @@
*/
class OpenAction
{
- /**
- * @var string
- */
- private $emailId;
-
- /**
- * @var Tracker
- */
- private $tracker;
-
/**
* @param string $emailId Email log ID.
* @param Tracker $tracker Tracker service.
*/
- public function __construct(string $emailId, Tracker $tracker)
+ public function __construct(private readonly string $emailId, private readonly Tracker $tracker)
{
- $this->emailId = $emailId;
- $this->tracker = $tracker;
}
/**
* @param Request $request PSR-7 Request.
* @param Response $response PSR-7 Response.
- * @return Response
*/
public function __invoke(Request $request, Response $response): Response
{
@@ -55,7 +42,7 @@ public function __invoke(Request $request, Response $response): Response
/**
* @return boolean|false|string
*/
- private function getBlankPng()
+ private function getBlankPng(): string
{
return base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=');
}
diff --git a/packages/email/src/Charcoal/Email/ApiModule.php b/packages/email/src/Charcoal/Email/ApiModule.php
index 1a1d3a98d..37fac45b5 100644
--- a/packages/email/src/Charcoal/Email/ApiModule.php
+++ b/packages/email/src/Charcoal/Email/ApiModule.php
@@ -19,28 +19,23 @@ class ApiModule extends AbstractModule
{
public const BASE_PATH = '/email/v1';
- /**
- * @return self
- */
- public function setUp()
+ #[\Override]
+ public function setUp(): static
{
$this->setupPublicRoutes();
return $this;
}
- /**
- * @return void
- */
- private function setupPublicRoutes()
+ private function setupPublicRoutes(): void
{
$container = $this->app()->getContainer();
- $this->app()->group(self::BASE_PATH, function () use ($container) {
+ $this->app()->group(self::BASE_PATH, function () use ($container): void {
$group = $this;
- $group->get('/link/{linkId}', function (Request $request, Response $response, array $args) use ($container) {
+ $group->get('/link/{linkId}', function (Request $request, Response $response, array $args) use ($container): \Psr\Http\Message\ResponseInterface {
$action = new LinkAction(
$args['linkId'],
$container['email/tracker'],
@@ -49,7 +44,7 @@ private function setupPublicRoutes()
return $action($request, $response);
});
- $group->get('/open/{emailId}[.png]', function (Request $request, Response $response, array $args) use ($container) {
+ $group->get('/open/{emailId}[.png]', function (Request $request, Response $response, array $args) use ($container): \Psr\Http\Message\ResponseInterface {
$action = new OpenAction(
$args['emailId'],
$container['email/tracker']
diff --git a/packages/email/src/Charcoal/Email/Email.php b/packages/email/src/Charcoal/Email/Email.php
index 670bac83e..ba001c927 100644
--- a/packages/email/src/Charcoal/Email/Email.php
+++ b/packages/email/src/Charcoal/Email/Email.php
@@ -46,38 +46,28 @@ class Email extends AbstractEntity implements
/**
* The campaign ID.
- *
- * @var string
*/
- private $campaign;
+ private ?string $campaign = null;
/**
* The recipient email address(es).
- *
- * @var array
*/
- private $to = [];
+ private array $to = [];
/**
* The CC recipient email address(es).
- *
- * @var array
*/
- private $cc = [];
+ private array $cc = [];
/**
* The BCC recipient email address(es).
- *
- * @var array
*/
- private $bcc = [];
+ private array $bcc = [];
/**
* The sender's email address.
- *
- * @var string
*/
- private $from;
+ private ?string $from = null;
/**
* The email address to reply to the message.
@@ -88,24 +78,18 @@ class Email extends AbstractEntity implements
/**
* The email subject.
- *
- * @var string
*/
- private $subject;
+ private ?string $subject = null;
/**
* The HTML message body.
- *
- * @var string
*/
- private $msgHtml;
+ private ?string $msgHtml = null;
/**
* The plain-text message body.
- *
- * @var string
*/
- private $msgTxt;
+ private ?string $msgTxt = null;
/**
* @var array
@@ -133,35 +117,18 @@ class Email extends AbstractEntity implements
/**
* The data to pass onto the view controller.
- *
- * @var array
*/
- private $templateData = [];
+ private array $templateData = [];
- /**
- * @var PHPMailer
- */
- private $phpMailer;
+ private \PHPMailer\PHPMailer\PHPMailer $phpMailer;
- /**
- * @var FactoryInterface
- */
- private $templateFactory;
+ private \Charcoal\Factory\FactoryInterface $templateFactory;
- /**
- * @var FactoryInterface
- */
- private $queueItemFactory;
+ private \Charcoal\Factory\FactoryInterface $queueItemFactory;
- /**
- * @var FactoryInterface
- */
- private $logFactory;
+ private \Charcoal\Factory\FactoryInterface $logFactory;
- /**
- * @var Tracker
- */
- private $tracker;
+ private \Charcoal\Email\Services\Tracker $tracker;
/**
* Construct a new Email object with the given dependencies.
@@ -191,9 +158,8 @@ public function __construct(array $data)
* Set the campaign ID.
*
* @param string $campaign The campaign identifier.
- * @return self
*/
- public function setCampaign(string $campaign)
+ public function setCampaign(string $campaign): static
{
$this->campaign = $campaign;
return $this;
@@ -203,10 +169,8 @@ public function setCampaign(string $campaign)
* Get the campaign identifier.
*
* If it has not been explicitely set, it will be auto-generated (with uniqid).
- *
- * @return string
*/
- public function campaign()
+ public function campaign(): string
{
if ($this->campaign === null) {
$this->campaign = $this->generateCampaign();
@@ -219,9 +183,8 @@ public function campaign()
*
* @param string|array $email The recipient email address(es).
* @throws InvalidArgumentException If the email address is invalid.
- * @return self
*/
- public function setTo($email)
+ public function setTo($email): static
{
if (is_string($email)) {
$email = [ $email ];
@@ -253,9 +216,8 @@ public function setTo($email)
*
* @param mixed $email The recipient email address to add.
* @throws InvalidArgumentException If the email address is invalid.
- * @return self
*/
- public function addTo($email)
+ public function addTo($email): static
{
$this->to[] = $this->parseEmail($email);
return $this;
@@ -266,7 +228,7 @@ public function addTo($email)
*
* @return string[]
*/
- public function to()
+ public function to(): array
{
return $this->to;
}
@@ -276,9 +238,8 @@ public function to()
*
* @param string|array $email The CC recipient email address(es).
* @throws InvalidArgumentException If the email address is invalid.
- * @return self
*/
- public function setCc($email)
+ public function setCc($email): static
{
if (is_string($email)) {
$email = [ $email ];
@@ -310,9 +271,8 @@ public function setCc($email)
*
* @param mixed $email The CC recipient email address to add.
* @throws InvalidArgumentException If the email address is invalid.
- * @return self
*/
- public function addCc($email)
+ public function addCc($email): static
{
$this->cc[] = $this->parseEmail($email);
return $this;
@@ -323,7 +283,7 @@ public function addCc($email)
*
* @return string[]
*/
- public function cc()
+ public function cc(): array
{
return $this->cc;
}
@@ -333,9 +293,8 @@ public function cc()
*
* @param string|array $email The BCC recipient email address(es).
* @throws InvalidArgumentException If the email address is invalid.
- * @return self
*/
- public function setBcc($email)
+ public function setBcc($email): static
{
if (is_string($email)) {
// Means we have a straight email
@@ -368,9 +327,8 @@ public function setBcc($email)
*
* @param mixed $email The BCC recipient email address to add.
* @throws InvalidArgumentException If the email address is invalid.
- * @return self
*/
- public function addBcc($email)
+ public function addBcc($email): static
{
$this->bcc[] = $this->parseEmail($email);
return $this;
@@ -381,7 +339,7 @@ public function addBcc($email)
*
* @return string[]
*/
- public function bcc()
+ public function bcc(): array
{
return $this->bcc;
}
@@ -391,10 +349,9 @@ public function bcc()
*
* @param string|array $email An email address.
* @throws InvalidArgumentException If the email is not a string or an array.
- * @return self
* @todo Implement optional "Sender" field.
*/
- public function setFrom($email)
+ public function setFrom($email): static
{
$this->from = $this->parseEmail($email);
return $this;
@@ -405,7 +362,7 @@ public function setFrom($email)
*
* @return string
*/
- public function from()
+ public function from(): ?string
{
if ($this->from === null) {
$this->setFrom($this->config()->defaultFrom());
@@ -418,9 +375,8 @@ public function from()
*
* @param mixed $email The sender's "Reply-To" email address.
* @throws InvalidArgumentException If the email is not a string or an array.
- * @return self
*/
- public function setReplyTo($email)
+ public function setReplyTo($email): static
{
$this->replyTo = $this->parseEmail($email);
return $this;
@@ -443,9 +399,8 @@ public function replyTo()
* Set the email subject.
*
* @param string $subject The email subject.
- * @return self
*/
- public function setSubject(string $subject)
+ public function setSubject(string $subject): static
{
$this->subject = $subject;
return $this;
@@ -465,9 +420,8 @@ public function subject(): string
* Set the email's HTML message body.
*
* @param string $body The HTML message body.
- * @return self
*/
- public function setMsgHtml(string $body)
+ public function setMsgHtml(string $body): static
{
$this->msgHtml = $body;
return $this;
@@ -478,8 +432,6 @@ public function setMsgHtml(string $body)
*
* If the message is not explitely set, it will be
* auto-generated from a template view.
- *
- * @return string
*/
public function msgHtml(): string
{
@@ -493,9 +445,8 @@ public function msgHtml(): string
* Set the email's plain-text message body.
*
* @param string $body The message's text body.
- * @return self
*/
- public function setMsgTxt(string $body)
+ public function setMsgTxt(string $body): static
{
$this->msgTxt = $body;
return $this;
@@ -506,8 +457,6 @@ public function setMsgTxt(string $body)
*
* If the plain-text message is not explitely set,
* it will be auto-generated from the HTML message.
- *
- * @return string
*/
public function msgTxt(): string
{
@@ -521,9 +470,8 @@ public function msgTxt(): string
* Set the email's attachments.
*
* @param array $attachments The file attachments.
- * @return self
*/
- public function setAttachments(array $attachments)
+ public function setAttachments(array $attachments): static
{
foreach ($attachments as $att) {
$this->addAttachment($att);
@@ -535,9 +483,8 @@ public function setAttachments(array $attachments)
* Add an attachment to the email.
*
* @param mixed $attachment A single file attachment.
- * @return self
*/
- public function addAttachment($attachment)
+ public function addAttachment($attachment): static
{
$this->attachments[] = $attachment;
return $this;
@@ -557,18 +504,15 @@ public function attachments()
* Enable or disable logging for this particular email.
*
* @param boolean $log The log-enabled flag.
- * @return self
*/
- public function setLogEnabled($log)
+ public function setLogEnabled($log): static
{
- $this->logEnabled = !!$log;
+ $this->logEnabled = (bool)$log;
return $this;
}
/**
* Determine if logging is enabled for this particular email.
- *
- * @return boolean
*/
public function logEnabled(): bool
{
@@ -582,18 +526,15 @@ public function logEnabled(): bool
* Enable or disable email open tracking for this particular email.
*
* @param boolean $track The track flag.
- * @return self
*/
- public function setTrackOpenEnabled($track)
+ public function setTrackOpenEnabled($track): static
{
- $this->trackOpenEnabled = !!$track;
+ $this->trackOpenEnabled = (bool)$track;
return $this;
}
/**
* Determine if email open tracking is enabled for this particular email.
- *
- * @return boolean
*/
public function trackOpenEnabled(): bool
{
@@ -607,18 +548,15 @@ public function trackOpenEnabled(): bool
* Enable or disable email links tracking for this particular email.
*
* @param boolean $track The track flag.
- * @return self
*/
- public function setTrackLinksEnabled($track)
+ public function setTrackLinksEnabled($track): static
{
- $this->trackLinksEnabled = !!$track;
+ $this->trackLinksEnabled = (bool)$track;
return $this;
}
/**
* Determine if email links tracking is enabled for this particular email.
- *
- * @return boolean
*/
public function trackLinksEnabled(): bool
{
@@ -694,10 +632,10 @@ public function send(): bool
$logId = uniqid();
- if ($this->trackOpenEnabled() === true) {
+ if ($this->trackOpenEnabled()) {
$this->tracker->addOpenTrackingImage($this, $logId);
}
- if ($this->trackLinksEnabled() === true) {
+ if ($this->trackLinksEnabled()) {
$this->tracker->replaceLinksWithTracker($this, $logId);
}
@@ -717,7 +655,7 @@ public function send(): bool
throw new EmailNotSentException($e->getMessage(), $e->getCode(), $e);
}
- if ($this->logEnabled() === true) {
+ if ($this->logEnabled()) {
try {
$this->logSend($ret, $logId, $mail);
} catch (PDOException $e) {
@@ -760,9 +698,8 @@ protected function setSmtpOptions(PHPMailer $mail)
* Enqueue the email for each recipient.
*
* @param mixed $ts A date/time to initiate the queue processing.
- * @return self
*/
- public function queue($ts = null)
+ public function queue($ts = null): static
{
$recipients = $this->to();
$author = $this->from();
@@ -773,7 +710,7 @@ public function queue($ts = null)
$queueId = $this->queueId();
foreach ($recipients as $to) {
- if (is_string($to) && !empty($to)) {
+ if (is_string($to) && ($to !== '' && $to !== '0')) {
$queueItem = $this->queueItemFactory()->create(EmailQueueItem::class);
$queueItem->setTo($to);
@@ -800,7 +737,7 @@ public function queue($ts = null)
* @param array $data The template data.
* @return Email Chainable
*/
- public function setTemplateData(array $data)
+ public function setTemplateData(array $data): static
{
$this->templateData = $data;
return $this;
@@ -808,8 +745,6 @@ public function setTemplateData(array $data)
/**
* Get the template data for the view.
- *
- * @return array
*/
public function templateData(): array
{
@@ -847,15 +782,12 @@ public function viewController()
* @param FactoryInterface $factory The factory to use to create email template objects.
* @return Email Chainable
*/
- protected function setTemplateFactory(FactoryInterface $factory)
+ protected function setTemplateFactory(FactoryInterface $factory): static
{
$this->templateFactory = $factory;
return $this;
}
- /**
- * @return FactoryInterface
- */
protected function templateFactory(): FactoryInterface
{
return $this->templateFactory;
@@ -865,15 +797,12 @@ protected function templateFactory(): FactoryInterface
* @param FactoryInterface $factory The factory to use to create email queue item objects.
* @return Email Chainable
*/
- protected function setQueueItemFactory(FactoryInterface $factory)
+ protected function setQueueItemFactory(FactoryInterface $factory): static
{
$this->queueItemFactory = $factory;
return $this;
}
- /**
- * @return FactoryInterface
- */
protected function queueItemFactory(): FactoryInterface
{
return $this->queueItemFactory;
@@ -883,15 +812,12 @@ protected function queueItemFactory(): FactoryInterface
* @param FactoryInterface $factory The factory to use to create log objects.
* @return Email Chainable
*/
- protected function setLogFactory(FactoryInterface $factory)
+ protected function setLogFactory(FactoryInterface $factory): static
{
$this->logFactory = $factory;
return $this;
}
- /**
- * @return FactoryInterface
- */
protected function logFactory(): FactoryInterface
{
return $this->logFactory;
@@ -899,9 +825,8 @@ protected function logFactory(): FactoryInterface
/**
* @param Tracker $tracker Tracker service.
- * @return void
*/
- public function setTracker(Tracker $tracker)
+ public function setTracker(Tracker $tracker): void
{
$this->tracker = $tracker;
}
@@ -910,25 +835,16 @@ public function setTracker(Tracker $tracker)
* Get the email's HTML message from the template, if applicable.
*
* @see ViewableInterface::render()
- * @return string
*/
protected function generateMsgHtml(): string
{
$templateIdent = $this->templateIdent();
- if (!$templateIdent) {
- $message = '';
- } else {
- $message = $this->render($templateIdent);
- }
-
- return $message;
+ return $templateIdent ? $this->render($templateIdent) : '';
}
/**
* Generates a unique identifier ideal for a campaign ID.
- *
- * @return string
*/
protected function generateCampaign(): string
{
@@ -984,18 +900,17 @@ protected function stripHtml(string $html): string
'##siu'
],
'',
- $str
+ (string)$str
);
- $str = strip_tags($str);
+ $str = strip_tags((string)$str);
// Trim whitespace
$str = str_replace("\t", '', $str);
$str = preg_replace('#\n\r|\r\n#', "\n", $str);
- $str = preg_replace('#\n{3,}#', "\n\n", $str);
- $str = preg_replace('/ {2,}/', ' ', $str);
- $str = implode("\n", array_map('trim', explode("\n", $str)));
- $str = trim($str) . "\n";
- return $str;
+ $str = preg_replace('#\n{3,}#', "\n\n", (string)$str);
+ $str = preg_replace('/ {2,}/', ' ', (string)$str);
+ $str = implode("\n", array_map(trim(...), explode("\n", (string)$str)));
+ return trim($str) . "\n";
}
/**
@@ -1004,7 +919,6 @@ protected function stripHtml(string $html): string
* @param boolean $result Success or failure.
* @param string $logId Email log id.
* @param PHPMailer $mailer The raw mailer.
- * @return void
*/
protected function logSend(bool $result, string $logId, PHPMailer $mailer): void
{
@@ -1045,10 +959,8 @@ protected function logSend(bool $result, string $logId, PHPMailer $mailer): void
/**
* Temporary hack to fulfills the Configurable Interface.
- *
- * @return EmailConfig
*/
- public function createConfig()
+ public function createConfig(): \Charcoal\Email\EmailConfig
{
// This should really be avoided.
$this->logger->warning('AbstractEmail::createConfig() was called, but should not.');
diff --git a/packages/email/src/Charcoal/Email/EmailAwareTrait.php b/packages/email/src/Charcoal/Email/EmailAwareTrait.php
index 8a0de6228..51c732278 100644
--- a/packages/email/src/Charcoal/Email/EmailAwareTrait.php
+++ b/packages/email/src/Charcoal/Email/EmailAwareTrait.php
@@ -19,16 +19,12 @@ trait EmailAwareTrait
/**
* @param Parser $parser Email parser service.
- * @return void
*/
protected function setParser(Parser $parser): void
{
$this->parser = $parser;
}
- /**
- * @return Parser
- */
protected function getParser(): Parser
{
if ($this->parser === null) {
@@ -40,7 +36,6 @@ protected function getParser(): Parser
/**
* @param mixed $email An email value (either a string or an array).
* @throws InvalidArgumentException If the email is invalid.
- * @return string
*/
protected function parseEmail($email): string
{
@@ -52,7 +47,6 @@ protected function parseEmail($email): string
*
* @param mixed $var An email array (containing an "email" key and optionally a "name" key).
* @throws InvalidArgumentException If the email is invalid.
- * @return array|null
*/
protected function emailToArray($var): ?array
{
@@ -64,7 +58,6 @@ protected function emailToArray($var): ?array
*
* @param array $arr An email array (containing an "email" key and optionally a "name" key).
* @throws InvalidArgumentException If the email array is invalid.
- * @return string
*/
protected function emailFromArray(array $arr): string
{
diff --git a/packages/email/src/Charcoal/Email/EmailConfig.php b/packages/email/src/Charcoal/Email/EmailConfig.php
index 068d46e92..dd1083ba3 100644
--- a/packages/email/src/Charcoal/Email/EmailConfig.php
+++ b/packages/email/src/Charcoal/Email/EmailConfig.php
@@ -17,94 +17,69 @@ class EmailConfig extends AbstractConfig
/**
* Whether SMTP should be used.
- *
- * @var boolean $smtp
*/
- private $smtp = false;
+ private bool $smtp = false;
/**
* The SMTP hostname.
- *
- * @var string $smtpHostname
*/
- private $smtpHostname;
+ private ?string $smtpHostname = null;
/**
* The SMTP port.
- *
- * @var integer $smtpPort
*/
- private $smtpPort;
+ private ?int $smtpPort = null;
/**
* The SMTP security type.
- *
- * @var string $smtpSecurity
*/
- private $smtpSecurity = '';
+ private string $smtpSecurity = '';
/**
* Whether SMTP requires authentication.
- *
- * @var boolean $smtpAuth
*/
- private $smtpAuth;
+ private ?bool $smtpAuth = null;
/**
* The SMTP username.
- *
- * @var string $smtpUsername
*/
- private $smtpUsername;
+ private ?string $smtpUsername = null;
/**
* The SMTP password.
- *
- * @var string $smtpPassword
*/
- private $smtpPassword;
+ private ?string $smtpPassword = null;
/**
* The default sender's email address.
- *
- * @var string $defaultFrom
*/
- private $defaultFrom;
+ private ?string $defaultFrom = null;
/**
* The default "Reply-To" email address.
- *
- * @var string $defaultReplyTo
*/
- private $defaultReplyTo;
+ private ?string $defaultReplyTo = null;
/**
* Whether the email (open) should be tracked by default.
- *
- * @var boolean $defaultTrack
*/
- private $defaultTrackOpenEnabled;
+ private ?bool $defaultTrackOpenEnabled = null;
/**
* Whether the email (links) should be tracked by default.
- *
- * @var boolean $defaultTrack
*/
- private $defaultTrackLinksEnabled;
+ private ?bool $defaultTrackLinksEnabled = null;
/**
* Whether the email should be logged by default.
- *
- * @var boolean $defaultLog
*/
- private $defaultLogEnabled;
+ private ?bool $defaultLogEnabled = null;
/**
* Default email configuration.
- *
- * @return array
*/
+ #[\Override]
public function defaults(): array
{
return [
@@ -124,20 +99,17 @@ public function defaults(): array
*
* @param boolean $smtp If the email should be sent using SMTP or not.
* @throws InvalidArgumentException If the SMTP state is not a boolean.
- * @return self
*/
- public function setSmtp($smtp)
+ public function setSmtp($smtp): static
{
- $this->smtp = !!$smtp;
+ $this->smtp = (bool)$smtp;
return $this;
}
/**
* Determine if SMTP should be used.
- *
- * @return boolean
*/
- public function smtp()
+ public function smtp(): bool
{
return $this->smtp;
}
@@ -147,9 +119,8 @@ public function smtp()
*
* @param string $hostname The SMTP hostname.
* @throws InvalidArgumentException If the SMTP hostname is not a string.
- * @return self
*/
- public function setSmtpHostname($hostname)
+ public function setSmtpHostname($hostname): static
{
if (!is_string($hostname)) {
throw new InvalidArgumentException(
@@ -167,7 +138,7 @@ public function setSmtpHostname($hostname)
*
* @return string
*/
- public function smtpHostname()
+ public function smtpHostname(): ?string
{
return $this->smtpHostname;
}
@@ -177,9 +148,8 @@ public function smtpHostname()
*
* @param integer $port The SMTP port.
* @throws InvalidArgumentException If the SMTP port is not an integer.
- * @return self
*/
- public function setSmtpPort($port)
+ public function setSmtpPort($port): static
{
if (!is_int($port)) {
throw new InvalidArgumentException(
@@ -197,7 +167,7 @@ public function setSmtpPort($port)
*
* @return integer
*/
- public function smtpPort()
+ public function smtpPort(): ?int
{
return $this->smtpPort;
}
@@ -206,11 +176,10 @@ public function smtpPort()
* Set whether SMTP requires authentication.
*
* @param boolean $auth The SMTP authentication flag (if auth is required).
- * @return self
*/
- public function setSmtpAuth($auth)
+ public function setSmtpAuth($auth): static
{
- $this->smtpAuth = !!$auth;
+ $this->smtpAuth = (bool)$auth;
return $this;
}
@@ -219,7 +188,7 @@ public function setSmtpAuth($auth)
*
* @return boolean
*/
- public function smtpAuth()
+ public function smtpAuth(): ?bool
{
return $this->smtpAuth;
}
@@ -229,9 +198,8 @@ public function smtpAuth()
*
* @param string $username The SMTP username, if using authentication.
* @throws InvalidArgumentException If the SMTP username is not a string.
- * @return self
*/
- public function setSmtpUsername($username)
+ public function setSmtpUsername($username): static
{
if (!is_string($username)) {
throw new InvalidArgumentException(
@@ -249,7 +217,7 @@ public function setSmtpUsername($username)
*
* @return string
*/
- public function smtpUsername()
+ public function smtpUsername(): ?string
{
return $this->smtpUsername;
}
@@ -259,9 +227,8 @@ public function smtpUsername()
*
* @param string $password The SMTP password, if using authentication.
* @throws InvalidArgumentException If the SMTP password is not a string.
- * @return self
*/
- public function setSmtpPassword($password)
+ public function setSmtpPassword($password): static
{
if (!is_string($password)) {
throw new InvalidArgumentException(
@@ -279,7 +246,7 @@ public function setSmtpPassword($password)
*
* @return string
*/
- public function smtpPassword()
+ public function smtpPassword(): ?string
{
return $this->smtpPassword;
}
@@ -289,9 +256,8 @@ public function smtpPassword()
*
* @param string $security The SMTP security type (empty, "TLS", or "SSL").
* @throws InvalidArgumentException If the security type is not valid (empty, "TLS", or "SSL").
- * @return self
*/
- public function setSmtpSecurity($security)
+ public function setSmtpSecurity($security): static
{
$security = strtoupper($security);
$validSecurity = [ '', 'TLS', 'SSL' ];
@@ -309,10 +275,8 @@ public function setSmtpSecurity($security)
/**
* Get the SMTP security type.
- *
- * @return string
*/
- public function smtpSecurity()
+ public function smtpSecurity(): string
{
return $this->smtpSecurity;
}
@@ -321,9 +285,8 @@ public function smtpSecurity()
* Set the default sender's email address.
*
* @param string|array $email The default "From" email address.
- * @return self
*/
- public function setDefaultFrom($email)
+ public function setDefaultFrom($email): static
{
$this->defaultFrom = $this->parseEmail($email);
return $this;
@@ -334,7 +297,7 @@ public function setDefaultFrom($email)
*
* @return string
*/
- public function defaultFrom()
+ public function defaultFrom(): ?string
{
return $this->defaultFrom;
}
@@ -343,9 +306,8 @@ public function defaultFrom()
* Set the default "Reply-To" email address.
*
* @param string|array $email The default "Reply-To" email address.
- * @return self
*/
- public function setDefaultReplyTo($email)
+ public function setDefaultReplyTo($email): static
{
$this->defaultReplyTo = $this->parseEmail($email);
return $this;
@@ -356,7 +318,7 @@ public function setDefaultReplyTo($email)
*
* @return string
*/
- public function defaultReplyTo()
+ public function defaultReplyTo(): ?string
{
return $this->defaultReplyTo;
}
@@ -365,11 +327,10 @@ public function defaultReplyTo()
* Set whether the email sending should be logged by default.
*
* @param boolean $log The default log flag.
- * @return self
*/
- public function setDefaultLogEnabled($log)
+ public function setDefaultLogEnabled($log): static
{
- $this->defaultLogEnabled = !!$log;
+ $this->defaultLogEnabled = (bool)$log;
return $this;
}
@@ -378,7 +339,7 @@ public function setDefaultLogEnabled($log)
*
* @return boolean
*/
- public function defaultLogEnabled()
+ public function defaultLogEnabled(): ?bool
{
return $this->defaultLogEnabled;
}
@@ -387,11 +348,10 @@ public function defaultLogEnabled()
* Set whether the email (open) should be tracked by default.
*
* @param boolean $track The default track flag.
- * @return self
*/
- public function setDefaultTrackOpenEnabled($track)
+ public function setDefaultTrackOpenEnabled($track): static
{
- $this->defaultTrackOpenEnabled = !!$track;
+ $this->defaultTrackOpenEnabled = (bool)$track;
return $this;
}
@@ -400,7 +360,7 @@ public function setDefaultTrackOpenEnabled($track)
*
* @return boolean
*/
- public function defaultTrackOpenEnabled()
+ public function defaultTrackOpenEnabled(): ?bool
{
return $this->defaultTrackOpenEnabled;
}
@@ -409,11 +369,10 @@ public function defaultTrackOpenEnabled()
* Set whether the email links should be tracked by default.
*
* @param boolean $track The default track flag.
- * @return self
*/
- public function setDefaultTrackLinksEnabled($track)
+ public function setDefaultTrackLinksEnabled($track): static
{
- $this->defaultTrackLinksEnabled = !!$track;
+ $this->defaultTrackLinksEnabled = (bool)$track;
return $this;
}
@@ -422,7 +381,7 @@ public function setDefaultTrackLinksEnabled($track)
*
* @return boolean
*/
- public function defaultTrackLinksEnabled()
+ public function defaultTrackLinksEnabled(): ?bool
{
return $this->defaultTrackLinksEnabled;
}
diff --git a/packages/email/src/Charcoal/Email/EmailInterface.php b/packages/email/src/Charcoal/Email/EmailInterface.php
index ca4204066..4ff73e087 100644
--- a/packages/email/src/Charcoal/Email/EmailInterface.php
+++ b/packages/email/src/Charcoal/Email/EmailInterface.php
@@ -156,8 +156,6 @@ public function setMsgHtml(string $body);
/**
* Get the email's HTML message body.
- *
- * @return string
*/
public function msgHtml(): string;
@@ -171,8 +169,6 @@ public function setMsgTxt(string $body);
/**
* Get the email's plain-text message body.
- *
- * @return string
*/
public function msgTxt(): string;
@@ -209,8 +205,6 @@ public function setLogEnabled($log);
/**
* Determine if logging is enabled for this particular email.
- *
- * @return boolean
*/
public function logEnabled(): bool;
@@ -224,8 +218,6 @@ public function setTrackOpenEnabled($track);
/**
* Determine if tracking is enabled for this particular email.
- *
- * @return boolean
*/
public function trackLinksEnabled(): bool;
@@ -239,8 +231,6 @@ public function setTrackLinksEnabled($track);
/**
* Determine if tracking is enabled for this particular email.
- *
- * @return boolean
*/
public function trackOpenEnabled(): bool;
diff --git a/packages/email/src/Charcoal/Email/EmailLog.php b/packages/email/src/Charcoal/Email/EmailLog.php
index 376ebda71..1a8ec67d9 100644
--- a/packages/email/src/Charcoal/Email/EmailLog.php
+++ b/packages/email/src/Charcoal/Email/EmailLog.php
@@ -1,5 +1,7 @@
to = $this->parseEmail($email);
- } catch (Exception $e) {
+ } catch (Exception) {
$this->logger->warning(sprintf('Invalid "to" email: "%s"', strval($email)));
}
@@ -103,7 +94,7 @@ public function setTo($email)
*
* @return string
*/
- public function to()
+ public function to(): ?string
{
return $this->to;
}
@@ -112,13 +103,12 @@ public function to()
* Set the sender's email address.
*
* @param string|array $email An email address.
- * @return self
*/
- public function setFrom($email)
+ public function setFrom($email): static
{
try {
$this->from = $this->parseEmail($email);
- } catch (Exception $e) {
+ } catch (Exception) {
$this->logger->warning(sprintf('Invalid "from" email: "%s"', strval($email)));
}
@@ -130,7 +120,7 @@ public function setFrom($email)
*
* @return string
*/
- public function from()
+ public function from(): ?string
{
return $this->from;
}
@@ -139,9 +129,8 @@ public function from()
* Set the email subject.
*
* @param string $subject The email subject.
- * @return self
*/
- public function setSubject($subject)
+ public function setSubject($subject): static
{
$this->subject = $subject;
@@ -162,9 +151,8 @@ public function subject()
* Set the email's HTML message body.
*
* @param string $body The HTML message body.
- * @return self
*/
- public function setMsgHtml($body)
+ public function setMsgHtml($body): static
{
$this->msgHtml = $body;
@@ -185,9 +173,8 @@ public function msgHtml()
* Set the email's plain-text message body.
*
* @param string $body The plain-text mesage body.
- * @return self
*/
- public function setMsgTxt($body)
+ public function setMsgTxt($body): static
{
$this->msgTxt = $body;
@@ -208,9 +195,8 @@ public function msgTxt()
* Set the campaign ID.
*
* @param string $campaign The campaign identifier.
- * @return self
*/
- public function setCampaign($campaign)
+ public function setCampaign($campaign): static
{
$this->campaign = $campaign;
@@ -240,9 +226,9 @@ public function campaign()
* processed.
*/
public function process(
- callable $alwaysCallback = null,
- callable $successCallback = null,
- callable $failureCallback = null
+ ?callable $alwaysCallback = null,
+ ?callable $successCallback = null,
+ ?callable $failureCallback = null
): ?bool {
$email = $this->emailFactory()->create('email');
$email->setData($this->data());
@@ -269,16 +255,13 @@ public function process(
// Clear cumbersome DB data
$this->setMsgHtml(null)
->setMsgTxt(null);
-
- array_push($propsToUpdate, 'msg_html', 'msg_txt');
-
+ $propsToUpdate[] = 'msg_html';
+ $propsToUpdate[] = 'msg_txt';
if ($successCallback !== null) {
$successCallback($this);
}
- } else {
- if ($failureCallback !== null) {
- $failureCallback($this);
- }
+ } elseif ($failureCallback !== null) {
+ $failureCallback($this);
}
$this->update(array_merge([
@@ -294,8 +277,8 @@ public function process(
/**
* @param Container $container Pimple DI container.
- * @return void
*/
+ #[\Override]
protected function setDependencies(Container $container): void
{
parent::setDependencies($container);
@@ -305,9 +288,9 @@ protected function setDependencies(Container $container): void
/**
* Hook called before saving the item.
*
- * @return boolean
* @see \Charcoal\Queue\QueueItemTrait::preSaveQueueItem()
*/
+ #[\Override]
protected function preSave(): bool
{
parent::preSave();
@@ -317,9 +300,6 @@ protected function preSave(): bool
return true;
}
- /**
- * @return FactoryInterface
- */
protected function emailFactory(): FactoryInterface
{
return $this->emailFactory;
@@ -327,7 +307,6 @@ protected function emailFactory(): FactoryInterface
/**
* @param FactoryInterface $factory The factory to create email objects.
- * @return void
*/
private function setEmailFactory(FactoryInterface $factory): void
{
diff --git a/packages/email/src/Charcoal/Email/EmailQueueManager.php b/packages/email/src/Charcoal/Email/EmailQueueManager.php
index 9d94e33fe..ff6b7af4f 100644
--- a/packages/email/src/Charcoal/Email/EmailQueueManager.php
+++ b/packages/email/src/Charcoal/Email/EmailQueueManager.php
@@ -1,5 +1,7 @@
queueId = $queueId;
@@ -110,9 +100,8 @@ public function queueId()
* Set the error code.
*
* @param string $errorCode The error code.
- * @return self
*/
- public function setErrorCode($errorCode)
+ public function setErrorCode($errorCode): static
{
$this->errorCode = $errorCode;
@@ -134,9 +123,8 @@ public function errorCode()
*
* @param string $messageId The Message-ID.
* @throws InvalidArgumentException If the Message-ID is not a string.
- * @return self
*/
- public function setMessageId($messageId)
+ public function setMessageId($messageId): static
{
if (!is_string($messageId)) {
throw new InvalidArgumentException(
@@ -154,7 +142,7 @@ public function setMessageId($messageId)
*
* @return string
*/
- public function messageId()
+ public function messageId(): ?string
{
return $this->messageId;
}
@@ -164,9 +152,8 @@ public function messageId()
*
* @param string $campaign The campaign identifier.
* @throws InvalidArgumentException If the campaign is invalid.
- * @return self
*/
- public function setCampaign($campaign)
+ public function setCampaign($campaign): static
{
if ($campaign !== null && !is_string($campaign)) {
throw new InvalidArgumentException(
@@ -194,9 +181,8 @@ public function campaign()
*
* @param string|array $email An email address.
* @throws InvalidArgumentException If the email address is invalid.
- * @return self
*/
- public function setFrom($email)
+ public function setFrom($email): static
{
$this->from = $this->parseEmail($email);
return $this;
@@ -207,7 +193,7 @@ public function setFrom($email)
*
* @return string
*/
- public function from()
+ public function from(): ?string
{
return $this->from;
}
@@ -216,9 +202,8 @@ public function from()
* Set the recipient's email address.
*
* @param string|array $email An email address.
- * @return self
*/
- public function setTo($email)
+ public function setTo($email): static
{
$this->to = $this->parseEmail($email);
return $this;
@@ -229,7 +214,7 @@ public function setTo($email)
*
* @return string
*/
- public function to()
+ public function to(): ?string
{
return $this->to;
}
@@ -239,9 +224,8 @@ public function to()
*
* @param string $subject The email subject.
* @throws InvalidArgumentException If the subject is not a string.
- * @return self
*/
- public function setSubject($subject)
+ public function setSubject($subject): static
{
if (!is_string($subject)) {
throw new InvalidArgumentException(
@@ -259,7 +243,7 @@ public function setSubject($subject)
*
* @return string
*/
- public function subject()
+ public function subject(): ?string
{
return $this->subject;
}
@@ -267,9 +251,8 @@ public function subject()
/**
* @param null|string|DateTime $ts The "send date" datetime value.
* @throws InvalidArgumentException If the ts is not a valid datetime value.
- * @return self
*/
- public function setSendTs($ts)
+ public function setSendTs($ts): static
{
if ($ts === null) {
$this->sendTs = null;
@@ -280,7 +263,7 @@ public function setSendTs($ts)
try {
$ts = new DateTime($ts);
} catch (Exception $e) {
- throw new InvalidArgumentException($e->getMessage());
+ throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
@@ -294,23 +277,20 @@ public function setSendTs($ts)
return $this;
}
- /**
- * @return null|DateTimeInterface
- */
- public function sendTs()
+ public function sendTs(): ?\DateTimeInterface
{
return $this->sendTs;
}
/**
* @see StorableTrait::preSave()
- * @return boolean
*/
+ #[\Override]
protected function preSave(): bool
{
parent::preSave();
- if ($this->sendTs() === null) {
+ if (!$this->sendTs() instanceof \DateTimeInterface) {
$this->setSendTs('now');
}
diff --git a/packages/email/src/Charcoal/Email/Objects/Link.php b/packages/email/src/Charcoal/Email/Objects/Link.php
index 4a3ae36f3..09c489bca 100644
--- a/packages/email/src/Charcoal/Email/Objects/Link.php
+++ b/packages/email/src/Charcoal/Email/Objects/Link.php
@@ -24,17 +24,13 @@ class Link extends AbstractModel
/**
* @param string $emailId The email (log) id.
- * @return self
*/
- public function setEmail(?string $emailId)
+ public function setEmail(?string $emailId): static
{
$this->email = $emailId;
return $this;
}
- /**
- * @return string|null
- */
public function email(): ?string
{
return $this->email;
@@ -42,17 +38,13 @@ public function email(): ?string
/**
* @param string $url The original (and target) URL.
- * @return self
*/
- public function setUrl(?string $url)
+ public function setUrl(?string $url): static
{
$this->url = $url;
return $this;
}
- /**
- * @return string|null
- */
public function url(): ?string
{
return $this->url;
diff --git a/packages/email/src/Charcoal/Email/Objects/LinkLog.php b/packages/email/src/Charcoal/Email/Objects/LinkLog.php
index e9d83e5aa..5f728b584 100644
--- a/packages/email/src/Charcoal/Email/Objects/LinkLog.php
+++ b/packages/email/src/Charcoal/Email/Objects/LinkLog.php
@@ -16,26 +16,16 @@
*/
class LinkLog extends AbstractModel
{
- /**
- * @var string|null
- */
- private $link;
+ private ?string $link = null;
- /**
- * @var DateTimeInterface|null
- */
- private $ts;
+ private ?\DateTimeInterface $ts = null;
- /**
- * @var string|null
- */
- private $ip;
+ private ?string $ip = null;
/**
* @param string|null $linkId The link id.
- * @return self
*/
- public function setLink(?string $linkId)
+ public function setLink(?string $linkId): static
{
$this->link = $linkId;
return $this;
@@ -52,9 +42,8 @@ public function link(): ?string
/**
* @param null|string|DateTimeInterface $ts The "timestamp" datetime value.
* @throws InvalidArgumentException If the timestamp is not a valid datetime value.
- * @return self
*/
- public function setTs($ts)
+ public function setTs($ts): static
{
if ($ts === null) {
$this->ts = null;
@@ -65,7 +54,7 @@ public function setTs($ts)
try {
$ts = new DateTime($ts);
} catch (Exception $e) {
- throw new InvalidArgumentException($e->getMessage());
+ throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
@@ -79,27 +68,20 @@ public function setTs($ts)
return $this;
}
- /**
- * @return null|DateTimeInterface
- */
- public function ts()
+ public function ts(): ?\DateTimeInterface
{
return $this->ts;
}
/**
* @param string|null $ip The IP address.
- * @return self
*/
- public function setIp(?string $ip)
+ public function setIp(?string $ip): static
{
$this->ip = $ip;
return $this;
}
- /**
- * @return string|null
- */
public function ip(): ?string
{
return $this->ip;
diff --git a/packages/email/src/Charcoal/Email/Objects/OpenLog.php b/packages/email/src/Charcoal/Email/Objects/OpenLog.php
index 6fca61256..0edc6e3b1 100644
--- a/packages/email/src/Charcoal/Email/Objects/OpenLog.php
+++ b/packages/email/src/Charcoal/Email/Objects/OpenLog.php
@@ -16,35 +16,22 @@
*/
class OpenLog extends AbstractModel
{
- /**
- * @var string|null
- */
- private $email;
+ private ?string $email = null;
- /**
- * @var DateTimeInterface|null
- */
- private $ts;
+ private ?\DateTimeInterface $ts = null;
- /**
- * @var string|null
- */
- private $ip;
+ private ?string $ip = null;
/**
* @param string|null $emailId The email (log) id.
- * @return self
*/
- public function setEmail(?string $emailId)
+ public function setEmail(?string $emailId): static
{
$this->email = $emailId;
return $this;
}
- /**
- * @return string|null
- */
public function email(): ?string
{
return $this->email;
@@ -53,9 +40,8 @@ public function email(): ?string
/**
* @param null|string|DateTimeInterface $ts The "timestamp" datetime value.
* @throws InvalidArgumentException If the timestamp is not a valid datetime value.
- * @return self
*/
- public function setTs($ts)
+ public function setTs($ts): static
{
if ($ts === null) {
$this->ts = null;
@@ -66,7 +52,7 @@ public function setTs($ts)
try {
$ts = new DateTime($ts);
} catch (Exception $e) {
- throw new InvalidArgumentException($e->getMessage());
+ throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
@@ -80,27 +66,20 @@ public function setTs($ts)
return $this;
}
- /**
- * @return null|DateTimeInterface
- */
- public function ts()
+ public function ts(): ?\DateTimeInterface
{
return $this->ts;
}
/**
* @param string|null $ip The IP address.
- * @return self
*/
- public function setIp(?string $ip)
+ public function setIp(?string $ip): static
{
$this->ip = $ip;
return $this;
}
- /**
- * @return string|null
- */
public function ip(): ?string
{
return $this->ip;
diff --git a/packages/email/src/Charcoal/Email/Script/ProcessQueueScript.php b/packages/email/src/Charcoal/Email/Script/ProcessQueueScript.php
index 086b89d3d..18a195eb4 100644
--- a/packages/email/src/Charcoal/Email/Script/ProcessQueueScript.php
+++ b/packages/email/src/Charcoal/Email/Script/ProcessQueueScript.php
@@ -27,17 +27,13 @@ class ProcessQueueScript extends AbstractScript implements CronScriptInterface
{
use CronScriptTrait;
- /**
- * @var FactoryInterface
- */
- private $queueItemFactory;
+ private ?\Charcoal\Factory\FactoryInterface $queueItemFactory = null;
/**
* Process all messages currently in queue.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
- * @return ResponseInterface
*/
public function run(RequestInterface $request, ResponseInterface $response): ResponseInterface
{
@@ -67,10 +63,9 @@ public function run(RequestInterface $request, ResponseInterface $response): Res
/**
* Default script arguments.
- *
- * @return array
*/
- public function defaultArguments()
+ #[\Override]
+ public function defaultArguments(): array
{
$arguments = [
'queue-id' => [
@@ -98,9 +93,7 @@ public function defaultArguments()
'castTo' => 'int',
],
];
-
- $arguments = array_merge(parent::defaultArguments(), $arguments);
- return $arguments;
+ return array_merge(parent::defaultArguments(), $arguments);
}
/**
@@ -108,7 +101,7 @@ public function defaultArguments()
*
* @return EmailQueueManager
*/
- protected function makeQueueManager()
+ protected function makeQueueManager(): object
{
$cli = $this->climate();
@@ -147,8 +140,6 @@ protected function makeQueueManager()
/**
* Retrieve the class name of the queue manager model.
- *
- * @return string
*/
protected function getQueueManagerClass(): string
{
@@ -162,7 +153,7 @@ protected function getProcessedQueueCallback(): callable
{
$climate = $this->climate();
- $callback = function ($success, $failures, $skipped) use ($climate): void {
+ return function ($success, $failures, $skipped) use ($climate): void {
if (!empty($success)) {
$climate->green()->out(sprintf('%s emails were successfully sent.', count($success)));
}
@@ -175,14 +166,12 @@ protected function getProcessedQueueCallback(): callable
$climate->dim()->out(sprintf('%s emails were skipped.', count($skipped)));
}
};
-
- return $callback;
}
/**
* @param Container $container Pimple DI container.
- * @return void
*/
+ #[\Override]
protected function setDependencies(Container $container): void
{
parent::setDependencies($container);
@@ -191,7 +180,6 @@ protected function setDependencies(Container $container): void
/**
* @param FactoryInterface $factory The factory to create queue items.
- * @return void
*/
private function setQueueItemFactory(FactoryInterface $factory): void
{
diff --git a/packages/email/src/Charcoal/Email/ServiceProvider/EmailServiceProvider.php b/packages/email/src/Charcoal/Email/ServiceProvider/EmailServiceProvider.php
index bbafb8c37..2c428bb21 100644
--- a/packages/email/src/Charcoal/Email/ServiceProvider/EmailServiceProvider.php
+++ b/packages/email/src/Charcoal/Email/ServiceProvider/EmailServiceProvider.php
@@ -33,7 +33,6 @@ class EmailServiceProvider implements ServiceProviderInterface
{
/**
* @param Container $container A pimple container instance.
- * @return void
*/
public function register(Container $container): void
{
@@ -43,65 +42,54 @@ public function register(Container $container): void
*/
$container['email/config'] = function (Container $container): EmailConfig {
$appConfig = $container['config'];
- $emailConfig = new EmailConfig($appConfig['email']);
- return $emailConfig;
+ return new EmailConfig($appConfig['email']);
};
/**
* @param Container $container Pimple DI container.
* @return ViewInterface
*/
- $container['email/view'] = function (Container $container): ViewInterface {
- return $container['view'];
- };
+ $container['email/view'] = (fn(Container $container): ViewInterface => $container['view']);
/**
* @param Container $container Pimple DI Container.
* @return FactoryInterface
*/
- $container['email/factory'] = function (Container $container): FactoryInterface {
- return new GenericFactory([
- 'map' => [
- 'email' => Email::class
- ],
- 'base_class' => EmailInterface::class,
- 'default_class' => Email::class,
- 'arguments' => [[
- 'logger' => $container['logger'],
- 'config' => $container['email/config'],
- 'view' => $container['email/view'],
- 'template_factory' => $container['template/factory'],
- 'queue_item_factory' => $container['model/factory'],
- 'log_factory' => $container['model/factory'],
- 'tracker' => $container['email/tracker']
- ]]
- ]);
- };
+ $container['email/factory'] = (fn(Container $container): FactoryInterface => new GenericFactory([
+ 'map' => [
+ 'email' => Email::class
+ ],
+ 'base_class' => EmailInterface::class,
+ 'default_class' => Email::class,
+ 'arguments' => [[
+ 'logger' => $container['logger'],
+ 'config' => $container['email/config'],
+ 'view' => $container['email/view'],
+ 'template_factory' => $container['template/factory'],
+ 'queue_item_factory' => $container['model/factory'],
+ 'log_factory' => $container['model/factory'],
+ 'tracker' => $container['email/tracker']
+ ]]
+ ]));
/**
* @return Parser
*/
- $container['email/parser'] = function (): Parser {
- return new Parser();
- };
+ $container['email/parser'] = (fn(): Parser => new Parser());
/**
* @param Container $container Pimple DI Container.
* @return Tracker
*/
- $container['email/tracker'] = function (Container $container): Tracker {
- return new Tracker(
- (string)$container['base-url'],
- $container['model/factory']
- );
- };
+ $container['email/tracker'] = (fn(Container $container): Tracker => new Tracker(
+ (string)$container['base-url'],
+ $container['model/factory']
+ ));
/**
* @param Container $container Pimple DI container.
* @return \Charcoal\Email\EmailInterface
*/
- $container['email'] = $container->factory(function (Container $container): EmailInterface {
- return $container['email/factory']->create('email');
- });
+ $container['email'] = $container->factory(fn(Container $container): EmailInterface => $container['email/factory']->create('email'));
}
}
diff --git a/packages/email/src/Charcoal/Email/Services/Parser.php b/packages/email/src/Charcoal/Email/Services/Parser.php
index 841a4bff7..64b3aebb6 100644
--- a/packages/email/src/Charcoal/Email/Services/Parser.php
+++ b/packages/email/src/Charcoal/Email/Services/Parser.php
@@ -19,7 +19,6 @@ class Parser
/**
* @param string|array $email An email value (either a string or an array).
* @throws InvalidArgumentException If the email is invalid.
- * @return string
*/
public function parse($email): string
{
@@ -40,7 +39,6 @@ public function parse($email): string
*
* @param string $var An email array (containing an "email" key and optionally a "name" key).
* @throws InvalidArgumentException If the email is invalid.
- * @return array
*/
public function emailToArray(string $var): array
{
@@ -56,7 +54,6 @@ public function emailToArray(string $var): array
*
* @param array $arr An email array (containing an "email" key and optionally a "name" key).
* @throws InvalidArgumentException If the email array is invalid.
- * @return string
*/
public function emailFromArray(array $arr): string
{
@@ -72,7 +69,8 @@ public function emailFromArray(array $arr): string
return $email;
}
- $name = str_replace('"', '', filter_var($arr['name'], FILTER_SANITIZE_STRING));
+ $name = htmlspecialchars($arr['name'], ENT_NOQUOTES, 'UTF-8');
+ $name = str_replace('"', '', $name);
return sprintf('"%s" <%s>', $name, $email);
}
}
diff --git a/packages/email/src/Charcoal/Email/Services/Tracker.php b/packages/email/src/Charcoal/Email/Services/Tracker.php
index a1c9c265a..83a329afc 100644
--- a/packages/email/src/Charcoal/Email/Services/Tracker.php
+++ b/packages/email/src/Charcoal/Email/Services/Tracker.php
@@ -22,30 +22,17 @@
*/
class Tracker
{
- /**
- * @var string
- */
- private $baseUrl;
-
- /**
- * @var FactoryInterface
- */
- private $modelFactory;
-
/**
* @param string $baseUrl Base URL.
* @param FactoryInterface $modelFactory Model factory to create link and log objects.
*/
- public function __construct(string $baseUrl, FactoryInterface $modelFactory)
+ public function __construct(private readonly string $baseUrl, private readonly FactoryInterface $modelFactory)
{
- $this->baseUrl = $baseUrl;
- $this->modelFactory = $modelFactory;
}
/**
* @param Email $email Email object to update.
* @param string $emailLogId Email log ID, to generate image link for.
- * @return void
*/
public function addOpenTrackingImage(Email &$email, string $emailLogId): void
{
@@ -64,7 +51,6 @@ public function addOpenTrackingImage(Email &$email, string $emailLogId): void
/**
* @param Email $email Email object to update.
* @param string $emailLogId Email log ID, to generate links for.
- * @return void
*/
public function replaceLinksWithTracker(Email &$email, string $emailLogId): void
{
@@ -83,7 +69,6 @@ public function replaceLinksWithTracker(Email &$email, string $emailLogId): void
/**
* @param string $emailLogId Email log ID, to track.
* @param string|null $ip Client IP address.
- * @return void
*/
public function trackOpen(string $emailLogId, ?string $ip): void
{
@@ -97,7 +82,6 @@ public function trackOpen(string $emailLogId, ?string $ip): void
/**
* @param string $linkId Link ID, to track.
* @param string|null $ip Client IP address.
- * @return void
*/
public function trackLink(string $linkId, ?string $ip): void
{
@@ -111,7 +95,6 @@ public function trackLink(string $linkId, ?string $ip): void
/**
* @param string $emailLogId Email log ID, to create link for.
* @param string $url URL to redirect to.
- * @return string
*/
private function createLink(string $emailLogId, string $url): string
{
diff --git a/packages/email/tests/Charcoal/AbstractTestCase.php b/packages/email/tests/Charcoal/AbstractTestCase.php
index 59ba12ea0..80f1772c4 100644
--- a/packages/email/tests/Charcoal/AbstractTestCase.php
+++ b/packages/email/tests/Charcoal/AbstractTestCase.php
@@ -1,5 +1,7 @@
obj = $this->getMockForTrait('\Charcoal\Email\EmailAwareTrait');
+ $this->obj = new class {
+ use \Charcoal\Email\EmailAwareTrait;
+ };
}
- public function getMethod($obj, $name)
+ public function getMethod($obj, $name): \ReflectionMethod
{
$class = new ReflectionClass($obj);
- $method = $class->getMethod($name);
- $method->setAccessible(true);
- return $method;
+ return $class->getMethod($name);
}
- /**
- * @dataProvider emailToArrayProvider
- */
- public function testEmailToArray($val, $exp)
+ #[\PHPUnit\Framework\Attributes\DataProvider('emailToArrayProvider')]
+ public function testEmailToArray(string $val, array $exp): void
{
$method = $this->getMethod($this->obj, 'emailToArray');
$res = $method->invokeArgs($this->obj, [$val]);
$this->assertEquals($res, $exp);
}
- public function emailToArrayProvider()
+ public static function emailToArrayProvider(): array
{
return [
['mat@locomotive.ca', ['email'=>'mat@locomotive.ca', 'name'=>'']],
diff --git a/packages/email/tests/Charcoal/Email/EmailConfigTest.php b/packages/email/tests/Charcoal/Email/EmailConfigTest.php
index e4941625b..a979ef820 100644
--- a/packages/email/tests/Charcoal/Email/EmailConfigTest.php
+++ b/packages/email/tests/Charcoal/Email/EmailConfigTest.php
@@ -18,7 +18,7 @@ protected function setUp(): void
{
$this->obj = new EmailConfig();
}
- public function testSetData()
+ public function testSetData(): void
{
$data = [
'smtp' => true,
@@ -43,7 +43,7 @@ public function testSetData()
$this->assertEquals(true, $this->obj->defaultTrackLinksEnabled());
}
- public function testSetSmtp()
+ public function testSetSmtp(): void
{
$ret = $this->obj->setSmtp(true);
$this->assertSame($ret, $this->obj);
@@ -53,7 +53,7 @@ public function testSetSmtp()
$this->assertFalse($this->obj->smtp());
}
- public function testSetSmtpHostname()
+ public function testSetSmtpHostname(): void
{
$ret = $this->obj->setSmtpHostname('foobar');
$this->assertSame($ret, $this->obj);
@@ -63,7 +63,7 @@ public function testSetSmtpHostname()
$this->obj->setSmtpHostname([]);
}
- public function testSetSmtpPort()
+ public function testSetSmtpPort(): void
{
$ret = $this->obj->setSmtpPort(42);
$this->assertSame($ret, $this->obj);
@@ -73,7 +73,7 @@ public function testSetSmtpPort()
$this->obj->setSmtpPort('foo');
}
- public function testSetSmtpAuth()
+ public function testSetSmtpAuth(): void
{
$ret = $this->obj->setSmtpAuth(true);
$this->assertSame($ret, $this->obj);
@@ -83,7 +83,7 @@ public function testSetSmtpAuth()
$this->assertFalse($this->obj->smtpAuth());
}
- public function testSetSmtpUsername()
+ public function testSetSmtpUsername(): void
{
$ret = $this->obj->setSmtpUsername('foobar');
$this->assertSame($ret, $this->obj);
@@ -93,7 +93,7 @@ public function testSetSmtpUsername()
$this->obj->setSmtpUsername([]);
}
- public function testSetSmtpPassword()
+ public function testSetSmtpPassword(): void
{
$ret = $this->obj->setSmtpPassword('foobar');
$this->assertSame($ret, $this->obj);
@@ -103,7 +103,7 @@ public function testSetSmtpPassword()
$this->obj->setSmtpPassword([]);
}
- public function testSetDefaultFrom()
+ public function testSetDefaultFrom(): void
{
$ret = $this->obj->setDefaultFrom('test@example.com');
$this->assertSame($ret, $this->obj);
@@ -119,7 +119,7 @@ public function testSetDefaultFrom()
$this->obj->setDefaultFrom(123);
}
- public function testSetDefaultReplyTo()
+ public function testSetDefaultReplyTo(): void
{
$ret = $this->obj->setDefaultReplyTo('test@example.com');
$this->assertSame($ret, $this->obj);
@@ -135,21 +135,21 @@ public function testSetDefaultReplyTo()
$this->obj->setDefaultReplyTo(123);
}
- public function testSetDefaultLogEnabled()
+ public function testSetDefaultLogEnabled(): void
{
$ret = $this->obj->setDefaultLogEnabled(true);
$this->assertSame($ret, $this->obj);
$this->assertEquals(true, $this->obj->defaultLogEnabled());
}
- public function testSetDefaultTrackOpenEnabled()
+ public function testSetDefaultTrackOpenEnabled(): void
{
$ret = $this->obj->setDefaultTrackOpenEnabled(true);
$this->assertSame($ret, $this->obj);
$this->assertEquals(true, $this->obj->defaultTrackOpenEnabled());
}
- public function testSetDefaultTrackLinksEnabled()
+ public function testSetDefaultTrackLinksEnabled(): void
{
$ret = $this->obj->setDefaultTrackLinksEnabled(true);
$this->assertSame($ret, $this->obj);
diff --git a/packages/email/tests/Charcoal/Email/EmailQueueItemTest.php b/packages/email/tests/Charcoal/Email/EmailQueueItemTest.php
index 173f407ac..4cb7f42e1 100644
--- a/packages/email/tests/Charcoal/Email/EmailQueueItemTest.php
+++ b/packages/email/tests/Charcoal/Email/EmailQueueItemTest.php
@@ -16,8 +16,6 @@ class EmailQueueItemTest extends AbstractTestCase
/**
* Set up the test.
- *
- * @return void
*/
protected function setUp(): void
{
@@ -26,20 +24,15 @@ protected function setUp(): void
/**
* Create tested class.
- *
- * @return EmailQueueItem
*/
- public function createObj()
+ public function createObj(): \Charcoal\Email\EmailQueueItem
{
return new EmailQueueItem([
'logger' => new NullLogger()
]);
}
- /**
- * @return void
- */
- public function testConstructor()
+ public function testConstructor(): void
{
$this->assertInstanceOf(QueueItemInterface::class, $this->obj);
}
diff --git a/packages/email/tests/Charcoal/Email/EmailQueueManagerTest.php b/packages/email/tests/Charcoal/Email/EmailQueueManagerTest.php
index b0b0324dc..747a28e68 100644
--- a/packages/email/tests/Charcoal/Email/EmailQueueManagerTest.php
+++ b/packages/email/tests/Charcoal/Email/EmailQueueManagerTest.php
@@ -26,7 +26,7 @@ protected function setUp(): void
]);
}
- public function testProto()
+ public function testProto(): void
{
$ret = $this->obj->queueItemProto();
$this->assertInstanceOf(EmailQueueItem::class, $ret);
diff --git a/packages/email/tests/Charcoal/Email/EmailTest.php b/packages/email/tests/Charcoal/Email/EmailTest.php
index c03d6f48f..71e4ff39e 100644
--- a/packages/email/tests/Charcoal/Email/EmailTest.php
+++ b/packages/email/tests/Charcoal/Email/EmailTest.php
@@ -32,7 +32,7 @@ protected function setUp(): void
]);
}
- public function testSetData()
+ public function testSetData(): void
{
$obj = $this->obj;
$ret = $obj->setData([
@@ -69,7 +69,7 @@ public function testSetData()
$this->assertEquals(true, $obj->trackLinksEnabled());
}
- public function testSetCampaign()
+ public function testSetCampaign(): void
{
$obj = $this->obj;
$ret = $obj->setCampaign('foo');
@@ -77,7 +77,7 @@ public function testSetCampaign()
$this->assertEquals('foo', $obj->campaign());
}
- public function testGenerateCampaign()
+ public function testGenerateCampaign(): void
{
$obj = $this->obj;
$ret = $obj->campaign();
@@ -92,7 +92,7 @@ public function testGenerateCampaign()
* - Resets the "to" value before setting it, at every call.
* - Throws an exception if the to argument is not a string.
*/
- public function testSetTo()
+ public function testSetTo(): void
{
$obj = $this->obj;
@@ -123,7 +123,7 @@ public function testSetTo()
$obj->setTo(false);
}
- public function testAddTo()
+ public function testAddTo(): void
{
$obj = $this->obj;
$ret = $obj->addTo('test@example.com');
@@ -137,7 +137,7 @@ public function testAddTo()
$obj->addTo(false);
}
- public function testSetCc()
+ public function testSetCc(): void
{
$obj = $this->obj;
@@ -160,7 +160,7 @@ public function testSetCc()
$obj->SetCc(false);
}
- public function testAddCc()
+ public function testAddCc(): void
{
$obj = $this->obj;
$ret = $obj->addCc('test@example.com');
@@ -174,7 +174,7 @@ public function testAddCc()
$obj->addCc(false);
}
- public function testSetBcc()
+ public function testSetBcc(): void
{
$obj = $this->obj;
@@ -197,7 +197,7 @@ public function testSetBcc()
$obj->setBcc(false);
}
- public function testAddBcc()
+ public function testAddBcc(): void
{
$obj = $this->obj;
$ret = $obj->addBcc('test@example.com');
@@ -211,7 +211,7 @@ public function testAddBcc()
$obj->addBcc(false);
}
- public function testSetFrom()
+ public function testSetFrom(): void
{
$obj = $this->obj;
//$config = $obj->config()->setDefaultFrom('default@example.com');
@@ -231,7 +231,7 @@ public function testSetFrom()
$obj->setFrom(false);
}
- public function testSetReplyTo()
+ public function testSetReplyTo(): void
{
$obj = $this->obj;
//$config = $obj->config()->setDefaultReplyTo('default@example.com');
@@ -251,7 +251,7 @@ public function testSetReplyTo()
$obj->setReplyTo(false);
}
- public function testSetSubject()
+ public function testSetSubject(): void
{
$obj = $this->obj;
$ret = $obj->setSubject('foo');
@@ -259,7 +259,7 @@ public function testSetSubject()
$this->assertEquals('foo', $obj->subject());
}
- public function testSetMsgHtml()
+ public function testSetMsgHtml(): void
{
$obj = $this->obj;
$ret = $obj->setMsgHtml('foo');
@@ -267,7 +267,7 @@ public function testSetMsgHtml()
$this->assertEquals('foo', $obj->msgHtml());
}
- public function testSetMsgTxt()
+ public function testSetMsgTxt(): void
{
$obj = $this->obj;
$ret = $obj->setMsgTxt('foo');
@@ -275,7 +275,7 @@ public function testSetMsgTxt()
$this->assertEquals('foo', $obj->msgTxt());
}
- public function testConvertHtml()
+ public function testConvertHtml(): void
{
$obj = $this->obj;
$html = file_get_contents(__DIR__.'/../../data/example.html');
@@ -287,7 +287,7 @@ public function testConvertHtml()
$this->assertEquals($txt, $obj->msgTxt());
}
- public function testSetAttachments()
+ public function testSetAttachments(): void
{
$obj = $this->obj;
$ret = $obj->setAttachments(['foo']);
@@ -295,7 +295,7 @@ public function testSetAttachments()
$this->assertEquals(['foo'], $obj->attachments());
}
- public function testSetLogEnabled()
+ public function testSetLogEnabled(): void
{
$obj = $this->obj;
// $this->config()->setDefaultLogEnabled(false);
@@ -309,7 +309,7 @@ public function testSetLogEnabled()
$this->assertNotTrue($obj->logEnabled());
}
- public function testSetTrackOpenEnabled()
+ public function testSetTrackOpenEnabled(): void
{
$obj = $this->obj;
// $this->config()->setDefaultTrackOpenEnabled(false);
@@ -323,7 +323,7 @@ public function testSetTrackOpenEnabled()
$this->assertNotTrue($obj->trackOpenEnabled());
}
- public function testSetTrackLinksEnabled()
+ public function testSetTrackLinksEnabled(): void
{
$obj = $this->obj;
// $this->config()->setDefaultTrackLinksEnabled(false);
diff --git a/packages/email/tests/Charcoal/Email/Objects/EmailLogTest.php b/packages/email/tests/Charcoal/Email/Objects/EmailLogTest.php
index d1ebb3f9c..80f8445de 100644
--- a/packages/email/tests/Charcoal/Email/Objects/EmailLogTest.php
+++ b/packages/email/tests/Charcoal/Email/Objects/EmailLogTest.php
@@ -22,7 +22,7 @@ protected function setUp(): void
]);
}
- public function testSetData()
+ public function testSetData(): void
{
$ret = $this->obj->setData([
'queue_id' => 'foo',
@@ -44,7 +44,7 @@ public function testSetData()
$this->assertEquals(new DateTime('2010-01-02 03:45:00'), $this->obj->sendTs());
}
- public function testKey()
+ public function testKey(): void
{
$this->assertEquals('id', $this->obj->key());
}
diff --git a/packages/email/tests/Charcoal/Email/Services/TrackerTest.php b/packages/email/tests/Charcoal/Email/Services/TrackerTest.php
index 51844cfa1..db1e8e58b 100644
--- a/packages/email/tests/Charcoal/Email/Services/TrackerTest.php
+++ b/packages/email/tests/Charcoal/Email/Services/TrackerTest.php
@@ -15,15 +15,12 @@
*/
class TrackerTest extends TestCase
{
- /**
- * @var Tracker
- */
- private $obj;
+ private \Charcoal\Email\Services\Tracker $obj;
/**
* @var Email
*/
- private $email;
+ private mixed $email;
/**
*
@@ -39,7 +36,7 @@ public function setUp(): void
/**
*
*/
- public function testAddOpenTrackingImageWithBody()
+ public function testAddOpenTrackingImageWithBody(): void
{
$html = '
Hello
';
$this->email->setMsgHtml($html);
@@ -52,7 +49,7 @@ public function testAddOpenTrackingImageWithBody()
/**
*
*/
- public function testAddOpenTrackingImageWithoutBody()
+ public function testAddOpenTrackingImageWithoutBody(): void
{
$html = '
Hello
';
$this->email->setMsgHtml($html);
@@ -64,7 +61,7 @@ public function testAddOpenTrackingImageWithoutBody()
/**
*
*/
- public function testReplaceLinksWithTracker()
+ public function testReplaceLinksWithTracker(): void
{
$html = '