diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml
index 60c800b..cfc0fb5 100644
--- a/.github/workflows/php.yml
+++ b/.github/workflows/php.yml
@@ -16,16 +16,16 @@ jobs:
cs:
uses: bedita/github-workflows/.github/workflows/php-cs.yml@v2
with:
- php_versions: '["8.3"]'
+ php_versions: '["8.4"]'
stan:
uses: bedita/github-workflows/.github/workflows/php-stan.yml@v2
with:
- php_versions: '["8.3"]'
+ php_versions: '["8.4"]'
unit-5:
uses: bedita/github-workflows/.github/workflows/php-unit.yml@v2
with:
- php_versions: '["8.3"]'
+ php_versions: '["8.3","8.4"]'
bedita_version: '5'
coverage_min_percentage: 99
diff --git a/composer.json b/composer.json
index d40a007..25dd92e 100644
--- a/composer.json
+++ b/composer.json
@@ -22,24 +22,21 @@
"require": {
"php": ">=8.3",
"bedita/php-sdk": "^4.1.0",
- "cakephp/cakephp": "^4.5",
+ "cakephp/cakephp": "^5.0",
"firebase/php-jwt": "^6.9",
- "cakephp/twig-view": "^1.3.0"
+ "cakephp/twig-view": "^2"
},
"require-dev": {
- "cakephp/authentication": "^2.9",
- "cakephp/authorization": "^2.2",
- "cakephp/cakephp-codesniffer": "^4.7",
+ "cakephp/authentication": "^3.0.3",
+ "cakephp/authorization": "^3.1.2",
+ "cakephp/cakephp-codesniffer": "^5.0",
"league/oauth2-client": "^2.6",
"josegonzalez/dotenv": "^3.2",
- "phpstan/phpstan": "^1.10",
- "phpstan/extension-installer": "^1.2",
+ "phpstan/extension-installer": "^1.4",
+ "phpstan/phpstan": "^1.12",
+ "phpstan/phpstan-phpunit": "^1.4",
"phpstan/phpstan-deprecation-rules": "^1.2",
- "phpunit/phpunit": "^9.6"
- },
- "suggest": {
- "cakephp/authentication": "^2.9 To use \"ApiIdentifier\", \"Identity\", \"IdentityHelper\" and other authentication features",
- "cakephp/authorization": "^2.2 To use \"RequestPolicy\" and other authorization features"
+ "phpunit/phpunit": "^11.1.3"
},
"autoload": {
"psr-4": {
@@ -67,8 +64,8 @@
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true,
- "phpstan/extension-installer": true,
- "cakephp/plugin-installer": true
+ "cakephp/plugin-installer": true,
+ "phpstan/extension-installer": true
}
}
}
diff --git a/config/bootstrap.php b/config/bootstrap.php
index 0166d5a..09611bb 100644
--- a/config/bootstrap.php
+++ b/config/bootstrap.php
@@ -1,4 +1,5 @@
for more details.
*/
+/*
+ * Configure paths required to find CakePHP + general filepath constants
+ */
+require __DIR__ . DIRECTORY_SEPARATOR . 'paths.php';
+
+/*
+ * Bootstrap CakePHP.
+ *
+ * Does the various bits of setup that CakePHP needs to do.
+ * This includes:
+ *
+ * - Registering the CakePHP autoloader.
+ * - Setting the default application paths.
+ */
+require CORE_PATH . 'config' . DS . 'bootstrap.php';
+
use Cake\Core\Configure;
+/**
+ * Load global functions.
+ */
+require CAKE . 'functions.php';
+
/**
* Setup API config if missing
*/
diff --git a/config/paths.php b/config/paths.php
new file mode 100644
index 0000000..6d5dad7
--- /dev/null
+++ b/config/paths.php
@@ -0,0 +1,66 @@
+
-
-
+
+
./src/
-
+
@@ -16,6 +23,6 @@
-
+
diff --git a/src/ApiClientProvider.php b/src/ApiClientProvider.php
index 722e282..f018223 100644
--- a/src/ApiClientProvider.php
+++ b/src/ApiClientProvider.php
@@ -27,9 +27,9 @@ class ApiClientProvider
/**
* BEdita API client
*
- * @var \BEdita\SDK\BEditaClient
+ * @var \BEdita\SDK\BEditaClient|null
*/
- private $apiClient = null;
+ private ?BEditaClient $apiClient = null;
/**
* Read singleton API client data.
diff --git a/src/Authenticator/OAuth2Authenticator.php b/src/Authenticator/OAuth2Authenticator.php
index d1e8667..16fe5b4 100644
--- a/src/Authenticator/OAuth2Authenticator.php
+++ b/src/Authenticator/OAuth2Authenticator.php
@@ -23,6 +23,7 @@
use Cake\Routing\Router;
use Cake\Utility\Hash;
use Firebase\JWT\JWT;
+use League\OAuth2\Client\Provider\AbstractProvider;
use Psr\Http\Message\ServerRequestInterface;
/**
@@ -37,9 +38,9 @@ class OAuth2Authenticator extends AbstractAuthenticator
/**
* External Auth provider
*
- * @var \League\OAuth2\Client\Provider\AbstractProvider
+ * @var \League\OAuth2\Client\Provider\AbstractProvider|null
*/
- protected $provider = null;
+ protected ?AbstractProvider $provider = null;
/**
* Authentication URL key
@@ -59,7 +60,7 @@ class OAuth2Authenticator extends AbstractAuthenticator
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'sessionKey' => 'oauth2state',
'redirect' => ['_name' => 'login'],
'providers' => [],
diff --git a/src/Command/CacheClearallCommand.php b/src/Command/CacheClearallCommand.php
index 10eb8ed..6df7308 100644
--- a/src/Command/CacheClearallCommand.php
+++ b/src/Command/CacheClearallCommand.php
@@ -17,7 +17,6 @@
use Cake\Command\CacheClearallCommand as BaseCommand;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
-use Cake\Filesystem\Folder;
/**
* Extend `CacheClearallCommand` to remove Twig compiled files.
@@ -37,8 +36,7 @@ public function execute(Arguments $args, ConsoleIo $io): ?int
return parent::execute($args, $io);
}
- $folder = new Folder($path); /* @phpstan-ignore-line */
- $folder->delete();
+ unlink($path);
$io->out('Cleared twig cache');
return parent::execute($args, $io);
diff --git a/src/Controller/ApiProxyTrait.php b/src/Controller/ApiProxyTrait.php
index e2c2577..bf7018f 100644
--- a/src/Controller/ApiProxyTrait.php
+++ b/src/Controller/ApiProxyTrait.php
@@ -14,13 +14,17 @@
*/
namespace BEdita\WebTools\Controller;
+use BEdita\SDK\BEditaClient;
use BEdita\SDK\BEditaClientException;
use BEdita\WebTools\ApiClientProvider;
use Cake\Http\Exception\BadRequestException;
use Cake\Http\Exception\MethodNotAllowedException;
+use Cake\Http\Response;
+use Cake\Http\ServerRequest;
use Cake\Routing\Router;
use Cake\Utility\Hash;
use Cake\View\ViewVarsTrait;
+use Throwable;
/**
* Use this Trait in a controller to directly proxy requests to BE4 API.
@@ -45,28 +49,28 @@ trait ApiProxyTrait
*
* @var \Cake\Http\ServerRequest
*/
- protected $request;
+ protected ServerRequest $request;
/**
* An instance of a Response object that contains information about the impending response.
*
* @var \Cake\Http\Response
*/
- protected $response;
+ protected Response $response;
/**
* BEdita API client
*
- * @var \BEdita\SDK\BEditaClient
+ * @var \BEdita\SDK\BEditaClient|null
*/
- protected $apiClient = null;
+ protected ?BEditaClient $apiClient = null;
/**
* Base URL used for mask links.
*
* @var string
*/
- protected $baseUrl = '';
+ protected string $baseUrl = '';
/**
* @inheritDoc
@@ -88,7 +92,7 @@ public function initialize(): void
* @param string $path The path on which build base URL
* @return void
*/
- protected function setBaseUrl($path): void
+ protected function setBaseUrl(string $path): void
{
$requestPath = $this->request->getPath();
$pos = strpos(rawurldecode($requestPath), $path);
@@ -106,7 +110,7 @@ protected function setBaseUrl($path): void
* @param string $path The path for API request
* @return void
*/
- public function get($path = ''): void
+ public function get(string $path = ''): void
{
$this->apiRequest([
'method' => 'get',
@@ -121,7 +125,7 @@ public function get($path = ''): void
* @param string $path The path for API request
* @return void
*/
- public function post($path = ''): void
+ public function post(string $path = ''): void
{
$this->apiRequest([
'method' => 'post',
@@ -136,7 +140,7 @@ public function post($path = ''): void
* @param string $path The path for API request
* @return void
*/
- public function patch($path = ''): void
+ public function patch(string $path = ''): void
{
$this->apiRequest([
'method' => 'patch',
@@ -151,7 +155,7 @@ public function patch($path = ''): void
* @param string $path The path for API request
* @return void
*/
- public function delete($path = ''): void
+ public function delete(string $path = ''): void
{
$this->apiRequest([
'method' => 'delete',
@@ -216,7 +220,7 @@ protected function apiRequest(array $options): void
$response = $this->maskResponseLinks($response);
$this->set($response);
$this->viewBuilder()->setOption('serialize', array_keys($response));
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
$this->handleError($e);
}
}
@@ -228,7 +232,7 @@ protected function apiRequest(array $options): void
* @param \Throwable $error The error thrown.
* @return void
*/
- protected function handleError(\Throwable $error): void
+ protected function handleError(Throwable $error): void
{
$status = $error->getCode();
if ($status < 100 || $status > 599) {
diff --git a/src/Controller/Component/ApiCacheComponent.php b/src/Controller/Component/ApiCacheComponent.php
index 69fff2a..02e4090 100644
--- a/src/Controller/Component/ApiCacheComponent.php
+++ b/src/Controller/Component/ApiCacheComponent.php
@@ -31,7 +31,7 @@ class ApiCacheComponent extends Component
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'cache' => '_apicache_',
];
@@ -40,7 +40,7 @@ class ApiCacheComponent extends Component
*
* @var array
*/
- protected $cacheIndex = [];
+ protected array $cacheIndex = [];
/**
* Use 'default' as fallback if no cache configuration is found.
diff --git a/src/Error/ExceptionRenderer.php b/src/Error/ExceptionRenderer.php
index 92fdb5b..7de9533 100644
--- a/src/Error/ExceptionRenderer.php
+++ b/src/Error/ExceptionRenderer.php
@@ -20,6 +20,8 @@
use Cake\Error\Renderer\WebExceptionRenderer;
use Cake\Http\Response;
use Cake\Log\LogTrait;
+use Exception;
+use Throwable;
/**
* Custom exception renderer class.
@@ -32,7 +34,7 @@ class ExceptionRenderer extends WebExceptionRenderer
/**
* @inheritDoc
*/
- protected function _template(\Throwable $exception, string $method, int $code): string
+ protected function _template(Throwable $exception, string $method, int $code): string
{
$template = 'error500';
if ($code < 500) {
@@ -60,7 +62,7 @@ protected function _getController(): Controller
*
* Handle BEditaClientException.
*/
- protected function getHttpCode(\Throwable $exception): int
+ protected function getHttpCode(Throwable $exception): int
{
if ($exception instanceof BEditaClientException) {
return $exception->getCode();
@@ -82,7 +84,7 @@ protected function _outputMessageSafe(string $template): Response
try {
$view = $this->controller->createView();
$body = $view->render($template, 'error');
- } catch (\Exception $e) {
+ } catch (Exception $e) {
// first log the new exception to trace the new error too.
$this->log($e->getMessage());
diff --git a/src/Http/BaseClient.php b/src/Http/BaseClient.php
index dadcd55..2674fd9 100644
--- a/src/Http/BaseClient.php
+++ b/src/Http/BaseClient.php
@@ -22,6 +22,7 @@
use Cake\Http\Client\Response;
use Cake\Log\LogTrait;
use Cake\Validation\Validator;
+use InvalidArgumentException;
/**
* Base class for clients.
@@ -36,7 +37,7 @@ abstract class BaseClient
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'auth' => null,
'logLevel' => 'error',
'url' => null,
@@ -47,7 +48,7 @@ abstract class BaseClient
*
* @var \Cake\Http\Client
*/
- protected $client;
+ protected Client $client;
/**
* Constructor. Initialize HTTP client.
@@ -71,7 +72,7 @@ public function __construct(array $config = [])
protected function defaultConfigName(): string
{
$shortName = App::shortName(static::class, 'Http', 'Client');
- [$plugin, $name] = pluginSplit($shortName);
+ [, $name] = pluginSplit($shortName);
return $name;
}
@@ -100,7 +101,9 @@ protected function validateConf(Validator $validator): void
{
$errors = $validator->validate($this->getConfig());
if (!empty($errors)) {
- throw new \InvalidArgumentException(sprintf('%s client config not valid: %s', static::class, json_encode($errors)));
+ throw new InvalidArgumentException(
+ sprintf('%s client config not valid: %s', static::class, json_encode($errors))
+ );
}
}
diff --git a/src/Identifier/ApiIdentifier.php b/src/Identifier/ApiIdentifier.php
index 16884a4..8e5604b 100644
--- a/src/Identifier/ApiIdentifier.php
+++ b/src/Identifier/ApiIdentifier.php
@@ -15,6 +15,7 @@
namespace BEdita\WebTools\Identifier;
+use ArrayAccess;
use Authentication\Identifier\AbstractIdentifier;
use BEdita\SDK\BEditaClientException;
use BEdita\WebTools\ApiClientProvider;
@@ -36,7 +37,7 @@ class ApiIdentifier extends AbstractIdentifier
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'fields' => [
self::CREDENTIAL_USERNAME => 'username',
self::CREDENTIAL_PASSWORD => 'password',
@@ -46,7 +47,7 @@ class ApiIdentifier extends AbstractIdentifier
/**
* @inheritDoc
*/
- public function identify(array $data)
+ public function identify(array $data): ArrayAccess|array|null
{
$usernameField = $this->getConfig('fields.' . self::CREDENTIAL_USERNAME);
$passwordField = $this->getConfig('fields.' . self::CREDENTIAL_PASSWORD);
@@ -86,7 +87,7 @@ public function identify(array $data)
* @param string $message The error message
* @return void
*/
- protected function setError($message)
+ protected function setError(string $message): void
{
$this->_errors[] = $message;
}
diff --git a/src/Identifier/OAuth2Identifier.php b/src/Identifier/OAuth2Identifier.php
index 6164bb0..c671734 100644
--- a/src/Identifier/OAuth2Identifier.php
+++ b/src/Identifier/OAuth2Identifier.php
@@ -14,6 +14,7 @@
*/
namespace BEdita\WebTools\Identifier;
+use ArrayAccess;
use Authentication\Identifier\AbstractIdentifier;
use BEdita\SDK\BEditaClientException;
use BEdita\WebTools\ApiClientProvider;
@@ -37,7 +38,7 @@ class OAuth2Identifier extends AbstractIdentifier
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'fields' => [
'auth_provider' => 'auth_provider',
'provider_username' => 'provider_username',
@@ -52,7 +53,7 @@ class OAuth2Identifier extends AbstractIdentifier
/**
* @inheritDoc
*/
- public function identify(array $credentials)
+ public function identify(array $credentials): ArrayAccess|array|null
{
try {
$result = $this->externalAuth($credentials);
diff --git a/src/Plugin.php b/src/Plugin.php
index 483e0d5..395012e 100644
--- a/src/Plugin.php
+++ b/src/Plugin.php
@@ -29,7 +29,7 @@ class Plugin extends BasePlugin
*
* @var bool
*/
- protected $routesEnabled = false;
+ protected bool $routesEnabled = false;
/**
* Use `cache clear_all` from BEdita\WebTools\Command\CacheClearallCommand
@@ -37,7 +37,7 @@ class Plugin extends BasePlugin
* @param \Cake\Console\CommandCollection $commands Console commands.
* @return \Cake\Console\CommandCollection
*/
- public function console($commands): CommandCollection
+ public function console(CommandCollection $commands): CommandCollection
{
parent::console($commands);
$commands->remove('cache clear_all');
diff --git a/src/Policy/RequestPolicy.php b/src/Policy/RequestPolicy.php
index e548396..b996e71 100644
--- a/src/Policy/RequestPolicy.php
+++ b/src/Policy/RequestPolicy.php
@@ -18,10 +18,12 @@
use Authorization\Policy\Exception\MissingMethodException;
use Authorization\Policy\RequestPolicyInterface;
use Authorization\Policy\Result;
+use Authorization\Policy\ResultInterface;
use Cake\Core\App;
use Cake\Core\InstanceConfigTrait;
use Cake\Http\ServerRequest;
use Cake\Utility\Hash;
+use LogicException;
/**
* RequestPolicy class.
@@ -68,7 +70,7 @@ class RequestPolicy implements RequestPolicyInterface
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'rules' => [],
'ruleRequired' => false,
];
@@ -89,9 +91,9 @@ public function __construct(array $config = [])
*
* @param \Authorization\IdentityInterface|null $identity Identity
* @param \Cake\Http\ServerRequest $request Server Request
- * @return bool|\Authorization\Policy\ResultInterface
+ * @return \Authorization\Policy\ResultInterface|bool
*/
- public function canAccess(?IdentityInterface $identity, ServerRequest $request)
+ public function canAccess(?IdentityInterface $identity, ServerRequest $request): bool|ResultInterface
{
$rule = $this->getRule($request);
if (empty($rule)) {
@@ -115,7 +117,7 @@ public function canAccess(?IdentityInterface $identity, ServerRequest $request)
}
if (!is_string($rule)) {
- throw new \LogicException(sprintf(
+ throw new LogicException(sprintf(
'Invalid rule for %s::%s() in RequestPolicy',
$request->getParam('controller'),
$request->getParam('action')
@@ -174,7 +176,7 @@ protected function applyRolesPolicy(IdentityInterface $identity, array $roles):
* @param \Cake\Http\ServerRequest $request Server Request
* @return mixed
*/
- protected function getRule(ServerRequest $request)
+ protected function getRule(ServerRequest $request): mixed
{
$controller = $request->getParam('controller');
$rule = $this->getConfig(sprintf('rules.%s', $controller));
@@ -187,7 +189,7 @@ protected function getRule(ServerRequest $request)
}
if (!is_array($rule)) {
- throw new \LogicException(sprintf('Invalid Rule for %s in RequestPolicy', $controller));
+ throw new LogicException(sprintf('Invalid Rule for %s in RequestPolicy', $controller));
}
$action = $request->getParam('action');
diff --git a/src/SingletonTrait.php b/src/SingletonTrait.php
index 58a2422..906720a 100644
--- a/src/SingletonTrait.php
+++ b/src/SingletonTrait.php
@@ -60,7 +60,7 @@ private function __clone()
*
* @return static|null
*/
- final public static function getInstance()
+ final public static function getInstance(): ?static
{
if (self::$uniqueInstance === null) {
self::$uniqueInstance = new static();
diff --git a/src/Utility/ApiTools.php b/src/Utility/ApiTools.php
index 16e61b0..abf10a0 100644
--- a/src/Utility/ApiTools.php
+++ b/src/Utility/ApiTools.php
@@ -1,5 +1,4 @@
$entity) {
- $response['included'][$key]['attributes'] = array_diff_key($entity['attributes'], array_flip($keysToRemove));
+ $response['included'][$key]['attributes'] = array_diff_key(
+ $entity['attributes'],
+ array_flip($keysToRemove)
+ );
}
}
@@ -56,7 +61,10 @@ public static function removeAttributes(array $response, array $keysToRemove): a
// remove attributes from included entities
if (isset($response['included'])) {
foreach ($response['included'] as $key => $entity) {
- $response['included'][$key]['attributes'] = array_diff_key($entity['attributes'], array_flip($keysToRemove));
+ $response['included'][$key]['attributes'] = array_diff_key(
+ $entity['attributes'],
+ array_flip($keysToRemove)
+ );
}
}
diff --git a/src/Utility/Asset/AssetStrategy.php b/src/Utility/Asset/AssetStrategy.php
index 730fac6..06371b7 100644
--- a/src/Utility/Asset/AssetStrategy.php
+++ b/src/Utility/Asset/AssetStrategy.php
@@ -31,7 +31,7 @@ abstract class AssetStrategy implements AssetStrategyInterface
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'manifestPath' => '',
];
@@ -40,7 +40,7 @@ abstract class AssetStrategy implements AssetStrategyInterface
*
* @var array
*/
- protected $assets = [];
+ protected array $assets = [];
/**
* Initialize an asset strategy instance. Called after the constructor.
diff --git a/src/Utility/Asset/AssetStrategyInterface.php b/src/Utility/Asset/AssetStrategyInterface.php
index 27b8c41..578b4b0 100644
--- a/src/Utility/Asset/AssetStrategyInterface.php
+++ b/src/Utility/Asset/AssetStrategyInterface.php
@@ -24,9 +24,9 @@ interface AssetStrategyInterface
*
* @param string $name The name used to looking for the asset
* @param string|null $extension Optional asset extension as 'js' or 'css'
- * @return string|array
+ * @return array|string|null
*/
- public function get(string $name, ?string $extension = null);
+ public function get(string $name, ?string $extension = null): string|array|null;
/**
* Load assets map optionally using a file path.
diff --git a/src/Utility/Asset/Strategy/EntrypointsStrategy.php b/src/Utility/Asset/Strategy/EntrypointsStrategy.php
index ce5e2fc..1aa8a37 100644
--- a/src/Utility/Asset/Strategy/EntrypointsStrategy.php
+++ b/src/Utility/Asset/Strategy/EntrypointsStrategy.php
@@ -15,7 +15,6 @@
namespace BEdita\WebTools\Utility\Asset\Strategy;
use BEdita\WebTools\Utility\Asset\AssetStrategy;
-use Cake\Utility\Hash;
/**
* Entrypoints asset strategy.
@@ -50,20 +49,19 @@ class EntrypointsStrategy extends AssetStrategy
/**
* @inheritDoc
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'manifestPath' => WWW_ROOT . 'build' . DS . 'entrypoints.json',
];
/**
* @inheritDoc
*/
- public function get(string $name, ?string $extension = null)
+ public function get(string $name, ?string $extension = null): array|string|null
{
- $path = sprintf('entrypoints.%s', $name);
if (!empty($extension)) {
- $path .= sprintf('.%s', $extension);
+ return $this->assets['entrypoints'][$name][$extension] ?? null;
}
- return Hash::get($this->assets, $path);
+ return $this->assets['entrypoints'][$name] ?? null;
}
}
diff --git a/src/Utility/Asset/Strategy/RevManifestStrategy.php b/src/Utility/Asset/Strategy/RevManifestStrategy.php
index 5d1fe71..0a97ab5 100644
--- a/src/Utility/Asset/Strategy/RevManifestStrategy.php
+++ b/src/Utility/Asset/Strategy/RevManifestStrategy.php
@@ -32,23 +32,19 @@ class RevManifestStrategy extends AssetStrategy
/**
* @inheritDoc
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'manifestPath' => WWW_ROOT . 'rev-manifest.json',
];
/**
* @inheritDoc
*/
- public function get(string $name, ?string $extension = null)
+ public function get(string $name, ?string $extension = null): array|string|null
{
if (!empty($extension)) {
- $name .= sprintf('.%s', $extension);
+ return $this->assets[sprintf('%s.%s', $name, $extension)] ?? null;
}
- if (empty($this->assets[$name])) {
- return null;
- }
-
- return $this->assets[$name];
+ return $this->assets[$name] ?? null;
}
}
diff --git a/src/Utility/AssetsRevisions.php b/src/Utility/AssetsRevisions.php
index 4199eb8..337653f 100644
--- a/src/Utility/AssetsRevisions.php
+++ b/src/Utility/AssetsRevisions.php
@@ -15,6 +15,7 @@
namespace BEdita\WebTools\Utility;
use BEdita\WebTools\Utility\Asset\AssetStrategyInterface;
+use LogicException;
/**
* Utility class to handle asset names with revisions/signatures.
@@ -26,9 +27,9 @@ class AssetsRevisions
/**
* The asset strategy adopted.
*
- * @var \BEdita\WebTools\Utility\Asset\AssetStrategyInterface
+ * @var \BEdita\WebTools\Utility\Asset\AssetStrategyInterface|null
*/
- protected static $strategy = null;
+ protected static ?AssetStrategyInterface $strategy = null;
/**
* Set an asset strategy to be used.
@@ -67,9 +68,9 @@ public static function clearStrategy(): void
*
* @param string $name Canonical asset name
* @param string $extension Optional extension to use to search asset, like 'js' or 'css'
- * @return string|array
+ * @return array|string
*/
- public static function get(string $name, ?string $extension = null)
+ public static function get(string $name, ?string $extension = null): string|array
{
$strategy = static::getStrategy();
if ($strategy === null) {
@@ -112,7 +113,7 @@ public static function loadManifest(?string $path = null): void
{
$strategy = static::getStrategy();
if ($strategy === null) {
- throw new \LogicException('Missing asset strategy');
+ throw new LogicException('Missing asset strategy');
}
$strategy->loadAssets($path);
diff --git a/src/View/Helper/HtmlHelper.php b/src/View/Helper/HtmlHelper.php
index 40a54b7..a364a4b 100644
--- a/src/View/Helper/HtmlHelper.php
+++ b/src/View/Helper/HtmlHelper.php
@@ -30,7 +30,7 @@ class HtmlHelper extends CakeHtmlHelper
/**
* Meta data for helper
*/
- protected $metadata = [
+ protected array $metadata = [
'description' => '',
'author' => '',
'docType' => '',
@@ -321,9 +321,9 @@ public function metaTwitter(array $data): string
* @param array $data The data
* @param string $field The field
* @param array|string|null $defaultVal The default val
- * @return array|string
+ * @return array|string|null
*/
- public function getMeta(array $data, string $field, $defaultVal = null)
+ public function getMeta(array $data, string $field, array|string|null $defaultVal = null): array|string|null
{
$meta = $data + $this->metadata;
@@ -369,7 +369,7 @@ public function css($url, array $options = []): ?string
* @param array $options The options to apply
* @return string|null
*/
- public function assets($name, array $options = []): ?string
+ public function assets(string $name, array $options = []): ?string
{
return sprintf(
'%s%s',
diff --git a/src/View/Helper/IdentityHelper.php b/src/View/Helper/IdentityHelper.php
index 7892930..2fa4f03 100644
--- a/src/View/Helper/IdentityHelper.php
+++ b/src/View/Helper/IdentityHelper.php
@@ -15,6 +15,7 @@
namespace BEdita\WebTools\View\Helper;
use Authentication\View\Helper\IdentityHelper as AuthenticationIdentityHelper;
+use BadMethodCallException;
/**
* Extends IdentityHelper allowing to delegate methods to the identity.
@@ -29,7 +30,7 @@ class IdentityHelper extends AuthenticationIdentityHelper
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'identityAttribute' => 'identity',
'delegateMethods' => [
'hasRole',
@@ -43,14 +44,14 @@ class IdentityHelper extends AuthenticationIdentityHelper
* @param array $args The arguments for the method.
* @return mixed
*/
- public function __call($method, $args)
+ public function __call(string $method, array $args): mixed
{
if (!in_array($method, (array)$this->getConfig('delegateMethods'))) {
- throw new \BadMethodCallException("Cannot call `{$method}`. Make sure to add it to `delegateMethods`.");
+ throw new BadMethodCallException("Cannot call `{$method}`. Make sure to add it to `delegateMethods`.");
}
if (!is_object($this->_identity)) {
- throw new \BadMethodCallException("Cannot call `{$method}` on stored identity since it is not an object.");
+ throw new BadMethodCallException("Cannot call `{$method}` on stored identity since it is not an object.");
}
$call = [$this->_identity, $method];
diff --git a/src/View/Helper/ThumbHelper.php b/src/View/Helper/ThumbHelper.php
index 57506f5..b3fef2b 100644
--- a/src/View/Helper/ThumbHelper.php
+++ b/src/View/Helper/ThumbHelper.php
@@ -19,6 +19,7 @@
use Cake\Log\LogTrait;
use Cake\Utility\Hash;
use Cake\View\Helper;
+use Exception;
/**
* Helper to obtain thumbnail url
@@ -32,7 +33,7 @@ class ThumbHelper extends Helper
*
* @var array
*/
- protected $_defaultConfig = [
+ protected array $_defaultConfig = [
'cache' => '_thumbs_',
];
@@ -91,13 +92,16 @@ public function initialize(array $config): void
* NO_URL: url not present in api response
* OK: thumb available, ready and with a proper url
*
- * @param int|string $imageId The image ID
+ * @param string|int|null $imageId The image ID
* @param array|null $options The thumbs options
* @param string|null $url The thumb url to populate when static::OK
* @return int|null
*/
- public function status($imageId, ?array $options = ['preset' => 'default'], &$url = ''): ?int
- {
+ public function status(
+ int|string|null $imageId,
+ ?array $options = ['preset' => 'default'],
+ ?string &$url = ''
+ ): ?int {
if (empty($imageId) && empty($options['ids'])) {
return static::NOT_ACCEPTABLE;
}
@@ -121,7 +125,7 @@ public function status($imageId, ?array $options = ['preset' => 'default'], &$ur
return static::NO_URL;
}
$url = $thumb['url'];
- } catch (\Exception $e) {
+ } catch (Exception $e) {
$this->log($e->getMessage(), 'error');
return static::NOT_AVAILABLE;
@@ -137,7 +141,7 @@ public function status($imageId, ?array $options = ['preset' => 'default'], &$ur
* @param array|null $options The thumbs options.
* @return string|int The url if available, the status code otherwise (see Thumb constants).
*/
- public function url($imageId, $options)
+ public function url(int $imageId, ?array $options): string|int
{
$url = null;
$status = $this->status($imageId, $options, $url);
@@ -154,7 +158,7 @@ public function url($imageId, $options)
* @param array $thumb The thumbnail data
* @return bool the acceptable flag
*/
- private function isAcceptable($thumb = []): bool
+ private function isAcceptable(array $thumb = []): bool
{
if (isset($thumb['acceptable']) && $thumb['acceptable'] === false) {
return false;
@@ -169,7 +173,7 @@ private function isAcceptable($thumb = []): bool
* @param array $thumb The thumbnail data
* @return bool the ready flag
*/
- private function isReady($thumb = []): bool
+ private function isReady(array $thumb = []): bool
{
if (!empty($thumb['ready']) && $thumb['ready'] === true) {
return true;
@@ -184,7 +188,7 @@ private function isReady($thumb = []): bool
* @param array $thumb The thumbnail data
* @return bool the url availability
*/
- private function hasUrl($thumb = []): bool
+ private function hasUrl(array $thumb = []): bool
{
if (!empty($thumb['url'])) {
return true;
diff --git a/src/View/Helper/WebComponentsHelper.php b/src/View/Helper/WebComponentsHelper.php
index 564cc73..4b77345 100644
--- a/src/View/Helper/WebComponentsHelper.php
+++ b/src/View/Helper/WebComponentsHelper.php
@@ -25,14 +25,14 @@ class WebComponentsHelper extends Helper
/**
* @inheritDoc
**/
- public $helpers = ['Html'];
+ public array $helpers = ['Html'];
/**
* A list of used identifiers.
*
* @var array
**/
- private $ids = [];
+ private array $ids = [];
/**
* Pass properties to an HTMLElement using attributes for plain values and inline scripts for array.
@@ -102,7 +102,7 @@ public function is(string $tagName, array $properties = [], string $scriptPath =
* @param string $scriptPath The path of the definition script to import.
* @return string An HTML node string like ``.
*/
- public function element(string $tagName, array $properties = [], $scriptPath = ''): string
+ public function element(string $tagName, array $properties = [], string $scriptPath = ''): string
{
if (!empty($scriptPath)) {
$this->Html->script($scriptPath, [ 'block' => 'scriptsComponents' ]);
diff --git a/src/View/Twig/BeditaTwigExtension.php b/src/View/Twig/BeditaTwigExtension.php
index 87a7062..6581a04 100644
--- a/src/View/Twig/BeditaTwigExtension.php
+++ b/src/View/Twig/BeditaTwigExtension.php
@@ -41,11 +41,9 @@ public function getFunctions(): array
{
return [
new TwigFunction('config', [Configure::class, 'read']),
- new TwigFunction('write_config', function ($key, $val) {
+ new TwigFunction('write_config', function ($key, $val): void {
// avoid unwanted return value display in templates
Configure::write($key, $val);
-
- return;
}),
];
}
diff --git a/tests/TestCase/ApiClientProviderTest.php b/tests/TestCase/ApiClientProviderTest.php
index 74547d6..38e18eb 100644
--- a/tests/TestCase/ApiClientProviderTest.php
+++ b/tests/TestCase/ApiClientProviderTest.php
@@ -16,12 +16,12 @@
use BEdita\WebTools\ApiClientProvider;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
/**
* {@see BEdita\WebTools\ApiClientProvider} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\ApiClientProvider
*/
+#[CoversClass(ApiClientProvider::class)]
class ApiClientProviderTest extends TestCase
{
/**
diff --git a/tests/TestCase/Authenticator/OAuth2AuthenticatorTest.php b/tests/TestCase/Authenticator/OAuth2AuthenticatorTest.php
index d6a3541..b2a39dd 100644
--- a/tests/TestCase/Authenticator/OAuth2AuthenticatorTest.php
+++ b/tests/TestCase/Authenticator/OAuth2AuthenticatorTest.php
@@ -15,6 +15,7 @@
namespace BEdita\WebTools\Test\TestCase\Authenticator;
+use ArrayAccess;
use Authentication\Authenticator\Result;
use Authentication\Identifier\IdentifierInterface;
use BEdita\WebTools\Authenticator\OAuth2Authenticator;
@@ -23,13 +24,21 @@
use Cake\Http\Session;
use Cake\TestSuite\TestCase;
use Cake\Utility\Hash;
+use Exception;
use Firebase\JWT\JWT;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Authenticator\OAuth2Authenticator} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Authenticator\OAuth2Authenticator
*/
+#[CoversClass(OAuth2Authenticator::class)]
+#[CoversMethod(OAuth2Authenticator::class, '__construct')]
+#[CoversMethod(OAuth2Authenticator::class, 'authenticate')]
+#[CoversMethod(OAuth2Authenticator::class, 'initProvider')]
+#[CoversMethod(OAuth2Authenticator::class, 'providerConnect')]
+#[CoversMethod(OAuth2Authenticator::class, 'redirectUri')]
class OAuth2AuthenticatorTest extends TestCase
{
/**
@@ -37,7 +46,7 @@ class OAuth2AuthenticatorTest extends TestCase
*
* @return array
*/
- public function authenticateProvider(): array
+ public static function authenticateProvider(): array
{
return [
'bad provider' => [
@@ -137,24 +146,19 @@ public function authenticateProvider(): array
* Test `authenticate` method
*
* @param array|\Exception $expected EXpected result.
- * @param array $config Request configuration.
+ * @param array $reqConfig Request configuration.
* @param array $authConfig Authenticator configuration.
* @param array $identity Identity data.
* @return void
- * @dataProvider authenticateProvider
- * @covers ::authenticate()
- * @covers ::providerConnect()
- * @covers ::initProvider()
- * @covers ::redirectUri()
- * @covers ::__construct()
*/
+ #[DataProvider('authenticateProvider')]
public function testAuthenticate(
$expected,
array $reqConfig,
array $authConfig = [],
array $identity = ['id' => 1]
): void {
- if ($expected instanceof \Exception) {
+ if ($expected instanceof Exception) {
$this->expectException(get_class($expected));
$this->expectExceptionCode($expected->getCode());
$this->expectExceptionMessage($expected->getMessage());
@@ -168,7 +172,7 @@ public function __construct($identity)
$this->identity = $identity;
}
- public function identify(array $credentials)
+ public function identify(array $credentials): ArrayAccess|array|null
{
return $this->identity;
}
@@ -180,7 +184,7 @@ public function getErrors(): array
};
$request = new ServerRequest($reqConfig);
$session = new Session();
- $session->write(Hash::get($reqConfig, 'data'));
+ $session->write((array)Hash::get($reqConfig, 'data'));
$request = $request->withAttribute('session', $session);
$authenticator = new OAuth2Authenticator($identifier, $authConfig);
$result = $authenticator->authenticate($request);
@@ -193,12 +197,11 @@ public function getErrors(): array
* Test JWT leeway config in `authenticate` method
*
* @return void
- * @covers ::authenticate()
*/
public function testAuthenticateLeeway(): void
{
$identifier = new class () implements IdentifierInterface {
- public function identify(array $credentials)
+ public function identify(array $credentials): ArrayAccess|array|null
{
return $credentials;
}
@@ -213,7 +216,9 @@ public function getErrors(): array
];
$request = new ServerRequest($reqConfig);
$session = new Session();
- $session->write(Hash::get($reqConfig, 'data'));
+ $val = Hash::get((array)$reqConfig, 'data');
+ $val = is_string($val) ? $val : (array)$val;
+ $session->write($val);
$request = $request->withAttribute('session', $session);
$authenticator = new OAuth2Authenticator($identifier, [
diff --git a/tests/TestCase/Command/CacheClearallCommandTest.php b/tests/TestCase/Command/CacheClearallCommandTest.php
index 8df7879..6bfac1d 100644
--- a/tests/TestCase/Command/CacheClearallCommandTest.php
+++ b/tests/TestCase/Command/CacheClearallCommandTest.php
@@ -1,5 +1,4 @@
useCommandRunner();
$this->command = new CacheClearallCommand();
}
@@ -52,7 +52,6 @@ protected function setUp(): void
* Test execute method
*
* @return void
- * @covers ::execute()
*/
public function testExecute(): void
{
diff --git a/tests/TestCase/Controller/ApiProxyTraitTest.php b/tests/TestCase/Controller/ApiProxyTraitTest.php
index 3e77d11..2b8c48b 100644
--- a/tests/TestCase/Controller/ApiProxyTraitTest.php
+++ b/tests/TestCase/Controller/ApiProxyTraitTest.php
@@ -23,14 +23,27 @@
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
use Cake\Utility\Hash;
+use LogicException;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
/**
* ApiProxyTraitTest class
*
* {@see \BEdita\WebTools\Controller\ApiProxyTrait} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Controller\ApiProxyTrait
*/
+#[CoversClass(ApiProxyTrait::class)]
+#[CoversMethod(ApiProxyTrait::class, 'apiRequest')]
+#[CoversMethod(ApiProxyTrait::class, 'delete')]
+#[CoversMethod(ApiProxyTrait::class, 'get')]
+#[CoversMethod(ApiProxyTrait::class, 'handleError')]
+#[CoversMethod(ApiProxyTrait::class, 'initialize')]
+#[CoversMethod(ApiProxyTrait::class, 'maskLinks')]
+#[CoversMethod(ApiProxyTrait::class, 'maskMultiLinks')]
+#[CoversMethod(ApiProxyTrait::class, 'maskResponseLinks')]
+#[CoversMethod(ApiProxyTrait::class, 'patch')]
+#[CoversMethod(ApiProxyTrait::class, 'post')]
+#[CoversMethod(ApiProxyTrait::class, 'setBaseUrl')]
class ApiProxyTraitTest extends TestCase
{
use IntegrationTestTrait;
@@ -38,9 +51,9 @@ class ApiProxyTraitTest extends TestCase
/**
* Instance of BEditaClient
*
- * @var \BEdita\SDK\BEditaClient
+ * @var \BEdita\SDK\BEditaClient|null
*/
- protected $apiClient = null;
+ protected ?BEditaClient $apiClient = null;
/**
* @inheritDoc
@@ -79,7 +92,6 @@ protected function getBaseUrl(): string
* Test that a request with a wrong method raises MethodNotAllowedException.
*
* @return void
- * @covers ::apiRequest()
*/
public function testMethodNotAllowedException(): void
{
@@ -98,13 +110,6 @@ public function testMethodNotAllowedException(): void
* Test get() method
*
* @return void
- * @covers ::initialize()
- * @covers ::get()
- * @covers ::setBaseUrl()
- * @covers ::apiRequest()
- * @covers ::maskResponseLinks()
- * @covers ::maskMultiLinks()
- * @covers ::maskLinks()
*/
public function testGet(): void
{
@@ -145,9 +150,6 @@ public function testGet(): void
* Test non found error proxied from API.
*
* @return void
- * @covers ::get()
- * @covers ::apiRequest()
- * @covers ::handleError()
*/
public function testNotFoundError(): void
{
@@ -168,7 +170,6 @@ public function testNotFoundError(): void
* Test that masking links with value searched equal to string works.
*
* @return void
- * @covers ::maskLinks()
*/
public function testMaskLinksString(): void
{
@@ -183,7 +184,6 @@ public function testMaskLinksString(): void
* Test that getting a list of objects the relationships links are masked.
*
* @return void
- * @covers ::maskResponseLinks()
*/
public function testMaskRelationshipsLinksGettingList(): void
{
@@ -204,7 +204,6 @@ public function testMaskRelationshipsLinksGettingList(): void
* Test that getting /home the resources links are masked.
*
* @return void
- * @covers ::maskResponseLinks()
*/
public function testMaskResourcesGettingHome(): void
{
@@ -223,7 +222,6 @@ public function testMaskResourcesGettingHome(): void
* is correctly handled
*
* @return void
- * @covers ::handleError()
*/
public function testNotBEditaClientException(): void
{
@@ -246,7 +244,7 @@ protected function setBaseUrl($path): void
->onlyMethods(['get'])
->getMock();
- $apiClientMock->method('get')->willThrowException(new \LogicException('Broken'));
+ $apiClientMock->method('get')->willThrowException(new LogicException('Broken'));
$controller->setApiClient($apiClientMock);
$controller->get('/gustavo');
@@ -263,7 +261,6 @@ protected function setBaseUrl($path): void
* Test that if BEditaClient return null the response has empty body.
*
* @return void
- * @covers ::apiRequest()
*/
public function testNullResponseFromBEditaClient(): void
{
@@ -299,7 +296,6 @@ protected function setBaseUrl($path): void
* Test that if path was unexpected an error 400 Bad Request was sent.
*
* @return void
- * @covers ::setBaseUrl()
*/
public function testErrorIfPathNotFound(): void
{
@@ -330,7 +326,6 @@ protected function setBaseUrl($path): void
* Test that url is urlencoded the baseUrl is found.
*
* @return void
- * @covers ::setBaseUrl()
*/
public function testMatchUrlEncodedPath(): void
{
@@ -353,8 +348,6 @@ public function get($path): void
* Test POST request
*
* @return void
- * @covers ::post()
- * @covers ::apiRequest()
*/
public function testPost(): void
{
@@ -380,8 +373,6 @@ public function testPost(): void
* Test PATCH request
*
* @return void
- * @covers ::patch()
- * @covers ::apiRequest()
*/
public function testPatch(): void
{
@@ -415,8 +406,6 @@ public function testPatch(): void
* Test DELETE request
*
* @return void
- * @covers ::delete()
- * @covers ::apiRequest()
*/
public function testDelete(): void
{
@@ -443,11 +432,6 @@ public function testDelete(): void
* Test that create a new object, modify it and delete it.
*
* @return void
- * @covers ::post()
- * @covers ::patch()
- * @covers ::delete()
- * @covers ::apiRequest()
- * @covers ::get()
*/
public function testMulti(): void
{
diff --git a/tests/TestCase/Controller/Component/ApiCacheComponentTest.php b/tests/TestCase/Controller/Component/ApiCacheComponentTest.php
index ed7eaeb..bc3142c 100644
--- a/tests/TestCase/Controller/Component/ApiCacheComponentTest.php
+++ b/tests/TestCase/Controller/Component/ApiCacheComponentTest.php
@@ -21,12 +21,18 @@
use Cake\Controller\ComponentRegistry;
use Cake\Core\Configure;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
/**
* {@see \BEdita\WebTools\Controller\Component\ApiCacheComponent} Test Case
- *
- * @coversDefaultClass \Bedita\WebTools\Controller\Component\ApiCacheComponent
*/
+#[CoversClass(ApiCacheComponent::class)]
+#[CoversMethod(ApiCacheComponent::class, 'cacheKey')]
+#[CoversMethod(ApiCacheComponent::class, 'get')]
+#[CoversMethod(ApiCacheComponent::class, 'initialize')]
+#[CoversMethod(ApiCacheComponent::class, 'readIndex')]
+#[CoversMethod(ApiCacheComponent::class, 'updateCacheIndex')]
class ApiCacheComponentTest extends TestCase
{
/**
@@ -62,7 +68,6 @@ public function tearDown(): void
* Initialize Api Cache component test
*
* @return void
- * @covers ::initialize()
*/
public function testInitialize(): void
{
@@ -87,7 +92,6 @@ public function testInitialize(): void
* Initialize Api Cache component test with custom config
*
* @return void
- * @covers ::initialize()
*/
public function testInitializeCustomConfig(): void
{
@@ -250,10 +254,6 @@ protected function setupClient(array $response): void
* Cached GET API call test
*
* @return void
- * @covers ::cacheKey()
- * @covers ::readIndex()
- * @covers ::updateCacheIndex()
- * @covers ::get()
*/
public function testGet(): void
{
@@ -281,9 +281,6 @@ public function testGet(): void
* Test cache API index
*
* @return void
- * @covers ::updateCacheIndex()
- * @covers ::readIndex()
- * @covers ::get()
*/
public function testIndex(): void
{
diff --git a/tests/TestCase/Controller/Component/ApiFormatterComponentTest.php b/tests/TestCase/Controller/Component/ApiFormatterComponentTest.php
index 7848b7a..8a8df4b 100644
--- a/tests/TestCase/Controller/Component/ApiFormatterComponentTest.php
+++ b/tests/TestCase/Controller/Component/ApiFormatterComponentTest.php
@@ -6,12 +6,20 @@
use BEdita\WebTools\Controller\Component\ApiFormatterComponent;
use Cake\Controller\ComponentRegistry;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Controller\Component\ApiFormatterComponent} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Controller\Component\ApiFormatterComponent
*/
+#[CoversClass(ApiFormatterComponent::class)]
+#[CoversMethod(ApiFormatterComponent::class, 'addIncluded')]
+#[CoversMethod(ApiFormatterComponent::class, 'cleanResponse')]
+#[CoversMethod(ApiFormatterComponent::class, 'embedIncluded')]
+#[CoversMethod(ApiFormatterComponent::class, 'extractFromIncluded')]
+#[CoversMethod(ApiFormatterComponent::class, 'extractTranslatedFields')]
+#[CoversMethod(ApiFormatterComponent::class, 'replaceWithTranslation')]
class ApiFormatterComponentTest extends TestCase
{
/**
@@ -49,7 +57,7 @@ public function tearDown(): void
*
* @return array
*/
- public function embedIncludedProvider(): array
+ public static function embedIncludedProvider(): array
{
$gustavo = ['id' => 1, 'type' => 'persons', 'attributes' => ['name' => 'Gustavo'], 'relationships' => [['chief_of' => [['id' => 777, 'type' => 'universes']]]]];
$tv = ['id' => 2, 'type' => 'things', 'attributes' => ['name' => 'Television'], 'relationships' => [['part_of' => [['id' => 888, 'type' => 'furnitures']]]]];
@@ -212,11 +220,8 @@ public function embedIncludedProvider(): array
* @param array $response The response data for test
* @param array $expected The expected resulting data
* @return void
- * @covers ::embedIncluded()
- * @covers ::addIncluded()
- * @covers ::extractFromIncluded()
- * @dataProvider embedIncludedProvider()
*/
+ #[DataProvider('embedIncludedProvider')]
public function testEmbedIncluded(array $response, array $expected): void
{
$actual = $this->ApiFormatter->embedIncluded($response);
@@ -228,7 +233,7 @@ public function testEmbedIncluded(array $response, array $expected): void
*
* @return array
*/
- public function replaceWithTranslationProvider(): array
+ public static function replaceWithTranslationProvider(): array
{
return [
'empty response data' => [
@@ -732,10 +737,8 @@ public function replaceWithTranslationProvider(): array
* @param array $response The response data
* @param string $lang The lang requested
* @return void
- * @covers ::replaceWithTranslation()
- * @covers ::extractTranslatedFields()
- * @dataProvider replaceWithTranslationProvider()
*/
+ #[DataProvider('replaceWithTranslationProvider')]
public function testReplaceWithTranslation(array $expected, array $response, string $lang): void
{
$actual = $this->ApiFormatter->replaceWithTranslation($response, $lang);
@@ -746,7 +749,6 @@ public function testReplaceWithTranslation(array $expected, array $response, str
* Test `cleanResponse()` method.
*
* @return void
- * @covers ::cleanResponse()
*/
public function testCleanResponse(): void
{
diff --git a/tests/TestCase/Error/ExceptionRendererTest.php b/tests/TestCase/Error/ExceptionRendererTest.php
index a384afd..dbc584a 100644
--- a/tests/TestCase/Error/ExceptionRendererTest.php
+++ b/tests/TestCase/Error/ExceptionRendererTest.php
@@ -24,13 +24,22 @@
use Cake\Http\ServerRequest;
use Cake\TestSuite\TestCase;
use Cake\View\View;
+use Exception;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
use TestApp\Controller\TestController;
use TestApp\View\AppView;
use Throwable;
/**
- * @coversDefaultClass \BEdita\WebTools\Error\ExceptionRenderer
+ * @see \BEdita\WebTools\Error\ExceptionRenderer
*/
+#[CoversClass(ExceptionRenderer::class)]
+#[CoversMethod(ExceptionRenderer::class, '_getController')]
+#[CoversMethod(ExceptionRenderer::class, '_outputMessageSafe')]
+#[CoversMethod(ExceptionRenderer::class, '_template')]
+#[CoversMethod(ExceptionRenderer::class, 'getHttpCode')]
class ExceptionRendererTest extends TestCase
{
/**
@@ -66,7 +75,7 @@ public function setError(Throwable $throwable)
*
* @return array
*/
- public function templateProvider(): array
+ public static function templateProvider(): array
{
return [
'400 exception' => [
@@ -94,14 +103,12 @@ public function templateProvider(): array
* @param \Exception $exception Expected error.
* @param string $expected Template.
* @return void
- * @dataProvider templateProvider
- * @covers ::_template()
- * @covers ::getHttpCode()
*/
- public function testTemplate(\Exception $exception, $expected)
+ #[DataProvider('templateProvider')]
+ public function testTemplate(Exception $exception, $expected)
{
$renderer = $this->extensionClass($exception);
- $renderer->setController(new ErrorController());
+ $renderer->setController(new ErrorController(new ServerRequest([])));
$renderer->render();
static::assertEquals($expected, $renderer->getTemplate());
}
@@ -114,7 +121,6 @@ public function testTemplate(\Exception $exception, $expected)
* and the `Error/error500.twig` will be used.
*
* @return void
- * @covers ::_outputMessageSafe()
*/
public function testOutputMessageSafe()
{
@@ -132,7 +138,7 @@ public function testOutputMessageSafe()
EventManager::instance()->on('View.beforeRender', $callback);
$renderer = $this->extensionClass(new NotFoundException('hello'));
- $controller = new ErrorController();
+ $controller = new ErrorController(new ServerRequest([]));
$customErrorMessage = 'Gustavo, take care of it.';
$controller->set(compact('customErrorMessage'));
$renderer->setController($controller);
@@ -149,7 +155,6 @@ public function testOutputMessageSafe()
* In that case the `\Cake\View\View` class is used.
*
* @return void
- * @covers ::_outputMessageSafe()
*/
public function testOutputMessageSafeFallback()
{
@@ -164,7 +169,7 @@ public function testOutputMessageSafeFallback()
if ($trigger === 1) {
static::assertInstanceOf(AppView::class, $event->getSubject());
// throw a new exception
- throw new \Exception('Oh my, another exception is here.');
+ throw new Exception('Oh my, another exception is here.');
}
// second time is the fallback then we can remove the listener
@@ -178,8 +183,8 @@ public function testOutputMessageSafeFallback()
EventManager::instance()->on('View.beforeRender', $callback);
$expected = 'The original error is here';
- $renderer = $this->extensionClass(new \Exception($expected));
- $renderer->setController(new TestController());
+ $renderer = $this->extensionClass(new Exception($expected));
+ $renderer->setController(new TestController(new ServerRequest([])));
$response = $renderer->render();
$body = (string)$response->getBody();
@@ -190,7 +195,6 @@ public function testOutputMessageSafeFallback()
* Test `_getController` method with `application/json` Accept header
*
* @return void
- * @covers ::_getController()
*/
public function testControllerJsonResponse(): void
{
diff --git a/tests/TestCase/Http/BaseClientTest.php b/tests/TestCase/Http/BaseClientTest.php
index fc2a630..96f6fc5 100644
--- a/tests/TestCase/Http/BaseClientTest.php
+++ b/tests/TestCase/Http/BaseClientTest.php
@@ -13,7 +13,7 @@
* See LICENSE.LGPL or for more details.
*/
-namespace BEdita\WebTools\Test\TestCase\Identifier;
+namespace BEdita\WebTools\Test\TestCase\Http;
use BEdita\WebTools\Http\BaseClient;
use Cake\Core\Configure;
@@ -21,27 +21,39 @@
use Cake\Http\Client\Response;
use Cake\TestSuite\TestCase;
use Cake\Validation\Validator;
+use InvalidArgumentException;
use Laminas\Diactoros\Stream;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Http\BaseClient} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Http\BaseClient
*/
+#[CoversClass(BaseClient::class)]
+#[CoversMethod(BaseClient::class, '__construct')]
+#[CoversMethod(BaseClient::class, 'createClient')]
+#[CoversMethod(BaseClient::class, 'defaultConfigName')]
+#[CoversMethod(BaseClient::class, 'delete')]
+#[CoversMethod(BaseClient::class, 'get')]
+#[CoversMethod(BaseClient::class, 'getHttpClient')]
+#[CoversMethod(BaseClient::class, 'getUrl')]
+#[CoversMethod(BaseClient::class, 'getValidator')]
+#[CoversMethod(BaseClient::class, 'logCall')]
+#[CoversMethod(BaseClient::class, 'patch')]
+#[CoversMethod(BaseClient::class, 'post')]
+#[CoversMethod(BaseClient::class, 'put')]
+#[CoversMethod(BaseClient::class, 'validateConf')]
class BaseClientTest extends TestCase
{
/**
* Test constructor against invalid configuration.
*
* @return void
- * @covers ::__construct()
- * @covers ::validateConf()
- * @covers ::getValidator()
- * @covers ::createClient()
*/
public function testInvalidConfig(): void
{
- $this->expectException(\InvalidArgumentException::class);
+ $this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('client config not valid: {"url":{"_empty":"This field cannot be left empty"}}');
$config = [
'auth' => [
@@ -61,16 +73,11 @@ public function getValidator(): Validator
* Basic test.
*
* @return void
- * @covers ::__construct()
- * @covers ::validateConf()
- * @covers ::getValidator()
- * @covers ::createClient()
- * @covers ::defaultConfigName()
- * @covers ::getHttpClient()
*/
public function testBase(): void
{
- Configure::write('BaseClientTest.php', ['url' => 'https://example.com']);
+ // note: key 'BaseClientTest.php:' with ':' because the class is anonymous
+ Configure::write('BaseClientTest.php:', ['url' => 'https://example.com']);
$config = [
'auth' => [
'type' => 'BearerAccessToken',
@@ -92,7 +99,6 @@ public function getValidator(): Validator
* Test `getUrl` method.
*
* @return void
- * @covers ::getUrl()
*/
public function testGetUrl(): void
{
@@ -119,7 +125,6 @@ public function getUrl(string $url): string
* Test `logCall` method.
*
* @return void
- * @covers ::logCall()
*/
public function testLogCall(): void
{
@@ -168,7 +173,7 @@ public function logCall(string $call, string $url, string $payload, Response $re
$response = $response->withStatus(200)->withBody($stream);
$payload = '{"data": "test"}';
$log = $client->logCall('/GET', 'https://example.com', $payload, $response);
- static::assertEquals('[OK] API BaseClientTest.php: | /GET https://example.com | with status 200: this is a response body - Payload: {"data": "test"}', $log);
+ static::assertEquals('[OK] API BaseClientTest.php:1 | /GET https://example.com | with status 200: this is a response body - Payload: {"data": "test"}', $log);
// log level debug, response with error
$config['logLevel'] = 'debug';
@@ -184,7 +189,7 @@ public function logCall(string $call, string $url, string $payload, Response $re
$response = $response->withStatus(400)->withBody($stream);
$payload = '{"data": "test"}';
$log = $client->logCall('/GET', 'https://example.com', $payload, $response);
- static::assertEquals('[ERROR] API BaseClientTest.php: | /GET https://example.com | with status 400: this is a response body for error - Payload: {"data": "test"}', $log);
+ static::assertEquals('[ERROR] API BaseClientTest.php:1 | /GET https://example.com | with status 400: this is a response body for error - Payload: {"data": "test"}', $log);
}
/**
@@ -192,7 +197,7 @@ public function logCall(string $call, string $url, string $payload, Response $re
*
* @return array
*/
- public function getPostPatchPutDeleteProvider(): array
+ public static function getPostPatchPutDeleteProvider(): array
{
return [
'get call' => ['get'],
@@ -207,14 +212,8 @@ public function getPostPatchPutDeleteProvider(): array
* Test `get`, `post`, `patch`, `put`, `delete` methods.
*
* @return void
- * @covers ::get()
- * @covers ::post()
- * @covers ::patch()
- * @covers ::put()
- * @covers ::delete()
- * @covers ::logCall()
- * @dataProvider getPostPatchPutDeleteProvider
*/
+ #[DataProvider('getPostPatchPutDeleteProvider')]
public function testGetPostPatchPutDelete(string $method): void
{
$config = [
@@ -298,7 +297,7 @@ public function logCall(string $call, string $url, string $payload, Response $re
$response = $client->$method('/whatever', ['data' => 'test']);
static::assertInstanceOf(Response::class, $response);
static::assertSame(200, $response->getStatusCode());
- $expected = sprintf('[OK] API BaseClientTest.php: | /%s api/v2/whatever | with status 200: this is a response body - Payload: {"data":"test"}', strtoupper($method));
+ $expected = sprintf('[OK] API BaseClientTest.php:2 | /%s api/v2/whatever | with status 200: this is a response body - Payload: {"data":"test"}', strtoupper($method));
static::assertSame($expected, $client->lastLog);
}
}
diff --git a/tests/TestCase/Identifier/ApiIdentifierTest.php b/tests/TestCase/Identifier/ApiIdentifierTest.php
index 1483a35..316b1d5 100644
--- a/tests/TestCase/Identifier/ApiIdentifierTest.php
+++ b/tests/TestCase/Identifier/ApiIdentifierTest.php
@@ -20,12 +20,15 @@
use BEdita\WebTools\Identifier\ApiIdentifier;
use Cake\TestSuite\TestCase;
use Cake\Utility\Hash;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
/**
* {@see \BEdita\WebTools\Identifier\ApiIdentifier} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Identifier\ApiIdentifier
*/
+#[CoversClass(ApiIdentifier::class)]
+#[CoversMethod(ApiIdentifier::class, 'identify')]
+#[CoversMethod(ApiIdentifier::class, 'setError')]
class ApiIdentifierTest extends TestCase
{
/**
@@ -41,30 +44,30 @@ class ApiIdentifierTest extends TestCase
/**
* The API client instance.
*
- * @var \BEdita\SDK\BEditaClient
+ * @var \BEdita\SDK\BEditaClient|null
*/
- protected $apiClient = null;
+ protected ?BEditaClient $apiClient = null;
/**
* The created user data.
*
- * @var array
+ * @var array|null
*/
- protected $user = null;
+ protected ?array $user = null;
/**
* The created role data.
*
- * @var array
+ * @var array|null
*/
- protected $role = null;
+ protected ?array $role = null;
/**
- * Undocumented variable
+ * JWT tokens.
*
- * @var array
+ * @var array|null
*/
- protected $jwtTokens = null;
+ protected ?array $jwtTokens = null;
/**
* @inheritDoc
@@ -155,7 +158,6 @@ protected function createUserAndRole(string $username, string $role): void
* Test missing data for identifier.
*
* @return void
- * @covers ::identify()
*/
public function testIdentifyMissingData(): void
{
@@ -170,8 +172,6 @@ public function testIdentifyMissingData(): void
* Test authentication failure.
*
* @return void
- * @covers ::identify()
- * @covers ::setError()
*/
public function testIdentifyAuthenticationFails(): void
{
@@ -191,7 +191,6 @@ public function testIdentifyAuthenticationFails(): void
* Test authentication ok.
*
* @return {void}
- * @covers ::identify()
*/
public function testIdentifyCorrect(): void
{
@@ -214,7 +213,6 @@ public function testIdentifyCorrect(): void
* Test that if missing `meta` from response then identification fails.
*
* @return void
- * @covers ::identify()
*/
public function testMissingMetaFromResponse(): void
{
diff --git a/tests/TestCase/Identifier/OAuth2IdentifierTest.php b/tests/TestCase/Identifier/OAuth2IdentifierTest.php
index 57b6447..897d20a 100644
--- a/tests/TestCase/Identifier/OAuth2IdentifierTest.php
+++ b/tests/TestCase/Identifier/OAuth2IdentifierTest.php
@@ -20,12 +20,17 @@
use BEdita\WebTools\ApiClientProvider;
use BEdita\WebTools\Identifier\OAuth2Identifier;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
/**
* {@see \BEdita\WebTools\Identifier\OAuth2Identifier} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Identifier\OAuth2Identifier
*/
+#[CoversClass(OAuth2Identifier::class)]
+#[CoversMethod(OAuth2Identifier::class, 'externalAuth')]
+#[CoversMethod(OAuth2Identifier::class, 'identify')]
+#[CoversMethod(OAuth2Identifier::class, 'signup')]
+#[CoversMethod(OAuth2Identifier::class, 'signupData')]
class OAuth2IdentifierTest extends TestCase
{
/**
@@ -41,8 +46,6 @@ public function tearDown(): void
* Test `identify` method with successful login.
*
* @return void
- * @covers ::identify()
- * @covers ::externalAuth()
*/
public function testIdentifyOk(): void
{
@@ -80,8 +83,6 @@ public function testIdentifyOk(): void
* Test `identify` method with unsuccessful login.
*
* @return void
- * @covers ::identify()
- * @covers ::externalAuth()
*/
public function testNullIdentify(): void
{
@@ -104,9 +105,6 @@ public function testNullIdentify(): void
* Test `identify` method with successful signup.
*
* @return void
- * @covers ::identify()
- * @covers ::signup()
- * @covers ::signupData()
*/
public function testOkSignup(): void
{
@@ -154,9 +152,6 @@ function () use (&$count) {
* Test `identify` method with unsuccessful signup.
*
* @return void
- * @covers ::identify()
- * @covers ::signup()
- * @covers ::signupData()
*/
public function testFailSignup(): void
{
diff --git a/tests/TestCase/IdentityTest.php b/tests/TestCase/IdentityTest.php
index 662d0e5..d50e1d0 100644
--- a/tests/TestCase/IdentityTest.php
+++ b/tests/TestCase/IdentityTest.php
@@ -18,19 +18,20 @@
use Authorization\Identity as AuthorizationIdentity;
use BEdita\WebTools\Identity;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
/**
* {@see BEdita\WebTools\Identity} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Identity
*/
+#[CoversClass(Identity::class)]
+#[CoversMethod(Identity::class, 'hasRole')]
class IdentityTest extends TestCase
{
/**
* Test hasRole()
*
* @return void
- * @covers ::hasRole()
*/
public function testHasRole(): void
{
@@ -52,7 +53,6 @@ public function testHasRole(): void
* Test that hasRole() returns False for identity without role set.
*
* @return void
- * @covers ::hasRole()
*/
public function testHasRoleWithoutRoleInEntity(): void
{
diff --git a/tests/TestCase/Media/UploadTraitTest.php b/tests/TestCase/Media/UploadTraitTest.php
index 48b6629..df9a2a1 100644
--- a/tests/TestCase/Media/UploadTraitTest.php
+++ b/tests/TestCase/Media/UploadTraitTest.php
@@ -20,13 +20,15 @@
use Cake\Http\Exception\BadRequestException;
use Cake\TestSuite\TestCase;
use Laminas\Diactoros\UploadedFile;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
use Psr\Http\Message\UploadedFileInterface;
/**
* {@see \BEdita\WebTools\Media\UploadTrait} Test Case
- *
- * @coversDefaultClass \Bedita\WebTools\Media\UploadTrait
*/
+#[CoversClass(UploadTrait::class)]
+#[CoversMethod(UploadTrait::class, 'uploadMedia')]
class UploadTraitTest extends TestCase
{
use UploadTrait;
@@ -57,7 +59,6 @@ public function upload(UploadedFileInterface $file, string $type, bool $private
* Test `uploadMedia()` method
*
* @return void
- * @covers ::uploadMedia()
*/
public function testUpload(): void
{
@@ -93,7 +94,6 @@ public function testUpload(): void
* Test `uploadMedia()` failure
*
* @return void
- * @covers ::uploadMedia()
*/
public function testFailUpload(): void
{
diff --git a/tests/TestCase/Middleware/OAuth2MiddlewareTest.php b/tests/TestCase/Middleware/OAuth2MiddlewareTest.php
index 93626c8..9b42fd5 100644
--- a/tests/TestCase/Middleware/OAuth2MiddlewareTest.php
+++ b/tests/TestCase/Middleware/OAuth2MiddlewareTest.php
@@ -21,15 +21,17 @@
use Cake\Http\Response;
use Cake\Http\ServerRequest;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* {@see BEdita\WebTools\Middleware\OAuth2Middleware} Test Case
- *
- * @coversDefaultClass BEdita\WebTools\Middleware\OAuth2Middleware
*/
+#[CoversClass(OAuth2Middleware::class)]
+#[CoversMethod(OAuth2Middleware::class, 'process')]
class OAuth2MiddlewareTest extends TestCase
{
/**
@@ -58,7 +60,6 @@ public function handle(ServerRequestInterface $request): ResponseInterface
* Test `process` with no authentication result.
*
* @return void
- * @covers ::process()
*/
public function testNoResult(): void
{
@@ -74,7 +75,6 @@ public function testNoResult(): void
* Test `process` with authentication result but without `authUrl`.
*
* @return void
- * @covers ::process()
*/
public function testResultNoAuth(): void
{
@@ -93,7 +93,6 @@ public function testResultNoAuth(): void
* Test `process` with authentication with `authUrl`.
*
* @return void
- * @covers ::process()
*/
public function testResultAuth(): void
{
diff --git a/tests/TestCase/PluginTest.php b/tests/TestCase/PluginTest.php
index 12dd297..db6ed70 100644
--- a/tests/TestCase/PluginTest.php
+++ b/tests/TestCase/PluginTest.php
@@ -15,26 +15,30 @@
namespace BEdita\WebTools\Test\TestCase;
use BEdita\WebTools\Command\CacheClearallCommand;
+use BEdita\WebTools\Plugin;
use Cake\Console\CommandCollection;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
use TestApp\Application;
/**
* {@see BEdita\WebTools\Plugin} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Plugin
*/
+#[CoversClass(Plugin::class)]
+#[CoversMethod(Plugin::class, 'bootstrap')]
+#[CoversMethod(Plugin::class, 'console')]
class PluginTest extends TestCase
{
/**
* Test `console` method
*
* @return void
- * @covers ::console
*/
public function testConsole(): void
{
$app = new Application(CONFIG);
+ $app->bootstrap();
$commands = $app->console(new CommandCollection([]));
$commands = $app->pluginConsole($commands);
$cacheClearAll = $commands->get('cache clear_all');
@@ -46,13 +50,14 @@ public function testConsole(): void
* Test `bootstrap` method
*
* @return void
- * @covers ::bootstrap
*/
public function testBootstrap(): void
{
$app = new Application(CONFIG);
+ $app->bootstrap();
$app->pluginBootstrap();
$plugins = $app->getPlugins();
- static::assertNotEmpty($plugins);
+ static::assertTrue($plugins->has('BEdita/WebTools'));
+ static::assertTrue($plugins->has('Cake/TwigView'));
}
}
diff --git a/tests/TestCase/Policy/RequestPolicyTest.php b/tests/TestCase/Policy/RequestPolicyTest.php
index ad9fb09..4f086c0 100644
--- a/tests/TestCase/Policy/RequestPolicyTest.php
+++ b/tests/TestCase/Policy/RequestPolicyTest.php
@@ -12,8 +12,9 @@
*
* See LICENSE.LGPL or for more details.
*/
-namespace BEdita\WebTools\Test\TestCase;
+namespace BEdita\WebTools\Test\TestCase\Policy;
+use ArrayObject;
use Authorization\AuthorizationService;
use Authorization\IdentityDecorator;
use Authorization\Policy\Exception\MissingMethodException;
@@ -21,7 +22,10 @@
use BEdita\WebTools\Policy\RequestPolicy;
use Cake\Http\ServerRequest;
use Cake\TestSuite\TestCase;
+use Exception;
use Laminas\Diactoros\Uri;
+use LogicException;
+use PHPUnit\Framework\Attributes\DataProvider;
use TestApp\Policy\CustomPolicy;
use TestApp\Policy\InvokeCustomPolicy;
@@ -37,7 +41,7 @@ class RequestPolicyTest extends TestCase
*
* @return array
*/
- public function canAccessProvider(): array
+ public static function canAccessProvider(): array
{
return [
'missing rule' => [
@@ -256,14 +260,14 @@ public function canAccessProvider(): array
],
],
'ko invalid policy instance' => [
- new \LogicException('Invalid rule for Dashboard::profile() in RequestPolicy'),
+ new LogicException('Invalid rule for Dashboard::profile() in RequestPolicy'),
(new ServerRequest(['uri' => new Uri('/dashboard/profile')]))
->withParam('controller', 'Dashboard')
->withParam('action', 'profile'),
[
'rules' => [
'Dashboard' => [
- 'profile' => new \ArrayObject(),
+ 'profile' => new ArrayObject(),
],
],
],
@@ -273,13 +277,13 @@ public function canAccessProvider(): array
],
],
'ko invalid rule' => [
- new \LogicException('Invalid Rule for Dashboard in RequestPolicy'),
+ new LogicException('Invalid Rule for Dashboard in RequestPolicy'),
(new ServerRequest(['uri' => new Uri('/dashboard/profile')]))
->withParam('controller', 'Dashboard')
->withParam('action', 'profile'),
[
'rules' => [
- 'Dashboard' => new \ArrayObject(),
+ 'Dashboard' => new ArrayObject(),
],
],
[
@@ -298,11 +302,11 @@ public function canAccessProvider(): array
* @param array $policyConfig Policy configuration
* @param array $identityData Identity data
* @return void
- * @dataProvider canAccessProvider()
*/
+ #[DataProvider('canAccessProvider')]
public function testCanAccess($expected, ServerRequest $request, array $policyConfig, ?array $identityData): void
{
- if ($expected instanceof \Exception) {
+ if ($expected instanceof Exception) {
$this->expectException(get_class($expected));
$this->expectExceptionMessage($expected->getMessage());
}
diff --git a/tests/TestCase/SingletonTraitTest.php b/tests/TestCase/SingletonTraitTest.php
index 450e50a..a530c0a 100644
--- a/tests/TestCase/SingletonTraitTest.php
+++ b/tests/TestCase/SingletonTraitTest.php
@@ -15,6 +15,7 @@
namespace BEdita\WebTools\Test\TestCase;
use Cake\TestSuite\TestCase;
+use ReflectionClass;
/**
* {@see BEdita\WebTools\SingletonTrait} Test Case
@@ -30,7 +31,7 @@ class SingletonTraitTest extends TestCase
*/
public function testNotInstantiable()
{
- $class = new \ReflectionClass(SingletonTestClass::class);
+ $class = new ReflectionClass(SingletonTestClass::class);
static::assertFalse($class->isInstantiable());
}
@@ -42,7 +43,7 @@ public function testNotInstantiable()
*/
public function testNotCloneable()
{
- $class = new \ReflectionClass(SingletonTestClass::class);
+ $class = new ReflectionClass(SingletonTestClass::class);
static::assertFalse($class->isCloneable());
}
diff --git a/tests/TestCase/Utility/ApiToolsTest.php b/tests/TestCase/Utility/ApiToolsTest.php
index 0120bcd..f79c637 100644
--- a/tests/TestCase/Utility/ApiToolsTest.php
+++ b/tests/TestCase/Utility/ApiToolsTest.php
@@ -16,25 +16,27 @@
use BEdita\WebTools\Utility\ApiTools;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Utility\ApiTools} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Utility\ApiTools
*/
+#[CoversClass(ApiTools::class)]
+#[CoversMethod(ApiTools::class, 'cleanResponse')]
+#[CoversMethod(ApiTools::class, 'recursiveRemoveKey')]
+#[CoversMethod(ApiTools::class, 'removeAttributes')]
+#[CoversMethod(ApiTools::class, 'removeIncluded')]
+#[CoversMethod(ApiTools::class, 'removeLinks')]
+#[CoversMethod(ApiTools::class, 'removeRelationships')]
+#[CoversMethod(ApiTools::class, 'removeSchema')]
class ApiToolsTest extends TestCase
{
/**
* Test clean response
*
* @return void
- * @covers ::cleanResponse()
- * @covers ::recursiveRemoveKey()
- * @covers ::removeAttributes()
- * @covers ::removeIncluded()
- * @covers ::removeLinks()
- * @covers ::removeRelationships()
- * @covers ::removeSchema()
*/
public function testCleanResponse(): void
{
@@ -140,7 +142,7 @@ public function testCleanResponse(): void
*
* @return array
*/
- public function cleanResponseAttributesProvider(): array
+ public static function cleanResponseAttributesProvider(): array
{
return [
'remove extra, single entity with included' => [
@@ -422,10 +424,8 @@ public function cleanResponseAttributesProvider(): array
* @return array
*
* @return void
- * @dataProvider cleanResponseAttributesProvider
- * @covers ::cleanResponse()
- * @covers ::removeAttributes()
*/
+ #[DataProvider('cleanResponseAttributesProvider')]
public function testCleanResponseAttributes(array $response, array $options, array $expected): void
{
$actual = ApiTools::cleanResponse($response, $options);
diff --git a/tests/TestCase/Utility/Asset/AssetStrategyTest.php b/tests/TestCase/Utility/Asset/AssetStrategyTest.php
index b0d875c..e207dc7 100644
--- a/tests/TestCase/Utility/Asset/AssetStrategyTest.php
+++ b/tests/TestCase/Utility/Asset/AssetStrategyTest.php
@@ -12,16 +12,20 @@
*
* See LICENSE.LGPL or for more details.
*/
-namespace BEdita\WebTools\Test\TestCase\Utility\Asset\Strategy;
+namespace BEdita\WebTools\Test\TestCase\Utility\Asset;
use BEdita\WebTools\Utility\Asset\AssetStrategy;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Utility\Asset\AssetStrategy} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Utility\Asset\AssetStrategy
*/
+#[CoversClass(AssetStrategy::class)]
+#[CoversMethod(AssetStrategy::class, '__construct')]
+#[CoversMethod(AssetStrategy::class, 'loadAssets')]
class AssetStrategyTest extends TestCase
{
/**
@@ -33,7 +37,7 @@ class AssetStrategyTest extends TestCase
protected function getInstance(array $config = []): AssetStrategy
{
return new class ($config) extends AssetStrategy {
- public function get(string $name, ?string $extension = null)
+ public function get(string $name, ?string $extension = null): string|array|null
{
return $this->assets;
}
@@ -45,7 +49,7 @@ public function get(string $name, ?string $extension = null)
*
* @return array
*/
- public function manifestPathProvider(): array
+ public static function manifestPathProvider(): array
{
return [
'default' => [
@@ -67,9 +71,8 @@ public function manifestPathProvider(): array
* @param string $expected The expected path
* @param array $config The configuration used
* @return void
- * @dataProvider manifestPathProvider()
- * @covers ::__construct()
*/
+ #[DataProvider('manifestPathProvider')]
public function testManifestPath(string $expected, array $config): void
{
$strategy = $this->getInstance($config);
@@ -81,7 +84,6 @@ public function testManifestPath(string $expected, array $config): void
* Test `loadASsets()`
*
* @return void
- * @covers ::loadAssets()
*/
public function testLoadAssets(): void
{
diff --git a/tests/TestCase/Utility/Asset/Strategy/EntrypointsStrategyTest.php b/tests/TestCase/Utility/Asset/Strategy/EntrypointsStrategyTest.php
index a2f9e09..a9696e0 100644
--- a/tests/TestCase/Utility/Asset/Strategy/EntrypointsStrategyTest.php
+++ b/tests/TestCase/Utility/Asset/Strategy/EntrypointsStrategyTest.php
@@ -16,12 +16,15 @@
use BEdita\WebTools\Utility\Asset\Strategy\EntrypointsStrategy;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Utility\Asset\Strategy\EntrypointsStrategy} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Utility\Asset\Strategy\EntrypointsStrategy
*/
+#[CoversClass(EntrypointsStrategy::class)]
+#[CoversMethod(EntrypointsStrategy::class, 'get')]
class EntrypointsStrategyTest extends TestCase
{
/**
@@ -29,7 +32,7 @@ class EntrypointsStrategyTest extends TestCase
*
* @return array
*/
- public function getProvider(): array
+ public static function getProvider(): array
{
return [
'not found' => [
@@ -62,16 +65,16 @@ public function getProvider(): array
/**
* Test that get asset name works as expected.
*
- * @param string $expected The expected path
- * @param array $name The configuration used
+ * @param array|null $expected The expected path
+ * @param string $name The name
+ * @param string|null $extension The extension
* @return void
- * @dataProvider getProvider()
- * @covers ::get()
*/
+ #[DataProvider('getProvider')]
public function testGet(?array $expected, string $name, ?string $extension = null): void
{
$strategy = new EntrypointsStrategy(['manifestPath' => WWW_ROOT . 'entrypoints.json']);
-
- static::assertEquals($expected, $strategy->get($name, $extension));
+ $actual = $strategy->get($name, $extension);
+ static::assertEquals($expected, $actual);
}
}
diff --git a/tests/TestCase/Utility/Asset/Strategy/RevManifestStrategyTest.php b/tests/TestCase/Utility/Asset/Strategy/RevManifestStrategyTest.php
index 0904f4c..4160529 100644
--- a/tests/TestCase/Utility/Asset/Strategy/RevManifestStrategyTest.php
+++ b/tests/TestCase/Utility/Asset/Strategy/RevManifestStrategyTest.php
@@ -16,12 +16,15 @@
use BEdita\WebTools\Utility\Asset\Strategy\RevManifestStrategy;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Utility\Asset\Strategy\RevManifestStrategy} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Utility\Asset\Strategy\RevManifestStrategy
*/
+#[CoversClass(RevManifestStrategy::class)]
+#[CoversMethod(RevManifestStrategy::class, 'get')]
class RevManifestStrategyTest extends TestCase
{
/**
@@ -29,7 +32,7 @@ class RevManifestStrategyTest extends TestCase
*
* @return array
*/
- public function getProvider(): array
+ public static function getProvider(): array
{
return [
'name' => [
@@ -56,15 +59,15 @@ public function getProvider(): array
* Test that get asset name works as expected.
*
* @param string $expected The expected path
- * @param array $name The configuration used
+ * @param string $name The name
+ * @param string|null $extension The extension
* @return void
- * @dataProvider getProvider()
- * @covers ::get()
*/
+ #[DataProvider('getProvider')]
public function testGet(?string $expected, string $name, ?string $extension = null): void
{
$strategy = new RevManifestStrategy();
-
- static::assertEquals($expected, $strategy->get($name, $extension));
+ $actual = $strategy->get($name, $extension);
+ static::assertEquals($expected, $actual);
}
}
diff --git a/tests/TestCase/Utility/AssetsRevisionsTest.php b/tests/TestCase/Utility/AssetsRevisionsTest.php
index 2d968b7..17d0c22 100644
--- a/tests/TestCase/Utility/AssetsRevisionsTest.php
+++ b/tests/TestCase/Utility/AssetsRevisionsTest.php
@@ -18,12 +18,21 @@
use BEdita\WebTools\Utility\Asset\Strategy\RevManifestStrategy;
use BEdita\WebTools\Utility\AssetsRevisions;
use Cake\TestSuite\TestCase;
+use LogicException;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\Utility\AssetsRevisions} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\Utility\AssetsRevisions
*/
+#[CoversClass(AssetsRevisions::class)]
+#[CoversMethod(AssetsRevisions::class, 'clearStrategy')]
+#[CoversMethod(AssetsRevisions::class, 'get')]
+#[CoversMethod(AssetsRevisions::class, 'getMulti')]
+#[CoversMethod(AssetsRevisions::class, 'getStrategy')]
+#[CoversMethod(AssetsRevisions::class, 'loadManifest')]
+#[CoversMethod(AssetsRevisions::class, 'setStrategy')]
class AssetsRevisionsTest extends TestCase
{
/**
@@ -32,6 +41,7 @@ class AssetsRevisionsTest extends TestCase
public function setUp(): void
{
AssetsRevisions::setStrategy(new RevManifestStrategy());
+ parent::setUp();
}
/**
@@ -40,15 +50,13 @@ public function setUp(): void
public function tearDown(): void
{
AssetsRevisions::clearStrategy();
+ parent::tearDown();
}
/**
* Test set, get and reset strategy
*
* @return void
- * @covers ::setStrategy()
- * @covers ::getStrategy()
- * @covers ::clearStrategy()
*/
public function testStrategy(): void
{
@@ -64,7 +72,7 @@ public function testStrategy(): void
*
* @return array
*/
- public function getProvider(): array
+ public static function getProvider(): array
{
return [
'simple' => [
@@ -95,9 +103,8 @@ public function getProvider(): array
* @param string $name The asset name
* @param string $extension The asset extension
* @return void
- * @dataProvider getProvider()
- * @covers ::get()
*/
+ #[DataProvider('getProvider')]
public function testGet(string $expected, string $name, ?string $extension = null): void
{
$result = AssetsRevisions::get($name, $extension);
@@ -108,7 +115,6 @@ public function testGet(string $expected, string $name, ?string $extension = nul
* Test that `get()` method returns the passed asset name when no strategy was set.
*
* @return void
- * @covers ::get()
*/
public function testGetWithoutStrategy(): void
{
@@ -121,7 +127,6 @@ public function testGetWithoutStrategy(): void
* Test `getMulti` method
*
* @return void
- * @covers ::getMulti()
*/
public function testGetMulti(): void
{
@@ -137,11 +142,9 @@ public function testGetMulti(): void
/**
* Test `loadManifest`
*
- * @covers ::loadManifest()
* @return void
- * @covers ::loadManifest()
*/
- public function testLoadManifest()
+ public function testLoadManifest(): void
{
// use different path
$path = '/some/path/manifest.json';
@@ -162,11 +165,10 @@ public function testLoadManifest()
*
* @return void
* @expectException \LogicException
- * @covers ::loadManifest()
*/
public function testLoadManifestWithoutStrategy(): void
{
- $this->expectException(\LogicException::class);
+ $this->expectException(LogicException::class);
AssetsRevisions::clearStrategy();
AssetsRevisions::loadManifest();
diff --git a/tests/TestCase/View/Helper/AssetHelperTest.php b/tests/TestCase/View/Helper/AssetHelperTest.php
index 202abe0..df89b2e 100644
--- a/tests/TestCase/View/Helper/AssetHelperTest.php
+++ b/tests/TestCase/View/Helper/AssetHelperTest.php
@@ -19,18 +19,19 @@
use BEdita\WebTools\View\Helper\AssetHelper;
use Cake\TestSuite\TestCase;
use Cake\View\View;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
/**
* {@see \BEdita\WebTools\View\Helper\AssetHelper} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\View\Helper\AssetHelper
*/
+#[CoversClass(AssetHelper::class)]
+#[CoversMethod(AssetHelper::class, 'get')]
class AssetHelperTest extends TestCase
{
/**
* Test `get` method
*
- * @covers ::get()
* @return void
*/
public function testGet(): void
diff --git a/tests/TestCase/View/Helper/HtmlHelperTest.php b/tests/TestCase/View/Helper/HtmlHelperTest.php
index 17cd891..90dca78 100644
--- a/tests/TestCase/View/Helper/HtmlHelperTest.php
+++ b/tests/TestCase/View/Helper/HtmlHelperTest.php
@@ -22,12 +22,27 @@
use Cake\Http\ServerRequest;
use Cake\TestSuite\TestCase;
use Cake\View\View;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\View\Helper\HtmlHelper} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\View\Helper\HtmlHelper
*/
+#[CoversClass(HtmlHelper::class)]
+#[CoversMethod(HtmlHelper::class, 'assets')]
+#[CoversMethod(HtmlHelper::class, 'css')]
+#[CoversMethod(HtmlHelper::class, 'getMeta')]
+#[CoversMethod(HtmlHelper::class, 'initialize')]
+#[CoversMethod(HtmlHelper::class, 'metaAll')]
+#[CoversMethod(HtmlHelper::class, 'metaAuthor')]
+#[CoversMethod(HtmlHelper::class, 'metaCss')]
+#[CoversMethod(HtmlHelper::class, 'metaDescription')]
+#[CoversMethod(HtmlHelper::class, 'metaGenerator')]
+#[CoversMethod(HtmlHelper::class, 'metaOpenGraph')]
+#[CoversMethod(HtmlHelper::class, 'metaTwitter')]
+#[CoversMethod(HtmlHelper::class, 'script')]
+#[CoversMethod(HtmlHelper::class, 'title')]
class HtmlHelperTest extends TestCase
{
/**
@@ -64,7 +79,7 @@ public function tearDown(): void
*
* @return array
*/
- public function titleProvider(): array
+ public static function titleProvider(): array
{
return [
'empty string' => [
@@ -103,14 +118,13 @@ public function titleProvider(): array
/**
* Test `title` method
*
- * @dataProvider titleProvider()
- * @covers ::title()
* @param string|null $controllerName The controller name
* @param string|null $actionName The action name
* @param string|null $viewVarTitle The title
* @param string $expected The expected title
* @return void
*/
+ #[DataProvider('titleProvider')]
public function testTitle(?string $controllerName, ?string $actionName, ?string $viewVarTitle, string $expected): void
{
$request = new ServerRequest([
@@ -130,7 +144,7 @@ public function testTitle(?string $controllerName, ?string $actionName, ?string
*
* @return array
*/
- public function metaDescriptionProvider(): array
+ public static function metaDescriptionProvider(): array
{
return [
'null description' => [
@@ -155,12 +169,11 @@ public function metaDescriptionProvider(): array
/**
* Test `metaDescription` method
*
- * @dataProvider metaDescriptionProvider()
- * @covers ::metaDescription()
* @param string|null $description The description
* @param string $expected The expected meta description
* @return void
*/
+ #[DataProvider('metaDescriptionProvider')]
public function testMetaDescription(?string $description, string $expected): void
{
$actual = $this->Html->metaDescription($description);
@@ -172,7 +185,7 @@ public function testMetaDescription(?string $description, string $expected): voi
*
* @return array
*/
- public function metaAuthorProvider(): array
+ public static function metaAuthorProvider(): array
{
return [
'null creator' => [
@@ -197,12 +210,11 @@ public function metaAuthorProvider(): array
/**
* Test `metaAuthor` method
*
- * @dataProvider metaAuthorProvider()
- * @covers ::metaAuthor()
* @param string|null $creator The content creator
* @param string $expected The expected meta content author
* @return void
*/
+ #[DataProvider('metaAuthorProvider')]
public function testMetaAuthor(?string $creator, string $expected): void
{
$actual = $this->Html->metaAuthor($creator);
@@ -214,7 +226,7 @@ public function testMetaAuthor(?string $creator, string $expected): void
*
* @return array
*/
- public function metaCssProvider(): array
+ public static function metaCssProvider(): array
{
return [
'empty docType' => [
@@ -231,12 +243,11 @@ public function metaCssProvider(): array
/**
* Test `metaCss` method
*
- * @dataProvider metaCssProvider()
- * @covers ::metaCss()
* @param string $docType The doc type
* @param string $expected The expected meta content author
* @return void
*/
+ #[DataProvider('metaCssProvider')]
public function testMetaCss(string $docType, string $expected): void
{
$actual = $this->Html->metaCss($docType);
@@ -248,7 +259,7 @@ public function testMetaCss(string $docType, string $expected): void
*
* @return array
*/
- public function metaGeneratorProvider(): array
+ public static function metaGeneratorProvider(): array
{
return [
'empty project and version 1' => [
@@ -281,12 +292,11 @@ public function metaGeneratorProvider(): array
/**
* Test `metaGenerator` method
*
- * @dataProvider metaGeneratorProvider()
- * @covers ::metaGenerator()
* @param array $project The project data ('name', 'version')
* @param string $expected The expected meta content author
* @return void
*/
+ #[DataProvider('metaGeneratorProvider')]
public function testMetaGenerator(array $project, string $expected): void
{
$actual = $this->Html->metaGenerator($project);
@@ -298,7 +308,7 @@ public function testMetaGenerator(array $project, string $expected): void
*
* @return array
*/
- public function metaAllProvider(): array
+ public static function metaAllProvider(): array
{
return [
'empty data' => [
@@ -325,12 +335,11 @@ public function metaAllProvider(): array
/**
* Test `metaAll` method
*
- * @dataProvider metaAllProvider()
- * @covers ::metaAll()
* @param array $data The data for meta
* @param string $expected The expected meta html
* @return void
*/
+ #[DataProvider('metaAllProvider')]
public function testMetaAll(array $data, string $expected): void
{
$actual = $this->Html->metaAll($data);
@@ -342,7 +351,7 @@ public function testMetaAll(array $data, string $expected): void
*
* @return array
*/
- public function metaOpenGraphProvider(): array
+ public static function metaOpenGraphProvider(): array
{
return [
'empty data' => [
@@ -364,12 +373,11 @@ public function metaOpenGraphProvider(): array
/**
* Test `metaOpenGraph` method
*
- * @dataProvider metaOpenGraphProvider()
- * @covers ::metaOpenGraph()
* @param array $data The data for meta
* @param string $expected The expected meta html
* @return void
*/
+ #[DataProvider('metaOpenGraphProvider')]
public function testMetaOpenGraph(array $data, string $expected): void
{
$actual = $this->Html->metaOpenGraph($data);
@@ -381,7 +389,7 @@ public function testMetaOpenGraph(array $data, string $expected): void
*
* @return array
*/
- public function metaTwitterProvider(): array
+ public static function metaTwitterProvider(): array
{
return [
'empty data' => [
@@ -405,12 +413,11 @@ public function metaTwitterProvider(): array
/**
* Test `metaTwitter` method
*
- * @dataProvider metaTwitterProvider()
- * @covers ::metaTwitter()
* @param array $data The data for meta
* @param string $expected The expected meta html
* @return void
*/
+ #[DataProvider('metaTwitterProvider')]
public function testMetaTwitter(array $data, string $expected): void
{
$actual = $this->Html->metaTwitter($data);
@@ -422,7 +429,7 @@ public function testMetaTwitter(array $data, string $expected): void
*
* @return array
*/
- public function getMetaProvider(): array
+ public static function getMetaProvider(): array
{
return [
// string
@@ -475,9 +482,6 @@ public function getMetaProvider(): array
/**
* Test `getMeta` method
*
- * @dataProvider getMetaProvider()
- * @covers ::getMeta()
- * @covers ::initialize()
* @param array $config The configuration
* @param array $data The data
* @param array $string The field for data
@@ -485,6 +489,7 @@ public function getMetaProvider(): array
* @param string|array|null $expected The expected meta
* @return void
*/
+ #[DataProvider('getMetaProvider')]
public function testGetMeta(array $config, array $data, string $field, $defaultVal = null, $expected = null): void
{
$this->Html = new HtmlHelper(new View(), $config);
@@ -497,7 +502,7 @@ public function testGetMeta(array $config, array $data, string $field, $defaultV
*
* @return array
*/
- public function scriptProvider(): array
+ public static function scriptProvider(): array
{
return [
'simple' => [
@@ -542,9 +547,8 @@ public function scriptProvider(): array
* @param string|string[] $name The asset name
* @param \BEdita\WebTools\Utility\Asset\AssetStrategyInterface $strategy The asset strategy to adopt
* @return void
- * @dataProvider scriptProvider()
- * @covers ::script()
*/
+ #[DataProvider('scriptProvider')]
public function testScript($expected, $name, AssetStrategyInterface $strategy): void
{
AssetsRevisions::setStrategy($strategy);
@@ -557,7 +561,7 @@ public function testScript($expected, $name, AssetStrategyInterface $strategy):
*
* @return array
*/
- public function cssProvider(): array
+ public static function cssProvider(): array
{
return [
'simple' => [
@@ -618,9 +622,8 @@ public function cssProvider(): array
* @param string|string[] $name The asset name
* @param \BEdita\WebTools\Utility\Asset\AssetStrategyInterface $strategy The asset strategy to adopt
* @return void
- * @dataProvider cssProvider()
- * @covers ::css()
*/
+ #[DataProvider('cssProvider')]
public function testCss($expected, $name, AssetStrategyInterface $strategy): void
{
AssetsRevisions::setStrategy($strategy);
@@ -633,7 +636,7 @@ public function testCss($expected, $name, AssetStrategyInterface $strategy): voi
*
* @return array
*/
- public function assetsProvider(): array
+ public static function assetsProvider(): array
{
return [
'css found and js fallback' => [
@@ -672,9 +675,8 @@ public function assetsProvider(): array
* @param string|string[] $name The asset name
* @param \BEdita\WebTools\Utility\Asset\AssetStrategyInterface $strategy The asset strategy to adopt
* @return void
- * @dataProvider assetsProvider()
- * @covers ::assets()
*/
+ #[DataProvider('assetsProvider')]
public function testAssets($expected, $name, AssetStrategyInterface $strategy): void
{
AssetsRevisions::setStrategy($strategy);
diff --git a/tests/TestCase/View/Helper/IdentityHelperTest.php b/tests/TestCase/View/Helper/IdentityHelperTest.php
index 78dc58c..d31fe97 100644
--- a/tests/TestCase/View/Helper/IdentityHelperTest.php
+++ b/tests/TestCase/View/Helper/IdentityHelperTest.php
@@ -12,27 +12,30 @@
*
* See LICENSE.LGPL or for more details.
*/
-namespace BEdita\WebTools\Test\TestCase;
+namespace BEdita\WebTools\Test\TestCase\View\Helper;
+use BadMethodCallException;
use BEdita\WebTools\Identity;
use BEdita\WebTools\View\Helper\IdentityHelper;
use Cake\Http\ServerRequest;
use Cake\TestSuite\TestCase;
use Cake\View\View;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
/**
* {@see BEdita\WebTools\View\Helper\IdentityHelper} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\View\Helper\IdentityHelper
*/
+#[CoversClass(IdentityHelper::class)]
+#[CoversMethod(IdentityHelper::class, '__call')]
class IdentityHelperTest extends TestCase
{
/**
* Keep Identity instance.
*
- * @var \BEdita\WebTools\Identity
+ * @var \BEdita\WebTools\Identity|null
*/
- protected $identity = null;
+ protected ?Identity $identity = null;
/**
* @inheritDoc
@@ -63,7 +66,6 @@ public function tearDown(): void
* Test that delegating a configured method works as expected.
*
* @return void
- * @covers ::__call()
*/
public function testDelgateOk(): void
{
@@ -79,11 +81,10 @@ public function testDelgateOk(): void
* Test that a `BadMethodCallException` is thrown calling method without identity.
*
* @return void
- * @covers ::__call()
*/
public function testDelegateNoIdentity(): void
{
- $this->expectException(\BadMethodCallException::class);
+ $this->expectException(BadMethodCallException::class);
$this->expectExceptionMessage('Cannot call `hasRole` on stored identity since it is not an object.');
$request = (new ServerRequest())->withAttribute('identity', null);
@@ -96,11 +97,10 @@ public function testDelegateNoIdentity(): void
* Test that a `BadMethodCallException` is thrown calling not delegated method.
*
* @return void
- * @covers ::__call()
*/
public function testDelegateBadDelegateMethod(): void
{
- $this->expectException(\BadMethodCallException::class);
+ $this->expectException(BadMethodCallException::class);
$this->expectExceptionMessage('Cannot call `fakeMethod`. Make sure to add it to `delegateMethods`.');
$request = (new ServerRequest())->withAttribute('identity', $this->identity);
diff --git a/tests/TestCase/View/Helper/ThumbHelperTest.php b/tests/TestCase/View/Helper/ThumbHelperTest.php
index 03556a6..404bd2f 100644
--- a/tests/TestCase/View/Helper/ThumbHelperTest.php
+++ b/tests/TestCase/View/Helper/ThumbHelperTest.php
@@ -22,12 +22,21 @@
use Cake\TestSuite\TestCase;
use Cake\Utility\Hash;
use Cake\View\View;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\View\Helper\ThumbHelper} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\View\Helper\ThumbHelper
*/
+#[CoversClass(ThumbHelper::class)]
+#[CoversMethod(ThumbHelper::class, 'getUrl')]
+#[CoversMethod(ThumbHelper::class, 'hasUrl')]
+#[CoversMethod(ThumbHelper::class, 'initialize')]
+#[CoversMethod(ThumbHelper::class, 'isAcceptable')]
+#[CoversMethod(ThumbHelper::class, 'isReady')]
+#[CoversMethod(ThumbHelper::class, 'status')]
+#[CoversMethod(ThumbHelper::class, 'url')]
class ThumbHelperTest extends TestCase
{
/**
@@ -135,7 +144,6 @@ private function _imageData($filename = 'test.png'): ?array
* Initialize Thumb Helper test
*
* @return void
- * @covers ::initialize()
*/
public function testInitialize(): void
{
@@ -149,7 +157,6 @@ public function testInitialize(): void
* Initialize Thumb Helper test, custom cfg
*
* @return void
- * @covers ::initialize()
*/
public function testInitializeCustomConfig(): void
{
@@ -172,7 +179,7 @@ public function testInitializeCustomConfig(): void
*
* @return array
*/
- public function urlProvider(): array
+ public static function urlProvider(): array
{
return [
'basic thumb default preset' => [
@@ -184,7 +191,7 @@ public function urlProvider(): array
],
'thumb error, return null' => [
[
- 'id' => 999999999999999999999999999999999999999999999,
+ 'id' => -1,
'options' => null, // use default preset
],
ThumbHelper::NOT_AVAILABLE,
@@ -195,13 +202,11 @@ public function urlProvider(): array
/**
* Test `url()` method.
*
- * @dataProvider urlProvider()
- * @covers ::url()
- * @covers ::status()
* @param array $input The input array.
* @param bool $expected The expected boolean.
* @return void
*/
+ #[DataProvider('urlProvider')]
public function testUrl(array $input, $expected): void
{
$id = empty($input['id']) ? $this->_image() : $input['id'];
@@ -218,12 +223,11 @@ public function testUrl(array $input, $expected): void
/**
* Test `status()` method.
*
- * @dataProvider urlProvider()
- * @covers ::status()
* @param array $input The input array.
* @param bool $expected The expected boolean.
* @return void
*/
+ #[DataProvider('urlProvider')]
public function testStatus(array $input, $expected): void
{
// case response with api call
@@ -254,8 +258,6 @@ public function testStatus(array $input, $expected): void
/**
* Test `isAcceptable()` method.
*
- * @covers ::status()
- * @covers ::isAcceptable()
* @return void
*/
public function testIsAcceptable(): void
@@ -310,8 +312,6 @@ public function testIsAcceptable(): void
/**
* Test `isReady()` method.
*
- * @covers ::status()
- * @covers ::isReady()
* @return void
*/
public function testIsReady(): void
@@ -364,8 +364,6 @@ public function testIsReady(): void
/**
* Test `hasUrl()` method.
*
- * @covers ::status()
- * @covers ::hasUrl()
* @return void
*/
public function testHasUrl(): void
@@ -418,7 +416,6 @@ public function testHasUrl(): void
/**
* Test `status()` method with missing input.
*
- * @covers ::status()
* @return void
*/
public function testStatusInput(): void
@@ -430,7 +427,6 @@ public function testStatusInput(): void
/**
* Test `getUrl()`
*
- * @covers ::getUrl()
* @return void
*/
public function testGetUrl(): void
diff --git a/tests/TestCase/View/Helper/WebComponentsHelperTest.php b/tests/TestCase/View/Helper/WebComponentsHelperTest.php
index eccd0d3..e3c0f61 100644
--- a/tests/TestCase/View/Helper/WebComponentsHelperTest.php
+++ b/tests/TestCase/View/Helper/WebComponentsHelperTest.php
@@ -17,12 +17,17 @@
use BEdita\WebTools\View\Helper\WebComponentsHelper;
use Cake\TestSuite\TestCase;
use Cake\View\View;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use PHPUnit\Framework\Attributes\DataProvider;
/**
* {@see \BEdita\WebTools\View\Helper\WebComponentsHelper} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\View\Helper\WebComponentsHelper
*/
+#[CoversClass(WebComponentsHelper::class)]
+#[CoversMethod(WebComponentsHelper::class, 'element')]
+#[CoversMethod(WebComponentsHelper::class, 'is')]
+#[CoversMethod(WebComponentsHelper::class, 'props')]
class WebComponentsHelperTest extends TestCase
{
/**
@@ -58,7 +63,7 @@ public function tearDown(): void
*
* @return array
*/
- public function propsProvider(): array
+ public static function propsProvider(): array
{
return [
'empty' => [
@@ -99,12 +104,11 @@ public function propsProvider(): array
/**
* Test `props` method
*
- * @dataProvider propsProvider()
- * @covers ::props()
* @param array $expected The expected result
* @param array $properties The element properties
* @return void
*/
+ #[DataProvider('propsProvider')]
public function testProps($expected, $properties): void
{
$result = $this->WebComponents->props($properties);
@@ -116,7 +120,7 @@ public function testProps($expected, $properties): void
*
* @return array
*/
- public function isProvider(): array
+ public static function isProvider(): array
{
return [
'simple' => [
@@ -141,12 +145,11 @@ public function isProvider(): array
/**
* Test `is` method
*
- * @dataProvider isProvider()
- * @covers ::is()
* @param string $expected The expected result
* @param array $properties The element properties
* @return void
*/
+ #[DataProvider('isProvider')]
public function testIs($expected, $properties): void
{
$result = $this->WebComponents->is($properties[0], $properties[1]);
@@ -157,7 +160,6 @@ public function testIs($expected, $properties): void
* Test `is` method with script path
*
* @return void
- * @covers ::is()
*/
public function testIsWithScript(): void
{
@@ -171,7 +173,7 @@ public function testIsWithScript(): void
*
* @return array
*/
- public function elementProvider(): array
+ public static function elementProvider(): array
{
return [
'simple' => [
@@ -196,12 +198,11 @@ public function elementProvider(): array
/**
* Test `element` method
*
- * @dataProvider elementProvider()
- * @covers ::element()
* @param string $expected The expected result
* @param array $properties The element properties
* @return void
*/
+ #[DataProvider('elementProvider')]
public function testElement($expected, $properties): void
{
$result = $this->WebComponents->element($properties[0], $properties[1]);
@@ -212,7 +213,6 @@ public function testElement($expected, $properties): void
* Test `element` method with script path
*
* @return void
- * @covers ::element()
*/
public function testElementWithScript(): void
{
diff --git a/tests/TestCase/View/Twig/BeditaTwigExtensionTest.php b/tests/TestCase/View/Twig/BeditaTwigExtensionTest.php
index bd96018..ee289ce 100644
--- a/tests/TestCase/View/Twig/BeditaTwigExtensionTest.php
+++ b/tests/TestCase/View/Twig/BeditaTwigExtensionTest.php
@@ -14,24 +14,31 @@
*/
namespace BEdita\WebTools\Test\TestCase\View\Twig;
+use BEdita\WebTools\View\Twig\BeditaTwigExtension;
+use Cake\Core\Configure;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\CoversMethod;
+use Twig\TwigFilter;
+use Twig\TwigFunction;
/**
* {@see \BEdita\WebTools\View\Twig\BeditaTwigExtension} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\View\Twig\BeditaTwigExtension
*/
+#[CoversClass(BeditaTwigExtension::class)]
+#[CoversMethod(BeditaTwigExtension::class, 'getFilters')]
+#[CoversMethod(BeditaTwigExtension::class, 'getFunctions')]
+#[CoversMethod(BeditaTwigExtension::class, 'getName')]
class BeditaTwigExtensionTest extends TestCase
{
/**
* Test `getName` method
*
* @return void
- * @covers ::getName()
*/
public function testGetName(): void
{
- $twigExtension = new \BEdita\WebTools\View\Twig\BeditaTwigExtension();
+ $twigExtension = new BeditaTwigExtension();
$this->assertEquals('bedita', $twigExtension->getName());
}
@@ -39,46 +46,44 @@ public function testGetName(): void
* Test `getFunctions` method
*
* @return void
- * @covers ::getFunctions()
*/
public function testGetFunctions(): void
{
- $twigExtension = new \BEdita\WebTools\View\Twig\BeditaTwigExtension();
+ $twigExtension = new BeditaTwigExtension();
$functions = $twigExtension->getFunctions();
$this->assertCount(2, $functions);
- $this->assertInstanceOf(\Twig\TwigFunction::class, $functions[0]);
+ $this->assertInstanceOf(TwigFunction::class, $functions[0]);
$this->assertEquals('config', $functions[0]->getName());
- $debug = \Cake\Core\Configure::read('debug');
+ $debug = Configure::read('debug');
$this->assertEquals($debug, $functions[0]->getCallable()('debug'));
- $this->assertInstanceOf(\Twig\TwigFunction::class, $functions[1]);
+ $this->assertInstanceOf(TwigFunction::class, $functions[1]);
$this->assertEquals('write_config', $functions[1]->getName());
$this->assertNull($functions[1]->getCallable()('debug', true));
$this->assertEquals(true, $functions[0]->getCallable()('debug'));
- \Cake\Core\Configure::write('debug', $debug);
+ Configure::write('debug', $debug);
}
/**
* Test `getFilters` method
*
* @return void
- * @covers ::getFilters()
*/
public function testGetFilters(): void
{
- $twigExtension = new \BEdita\WebTools\View\Twig\BeditaTwigExtension();
+ $twigExtension = new BeditaTwigExtension();
$filters = $twigExtension->getFilters();
$this->assertCount(3, $filters);
- $this->assertInstanceOf(\Twig\TwigFilter::class, $filters[0]);
+ $this->assertInstanceOf(TwigFilter::class, $filters[0]);
$this->assertEquals('shuffle', $filters[0]->getName());
$actual = $filters[0]->getCallable()([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$this->assertCount(10, $actual);
$this->assertNotEquals([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], $actual);
- $this->assertInstanceOf(\Twig\TwigFilter::class, $filters[1]);
+ $this->assertInstanceOf(TwigFilter::class, $filters[1]);
$this->assertEquals('ksort', $filters[1]->getName());
$actual = $filters[1]->getCallable()(['c' => 2, 'a' => 0, 'b' => 1]);
$expected = ['a' => 0, 'b' => 1, 'c' => 2];
$this->assertEquals($expected, $actual);
- $this->assertInstanceOf(\Twig\TwigFilter::class, $filters[2]);
+ $this->assertInstanceOf(TwigFilter::class, $filters[2]);
$this->assertEquals('krsort', $filters[2]->getName());
$actual = $filters[2]->getCallable()(['c' => 2, 'a' => 0, 'b' => 1]);
$expected = ['c' => 2, 'b' => 1, 'a' => 0];
diff --git a/tests/TestCase/View/TwigViewTest.php b/tests/TestCase/View/TwigViewTest.php
index 03698f0..3519833 100644
--- a/tests/TestCase/View/TwigViewTest.php
+++ b/tests/TestCase/View/TwigViewTest.php
@@ -16,12 +16,12 @@
use BEdita\WebTools\View\TwigView;
use Cake\TestSuite\TestCase;
+use PHPUnit\Framework\Attributes\CoversClass;
/**
* {@see \BEdita\WebTools\View\TwigView} Test Case
- *
- * @coversDefaultClass \BEdita\WebTools\View\TwigView
*/
+#[CoversClass(TwigView::class)]
class TwigViewTest extends TestCase
{
/**
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index 5f4e57d..643861f 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -12,11 +12,14 @@
*
* See LICENSE.LGPL or for more details.
*/
+
+use BEdita\WebTools\Plugin as WebToolsPlugin;
use Cake\Cache\Cache;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Datasource\ConnectionManager;
use Cake\Routing\Router;
+use josegonzalez\Dotenv\Loader;
/**
* Test suite bootstrap for BEdita/WebTools.
@@ -26,8 +29,10 @@
* installed as a dependency of an application.
*/
+require dirname(__DIR__) . '/vendor/autoload.php';
+
if (!getenv('BEDITA_API') && file_exists(dirname(__DIR__) . '/tests/.env')) {
- $dotenv = new \josegonzalez\Dotenv\Loader([dirname(__DIR__) . '/tests/.env']);
+ $dotenv = new Loader([dirname(__DIR__) . '/tests/.env']);
$dotenv->parse()
->putenv()
->toEnv()
@@ -48,21 +53,18 @@
$root = $findRoot(__FILE__);
unset($findRoot);
-chdir($root);
-
-require_once 'vendor/cakephp/cakephp/src/basics.php';
-require_once 'vendor/autoload.php';
+if (!defined('DS')) {
+ define('DS', DIRECTORY_SEPARATOR);
+}
+// before calling bootstrap, define some constants
+define('APP', $root . DS . 'tests' . DS . 'test_app' . DS);
+define('CACHE', sys_get_temp_dir() . DS . 'cache' . DS);
+define('CONFIG', $root . DS . 'test_app' . DS . 'config' . DS);
+define('WWW_ROOT', $root . DS . 'tests' . DS . 'test_app' . DS . 'webroot' . DS);
-define('ROOT', $root . DS . 'tests' . DS . 'test_app' . DS);
-define('APP', ROOT . 'TestApp' . DS);
-define('TMP', sys_get_temp_dir() . DS);
-define('LOGS', TMP . 'logs' . DS);
-define('CACHE', TMP . 'cache' . DS);
-define('CONFIG', ROOT . DS . 'config' . DS);
-define('WWW_ROOT', ROOT . DS . 'webroot' . DS);
+require $root . DS . 'config' . DS . 'bootstrap.php';
-define('CAKE_CORE_INCLUDE_PATH', ROOT);
-define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
+chdir($root);
Configure::write('debug', true);
@@ -112,5 +114,4 @@
ConnectionManager::setConfig('test', ['url' => getenv('db_dsn')]);
Router::reload();
-require $root . DS . 'config' . DS . 'bootstrap.php';
-Plugin::getCollection()->add(new \BEdita\WebTools\Plugin());
+Plugin::getCollection()->add(new WebToolsPlugin());
diff --git a/tests/test_app/TestApp/Application.php b/tests/test_app/TestApp/Application.php
index 6644f2b..862257c 100644
--- a/tests/test_app/TestApp/Application.php
+++ b/tests/test_app/TestApp/Application.php
@@ -3,6 +3,7 @@
namespace TestApp;
+use BEdita\WebTools\Plugin;
use Cake\Http\BaseApplication;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Middleware\RoutingMiddleware;
@@ -23,6 +24,7 @@ class Application extends BaseApplication
*/
public function bootstrap(): void
{
+ $this->addPlugin(new Plugin());
}
/**
diff --git a/tests/test_app/TestApp/Policy/CustomPolicy.php b/tests/test_app/TestApp/Policy/CustomPolicy.php
index e3a8aea..6d7bb09 100644
--- a/tests/test_app/TestApp/Policy/CustomPolicy.php
+++ b/tests/test_app/TestApp/Policy/CustomPolicy.php
@@ -5,11 +5,12 @@
use Authorization\IdentityInterface;
use Authorization\Policy\RequestPolicyInterface;
+use Authorization\Policy\ResultInterface;
use Cake\Http\ServerRequest;
class CustomPolicy implements RequestPolicyInterface
{
- public function canAccess(?IdentityInterface $identity, ServerRequest $request)
+ public function canAccess(?IdentityInterface $identity, ServerRequest $request): ResultInterface|bool
{
return true;
}