diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index 8786e7b..d43bc45 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -41,17 +41,35 @@ return (new PhpCsFixer\Config) ->setRiskyAllowed(true) ->setHideProgress(false) ->setRules([ - '@PSR2' => true, - 'strict_param' => true, - 'array_syntax' => ['syntax' => 'short'], - '@PhpCsFixer' => true, - '@PHP73Migration' => true, - 'no_php4_constructor' => true, - 'no_unused_imports' => true, - 'no_useless_else' => true, - 'no_superfluous_phpdoc_tags' => false, - 'void_return' => true, - 'yoda_style' => false, + '@PhpCsFixer' => true, + // '@PhpCsFixer:risky' => true, + '@PHP82Migration' => true, + '@PHP80Migration:risky' => true, + '@PSR12' => true, + '@PSR12:risky' => true, + '@PHPUnit100Migration:risky' => true, + + 'binary_operator_spaces' => [ + 'default' => 'align_single_space_minimal', + 'operators' => [ + '=' => 'align_single_space', + '=>' => 'align_single_space', + ], + ], + 'types_spaces' => [ + 'space' => 'single', + 'space_multiple_catch' => 'single', + ], + + // Annoyance-fixers: + 'concat_space' => ['spacing' => 'one'], // This one is a matter of taste. + 'no_superfluous_phpdoc_tags' => [ + 'allow_mixed' => false, + 'allow_unused_params' => false, + 'remove_inheritdoc' => true, + ], + 'yoda_style' => false, // Disabled as its annoying. Comes with @PhpCsFixer + 'native_function_invocation' => false, // Disabled as adding count($i) -> \count($i) is annoying, but supposedly more performant ]) ->setFinder($finder) ; diff --git a/bin/find-autoloader.php b/bin/find-autoloader.php index bea51fa..a58ba45 100644 --- a/bin/find-autoloader.php +++ b/bin/find-autoloader.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + function detectAndLoadVendor($path = __DIR__): void { $path = realpath($path); @@ -11,12 +13,12 @@ function detectAndLoadVendor($path = __DIR__): void if ($fileInfo->isDir() && 'vendor' == $fileInfo->getFilename()) { define('VENDOR_PATH', $fileInfo->getRealPath()); - require_once VENDOR_PATH.'/autoload.php'; + require_once VENDOR_PATH . '/autoload.php'; return; } } - detectAndLoadVendor($path.'/../'); + detectAndLoadVendor($path . '/../'); } detectAndLoadVendor(); diff --git a/src/Annotations/JsonSchema.php b/src/Annotations/JsonSchema.php index 26616f8..2bce6bb 100644 --- a/src/Annotations/JsonSchema.php +++ b/src/Annotations/JsonSchema.php @@ -8,7 +8,6 @@ use Doctrine\Common\Annotations\Annotation\Required; /** * @Annotation - * * @Target("METHOD") */ class JsonSchema diff --git a/src/Annotations/Route.php b/src/Annotations/Route.php index bc61f9f..249cccb 100644 --- a/src/Annotations/Route.php +++ b/src/Annotations/Route.php @@ -8,12 +8,10 @@ use Doctrine\Common\Annotations\Annotation\Required; /** * @Annotation - * * @Target("METHOD") */ class Route { - /** @var array */ public array $methods = ['GET']; /** @@ -21,12 +19,9 @@ class Route */ public string $path; - /** @var string */ public string $access = \Benzine\Router\Route::ACCESS_PUBLIC; - /** @var int */ public int $weight = 100; - /** @var array */ public array $domains = []; } diff --git a/src/App.php b/src/App.php index f8ae700..6951f29 100644 --- a/src/App.php +++ b/src/App.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine; use Benzine\Middleware\JsonResponseExecTimeMiddleware; @@ -31,7 +33,10 @@ use DebugBar\DebugBar; use DI\Container; use DI\ContainerBuilder; use Faker\Factory as FakerFactory; +use Faker\Generator; use Faker\Provider; +use Kint\Twig\TwigExtension; +use Middlewares\ContentLength; use Middlewares\TrailingSlash; use Monolog\Formatter\LineFormatter; use Monolog\Handler\StreamHandler; @@ -57,30 +62,26 @@ class App protected EnvironmentService $environmentService; protected ConfigurationService $configurationService; - protected \Slim\App $app; + protected Slim\App $app; protected Logger $logger; protected DebugBar $debugBar; protected Router $router; - protected bool $isSessionsEnabled = true; + protected bool $isSessionsEnabled = true; protected bool $interrogateControllersComplete = false; - protected ?CachePoolChain $cachePoolChain = null; - private array $viewPaths = []; - private string $cachePath = APP_ROOT.'/cache'; - private string $logPath = APP_ROOT.'/logs'; - private array $supportedLanguages = ['en_US']; - private bool $debugMode = false; + protected ?CachePoolChain $cachePoolChain = null; + private array $viewPaths = []; + private string $cachePath = APP_ROOT . '/cache'; + private string $logPath = APP_ROOT . '/logs'; + private array $supportedLanguages = ['en_US']; + private bool $debugMode = false; private static bool $isInitialised = false; public function __construct() { - if (!ini_get('auto_detect_line_endings')) { - ini_set('auto_detect_line_endings', '1'); - } - // Configure Dependency Injector - $container = $this->setupContainer(); - $this->logger = $container->get(Logger::class); + $container = $this->setupContainer(); + $this->logger = $container->get(Logger::class); $this->debugBar = $container->get(DebugBar::class); AppFactory::setContainer($container); @@ -91,8 +92,8 @@ class App } // Configure default expected views paths - $this->viewPaths[] = APP_ROOT.'/views/'; - $this->viewPaths[] = APP_ROOT.'/src/Views/'; + $this->viewPaths[] = APP_ROOT . '/views/'; + $this->viewPaths[] = APP_ROOT . '/src/Views/'; // Configure Slim $this->app = AppFactory::create(); @@ -132,19 +133,11 @@ class App return $this; } - /** - * @return array - */ public function getViewPaths(): array { return $this->viewPaths; } - /** - * @param array $viewPaths - * - * @return App - */ public function setViewPaths(array $viewPaths): App { $this->viewPaths = $viewPaths; @@ -152,19 +145,11 @@ class App return $this; } - /** - * @return string - */ public function getLogPath(): string { return $this->logPath; } - /** - * @param string $logPath - * - * @return App - */ public function setLogPath(string $logPath): App { $this->logPath = $logPath; @@ -182,7 +167,7 @@ class App public function setupContainer(): Container { - $app = $this; + $app = $this; $container = (new ContainerBuilder()) ->useAutowiring(true) @@ -207,7 +192,7 @@ class App } $twigCachePath = "{$this->getCachePath()}/twig"; - $twigSettings = []; + $twigSettings = []; if ($environmentService->has('TWIG_CACHE') && 'on' == strtolower($environmentService->get('TWIG_CACHE'))) { $twigSettings['cache'] = $twigCachePath; @@ -215,7 +200,7 @@ class App if (!(new Filesystem())->exists($twigCachePath)) { try { - (new Filesystem())->mkdir($twigCachePath, 0777); + (new Filesystem())->mkdir($twigCachePath, 0o777); } catch (IOException $IOException) { unset($twigSettings['cache']); if (!in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) { @@ -245,7 +230,7 @@ class App $twig->addExtension(new Twig\Extension\DebugExtension()); // Add Twig extension to integrate Kint - $twig->addExtension(new \Kint\Twig\TwigExtension()); + $twig->addExtension(new TwigExtension()); // Add Twig extension to check if something is an instance of a known class or entity $twig->addExtension(new Extensions\InstanceOfExtension()); @@ -267,9 +252,7 @@ class App }); // This is required as some plugins for Slim expect there to be a twig available as "view" - $container->set('view', function (Slim\Views\Twig $twig) { - return $twig; - }); + $container->set('view', fn (Slim\Views\Twig $twig) => $twig); $container->set(Translation\Translator::class, function (SessionService $sessionService) { $selectedLanguage = $sessionService->has('Language') ? $sessionService->get('Language') : 'en_US'; @@ -286,7 +269,7 @@ class App $translator->addLoader('yaml', $yamlLoader); // add some resources to the translator - $translator->addResource('yaml', APP_ROOT."/src/Strings/{$selectedLanguage}.yaml", $selectedLanguage); + $translator->addResource('yaml', APP_ROOT . "/src/Strings/{$selectedLanguage}.yaml", $selectedLanguage); return $translator; }); @@ -298,7 +281,7 @@ class App ); }); - $container->set(\Faker\Generator::class, function () { + $container->set(Generator::class, function () { $faker = FakerFactory::create(); $faker->addProvider(new Provider\Base($faker)); $faker->addProvider(new Provider\DateTime($faker)); @@ -339,7 +322,7 @@ class App $container->set('MonologFormatter', function (EnvironmentService $environmentService) { return new LineFormatter( // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%" - $environmentService->get('MONOLOG_FORMAT', '[%datetime%] %channel%.%level_name%: %message% %context% %extra%')."\n", + $environmentService->get('MONOLOG_FORMAT', '[%datetime%] %channel%.%level_name%: %message% %context% %extra%') . "\n", 'Y n j, g:i a' ); }); @@ -361,11 +344,11 @@ class App ))); // Configure a pretty CLI Handler - $cliHandler = new StreamHandler('php://stdout', Logger::DEBUG); + $cliHandler = new StreamHandler('php://stdout', Logger::DEBUG); $cliFormatter = new ColoredLineFormatter( new TrafficLight(), // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%" - $environmentService->get('MONOLOG_FORMAT', '[%datetime%] %level_name%: %message%')."\n", + $environmentService->get('MONOLOG_FORMAT', '[%datetime%] %level_name%: %message%') . "\n", 'g:i' ); $cliHandler->setFormatter($cliFormatter); @@ -392,9 +375,7 @@ class App ); }); - $container->set(TrailingSlash::class, function () { - return (new TrailingSlash())->redirect(); - }); + $container->set(TrailingSlash::class, fn () => (new TrailingSlash())->redirect()); $container->set(DebugBar::class, function (Logger $logger) { return (new DebugBar()) @@ -414,7 +395,7 @@ class App ); }); - $this->environmentService = $container->get(Services\EnvironmentService::class); + $this->environmentService = $container->get(EnvironmentService::class); if ($this->environmentService->has('TIMEZONE')) { date_default_timezone_set($this->environmentService->get('TIMEZONE')); } elseif ((new Filesystem())->exists('/etc/timezone')) { @@ -434,11 +415,11 @@ class App // Middlewares $this->app->addBodyParsingMiddleware(); // $this->app->add($container->get(\Middlewares\Geolocation::class)); - $this->app->add($container->get(\Middlewares\TrailingSlash::class)); + $this->app->add($container->get(TrailingSlash::class)); // $this->app->add($container->get(\Middlewares\Whoops::class)); // $this->app->add($container->get(\Middlewares\Minifier::class)); // $this->app->add($container->get(\Middlewares\GzipEncoder::class)); - $this->app->add($container->get(\Middlewares\ContentLength::class)); + $this->app->add($container->get(ContentLength::class)); } /** @@ -453,7 +434,7 @@ class App $tempApp = new $calledClass(); /** @var ConfigurationService $config */ - $config = $tempApp->get(ConfigurationService::class); + $config = $tempApp->get(ConfigurationService::class); $configCoreClass = $config->getCore(); if ($configCoreClass != get_called_class()) { self::$instance = new $configCoreClass(); @@ -499,7 +480,7 @@ class App public function runHttp(): void { $serverRequestCreator = ServerRequestCreatorFactory::create(); - $request = $serverRequestCreator->createServerRequestFromGlobals(); + $request = $serverRequestCreator->createServerRequestFromGlobals(); $this->loadAllRoutes($request); @@ -532,7 +513,7 @@ class App public function addSupportedLanguage(string $supportedLanguage): self { $this->supportedLanguages[] = $supportedLanguage; - $this->supportedLanguages = array_unique($this->supportedLanguages); + $this->supportedLanguages = array_unique($this->supportedLanguages); return $this; } @@ -573,7 +554,7 @@ class App $this->interrogateControllers(); $this->debugBar['time']->stopMeasure('interrogateControllers'); - $timeToBootstrapMs = (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000; + $timeToBootstrapMs = (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000; $bootstrapTooLongThresholdMs = 300; if ($timeToBootstrapMs >= $bootstrapTooLongThresholdMs && php_sapi_name() != 'cli') { $this->logger->warning(sprintf('Bootstrap complete in %sms which is more than the threshold of %sms', number_format($timeToBootstrapMs, 2), $bootstrapTooLongThresholdMs)); @@ -586,7 +567,7 @@ class App protected function interrogateTranslations(): void { - $stringPath = APP_ROOT.'/src/Strings'; + $stringPath = APP_ROOT . '/src/Strings'; if (!(new Filesystem())->exists($stringPath)) { return; } @@ -615,7 +596,7 @@ class App $appClass = new \ReflectionClass(static::class); $this->router->loadRoutesFromAnnotations( [ - APP_ROOT.'/src/Controllers', + APP_ROOT . '/src/Controllers', ], $appClass->getNamespaceName() ); diff --git a/src/Controllers/AbstractController.php b/src/Controllers/AbstractController.php index 412741a..1abf92f 100644 --- a/src/Controllers/AbstractController.php +++ b/src/Controllers/AbstractController.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Controllers; use Benzine\Controllers\Filters\Filter; @@ -17,8 +19,7 @@ abstract class AbstractController public function __construct( protected Logger $logger, protected CacheProvider $cacheProvider - ) { - } + ) {} public function xmlResponse(\SimpleXMLElement $root, Request $request, Response $response): Response { @@ -69,7 +70,7 @@ abstract class AbstractController return true; } - throw new FilterDecodeException('Could not decode given Filter. Reason: Not JSON. Given: "'.$filterText.'"'); + throw new FilterDecodeException('Could not decode given Filter. Reason: Not JSON. Given: "' . $filterText . '"'); } } @@ -103,7 +104,7 @@ abstract class AbstractController } // Generate an etag - $etag = md5($filesystem->lastModified($filename).$filename); + $etag = md5($filesystem->lastModified($filename) . $filename); $response = $this->cacheProvider->withEtag($response, $etag); // Detect mimetype for content-type header from file meta @@ -113,7 +114,7 @@ abstract class AbstractController // No dice? Early-load the data and interrogate that for mimetype then I GUESS. if (!$mimetype) { - $data = $filesystem->read($filename); + $data = $filesystem->read($filename); $mimetype = (new FinfoMimeTypeDetector()) ->detectMimeTypeFromBuffer($data) ; diff --git a/src/Controllers/AbstractCrudController.php b/src/Controllers/AbstractCrudController.php index 60cb12b..544822b 100644 --- a/src/Controllers/AbstractCrudController.php +++ b/src/Controllers/AbstractCrudController.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Controllers; use Benzine\ORM\Interfaces\ModelInterface; @@ -15,7 +17,7 @@ abstract class AbstractCrudController extends AbstractController $service = $this->getService(); if ($this->requestHasFilters($request, $response)) { $filterBehaviours = $this->parseFilters($request, $response); - $foundObjects = $service->getAll( + $foundObjects = $service->getAll( $filterBehaviours->getLimit(), $filterBehaviours->getOffset(), $filterBehaviours->getWheres(), @@ -32,8 +34,8 @@ abstract class AbstractCrudController extends AbstractController return $this->jsonResponse( [ - 'Status' => 'Okay', - 'Action' => 'LIST', + 'Status' => 'Okay', + 'Action' => 'LIST', $this->service->getTermPlural() => $objects, ], $request, @@ -47,8 +49,8 @@ abstract class AbstractCrudController extends AbstractController if ($object) { return $this->jsonResponse( [ - 'Status' => 'Okay', - 'Action' => 'GET', + 'Status' => 'Okay', + 'Action' => 'GET', $this->service->getTermSingular() => $object->__toArray(), ], $request, @@ -79,8 +81,8 @@ abstract class AbstractCrudController extends AbstractController return $this->jsonResponse( [ - 'Status' => 'Okay', - 'Action' => 'CREATE', + 'Status' => 'Okay', + 'Action' => 'CREATE', $this->service->getTermSingular() => $object->__toArray(), ], $request, @@ -101,8 +103,8 @@ abstract class AbstractCrudController extends AbstractController return $this->jsonResponse( [ - 'Status' => 'Okay', - 'Action' => 'DELETE', + 'Status' => 'Okay', + 'Action' => 'DELETE', $this->service->getTermSingular() => $array, ], $request, diff --git a/src/Controllers/AbstractHTMLController.php b/src/Controllers/AbstractHTMLController.php index 0f6683f..15a6e2f 100644 --- a/src/Controllers/AbstractHTMLController.php +++ b/src/Controllers/AbstractHTMLController.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Controllers; use DebugBar\DebugBar; @@ -48,7 +50,7 @@ abstract class AbstractHTMLController extends AbstractController )->withHeader('Content-Type', 'text/html'); $renderTimeLimitMs = 500; - $renderTimeMs = (microtime(true) - $renderStart) * 1000; + $renderTimeMs = (microtime(true) - $renderStart) * 1000; if ($renderTimeMs >= $renderTimeLimitMs) { $this->logger->debug(sprintf( diff --git a/src/Controllers/Filters/Filter.php b/src/Controllers/Filters/Filter.php index b6a9d7d..1971c22 100644 --- a/src/Controllers/Filters/Filter.php +++ b/src/Controllers/Filters/Filter.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Controllers\Filters; use Benzine\Exceptions\FilterDecodeException; @@ -20,8 +22,6 @@ class Filter /** * @throws FilterDecodeException - * - * @return Filter */ public function setOrderDirection(string $orderDirection): self { @@ -34,8 +34,6 @@ class Filter } /** - * @param $header - * * @throws FilterDecodeException */ public function parseFromHeader($header): self @@ -75,11 +73,6 @@ class Filter return $this->limit; } - /** - * @param mixed $limit - * - * @return Filter - */ public function setLimit($limit): self { $this->limit = $limit; @@ -92,11 +85,6 @@ class Filter return $this->offset; } - /** - * @param mixed $offset - * - * @return Filter - */ public function setOffset($offset): self { $this->offset = $offset; @@ -109,11 +97,6 @@ class Filter return $this->wheres; } - /** - * @param mixed $wheres - * - * @return Filter - */ public function setWheres($wheres): self { $this->wheres = $wheres; @@ -126,11 +109,6 @@ class Filter return $this->order; } - /** - * @param mixed $order - * - * @return Filter - */ public function setOrder($order): self { $this->order = $order; diff --git a/src/Controllers/Filters/FilterCondition.php b/src/Controllers/Filters/FilterCondition.php index a65ebf1..4bbf338 100644 --- a/src/Controllers/Filters/FilterCondition.php +++ b/src/Controllers/Filters/FilterCondition.php @@ -1,17 +1,19 @@ <?php +declare(strict_types=1); + namespace Benzine\Controllers\Filters; class FilterCondition { - public const CONDITION_EQUAL = '='; - public const CONDITION_NOT_EQUAL = '!='; - public const CONDITION_GREATER_THAN = '>'; - public const CONDITION_LESS_THAN = '<'; + public const CONDITION_EQUAL = '='; + public const CONDITION_NOT_EQUAL = '!='; + public const CONDITION_GREATER_THAN = '>'; + public const CONDITION_LESS_THAN = '<'; public const CONDITION_GREATER_THAN_OR_EQUAL = '>='; - public const CONDITION_LESS_THAN_OR_EQUAL = '<='; - public const CONDITION_LIKE = 'LIKE'; - public const CONDITION_NOT_LIKE = 'NOT LIKE'; - public const CONDITION_IN = 'IN'; - public const CONDITION_NOT_IN = 'NOT IN'; + public const CONDITION_LESS_THAN_OR_EQUAL = '<='; + public const CONDITION_LIKE = 'LIKE'; + public const CONDITION_NOT_LIKE = 'NOT LIKE'; + public const CONDITION_IN = 'IN'; + public const CONDITION_NOT_IN = 'NOT IN'; } diff --git a/src/Exceptions/BenzineConfigurationException.php b/src/Exceptions/BenzineConfigurationException.php index 9e6fca0..a9e9034 100644 --- a/src/Exceptions/BenzineConfigurationException.php +++ b/src/Exceptions/BenzineConfigurationException.php @@ -1,7 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Exceptions; -class BenzineConfigurationException extends BenzineException -{ -} +class BenzineConfigurationException extends BenzineException {} diff --git a/src/Exceptions/BenzineException.php b/src/Exceptions/BenzineException.php index 38c6940..9e6851c 100644 --- a/src/Exceptions/BenzineException.php +++ b/src/Exceptions/BenzineException.php @@ -1,7 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Exceptions; -class BenzineException extends \Exception -{ -} +class BenzineException extends \Exception {} diff --git a/src/Exceptions/DbConfigException.php b/src/Exceptions/DbConfigException.php index b1e6db6..832bd88 100644 --- a/src/Exceptions/DbConfigException.php +++ b/src/Exceptions/DbConfigException.php @@ -1,7 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Exceptions; -class DbConfigException extends BenzineException -{ -} +class DbConfigException extends BenzineException {} diff --git a/src/Exceptions/DbRuntimeException.php b/src/Exceptions/DbRuntimeException.php index dbbf7c5..1e49bb6 100644 --- a/src/Exceptions/DbRuntimeException.php +++ b/src/Exceptions/DbRuntimeException.php @@ -1,7 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Exceptions; -class DbRuntimeException extends BenzineException -{ -} +class DbRuntimeException extends BenzineException {} diff --git a/src/Exceptions/FilterDecodeException.php b/src/Exceptions/FilterDecodeException.php index 7dc8106..cff64bb 100644 --- a/src/Exceptions/FilterDecodeException.php +++ b/src/Exceptions/FilterDecodeException.php @@ -1,7 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Exceptions; -class FilterDecodeException extends BenzineException -{ -} +class FilterDecodeException extends BenzineException {} diff --git a/src/Exceptions/JsonErrorHandler.php b/src/Exceptions/JsonErrorHandler.php index 414c040..fa7600a 100644 --- a/src/Exceptions/JsonErrorHandler.php +++ b/src/Exceptions/JsonErrorHandler.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Exceptions; use Slim\Interfaces\ErrorRendererInterface; @@ -10,8 +12,8 @@ class JsonErrorHandler implements ErrorRendererInterface { return json_encode([ 'error' => $exception->getMessage(), - 'where' => $exception->getFile().':'.$exception->getLine(), - 'code' => $exception->getCode(), + 'where' => $exception->getFile() . ':' . $exception->getLine(), + 'code' => $exception->getCode(), ], JSON_PRETTY_PRINT); } } diff --git a/src/Exceptions/WorkerException.php b/src/Exceptions/WorkerException.php index 1de397f..7a04e5a 100644 --- a/src/Exceptions/WorkerException.php +++ b/src/Exceptions/WorkerException.php @@ -1,7 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Exceptions; -class WorkerException extends BenzineException -{ -} +class WorkerException extends BenzineException {} diff --git a/src/Guzzle/JsonResponse.php b/src/Guzzle/JsonResponse.php index d1b6694..670da3d 100644 --- a/src/Guzzle/JsonResponse.php +++ b/src/Guzzle/JsonResponse.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Guzzle; use Psr\Http\Message\ResponseInterface; @@ -9,8 +11,7 @@ class JsonResponse implements ResponseInterface { public function __construct( protected ResponseInterface $response - ) { - } + ) {} public function json() { diff --git a/src/Middleware/JsonResponseExecTimeMiddleware.php b/src/Middleware/JsonResponseExecTimeMiddleware.php index c10e0fc..2a9b617 100644 --- a/src/Middleware/JsonResponseExecTimeMiddleware.php +++ b/src/Middleware/JsonResponseExecTimeMiddleware.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Middleware; use Psr\Http\Message\ResponseInterface; @@ -18,10 +20,10 @@ class JsonResponseExecTimeMiddleware implements MiddlewareInterface if ($responseJson === null) { return $response; } - $memoryUsageBytes = memory_get_peak_usage(); + $memoryUsageBytes = memory_get_peak_usage(); $responseJson['Exec'] = [ - 'TimeSeconds' => (float) number_format(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 5), - 'MemoryBytes' => $memoryUsageBytes, + 'TimeSeconds' => (float) number_format(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 5), + 'MemoryBytes' => $memoryUsageBytes, 'MemoryMegaBytes' => (float) number_format($memoryUsageBytes / 1024 / 1024, 3), ]; diff --git a/src/Middleware/JsonValidationMiddleware.php b/src/Middleware/JsonValidationMiddleware.php index 959266a..3bd2573 100644 --- a/src/Middleware/JsonValidationMiddleware.php +++ b/src/Middleware/JsonValidationMiddleware.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Middleware; use Benzine\Annotations\JsonSchema; @@ -49,15 +51,16 @@ class JsonValidationMiddleware implements MiddlewareInterface try { // Validate it... $schema->in(json_decode($request->getBody()->getContents())); + // And if we get here, we're golden. return $handler->handle($request); } catch (Exception $exception) { // Whelp, we've failed validation, build a failure message. $response = new Response(); - $content = json_encode([ + $content = json_encode([ 'Status' => 'FAIL', 'Reason' => "Invalid JSON, doesn't match schema!", - 'Error' => $exception->getMessage(), + 'Error' => $exception->getMessage(), ], JSON_PRETTY_PRINT); $response->getBody()->write($content); diff --git a/src/Models/Traits/AuthableTrait.php b/src/Models/Traits/AuthableTrait.php index bb2edf5..d27aa5b 100644 --- a/src/Models/Traits/AuthableTrait.php +++ b/src/Models/Traits/AuthableTrait.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Models\Traits; use Carbon\Carbon; diff --git a/src/Redis/Lua/AbstractLuaExtension.php b/src/Redis/Lua/AbstractLuaExtension.php index 8027057..48f7cde 100644 --- a/src/Redis/Lua/AbstractLuaExtension.php +++ b/src/Redis/Lua/AbstractLuaExtension.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Redis\Lua; use Benzine\Redis\Redis; diff --git a/src/Redis/Lua/SetIfHigher.php b/src/Redis/Lua/SetIfHigher.php index 6ddcaca..5bf1142 100644 --- a/src/Redis/Lua/SetIfHigher.php +++ b/src/Redis/Lua/SetIfHigher.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Redis\Lua; class SetIfHigher extends AbstractLuaExtension @@ -7,16 +9,16 @@ class SetIfHigher extends AbstractLuaExtension protected function getScript(): string { return <<<'LUA' - local c = tonumber(redis.call('get', KEYS[1])); - if c then - if tonumber(ARGV[1]) > c then - redis.call('set', KEYS[1], ARGV[1]) - return tonumber(ARGV[1]) - c - else - return 0 - end - else - return redis.call('set', KEYS[1], ARGV[1]) + local c = tonumber(redis.call('get', KEYS[1])); + if c then + if tonumber(ARGV[1]) > c then + redis.call('set', KEYS[1], ARGV[1]) + return tonumber(ARGV[1]) - c + else + return 0 + end + else + return redis.call('set', KEYS[1], ARGV[1]) end LUA; } diff --git a/src/Redis/Lua/SetIfLower.php b/src/Redis/Lua/SetIfLower.php index 408d00c..d0fc7ab 100644 --- a/src/Redis/Lua/SetIfLower.php +++ b/src/Redis/Lua/SetIfLower.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Redis\Lua; class SetIfLower extends AbstractLuaExtension @@ -7,16 +9,16 @@ class SetIfLower extends AbstractLuaExtension protected function getScript(): string { return <<<'LUA' - local c = tonumber(redis.call('get', KEYS[1])); - if c then - if tonumber(ARGV[1]) < c then - redis.call('set', KEYS[1], ARGV[1]) - return tonumber(ARGV[1]) - c - else - return 0 - end - else - return redis.call('set', KEYS[1], ARGV[1]) + local c = tonumber(redis.call('get', KEYS[1])); + if c then + if tonumber(ARGV[1]) < c then + redis.call('set', KEYS[1], ARGV[1]) + return tonumber(ARGV[1]) - c + else + return 0 + end + else + return redis.call('set', KEYS[1], ARGV[1]) end LUA; } diff --git a/src/Redis/Lua/ZAddIfHigher.php b/src/Redis/Lua/ZAddIfHigher.php index e6efe50..d3025b7 100644 --- a/src/Redis/Lua/ZAddIfHigher.php +++ b/src/Redis/Lua/ZAddIfHigher.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Redis\Lua; class ZAddIfHigher extends AbstractLuaExtension @@ -7,17 +9,17 @@ class ZAddIfHigher extends AbstractLuaExtension protected function getScript(): string { return <<<'LUA' - local c = tonumber(redis.call('zscore', KEYS[1], ARGV[1])); - if c then - if tonumber(KEYS[2]) > c then - redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) - return tonumber(KEYS[2]) - c - else + local c = tonumber(redis.call('zscore', KEYS[1], ARGV[1])); + if c then + if tonumber(KEYS[2]) > c then + redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) + return tonumber(KEYS[2]) - c + else return 0 - end - else - redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) - return 'OK' + end + else + redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) + return 'OK' end LUA; } diff --git a/src/Redis/Lua/ZAddIfLower.php b/src/Redis/Lua/ZAddIfLower.php index e2dfb08..36fff8e 100644 --- a/src/Redis/Lua/ZAddIfLower.php +++ b/src/Redis/Lua/ZAddIfLower.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Redis\Lua; class ZAddIfLower extends AbstractLuaExtension @@ -7,17 +9,17 @@ class ZAddIfLower extends AbstractLuaExtension protected function getScript(): string { return <<<'LUA' - local c = tonumber(redis.call('zscore', KEYS[1], ARGV[1])); - if c then - if tonumber(KEYS[2]) < c then - redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) - return tonumber(KEYS[2]) - c - else + local c = tonumber(redis.call('zscore', KEYS[1], ARGV[1])); + if c then + if tonumber(KEYS[2]) < c then + redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) + return tonumber(KEYS[2]) - c + else return 0 - end - else - redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) - return 'OK' + end + else + redis.call('zadd', KEYS[1], KEYS[2], ARGV[1]) + return 'OK' end LUA; } diff --git a/src/Redis/Redis.php b/src/Redis/Redis.php index afa3759..4f080f3 100644 --- a/src/Redis/Redis.php +++ b/src/Redis/Redis.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Redis; use Monolog\Logger; @@ -230,14 +232,14 @@ class Redis /** @var Lua\AbstractLuaExtension[] */ private array $scripts; - public function __construct(Logger $logger, string $host, int $port = 6379, string $password = null, float $timeout = 0.0) + public function __construct(Logger $logger, string $host, int $port = 6379, ?string $password = null, float $timeout = 0.0) { $this->logger = $logger; - $this->host = $host; - $this->port = $port; + $this->host = $host; + $this->port = $port; $this->password = $password; - $this->timeout = $timeout; + $this->timeout = $timeout; $this->redis = new \Redis(); } diff --git a/src/Router/Route.php b/src/Router/Route.php index 1f03aac..a70b1b0 100644 --- a/src/Router/Route.php +++ b/src/Router/Route.php @@ -1,12 +1,14 @@ <?php +declare(strict_types=1); + namespace Benzine\Router; use Slim\App; class Route { - public const ACCESS_PUBLIC = 'public'; + public const ACCESS_PUBLIC = 'public'; public const ACCESS_PRIVATE = 'private'; public const ARGUMENT_ACCESS = '_access'; @@ -19,7 +21,7 @@ class Route protected $routerPattern; protected $httpEndpoint; protected $httpMethod = 'GET'; - protected $weight = 0; + protected $weight = 0; protected $singular; protected $plural; protected $properties; @@ -28,7 +30,7 @@ class Route protected $exampleEntity; protected $exampleEntityFinderFunction; protected array $callbackProperties = []; - protected array $arguments = [ + protected array $arguments = [ self::ARGUMENT_ACCESS => self::ACCESS_PUBLIC, ]; protected array $validDomains = []; @@ -49,7 +51,6 @@ class Route } /** - * @param $name * @param null $default * * @return $this @@ -58,21 +59,21 @@ class Route { return $this->populateCallbackProperty($name, [ 'isMandatory' => $mandatory, - 'default' => $default, + 'default' => $default, ]); } public function populateCallbackProperty(string $name, array $property) { - $property['name'] = $name; + $property['name'] = $name; $this->callbackProperties[$name] = array_merge( [ - 'in' => null, + 'in' => null, 'description' => null, 'isMandatory' => null, - 'default' => null, - 'type' => null, - 'examples' => [], + 'default' => null, + 'type' => null, + 'examples' => [], ], $property ); @@ -100,7 +101,7 @@ class Route if (is_numeric($name)) { $this->properties[] = $type; } else { - $this->properties[] = $name; + $this->properties[] = $name; $this->propertyData[$name]['type'] = $type; } } @@ -109,15 +110,13 @@ class Route } /** - * @param mixed $propertyOptions - * * @return Route */ public function setPropertyOptions($propertyOptions) { $this->propertyOptions = []; foreach ($propertyOptions as $name => $options) { - $this->propertyOptions[$name] = $options; + $this->propertyOptions[$name] = $options; $this->propertyData[$name]['options'] = $options; } @@ -166,7 +165,7 @@ class Route public function setArgument(string $argument, $value): Route { - $argument = $this->prefixArgumentKey($argument); + $argument = $this->prefixArgumentKey($argument); $this->arguments[$argument] = $value; return $this; @@ -322,8 +321,6 @@ class Route } /** - * @param mixed $exampleEntity - * * @return Route */ public function setExampleEntity($exampleEntity) @@ -339,8 +336,6 @@ class Route } /** - * @param mixed $exampleEntityFinderFunction - * * @return Route */ public function setExampleEntityFinderFunction($exampleEntityFinderFunction) @@ -389,7 +384,7 @@ class Route return count($this->validDomains) > 0; } - public function isInContainedInValidDomains(string $host = null): bool + public function isInContainedInValidDomains(?string $host = null): bool { if (null === $host) { return false; @@ -413,7 +408,7 @@ class Route private function prefixArgumentKey(string $key) { - if (0 !== strpos($key, '_')) { + if (!str_starts_with($key, '_')) { $key = "_{$key}"; } diff --git a/src/Router/Router.php b/src/Router/Router.php index 6a1e782..06ce017 100644 --- a/src/Router/Router.php +++ b/src/Router/Router.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Router; use Cache\Adapter\Chain\CachePoolChain; @@ -22,13 +24,13 @@ class Router public function __construct(Logger $logger, CachePoolChain $cachePoolChain) { - $this->logger = $logger; + $this->logger = $logger; $this->cachePoolChain = $cachePoolChain; } public function loadRoutesFromAnnotations( array $controllerPaths, - string $baseNamespace = null + ?string $baseNamespace = null ): void { AnnotationRegistry::registerLoader('class_exists'); @@ -39,15 +41,15 @@ class Router continue; } - $dirIterator = new \RecursiveDirectoryIterator($controllerPath); + $dirIterator = new \RecursiveDirectoryIterator($controllerPath); $iteratorIterator = new \RecursiveIteratorIterator($dirIterator); - $phpFiles = new \RegexIterator($iteratorIterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH); + $phpFiles = new \RegexIterator($iteratorIterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH); foreach ($phpFiles as $controllerFile) { - $fileClassName = ltrim(str_replace([$controllerPath, '/', '.php'], ['', '\\', ''], $controllerFile[0]), '\\'); + $fileClassName = ltrim(str_replace([$controllerPath, '/', '.php'], ['', '\\', ''], $controllerFile[0]), '\\'); $expectedClasses = [ - $baseNamespace.'\\Controllers\\'.$fileClassName, - 'Benzine\\Controllers\\'.$fileClassName, + $baseNamespace . '\\Controllers\\' . $fileClassName, + 'Benzine\\Controllers\\' . $fileClassName, ]; foreach ($expectedClasses as $expectedClass) { @@ -82,8 +84,8 @@ class Router $newRoute ->setHttpMethod($httpMethod) - ->setRouterPattern('/'.ltrim($routeAnnotation->path, '/')) - ->setCallback($expectedClass.':'.$method->name) + ->setRouterPattern('/' . ltrim($routeAnnotation->path, '/')) + ->setCallback($expectedClass . ':' . $method->name) ->setWeight($routeAnnotation->weight) ; @@ -101,7 +103,7 @@ class Router } } - public function populateRoutes(App $app, ServerRequestInterface $request = null): App + public function populateRoutes(App $app, ?ServerRequestInterface $request = null): App { if ($this->routesArePopulated) { return $app; @@ -141,13 +143,13 @@ class Router public function loadCache(): bool { - $time = microtime(true); + $time = microtime(true); $cacheItem = $this->cachePoolChain->getItem('routes'); if (!$cacheItem || null === $cacheItem->get()) { return false; } - $this->routes = $cacheItem->get(); + $this->routes = $cacheItem->get(); $timeToLoadFromCacheMs = (microtime(true) - $time) * 1000; if ($timeToLoadFromCacheMs >= 500) { $this->logger->warning(sprintf('Loaded routes from Cache in %sms, which is slower than 500ms', number_format($timeToLoadFromCacheMs, 2))); @@ -168,13 +170,13 @@ class Router $this->cachePoolChain->save($routeItem); // $this->logger->info('Cached router to cache pool'); } catch (CachePoolException $cachePoolException) { - $this->logger->critical('Cache Pool Exception: '.$cachePoolException->getMessage()); + $this->logger->critical('Cache Pool Exception: ' . $cachePoolException->getMessage()); } return $this; } - protected function weighRoutes(string $host = null): self + protected function weighRoutes(?string $host = null): self { $allocatedRoutes = []; if (is_array($this->routes) && count($this->routes) > 0) { @@ -189,7 +191,7 @@ class Router }); foreach ($this->routes as $index => $route) { - $routeKey = $route->getHttpMethod().$route->getRouterPattern(); + $routeKey = $route->getHttpMethod() . $route->getRouterPattern(); if (!isset($allocatedRoutes[$routeKey]) && ($route->isInContainedInValidDomains($host) || !$route->hasValidDomains())) { $allocatedRoutes[$routeKey] = true; } else { diff --git a/src/Services/ConfigurationService.php b/src/Services/ConfigurationService.php index 3ec4b4a..6f03113 100644 --- a/src/Services/ConfigurationService.php +++ b/src/Services/ConfigurationService.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Services; use Benzine\App; @@ -9,14 +11,14 @@ use Symfony\Component\Yaml\Yaml; class ConfigurationService { - public const KEY_APP_NAME = 'application/name'; - public const KEY_APP_ROOT = 'application/root'; - public const KEY_DEBUG_ENABLE = 'application/debug'; - public const KEY_DEFAULT_ACCESS = 'application/default_access'; - public const KEY_TIMEZONE = 'application/timezone'; - public const KEY_LOCALE = 'application/locale'; - public const KEY_SESSION_ENABLED = 'application/session_enabled'; - public const KEY_LOG_FORMAT_DATE = 'logging/format_date'; + public const KEY_APP_NAME = 'application/name'; + public const KEY_APP_ROOT = 'application/root'; + public const KEY_DEBUG_ENABLE = 'application/debug'; + public const KEY_DEFAULT_ACCESS = 'application/default_access'; + public const KEY_TIMEZONE = 'application/timezone'; + public const KEY_LOCALE = 'application/locale'; + public const KEY_SESSION_ENABLED = 'application/session_enabled'; + public const KEY_LOG_FORMAT_DATE = 'logging/format_date'; public const KEY_LOG_FORMAT_MESSAGE = 'logging/format_message'; protected App $app; @@ -28,9 +30,9 @@ class ConfigurationService public function __construct(App $app, EnvironmentService $environmentService) { - $this->app = $app; + $this->app = $app; $this->environmentService = $environmentService; - $this->findConfig(); + $this->findConfig($this->environmentService->get('BENZINE_CONFIG_PATH', null)); $this->setupDefines(); } @@ -42,7 +44,7 @@ class ConfigurationService /** * @return null|array|string */ - public function get(string $key, string $defaultValue = null) + public function get(string $key, ?string $defaultValue = null) { $scope = $this->config; foreach (explode('/', strtolower($key)) as $keyBit) { @@ -101,16 +103,16 @@ class ConfigurationService /** * Locate .benzine.yml. */ - protected function findConfig(string $path = null): bool + protected function findConfig(?string $path = null): bool { if (!$path) { $path = getcwd(); // $path = dirname($this->environmentService->get('SCRIPT_FILENAME')); } - if (!(new Filesystem())->exists($path.'/.benzine.yml')) { + if (!(new Filesystem())->exists($path . '/.benzine.yml')) { $this->configNotFoundInPaths[] = $path; - $currentDirElem = explode(DIRECTORY_SEPARATOR, $path); + $currentDirElem = explode(DIRECTORY_SEPARATOR, $path); array_pop($currentDirElem); $parentPath = implode(DIRECTORY_SEPARATOR, $currentDirElem); @@ -125,7 +127,7 @@ class ConfigurationService )); } - $this->parseFile($path.'/.benzine.yml'); + $this->parseFile($path . '/.benzine.yml'); $this->appRoot = $path; return true; diff --git a/src/Services/EnvironmentService.php b/src/Services/EnvironmentService.php index 6682a83..34e3dcd 100644 --- a/src/Services/EnvironmentService.php +++ b/src/Services/EnvironmentService.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Services; class EnvironmentService @@ -24,7 +26,7 @@ class EnvironmentService return $this->environmentVariables; } - public function get(string $key, string $default = null) + public function get(string $key, ?string $default = null) { if (isset($this->environmentVariables[$key])) { return $this->environmentVariables[$key]; diff --git a/src/Services/QueueService.php b/src/Services/QueueService.php index 8bbc139..2f60d9e 100644 --- a/src/Services/QueueService.php +++ b/src/Services/QueueService.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Services; use Benzine\Redis\Redis; @@ -17,7 +19,7 @@ class QueueService Redis $redis, Logger $logger ) { - $this->redis = $redis; + $this->redis = $redis; $this->logger = $logger; } @@ -30,7 +32,7 @@ class QueueService { $this->redis->multi(); foreach ($queueItems as $item) { - $itemId = UUID::v4(); + $itemId = UUID::v4(); $serialised = serialize($item); // Set the data element itself $this->redis->set("queue:data:{$queueName}:{$itemId}", $serialised); @@ -110,7 +112,7 @@ class QueueService $this->redis->get("queue:data:{$queueName}:{$itemId}"); $this->redis->del(["queue:data:{$queueName}:{$itemId}"]); $this->redis->decr("queue:length:{$queueName}"); - $response = $this->redis->exec(); + $response = $this->redis->exec(); $workerWorkItems[] = unserialize($response[0]); } if ($this->redis->get("queue:length:{$queueName}") <= 0) { diff --git a/src/Services/SessionService.php b/src/Services/SessionService.php index 02415a7..16f2424 100644 --- a/src/Services/SessionService.php +++ b/src/Services/SessionService.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Services; use Benzine\Redis\Redis; @@ -10,7 +12,7 @@ class SessionService implements \SessionHandlerInterface protected $oldID; private ?bool $redisIsAvailable = null; - private int $lifetime = 43200; + private int $lifetime = 43200; private array $dirtyCheck = []; public function __construct(Redis $redis) @@ -87,8 +89,8 @@ class SessionService implements \SessionHandlerInterface public function read($session_id) { if ($this->useAPCU()) { - if (apcu_exists('read-'.$session_id)) { - return apcu_fetch('read-'.$session_id); + if (apcu_exists('read-' . $session_id)) { + return apcu_fetch('read-' . $session_id); } } @@ -110,9 +112,9 @@ class SessionService implements \SessionHandlerInterface } if ($this->useAPCU()) { - apcu_store('read-'.$session_id, $result, 30); + apcu_store('read-' . $session_id, $result, 30); } else { - $this->dirtyCheck['read-'.$session_id] = crc32($result); + $this->dirtyCheck['read-' . $session_id] = crc32($result); } return $result; @@ -127,9 +129,9 @@ class SessionService implements \SessionHandlerInterface public function write($session_id, $session_data): bool { if ($this->useAPCU()) { - $dirty = crc32(apcu_fetch('read-'.$session_id)) != crc32($session_data); + $dirty = crc32(apcu_fetch('read-' . $session_id)) != crc32($session_data); } else { - $dirty = $this->dirtyCheck['read-'.$session_id] != crc32($session_data); + $dirty = $this->dirtyCheck['read-' . $session_id] != crc32($session_data); } if ($this->useRedis() && $dirty) { @@ -138,7 +140,7 @@ class SessionService implements \SessionHandlerInterface } if ($this->useAPCU()) { - apcu_store('read-'.$session_id, $session_data); + apcu_store('read-' . $session_id, $session_data); } return true; diff --git a/src/Twig/Extensions/ArrayUniqueTwigExtension.php b/src/Twig/Extensions/ArrayUniqueTwigExtension.php index 720edc8..29f71c2 100644 --- a/src/Twig/Extensions/ArrayUniqueTwigExtension.php +++ b/src/Twig/Extensions/ArrayUniqueTwigExtension.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Twig\Extensions; use Twig\Extension\AbstractExtension; diff --git a/src/Twig/Extensions/ArrayValuesTwigExtension.php b/src/Twig/Extensions/ArrayValuesTwigExtension.php index 2cee7ef..412acfe 100644 --- a/src/Twig/Extensions/ArrayValuesTwigExtension.php +++ b/src/Twig/Extensions/ArrayValuesTwigExtension.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Twig\Extensions; use Twig\Extension\AbstractExtension; diff --git a/src/Twig/Extensions/FilterAlphanumericOnlyTwigExtension.php b/src/Twig/Extensions/FilterAlphanumericOnlyTwigExtension.php index ff1a77e..b59681b 100644 --- a/src/Twig/Extensions/FilterAlphanumericOnlyTwigExtension.php +++ b/src/Twig/Extensions/FilterAlphanumericOnlyTwigExtension.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Twig\Extensions; use Twig\Extension\AbstractExtension; diff --git a/src/Twig/Extensions/InflectionExtension.php b/src/Twig/Extensions/InflectionExtension.php index 4b09e62..74b496e 100644 --- a/src/Twig/Extensions/InflectionExtension.php +++ b/src/Twig/Extensions/InflectionExtension.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Twig\Extensions; use MatthewBaggett\Inflection\Inflect; @@ -10,13 +12,9 @@ class InflectionExtension extends AbstractExtension { public function getFilters() { - $filters = []; - $filters['pluralize'] = new TwigFilter('pluralize', function (string $word = null): string { - return !empty($word) ? Inflect::pluralize($word) : ''; - }); - $filters['singularize'] = new TwigFilter('singularize', function (string $word = null): string { - return !empty($word) ? Inflect::singularize($word) : ''; - }); + $filters = []; + $filters['pluralize'] = new TwigFilter('pluralize', fn (?string $word = null): string => !empty($word) ? Inflect::pluralize($word) : ''); + $filters['singularize'] = new TwigFilter('singularize', fn (?string $word = null): string => !empty($word) ? Inflect::singularize($word) : ''); return $filters; } diff --git a/src/Twig/Extensions/InstanceOfExtension.php b/src/Twig/Extensions/InstanceOfExtension.php index 38bb58d..6947d3b 100644 --- a/src/Twig/Extensions/InstanceOfExtension.php +++ b/src/Twig/Extensions/InstanceOfExtension.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Twig\Extensions; use Twig\Extension\AbstractExtension; diff --git a/src/Twig/Extensions/TransformExtension.php b/src/Twig/Extensions/TransformExtension.php index fe4b504..da1f799 100644 --- a/src/Twig/Extensions/TransformExtension.php +++ b/src/Twig/Extensions/TransformExtension.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Twig\Extensions; use Camel\CaseTransformer; @@ -22,12 +24,10 @@ class TransformExtension extends AbstractExtension $filters = []; foreach ($this->transformers as $fromTransformer) { foreach ($this->transformers as $toTransformer) { - $name = 'transform_'.strtolower($fromTransformer).'_to_'.strtolower($toTransformer); - $context = $this; + $name = 'transform_' . strtolower($fromTransformer) . '_to_' . strtolower($toTransformer); + $context = $this; $filters[$name] = - new TwigFilter($name, function (string $word) use ($context, $fromTransformer, $toTransformer): string { - return $context->transform($word, $fromTransformer, $toTransformer); - }); + new TwigFilter($name, fn (string $word): string => $context->transform($word, $fromTransformer, $toTransformer)); } } @@ -37,7 +37,7 @@ class TransformExtension extends AbstractExtension public function transform($string, $from, $to) { $fromTransformer = $this->getTransformer($from); - $toTransformer = $this->getTransformer($to); + $toTransformer = $this->getTransformer($to); $transformer = new CaseTransformer($fromTransformer, $toTransformer); diff --git a/src/Twig/Extensions/TransformExtensionException.php b/src/Twig/Extensions/TransformExtensionException.php index e43e344..3847678 100644 --- a/src/Twig/Extensions/TransformExtensionException.php +++ b/src/Twig/Extensions/TransformExtensionException.php @@ -1,7 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Twig\Extensions; -final class TransformExtensionException extends \Exception -{ -} +final class TransformExtensionException extends \Exception {} diff --git a/src/Workers/AbstractForeverLoopWorker.php b/src/Workers/AbstractForeverLoopWorker.php index 9d45450..c2899b6 100644 --- a/src/Workers/AbstractForeverLoopWorker.php +++ b/src/Workers/AbstractForeverLoopWorker.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Workers; abstract class AbstractForeverLoopWorker extends AbstractWorker implements WorkerInterface diff --git a/src/Workers/AbstractQueueWorker.php b/src/Workers/AbstractQueueWorker.php index 25d7dd0..664de63 100644 --- a/src/Workers/AbstractQueueWorker.php +++ b/src/Workers/AbstractQueueWorker.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Workers; use Benzine\Services\EnvironmentService; @@ -117,7 +119,7 @@ abstract class AbstractQueueWorker extends AbstractWorker return false; } - $items = $this->queueService->pop($this->inputQueue); + $items = $this->queueService->pop($this->inputQueue); $this->resultItems = []; // If there are no items popped, return fast. @@ -144,9 +146,9 @@ abstract class AbstractQueueWorker extends AbstractWorker $e->getMessage() ), [ - 'file' => $e->getFile(), - 'line' => $e->getLine(), - 'code' => $e->getCode(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'code' => $e->getCode(), 'trace' => array_slice($e->getTrace(), 0, 5), ] ); diff --git a/src/Workers/AbstractWorker.php b/src/Workers/AbstractWorker.php index 9861072..4e3dbf8 100644 --- a/src/Workers/AbstractWorker.php +++ b/src/Workers/AbstractWorker.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Workers; use Benzine\Services\EnvironmentService; @@ -10,13 +12,13 @@ abstract class AbstractWorker implements WorkerInterface protected Logger $logger; protected EnvironmentService $environmentService; protected int $timeBetweenRuns = 5; - protected bool $stopOnZero = false; + protected bool $stopOnZero = false; public function __construct( Logger $logger, EnvironmentService $environmentService ) { - $this->logger = $logger; + $this->logger = $logger; $this->environmentService = $environmentService; $this->setUp(); $this->logger->info( @@ -27,13 +29,8 @@ abstract class AbstractWorker implements WorkerInterface ); } - protected function setUp(): void - { - } + protected function setUp(): void {} - /** - * @param bool $stopOnZero - */ public function setStopOnZero(bool $stopOnZero): self { $this->stopOnZero = $stopOnZero; diff --git a/src/Workers/ExampleQueueWorker.php b/src/Workers/ExampleQueueWorker.php index fe32e8a..50ceb2c 100644 --- a/src/Workers/ExampleQueueWorker.php +++ b/src/Workers/ExampleQueueWorker.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Workers; class ExampleQueueWorker extends AbstractQueueWorker diff --git a/src/Workers/WaitForEmitWorker.php b/src/Workers/WaitForEmitWorker.php index bb8a3e6..de91bcf 100644 --- a/src/Workers/WaitForEmitWorker.php +++ b/src/Workers/WaitForEmitWorker.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Workers; use Benzine\Redis\Redis; diff --git a/src/Workers/WorkerInterface.php b/src/Workers/WorkerInterface.php index b0a2be0..58681e3 100644 --- a/src/Workers/WorkerInterface.php +++ b/src/Workers/WorkerInterface.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Workers; interface WorkerInterface diff --git a/src/Workers/WorkerWorkItem.php b/src/Workers/WorkerWorkItem.php index 411335c..e8669ce 100644 --- a/src/Workers/WorkerWorkItem.php +++ b/src/Workers/WorkerWorkItem.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Workers; use Benzine\Exceptions\WorkerException; @@ -12,7 +14,7 @@ class WorkerWorkItem implements \Serializable public function __call($name, $arguments) { $method = substr(strtolower($name), 0, 3); - $field = substr(strtolower($name), 3); + $field = substr(strtolower($name), 3); switch ($method) { case 'set': @@ -40,7 +42,7 @@ class WorkerWorkItem implements \Serializable public static function Factory(object $object) { - $class = get_class($object); + $class = $object::class; return (new WorkerWorkItem()) ->setKey($class, $object) @@ -52,9 +54,6 @@ class WorkerWorkItem implements \Serializable return $this->data; } - /** - * @return WorkerWorkItem - */ public function setData(array $data): self { $this->data = $data; diff --git a/tests/AbstractBaseTestCase.php b/tests/AbstractBaseTestCase.php index b230af8..92efb8d 100644 --- a/tests/AbstractBaseTestCase.php +++ b/tests/AbstractBaseTestCase.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests; use Faker\Factory as FakerFactory; @@ -55,8 +57,8 @@ abstract class AbstractBaseTestCase extends AbstractTestCase */ public function invokeMethod(&$object, $methodName, array $parameters = []) { - $reflection = new \ReflectionClass(get_class($object)); - $method = $reflection->getMethod($methodName); + $reflection = new \ReflectionClass($object::class); + $method = $reflection->getMethod($methodName); $method->setAccessible(true); return $method->invokeArgs($object, $parameters); @@ -64,8 +66,8 @@ abstract class AbstractBaseTestCase extends AbstractTestCase public function setProtectedProperty(&$object, $property, $value) { - $reflection = new \ReflectionClass(get_class($object)); - $prop = $reflection->getProperty($property); + $reflection = new \ReflectionClass($object::class); + $prop = $reflection->getProperty($property); $prop->setAccessible(true); return $prop->setValue($object, $value); @@ -73,8 +75,8 @@ abstract class AbstractBaseTestCase extends AbstractTestCase public function getProtectedProperty(&$object, $property) { - $reflection = new \ReflectionClass(get_class($object)); - $prop = $reflection->getProperty($property); + $reflection = new \ReflectionClass($object::class); + $prop = $reflection->getProperty($property); $prop->setAccessible(true); return $prop->getValue($object); diff --git a/tests/AbstractRoutesTestCase.php b/tests/AbstractRoutesTestCase.php index a28f079..b2abcb5 100644 --- a/tests/AbstractRoutesTestCase.php +++ b/tests/AbstractRoutesTestCase.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests; use Benzine\Tests\Traits\AppTestTrait; @@ -38,7 +40,7 @@ abstract class AbstractRoutesTestCase extends AbstractBaseTestCase if ($isJsonRequest) { if ($dataOrPost !== null) { $dataOrPost = json_decode(json_encode($dataOrPost), true); - $request = $request->withParsedBody($dataOrPost); + $request = $request->withParsedBody($dataOrPost); } $request = $request->withHeader('Content-Type', 'application/json'); } else { diff --git a/tests/AbstractSeleniumTestCase.php b/tests/AbstractSeleniumTestCase.php index 77f03d7..831ee2f 100644 --- a/tests/AbstractSeleniumTestCase.php +++ b/tests/AbstractSeleniumTestCase.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests; use Benzine\App; @@ -23,10 +25,10 @@ abstract class AbstractSeleniumTestCase extends AbstractBaseTestCase { parent::setUpBeforeClass(); - self::$logger = App::DI(Logger::class); + self::$logger = App::DI(Logger::class); self::$environmentService = App::DI(EnvironmentService::class); - $capabilities = [WebDriverCapabilityType::BROWSER_NAME => 'chrome']; + $capabilities = [WebDriverCapabilityType::BROWSER_NAME => 'chrome']; self::$webDriver = RemoteWebDriver::create( sprintf( 'http://%s:%d/wd/hub', @@ -40,7 +42,7 @@ abstract class AbstractSeleniumTestCase extends AbstractBaseTestCase self::$webDriver->manage()->timeouts()->implicitlyWait(3); - self::$screenshotsDir = APP_ROOT.'/build/Screenshots/'.date('Y-m-d H-i-s').'/'; + self::$screenshotsDir = APP_ROOT . '/build/Screenshots/' . date('Y-m-d H-i-s') . '/'; } public static function tearDownAfterClass(): void @@ -68,9 +70,9 @@ abstract class AbstractSeleniumTestCase extends AbstractBaseTestCase protected function takeScreenshot($name): void { if (!(new Filesystem())->exists(self::$screenshotsDir)) { - (new Filesystem())->mkdir(self::$screenshotsDir, 0777); + (new Filesystem())->mkdir(self::$screenshotsDir, 0o777); } - self::$webDriver->takeScreenshot(self::$screenshotsDir.self::$screenshotIndex."_{$name}.jpg"); + self::$webDriver->takeScreenshot(self::$screenshotsDir . self::$screenshotIndex . "_{$name}.jpg"); ++self::$screenshotIndex; } } diff --git a/tests/AbstractTestCase.php b/tests/AbstractTestCase.php index 1c471d2..f0ac8cb 100644 --- a/tests/AbstractTestCase.php +++ b/tests/AbstractTestCase.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests; use PHPUnit\Framework\TestCase; @@ -17,8 +19,8 @@ abstract class AbstractTestCase extends TestCase public function setUp(): void { parent::setUp(); - $this->singleTestTime = microtime(true); - $this->waypoint_count = 0; + $this->singleTestTime = microtime(true); + $this->waypoint_count = 0; $this->waypoint_last_time = $this->singleTestTime; } @@ -27,7 +29,7 @@ abstract class AbstractTestCase extends TestCase parent::tearDown(); if (defined('DEBUG') && DEBUG) { $time = microtime(true) - $this->singleTestTime; - echo ''.get_called_class().':'.$this->getName().': Took '.number_format($time, 3)." seconds\n\n"; + echo '' . get_called_class() . ':' . $this->getName() . ': Took ' . number_format($time, 3) . " seconds\n\n"; } } @@ -35,7 +37,7 @@ abstract class AbstractTestCase extends TestCase { if (defined('DEBUG') && DEBUG) { $time_since_last_waypoint = number_format((microtime(true) - $this->waypoint_last_time) * 1000, 2, '.', ''); - $time_since_begin = number_format((microtime(true) - $this->singleTestTime) * 1000, 2, '.', ''); + $time_since_begin = number_format((microtime(true) - $this->singleTestTime) * 1000, 2, '.', ''); ++$this->waypoint_count; if (1 == $this->waypoint_count) { echo "\n"; diff --git a/tests/Traits/AppTestTrait.php b/tests/Traits/AppTestTrait.php index c8137c8..97e7db0 100644 --- a/tests/Traits/AppTestTrait.php +++ b/tests/Traits/AppTestTrait.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests\Traits; use Benzine\App as BenzineApp; @@ -30,9 +32,9 @@ trait AppTestTrait */ protected function setupContainer(): void { - $this->benzineApp = require __DIR__.'/../../../../../bootstrap.php'; - $this->slimApp = $this->benzineApp->getApp(); - $container = $this->slimApp->getContainer(); + $this->benzineApp = require __DIR__ . '/../../../../../bootstrap.php'; + $this->slimApp = $this->benzineApp->getApp(); + $container = $this->slimApp->getContainer(); if ($container === null) { throw new \UnexpectedValueException('Container must be initialized'); @@ -41,7 +43,7 @@ trait AppTestTrait $this->container = $container; $serverRequestCreator = ServerRequestCreatorFactory::create(); - $request = $serverRequestCreator->createServerRequestFromGlobals(); + $request = $serverRequestCreator->createServerRequestFromGlobals(); $this->benzineApp->loadAllRoutes($request); } @@ -98,7 +100,7 @@ trait AppTestTrait * @param string|UriInterface $uri The URI * @param null|array $data The json data */ - protected function createJsonRequest(string $method, $uri, array $data = null): ServerRequestInterface + protected function createJsonRequest(string $method, $uri, ?array $data = null): ServerRequestInterface { $request = $this->createRequest($method, $uri); @@ -116,7 +118,7 @@ trait AppTestTrait * @param string|UriInterface $uri The URI * @param null|array $data The form data */ - protected function createFormRequest(string $method, $uri, array $data = null): ServerRequestInterface + protected function createFormRequest(string $method, $uri, ?array $data = null): ServerRequestInterface { $request = $this->createRequest($method, $uri); diff --git a/tests/Traits/ArrayEquitabilityTrait.php b/tests/Traits/ArrayEquitabilityTrait.php index 0539b80..8b5d713 100644 --- a/tests/Traits/ArrayEquitabilityTrait.php +++ b/tests/Traits/ArrayEquitabilityTrait.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests\Traits; trait ArrayEquitabilityTrait diff --git a/tests/Traits/DatabaseAccessTrait.php b/tests/Traits/DatabaseAccessTrait.php index 270dc5e..0b6d7f2 100644 --- a/tests/Traits/DatabaseAccessTrait.php +++ b/tests/Traits/DatabaseAccessTrait.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests\Traits; use Slim\Container; diff --git a/tests/Traits/FakeDataTrait.php b/tests/Traits/FakeDataTrait.php index 4e862ea..9748bdc 100644 --- a/tests/Traits/FakeDataTrait.php +++ b/tests/Traits/FakeDataTrait.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests\Traits; use Faker\Factory as FakerFactory; diff --git a/tests/Traits/OverrideProtectionTrait.php b/tests/Traits/OverrideProtectionTrait.php index 5864aa3..7153b0c 100644 --- a/tests/Traits/OverrideProtectionTrait.php +++ b/tests/Traits/OverrideProtectionTrait.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace Benzine\Tests\Traits; trait OverrideProtectionTrait @@ -15,8 +17,8 @@ trait OverrideProtectionTrait */ public function invokeMethod(&$object, $methodName, array $parameters = []) { - $reflection = new \ReflectionClass(get_class($object)); - $method = $reflection->getMethod($methodName); + $reflection = new \ReflectionClass($object::class); + $method = $reflection->getMethod($methodName); $method->setAccessible(true); return $method->invokeArgs($object, $parameters); @@ -24,8 +26,8 @@ trait OverrideProtectionTrait public function setProtectedProperty(&$object, $property, $value) { - $reflection = new \ReflectionClass(get_class($object)); - $prop = $reflection->getProperty($property); + $reflection = new \ReflectionClass($object::class); + $prop = $reflection->getProperty($property); $prop->setAccessible(true); return $prop->setValue($object, $value); @@ -33,8 +35,8 @@ trait OverrideProtectionTrait public function getProtectedProperty(&$object, $property) { - $reflection = new \ReflectionClass(get_class($object)); - $prop = $reflection->getProperty($property); + $reflection = new \ReflectionClass($object::class); + $prop = $reflection->getProperty($property); $prop->setAccessible(true); return $prop->getValue($object);