From 0d2207dee3f1c08ae08a782d44124f8305afe4ad Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Mon, 23 Dec 2024 23:53:08 +0000 Subject: [PATCH 1/4] feat(cache): add set method --- src/Cache/Adapter/CacheAdapterInterface.php | 10 +++++++++ src/Cache/Adapter/DatabaseAdapter.php | 8 +++++++ src/Cache/Adapter/FilesystemAdapter.php | 8 +++++++ src/Cache/Adapter/RedisAdapter.php | 8 +++++++ src/Database/Barry/Relation.php | 4 ++-- src/Database/Barry/Relations/BelongsTo.php | 2 +- src/Database/Barry/Relations/HasOne.php | 2 +- tests/Cache/CacheRedisTest.php | 24 ++++++++++++++++++++- 8 files changed, 61 insertions(+), 5 deletions(-) diff --git a/src/Cache/Adapter/CacheAdapterInterface.php b/src/Cache/Adapter/CacheAdapterInterface.php index 77f855e3..c1078ca8 100644 --- a/src/Cache/Adapter/CacheAdapterInterface.php +++ b/src/Cache/Adapter/CacheAdapterInterface.php @@ -14,6 +14,16 @@ interface CacheAdapterInterface */ public function add(string $key, mixed $data, ?int $time = null): bool; + /** + * Set a new enter + * + * @param string $key + * @param mixed $data + * @param ?int $time + * @return bool + */ + public function set(string $key, mixed $data, ?int $time = null): bool; + /** * Add many item * diff --git a/src/Cache/Adapter/DatabaseAdapter.php b/src/Cache/Adapter/DatabaseAdapter.php index 44f1e11e..095a7952 100644 --- a/src/Cache/Adapter/DatabaseAdapter.php +++ b/src/Cache/Adapter/DatabaseAdapter.php @@ -52,6 +52,14 @@ public function add(string $key, mixed $data, ?int $time = null): bool return $this->query->insert(['keyname' => $key, "data" => serialize($content), "expire" => $time]); } + /** + * @inheritDoc + */ + public function set(string $key, mixed $data, ?int $time = null): bool + { + return $this->add($key, $data, $time); + } + /** * @inheritDoc */ diff --git a/src/Cache/Adapter/FilesystemAdapter.php b/src/Cache/Adapter/FilesystemAdapter.php index 99ff1ec9..e4337a46 100644 --- a/src/Cache/Adapter/FilesystemAdapter.php +++ b/src/Cache/Adapter/FilesystemAdapter.php @@ -61,6 +61,14 @@ public function add(string $key, mixed $data, ?int $time = 60): bool ); } + /** + * @inheritDoc + */ + public function set(string $key, mixed $data, ?int $time = null): bool + { + return $this->add($key, $data, $time); + } + /** * @inheritDoc */ diff --git a/src/Cache/Adapter/RedisAdapter.php b/src/Cache/Adapter/RedisAdapter.php index f076f678..108190fa 100644 --- a/src/Cache/Adapter/RedisAdapter.php +++ b/src/Cache/Adapter/RedisAdapter.php @@ -66,6 +66,14 @@ public function add(string $key, mixed $data, ?int $time = null): bool return $this->redis->set($key, $content, $options); } + /** + * @inheritDoc + */ + public function set(string $key, mixed $data, ?int $time = null): bool + { + return $this->add($key, $data, $time); + } + /** * @inheritDoc */ diff --git a/src/Database/Barry/Relation.php b/src/Database/Barry/Relation.php index 2a11d475..bcc2f0f1 100644 --- a/src/Database/Barry/Relation.php +++ b/src/Database/Barry/Relation.php @@ -116,8 +116,8 @@ public function __call(string $method, array $args) } /** - * Create a new row of the related - * + * Create a new row of the related + * * @param array $attributes * @return Model */ diff --git a/src/Database/Barry/Relations/BelongsTo.php b/src/Database/Barry/Relations/BelongsTo.php index f31a483e..1e35ff35 100644 --- a/src/Database/Barry/Relations/BelongsTo.php +++ b/src/Database/Barry/Relations/BelongsTo.php @@ -38,7 +38,7 @@ public function __construct( public function getResults(): ?Model { $key = $this->query->getTable() . ":belongsto:" . $this->related->getTable() . ":" . $this->foreign_key; - + $cache = Cache::store('file')->get($key); if (!is_null($cache)) { diff --git a/src/Database/Barry/Relations/HasOne.php b/src/Database/Barry/Relations/HasOne.php index 880a784c..32c155ff 100644 --- a/src/Database/Barry/Relations/HasOne.php +++ b/src/Database/Barry/Relations/HasOne.php @@ -34,7 +34,7 @@ public function __construct(Model $related, Model $parent, string $foreign_key, public function getResults(): ?Model { $key = $this->query->getTable() . ":hasone:" . $this->related->getTable() . ":" . $this->foreign_key; - + $cache = Cache::store('file')->get($key); if (!is_null($cache)) { diff --git a/tests/Cache/CacheRedisTest.php b/tests/Cache/CacheRedisTest.php index d24d8aae..fb6c3126 100644 --- a/tests/Cache/CacheRedisTest.php +++ b/tests/Cache/CacheRedisTest.php @@ -45,7 +45,7 @@ public function test_get_callback_cache() public function test_add_array_cache() { $result = Cache::add('address', [ - 'tel' => "49929598", + 'tel' => "0700000000", 'city' => "Abidjan", 'country' => "Cote d'ivoire" ]); @@ -53,6 +53,17 @@ public function test_add_array_cache() $this->assertEquals($result, true); } + public function test_set_array_cache() + { + $result = Cache::set('address_2', [ + 'tel' => "0700000000", + 'city' => "Yop", + 'country' => "Cote d'ivoire" + ]); + + $this->assertEquals($result, true); + } + public function test_get_array_cache() { $result = Cache::get('address'); @@ -64,6 +75,17 @@ public function test_get_array_cache() $this->assertArrayHasKey('country', $result); } + public function test_get_2_array_cache() + { + $result = Cache::get('address_2'); + + $this->assertEquals(true, is_array($result)); + $this->assertEquals(count($result), 3); + $this->assertArrayHasKey('tel', $result); + $this->assertArrayHasKey('city', $result); + $this->assertArrayHasKey('country', $result); + } + public function test_has() { $first_result = Cache::has('name'); From 8ca335982a03fdc5f21fc72ce8a459921a796366 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Tue, 31 Dec 2024 12:36:32 +0000 Subject: [PATCH 2/4] feat: init notification associate to user --- src/Notification/CanSendNotification.php | 11 ++++ src/Notification/Channel/ChannelInterface.php | 14 +++++ src/Notification/Channel/DatabaseChannel.php | 18 ++++++ src/Notification/Channel/MailChannel.php | 23 +++++++ src/Notification/Notification.php | 63 +++++++++++++++++++ 5 files changed, 129 insertions(+) create mode 100644 src/Notification/CanSendNotification.php create mode 100644 src/Notification/Channel/ChannelInterface.php create mode 100644 src/Notification/Channel/DatabaseChannel.php create mode 100644 src/Notification/Channel/MailChannel.php create mode 100644 src/Notification/Notification.php diff --git a/src/Notification/CanSendNotification.php b/src/Notification/CanSendNotification.php new file mode 100644 index 00000000..1bedd618 --- /dev/null +++ b/src/Notification/CanSendNotification.php @@ -0,0 +1,11 @@ +process($this); + } +} diff --git a/src/Notification/Channel/ChannelInterface.php b/src/Notification/Channel/ChannelInterface.php new file mode 100644 index 00000000..08cedc74 --- /dev/null +++ b/src/Notification/Channel/ChannelInterface.php @@ -0,0 +1,14 @@ +send($message); + } + } +} diff --git a/src/Notification/Notification.php b/src/Notification/Notification.php new file mode 100644 index 00000000..9eb1ad00 --- /dev/null +++ b/src/Notification/Notification.php @@ -0,0 +1,63 @@ + MailChannel::class, + "database" => DatabaseChannel::class, + ]; + + /** + * Returns the available channels to be used + * + * @param \Bow\Database\Barry\Model $notifiable + * @return array + */ + abstract public function channels(Model $notifiable): array; + + /** + * Send notification to mail + * + * @param \Bow\Database\Barry\Model $notifiable + * @return Message + */ + abstract public function toMail(Model $notifiable): Message; + + /** + * Send notification to database + * + * @param \Bow\Database\Barry\Model $notifiable + * @return array + */ + abstract public function toDatabase(Model $notifiable): array; + + /** + * Process the notification + * @param \Bow\Database\Barry\Model $notifiable + * @return void + */ + final function process(Model $notifiable) + { + $channels = $this->channels($notifiable); + + foreach ($channels as $channel) { + if (array_key_exists($channel, $this->channels)) { + $result = $this->{"to" . ucfirst($channel)}($notifiable); + $target_channel = new $this->channels[$channel](); + $target_channel->send($result); + } + } + } +} From 87816b93ff6dcb5a3eb0a12fdf50c248ad2b3f98 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Mon, 13 Jan 2025 20:17:44 +0000 Subject: [PATCH 3/4] refactor: notification package --- src/Notification/Channel/DatabaseChannel.php | 1 + src/Notification/Notification.php | 14 +++++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Notification/Channel/DatabaseChannel.php b/src/Notification/Channel/DatabaseChannel.php index 8174ef2e..dff95042 100644 --- a/src/Notification/Channel/DatabaseChannel.php +++ b/src/Notification/Channel/DatabaseChannel.php @@ -14,5 +14,6 @@ class DatabaseChannel implements ChannelInterface */ public function send(mixed $message) { + } } diff --git a/src/Notification/Notification.php b/src/Notification/Notification.php index 9eb1ad00..21ee69d5 100644 --- a/src/Notification/Notification.php +++ b/src/Notification/Notification.php @@ -31,9 +31,14 @@ abstract public function channels(Model $notifiable): array; * Send notification to mail * * @param \Bow\Database\Barry\Model $notifiable - * @return Message + * @return mixed */ - abstract public function toMail(Model $notifiable): Message; + public function toMail(Model $notifiable): ?Message + { + $message = new Message(); + + return $message; + } /** * Send notification to database @@ -41,7 +46,10 @@ abstract public function toMail(Model $notifiable): Message; * @param \Bow\Database\Barry\Model $notifiable * @return array */ - abstract public function toDatabase(Model $notifiable): array; + public function toDatabase(Model $notifiable): array + { + return []; + } /** * Process the notification From 82b7d52015d984ccdb5c47a0bec1669676c1c5a2 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Wed, 15 Jan 2025 23:15:42 +0000 Subject: [PATCH 4/4] refactor: refactoring with phpstorm to deep debugs --- composer.json | 9 +- src/Application/Application.php | 31 ++- .../Exception/BaseErrorHandler.php | 21 +- src/Auth/Auth.php | 12 +- src/Auth/Authentication.php | 4 +- src/Auth/Guards/GuardContract.php | 16 +- src/Auth/Guards/JwtGuard.php | 44 ++-- src/Auth/Traits/LoginUserTrait.php | 12 +- src/Cache/Adapter/DatabaseAdapter.php | 30 ++- src/Cache/Adapter/FilesystemAdapter.php | 13 +- src/Cache/Adapter/RedisAdapter.php | 10 +- src/Cache/Cache.php | 6 +- src/Configuration/EnvConfiguration.php | 3 +- src/Configuration/Loader.php | 4 +- src/Configuration/LoggerConfiguration.php | 5 +- src/Console/{Command => }/AbstractCommand.php | 4 +- src/Console/Argument.php | 18 +- src/Console/Color.php | 4 +- src/Console/Command.php | 2 +- src/Console/Command/AppEventCommand.php | 4 +- src/Console/Command/ClearCommand.php | 9 +- src/Console/Command/ConfigurationCommand.php | 4 +- src/Console/Command/ConsoleCommand.php | 4 +- src/Console/Command/ControllerCommand.php | 4 +- src/Console/Command/EventListenerCommand.php | 4 +- src/Console/Command/ExceptionCommand.php | 6 +- src/Console/Command/GenerateCacheCommand.php | 1 + src/Console/Command/GenerateKeyCommand.php | 1 + src/Console/Command/GenerateQueueCommand.php | 1 + .../GenerateResourceControllerCommand.php | 6 +- .../Command/GenerateSessionCommand.php | 1 + src/Console/Command/MiddlewareCommand.php | 4 +- src/Console/Command/MigrationCommand.php | 59 +++-- src/Console/Command/ModelCommand.php | 5 +- src/Console/Command/ProducerCommand.php | 4 +- src/Console/Command/ReplCommand.php | 9 +- src/Console/Command/SeederCommand.php | 40 +-- src/Console/Command/ServerCommand.php | 2 + src/Console/Command/ServiceCommand.php | 1 + src/Console/Command/ValidationCommand.php | 1 + src/Console/Command/WorkerCommand.php | 1 + src/Console/Console.php | 22 +- src/Console/Generator.php | 12 +- src/Console/README.md | 2 +- src/Console/Setting.php | 2 +- src/Console/Traits/ConsoleTrait.php | 6 +- src/Console/stubs/controller/service.stub | 6 +- src/Console/stubs/model/queue.stub | 2 +- src/Container/Action.php | 26 +- src/Container/Capsule.php | 8 +- src/Container/ContainerConfiguration.php | 1 - src/Contracts/CollectionInterface.php | 2 +- src/Database/Barry/Builder.php | 14 +- src/Database/Barry/Concerns/Relationship.php | 18 +- src/Database/Barry/Model.php | 137 +++++------ src/Database/Barry/Relation.php | 6 +- src/Database/Barry/Relations/BelongsTo.php | 6 +- .../Barry/Relations/BelongsToMany.php | 2 + src/Database/Barry/Relations/HasMany.php | 7 +- src/Database/Barry/Relations/HasOne.php | 6 +- .../Barry/Traits/ArrayAccessTrait.php | 4 +- src/Database/Barry/Traits/CanSerialized.php | 5 +- src/Database/Collection.php | 2 +- .../Connection/AbstractConnection.php | 2 +- .../Connection/Adapter/MysqlAdapter.php | 8 +- .../Connection/Adapter/PostgreSQLAdapter.php | 6 +- .../Connection/Adapter/SqliteAdapter.php | 4 +- src/Database/Connection/Connection.php | 2 +- src/Database/Database.php | 16 +- .../Migration/Compose/MysqlCompose.php | 3 +- .../Migration/Compose/PgsqlCompose.php | 21 +- .../Migration/Compose/SqliteCompose.php | 8 +- src/Database/Migration/Migration.php | 16 +- src/Database/Migration/SQLGenerator.php | 43 ++-- .../Migration/Shortcut/ConstraintColumn.php | 4 +- .../Migration/Shortcut/DateColumn.php | 15 +- .../Migration/Shortcut/MixedColumn.php | 49 ++-- .../Migration/Shortcut/NumberColumn.php | 45 +++- .../Migration/Shortcut/TextColumn.php | 12 + src/Database/Pagination.php | 12 +- src/Database/QueryBuilder.php | 9 +- src/Database/Redis.php | 7 +- src/Event/Dispatchable.php | 16 +- src/Event/Event.php | 26 +- src/Event/EventProducer.php | 4 +- src/Http/Client/HttpClient.php | 29 ++- src/Http/Client/Response.php | 5 +- src/Http/HttpStatus.php | 6 +- src/Http/Redirect.php | 4 +- src/Http/Request.php | 72 +++--- src/Http/Response.php | 21 +- src/Http/ServerAccessControl.php | 4 +- src/Mail/Driver/NativeDriver.php | 2 +- src/Mail/Driver/SmtpDriver.php | 19 +- src/Mail/Mail.php | 25 +- src/Mail/MailQueueProducer.php | 4 +- src/Mail/Message.php | 21 +- src/Notification/Channel/DatabaseChannel.php | 1 - src/Queue/Adapters/BeanstalkdAdapter.php | 62 ++--- src/Queue/Adapters/DatabaseAdapter.php | 12 +- src/Session/Cookie.php | 25 +- src/Session/Driver/ArrayDriver.php | 38 +-- src/Session/Driver/DatabaseDriver.php | 39 +-- src/Session/Driver/DurationTrait.php | 2 +- src/Session/Driver/FilesystemDriver.php | 10 +- src/Session/Session.php | 81 ++++--- src/Storage/Contracts/FilesystemInterface.php | 36 +-- src/Storage/Service/DiskFilesystemService.php | 24 +- src/Storage/Service/FTPService.php | 170 ++++++------- src/Storage/Service/S3Service.php | 110 ++++----- src/Storage/Storage.php | 34 +-- src/Storage/Temporary.php | 13 +- src/Support/Arraydotify.php | 16 +- src/Support/Collection.php | 67 +++-- src/Support/Env.php | 9 +- src/Support/Log.php | 6 +- src/Support/LoggerService.php | 24 +- src/Support/Serializes.php | 10 +- src/Support/Str.php | 101 +++----- src/Support/Util.php | 9 +- src/Support/helpers.php | 229 +++++++++--------- src/Testing/Features/SeedingHelper.php | 1 + src/Testing/Response.php | 4 +- src/Testing/TestCase.php | 28 ++- src/Translate/Translator.php | 26 +- src/Validation/README.md | 2 +- src/Validation/RequestValidation.php | 31 ++- src/Validation/Rules/DatabaseRule.php | 24 +- src/Validation/Rules/EmailRule.php | 2 +- src/Validation/Rules/StringRule.php | 13 +- src/Validation/Validate.php | 2 +- src/Validation/Validator.php | 2 +- src/View/Engine/PHPEngine.php | 1 - src/View/Engine/TwigEngine.php | 14 +- src/View/EngineAbstract.php | 5 +- src/View/View.php | 19 +- src/View/ViewConfiguration.php | 3 - tests/Auth/AuthenticationTest.php | 3 +- tests/Config/stubs/policier.php | 10 - tests/Console/Stubs/CustomCommand.php | 2 +- ...test_generate_queue_migration_stubs__1.txt | 2 +- tests/Container/CapsuleTest.php | 2 +- tests/Container/Stubs/MyClass.php | 2 +- tests/Filesystem/FTPServiceTest.php | 15 +- tests/Hashing/SecurityTest.php | 9 + tests/Queue/MailQueueTest.php | 1 + tests/Queue/QueueTest.php | 2 +- tests/Translate/TranslationTest.php | 4 +- 148 files changed, 1357 insertions(+), 1255 deletions(-) rename src/Console/{Command => }/AbstractCommand.php (90%) diff --git a/composer.json b/composer.json index a64fd6ab..5f9ba5bd 100644 --- a/composer.json +++ b/composer.json @@ -11,15 +11,16 @@ "php": "^8.1", "bowphp/tintin": "^3.0", "filp/whoops": "^2.1", - "nesbot/carbon": "^2.16", + "nesbot/carbon": "3.8.4", "psy/psysh": "v0.12.*", "fakerphp/faker": "^1.20", "neitanod/forceutf8": "^2.0", - "ramsey/uuid": "^4.7" + "ramsey/uuid": "^4.7", + "ext-ftp": "*" }, "require-dev": { - "pda/pheanstalk": "^4.0.5", - "phpunit/phpunit": "^9", + "pda/pheanstalk": "^5.0", + "phpunit/phpunit": "^9.6", "monolog/monolog": "^1.22", "twig/twig": "^3", "squizlabs/php_codesniffer": "3.*", diff --git a/src/Application/Application.php b/src/Application/Application.php index 50541f31..cbcd2bc0 100644 --- a/src/Application/Application.php +++ b/src/Application/Application.php @@ -9,6 +9,7 @@ use Bow\Container\Action; use Bow\Configuration\Loader; use Bow\Contracts\ResponseInterface; +use Bow\Http\Exception\BadRequestException; use Bow\Http\Exception\HttpException; use Bow\Http\Request; use Bow\Http\Response; @@ -16,6 +17,7 @@ use Bow\Router\Resource; use Bow\Router\Router; use Bow\Router\Route; +use ReflectionException; class Application extends Router { @@ -24,21 +26,21 @@ class Application extends Router * * @var Capsule */ - private $capsule; + private Capsule $capsule; /** * The booting flag * * @var bool */ - private $booted = false; + private bool $booted = false; /** * The Application instance * - * @var Application + * @var ?Application */ - private static $instance; + private static ?Application $instance = null; /** * The HTTP Request @@ -62,7 +64,7 @@ class Application extends Router private Loader $config; /** - * This define if the X-powered-By header must be put in response + * This defines if the X-powered-By header must be put in response * * @var bool */ @@ -74,6 +76,7 @@ class Application extends Router * @param Request $request * @param Response $response * @return void + * @throws BadRequestException */ public function __construct(Request $request, Response $response) { @@ -87,6 +90,7 @@ public function __construct(Request $request, Response $response) $this->capsule->instance('app', $this); $this->request->capture(); + parent::__construct($request->method(), $request->get('_method')); } @@ -114,7 +118,7 @@ public function bind(Loader $config): void $this->setBaseRoute($config['app']['root']); } - // We active the auto csrf switcher + // We activate the auto csrf switcher $this->setAutoCsrf($config['app']['auto_csrf'] ?? false); $this->capsule->instance('config', $config); @@ -144,6 +148,7 @@ private function boot(): void * @param Request $request * @param Response $response * @return Application + * @throws BadRequestException */ public static function make(Request $request, Response $response): Application { @@ -155,7 +160,7 @@ public static function make(Request $request, Response $response): Application } /** - * Check if is running on php cli + * Check if it is running on php cli * * @return bool */ @@ -168,7 +173,7 @@ public function isRunningOnCli(): bool * Launcher of the application * * @return ?bool - * @throws RouterException + * @throws RouterException|ReflectionException */ public function send(): ?bool { @@ -244,7 +249,7 @@ public function send(): ?bool * * @param mixed $response * @param int $code - * @return null + * @return void */ private function sendResponse(mixed $response, int $code = 200): void { @@ -267,7 +272,7 @@ public function disablePoweredByMention(): void } /** - * Make the REST API base on route and ressource controller. + * Make the REST API base on route and resource controller. * * @param string $url * @param string|array $controller_name @@ -305,7 +310,7 @@ public function rest(string $url, string|array $controller_name, array $where = } } - if (is_null($controller) || !is_string($controller)) { + if (!is_string($controller)) { throw new ApplicationException( "[REST] No defined controller!", E_ERROR @@ -346,7 +351,7 @@ public function abort(int $code = 500, string $message = '', array $headers = [] } /** - * Build dependance + * Build dependence * * @param ?string $name * @param ?callable $callable @@ -378,7 +383,7 @@ public function container(?string $name = null, ?callable $callable = null): mix * This point method on the container system * * @param array $params - * @return Capsule + * @return mixed * @throws ApplicationException */ public function __invoke(...$params): mixed diff --git a/src/Application/Exception/BaseErrorHandler.php b/src/Application/Exception/BaseErrorHandler.php index b1c475f1..a12f79d2 100644 --- a/src/Application/Exception/BaseErrorHandler.php +++ b/src/Application/Exception/BaseErrorHandler.php @@ -4,6 +4,7 @@ namespace Bow\Application\Exception; +use JetBrains\PhpStorm\NoReturn; use PDOException; use Bow\View\View; use Bow\Http\Exception\HttpException; @@ -20,7 +21,7 @@ class BaseErrorHandler * @param array $data * @return string */ - protected function render($view, $data = []): string + protected function render(string $view, array $data = []): string { return View::parse($view, $data)->getContent(); } @@ -28,11 +29,11 @@ protected function render($view, $data = []): string /** * Send the json as response * - * @param string $data - * @param mixed $code - * @return mixed + * @param $exception + * @param mixed|null $code + * @return void */ - protected function json($exception, $code = null) + #[NoReturn] protected function json($exception, mixed $code = null): void { if ($exception instanceof TokenInvalidException) { $code = 'TOKEN_INVALID'; @@ -50,8 +51,12 @@ protected function json($exception, $code = null) } } - if (app_env("APP_ENV") == "production" && $exception instanceof PDOException) { - $message = 'An SQL error occurs. For security, we did not display the message.'; + if ($exception instanceof PDOException) { + if (app_env("APP_ENV") == "production") { + $message = 'An SQL error occurs. For security, we did not display the message.'; + } else { + $message = $exception->getMessage(); + } } else { $message = $exception->getMessage(); } @@ -78,6 +83,6 @@ protected function json($exception, $code = null) response()->status($status); - return die(json_encode($response)); + die(json_encode($response)); } } diff --git a/src/Auth/Auth.php b/src/Auth/Auth.php index 190e090a..27651c43 100644 --- a/src/Auth/Auth.php +++ b/src/Auth/Auth.php @@ -15,7 +15,7 @@ class Auth /** * The Auth instance * - * @var GuardContract + * @var ?GuardContract */ private static ?GuardContract $instance = null; @@ -29,7 +29,7 @@ class Auth /** * The current guard * - * @var string + * @var ?string */ private static ?string $guard = null; @@ -37,9 +37,10 @@ class Auth * Configure Auth system * * @param array $config - * @return GuardContract + * @return ?GuardContract + * @throws AuthenticationException */ - public static function configure(array $config) + public static function configure(array $config): ?GuardContract { if (!is_null(static::$instance)) { return static::$instance; @@ -61,7 +62,7 @@ public static function getInstance(): ?GuardContract } /** - * Check if user is authenticate + * Check if user is authenticated * * @param null|string $guard * @return GuardContract @@ -102,6 +103,7 @@ public static function guard(?string $guard = null): GuardContract * @param string $method * @param array $params * @return ?GuardContract + * @throws ErrorException */ public static function __callStatic(string $method, array $params) { diff --git a/src/Auth/Authentication.php b/src/Auth/Authentication.php index 4dbec6c1..e16e9a0a 100644 --- a/src/Auth/Authentication.php +++ b/src/Auth/Authentication.php @@ -13,13 +13,13 @@ class Authentication extends Model * * @return mixed */ - public function getAuthenticateUserId() + public function getAuthenticateUserId(): mixed { return $this->attributes[$this->primary_key]; } /** - * Define the additionals values + * Define the additional values * * @return array */ diff --git a/src/Auth/Guards/GuardContract.php b/src/Auth/Guards/GuardContract.php index 57e0cf25..d967260f 100644 --- a/src/Auth/Guards/GuardContract.php +++ b/src/Auth/Guards/GuardContract.php @@ -6,9 +6,10 @@ use Bow\Auth\Auth; use Bow\Auth\Authentication; +use Bow\Auth\Exception\AuthenticationException; /** - * @method ?\Policier\Token getToken() + * @method ?\Bow\Policier\Token getToken() */ abstract class GuardContract { @@ -27,7 +28,7 @@ abstract class GuardContract abstract public function id(): mixed; /** - * Check if user is authenticate + * Check if user is authenticated * * @return bool */ @@ -58,12 +59,12 @@ abstract public function login(Authentication $user): bool; /** * Get authenticated user * - * @return Authentication + * @return ?Authentication */ abstract public function user(): ?Authentication; /** - * Check if user is authenticate + * Check if user is authenticated * * @param array $credentials * @return bool @@ -81,12 +82,13 @@ public function getName(): string } /** - * Load the a guard + * Load the guard * - * @param string $guard + * @param string|null $guard * @return GuardContract + * @throws AuthenticationException */ - public function guard($guard = null): GuardContract + public function guard(string $guard = null): GuardContract { if ($guard) { $this->guard = $guard; diff --git a/src/Auth/Guards/JwtGuard.php b/src/Auth/Guards/JwtGuard.php index 4edf0309..8b02d453 100644 --- a/src/Auth/Guards/JwtGuard.php +++ b/src/Auth/Guards/JwtGuard.php @@ -5,9 +5,10 @@ namespace Bow\Auth\Guards; use Bow\Security\Hash; +use Bow\Support\Log; +use Exception; use Policier\Policier; use Bow\Auth\Authentication; -use Bow\Auth\Guards\GuardContract; use Bow\Auth\Traits\LoginUserTrait; use Bow\Auth\Exception\AuthenticationException; use Policier\Token; @@ -26,7 +27,7 @@ class JwtGuard extends GuardContract /** * Defines token data * - * @var Token + * @var ?Token */ private ?Token $token = null; @@ -35,6 +36,7 @@ class JwtGuard extends GuardContract * * @param array $provider * @param string $guard + * @throws AuthenticationException */ public function __construct(array $provider, string $guard) { @@ -47,14 +49,17 @@ public function __construct(array $provider, string $guard) } /** - * Check if user is authenticate + * Check if user is authenticated * * @param array $credentials * @return bool + * @throws AuthenticationException + * @throws Exception */ public function attempts(array $credentials): bool { $user = $this->makeLogin($credentials); + $this->token = null; if (is_null($user)) { @@ -74,9 +79,10 @@ public function attempts(array $credentials): bool } /** - * Check if user is authenticate + * Check if user is authenticated * * @return bool + * @throws Exception */ public function check(): bool { @@ -85,7 +91,7 @@ public function check(): bool if (is_null($this->token)) { try { $this->token = $policier->getParsedToken(); - } catch (\Exception $e) { + } catch (Exception $e) { return false; } } @@ -111,6 +117,7 @@ public function check(): bool * Check if user is guest * * @return bool + * @throws Exception */ public function guest(): bool { @@ -118,11 +125,13 @@ public function guest(): bool } /** - * Check if user is authenticate + * Check if user is authenticated * - * @return bool + * @return ?Authentication + * @throws AuthenticationException + * @throws Exception */ - public function user(): Authentication + public function user(): ?Authentication { if (!$this->check()) { throw new AuthenticationException( @@ -153,7 +162,8 @@ public function getToken(): ?Token * Make direct login * * @param Authentication $user - * @return string + * @return bool + * @throws Exception */ public function login(Authentication $user): bool { @@ -168,7 +178,7 @@ public function login(Authentication $user): bool } /** - * Destruit token + * Destruct token * * @return bool */ @@ -180,7 +190,8 @@ public function logout(): bool /** * Get the user id * - * @return bool + * @return int|string + * @throws AuthenticationException */ public function id(): int|string { @@ -195,23 +206,24 @@ public function id(): int|string * Get the Policier instance * * @return Policier + * @throws Exception */ - private function getPolicier() + private function getPolicier(): Policier { if (!class_exists(Policier::class)) { - throw new \Exception('Please install bowphp/policier: composer require bowphp/policier'); + throw new Exception('Please install bowphp/policier: composer require bowphp/policier'); } $policier = Policier::getInstance(); if (is_null($policier)) { - throw new \Exception('Please load the \Policier\Bow\PolicierConfiguration::class configuration.'); + throw new Exception('Please load the \Policier\Bow\PolicierConfiguration::class configuration.'); } $config = (array) config('policier'); - if (!isset($config['signkey']) || is_null($config['signkey'])) { - throw new \Exception('Please set the signkey.'); + if (!isset($config['signkey'])) { + throw new Exception('Please set the signkey.'); } return $policier; diff --git a/src/Auth/Traits/LoginUserTrait.php b/src/Auth/Traits/LoginUserTrait.php index 8dc184e8..8f651ae8 100644 --- a/src/Auth/Traits/LoginUserTrait.php +++ b/src/Auth/Traits/LoginUserTrait.php @@ -4,6 +4,7 @@ namespace Bow\Auth\Traits; +use Bow\Auth\Authentication; use Bow\Database\Barry\Model; use Bow\Auth\Exception\AuthenticationException; @@ -13,9 +14,10 @@ trait LoginUserTrait * Make login * * @param array $credentials - * @return ?Model + * @return ?Authentication + * @throws AuthenticationException */ - private function makeLogin(array $credentials): ?Model + private function makeLogin(array $credentials): ?Authentication { $model = $this->provider['model']; $fields = $this->provider['credentials']; @@ -44,10 +46,10 @@ private function makeLogin(array $credentials): ?Model * Get user by key * * @param string $key - * @param string $value - * @return \Bow\Database\Barry\Model|null + * @param float|int|string $value + * @return Model|null */ - private function getUserBy($key, $value) + private function getUserBy(string $key, float|int|string $value): ?Authentication { $model = $this->provider['model']; diff --git a/src/Cache/Adapter/DatabaseAdapter.php b/src/Cache/Adapter/DatabaseAdapter.php index 095a7952..4f3e3c28 100644 --- a/src/Cache/Adapter/DatabaseAdapter.php +++ b/src/Cache/Adapter/DatabaseAdapter.php @@ -3,6 +3,8 @@ namespace Bow\Cache\Adapter; use Bow\Database\Database; +use Bow\Database\Exception\ConnectionException; +use Bow\Database\Exception\QueryBuilderException; use Bow\Database\QueryBuilder; use Bow\Cache\Adapter\CacheAdapterInterface; @@ -19,7 +21,8 @@ class DatabaseAdapter implements CacheAdapterInterface * RedisAdapter constructor. * * @param array $config - * @return mixed + * @return void + * @throws ConnectionException */ public function __construct(array $config) { @@ -28,6 +31,7 @@ public function __construct(array $config) /** * @inheritDoc + * @throws \Exception */ public function add(string $key, mixed $data, ?int $time = null): bool { @@ -54,6 +58,7 @@ public function add(string $key, mixed $data, ?int $time = null): bool /** * @inheritDoc + * @throws \Exception */ public function set(string $key, mixed $data, ?int $time = null): bool { @@ -62,6 +67,7 @@ public function set(string $key, mixed $data, ?int $time = null): bool /** * @inheritDoc + * @throws QueryBuilderException */ public function get(string $key, mixed $default = null): mixed { @@ -77,7 +83,8 @@ public function get(string $key, mixed $default = null): mixed } /** - * @inheritDoc + * Update value from key + * @throws \Exception */ public function update(string $key, mixed $data, ?int $time = null): mixed { @@ -103,6 +110,7 @@ public function update(string $key, mixed $data, ?int $time = null): mixed /** * @inheritDoc + * @throws \Exception */ public function addMany(array $data): bool { @@ -117,6 +125,7 @@ public function addMany(array $data): bool /** * @inheritDoc + * @throws \Exception */ public function forever(string $key, mixed $data): bool { @@ -125,6 +134,7 @@ public function forever(string $key, mixed $data): bool /** * @inheritDoc + * @throws \Exception */ public function push(string $key, array $data): bool { @@ -137,11 +147,13 @@ public function push(string $key, array $data): bool $value = (array) unserialize($result->data); $result->data = serialize(array_merge($value, $data)); - return $$this->query->where("keyname", $key)->update((array) $result); + return (bool) $this->query->where("keyname", $key)->update((array) $result); } /** * @inheritDoc + * @throws QueryBuilderException + * @throws \Exception */ public function addTime(string $key, int $time): bool { @@ -153,11 +165,13 @@ public function addTime(string $key, int $time): bool $result->expire = date("Y-m-d H:i:s", strtotime($result->expire) + $time); - return $$this->query->where("keyname", $key)->update((array) $result); + return (bool) $this->query->where("keyname", $key)->update((array) $result); } /** * @inheritDoc + * @throws QueryBuilderException + * @throws \Exception */ public function timeOf(string $key): int|bool|string { @@ -172,6 +186,8 @@ public function timeOf(string $key): int|bool|string /** * @inheritDoc + * @throws QueryBuilderException + * @throws \Exception */ public function forget(string $key): bool { @@ -184,6 +200,7 @@ public function forget(string $key): bool /** * @inheritDoc + * @throws QueryBuilderException */ public function has(string $key): bool { @@ -192,12 +209,11 @@ public function has(string $key): bool /** * @inheritDoc + * @throws QueryBuilderException */ public function expired(string $key): bool { - $data = $this->get($key); - - return $data; + return $this->get($key); } /** diff --git a/src/Cache/Adapter/FilesystemAdapter.php b/src/Cache/Adapter/FilesystemAdapter.php index e4337a46..cb6cdac1 100644 --- a/src/Cache/Adapter/FilesystemAdapter.php +++ b/src/Cache/Adapter/FilesystemAdapter.php @@ -7,14 +7,13 @@ use Bow\Support\Str; use RecursiveIteratorIterator; use RecursiveDirectoryIterator; -use Bow\Cache\Adapter\CacheAdapterInterface; class FilesystemAdapter implements CacheAdapterInterface { /** * The cache directory * - * @var string + * @var ?string */ private ?string $directory = null; @@ -28,8 +27,7 @@ class FilesystemAdapter implements CacheAdapterInterface /** * Cache constructor. * - * @param string $base_directory - * @return mixed + * @param array $config */ public function __construct(array $config) { @@ -122,7 +120,7 @@ public function push(string $key, array $data): bool $this->with_meta = false; if (is_array($cache['content'])) { - array_push($cache['content'], $content); + $cache['content'][] = $content; } else { $cache['content'] .= $content; } @@ -263,7 +261,7 @@ public function expired(string $key): bool $this->with_meta = false; - return $expire_at == '+' ? false : (time() > $expire_at); + return !($expire_at == '+') && time() > $expire_at; } /** @@ -283,9 +281,6 @@ public function clear(): void } } - /** - * @inheritDoc - */ private function makeHashFilename(string $key, bool $make_group_directory = false): string { $hash = hash('sha256', '/bow_' . $key); diff --git a/src/Cache/Adapter/RedisAdapter.php b/src/Cache/Adapter/RedisAdapter.php index 108190fa..7df64343 100644 --- a/src/Cache/Adapter/RedisAdapter.php +++ b/src/Cache/Adapter/RedisAdapter.php @@ -3,7 +3,6 @@ namespace Bow\Cache\Adapter; use Redis; -use Bow\Cache\Adapter\CacheAdapterInterface; use Bow\Database\Redis as RedisStore; class RedisAdapter implements CacheAdapterInterface @@ -19,7 +18,7 @@ class RedisAdapter implements CacheAdapterInterface * RedisAdapter constructor. * * @param array $config - * @return mixed + * @return void */ public function __construct(array $config) { @@ -36,8 +35,9 @@ public function __construct(array $config) * Ping the redis service * * @param ?string $message + * @return RedisAdapter */ - public function ping(?string $message = null) + public function ping(?string $message = null): RedisAdapter { $this->redis->ping($message); @@ -157,7 +157,9 @@ public function has(string $key): bool */ public function expired(string $key): bool { - return $this->redis->expire($key); + $result = $this->redis->expiretime($key); + + return $result < -1; } /** diff --git a/src/Cache/Cache.php b/src/Cache/Cache.php index bf4a4514..e27926a8 100644 --- a/src/Cache/Cache.php +++ b/src/Cache/Cache.php @@ -43,8 +43,9 @@ class Cache * Cache configuration method * * @param array $config + * @return CacheAdapterInterface|null */ - public static function configure(array $config) + public static function configure(array $config): ?CacheAdapterInterface { if (!is_null(static::$instance)) { return static::$instance; @@ -64,6 +65,7 @@ public static function configure(array $config) * Get the cache instance * * @return CacheAdapterInterface + * @throws ErrorException */ public static function getInstance(): CacheAdapterInterface { @@ -77,7 +79,7 @@ public static function getInstance(): CacheAdapterInterface /** * Get the cache instance * - * @param string $driver + * @param string $store * @return CacheAdapterInterface */ public static function store(string $store): CacheAdapterInterface diff --git a/src/Configuration/EnvConfiguration.php b/src/Configuration/EnvConfiguration.php index 20474708..eecd9548 100644 --- a/src/Configuration/EnvConfiguration.php +++ b/src/Configuration/EnvConfiguration.php @@ -5,9 +5,7 @@ namespace Bow\Configuration; use Bow\Support\Env; -use Bow\Configuration\Loader; use InvalidArgumentException; -use Bow\Configuration\Configuration; class EnvConfiguration extends Configuration { @@ -24,6 +22,7 @@ public function create(Loader $config): void . "Copy the .env.example.json file to .env.json" ); } + Env::load($config['app.env_file']); }); } diff --git a/src/Configuration/Loader.php b/src/Configuration/Loader.php index 010afa34..aa1aa944 100644 --- a/src/Configuration/Loader.php +++ b/src/Configuration/Loader.php @@ -13,7 +13,7 @@ class Loader implements \ArrayAccess { /** - * @var Loader + * @var ?Loader */ protected static ?Loader $instance = null; @@ -110,7 +110,7 @@ public function getBasePath(): string * @return Loader * @throws */ - public static function configure($base_path): Loader + public static function configure(string $base_path): Loader { if (!static::$instance instanceof Loader) { static::$instance = new static($base_path); diff --git a/src/Configuration/LoggerConfiguration.php b/src/Configuration/LoggerConfiguration.php index e98f5519..a2049f48 100644 --- a/src/Configuration/LoggerConfiguration.php +++ b/src/Configuration/LoggerConfiguration.php @@ -51,9 +51,10 @@ public function run(): void * Loader view logger * * @param Logger $monolog + * @param $error_handler * @return void */ - private function loadFrontLogger(Logger $monolog, $error_handler) + private function loadFrontLogger(Logger $monolog, $error_handler): void { $whoops = new \Whoops\Run(); @@ -100,7 +101,7 @@ function ($exception, $inspector, $run) use ($monolog, $error_handler) { * @return Logger * @throws \Exception */ - private function loadFileLogger($log_dir, $name) + private function loadFileLogger(string $log_dir, string $name): Logger { $monolog = new Logger($name); diff --git a/src/Console/Command/AbstractCommand.php b/src/Console/AbstractCommand.php similarity index 90% rename from src/Console/Command/AbstractCommand.php rename to src/Console/AbstractCommand.php index 695a0300..f9291207 100644 --- a/src/Console/Command/AbstractCommand.php +++ b/src/Console/AbstractCommand.php @@ -2,10 +2,8 @@ declare(strict_types=1); -namespace Bow\Console\Command; +namespace Bow\Console; -use Bow\Console\Setting; -use Bow\Console\Argument; use Bow\Console\Traits\ConsoleTrait; abstract class AbstractCommand diff --git a/src/Console/Argument.php b/src/Console/Argument.php index 27b6520f..7a2ac779 100644 --- a/src/Console/Argument.php +++ b/src/Console/Argument.php @@ -24,9 +24,9 @@ class Argument /** * The command first argument - * php bow add:constroller [target] + * php bow add:controller [target] * - * @var string + * @var ?string */ private ?string $target = null; @@ -34,7 +34,7 @@ class Argument * The command first argument * php bow [command]:action * - * @var string + * @var ?string */ private ?string $command = null; @@ -42,7 +42,7 @@ class Argument * The command first argument * php bow command:[action] * - * @var string + * @var ?string */ private ?string $action = null; @@ -121,7 +121,7 @@ public function getParameters(): Collection /** * Retrieves the target value * - * @return string + * @return ?string */ public function getTarget(): ?string { @@ -131,7 +131,7 @@ public function getTarget(): ?string /** * Retrieves the command value * - * @return string + * @return ?string */ public function getCommand(): ?string { @@ -141,7 +141,7 @@ public function getCommand(): ?string /** * Retrieves the command action * - * @return string + * @return ?string */ public function getAction(): ?string { @@ -185,7 +185,7 @@ private function initCommand(string $param): void } /** - * Read ligne + * Read line * * @param string $message * @return bool @@ -196,7 +196,7 @@ public function readline(string $message): bool $input = strtolower(trim(readline())); - if (is_null($input) || strlen($input) == 0) { + if (strlen($input) == 0) { $input = 'n'; } diff --git a/src/Console/Color.php b/src/Console/Color.php index 196e0292..1eccbc15 100644 --- a/src/Console/Color.php +++ b/src/Console/Color.php @@ -64,7 +64,7 @@ public static function danger(string $message): string /** * Blue message with '[info]' prefix * - * @param $message + * @param string $message * @return string */ public static function info(string $message): string @@ -84,7 +84,7 @@ public static function warning(string $message): string } /** - * Greean message with '[success]' prefix + * Green message with '[success]' prefix * * @param string $message * @return string diff --git a/src/Console/Command.php b/src/Console/Command.php index a2966093..145a2fb0 100644 --- a/src/Console/Command.php +++ b/src/Console/Command.php @@ -4,7 +4,6 @@ namespace Bow\Console; -use Bow\Console\Command\AbstractCommand; use Bow\Support\Str; class Command extends AbstractCommand @@ -57,6 +56,7 @@ class Command extends AbstractCommand * @param string $command * @param array $rest * @return mixed + * @throws \ErrorException */ public function call(string $command, string $action, ...$rest): mixed { diff --git a/src/Console/Command/AppEventCommand.php b/src/Console/Command/AppEventCommand.php index 2dde69e4..29c29b78 100644 --- a/src/Console/Command/AppEventCommand.php +++ b/src/Console/Command/AppEventCommand.php @@ -4,7 +4,9 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class AppEventCommand extends AbstractCommand { @@ -14,7 +16,7 @@ class AppEventCommand extends AbstractCommand * @param string $event * @return void */ - public function generate(string $event): void + #[NoReturn] public function generate(string $event): void { $generator = new Generator( $this->setting->getEventDirectory(), diff --git a/src/Console/Command/ClearCommand.php b/src/Console/Command/ClearCommand.php index 3c17ef19..2d26cd45 100644 --- a/src/Console/Command/ClearCommand.php +++ b/src/Console/Command/ClearCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; class ClearCommand extends AbstractCommand @@ -13,6 +14,7 @@ class ClearCommand extends AbstractCommand * * @param string $action * @return void + * @throws \ErrorException */ public function make(string $action): void { @@ -32,7 +34,7 @@ public function make(string $action): void * * @return void */ - private function clear($action) + private function clear(string $action): void { if ($action == 'all') { $this->unlinks($this->setting->getVarDirectory() . '/view/*/*'); @@ -79,11 +81,10 @@ private function clear($action) /** * Delete file * - * @param string $dirname - * + * @param string $dirname * @return void */ - private function unlinks($dirname) + private function unlinks(string $dirname): void { $glob = glob($dirname); diff --git a/src/Console/Command/ConfigurationCommand.php b/src/Console/Command/ConfigurationCommand.php index d28872f1..5a5d6593 100644 --- a/src/Console/Command/ConfigurationCommand.php +++ b/src/Console/Command/ConfigurationCommand.php @@ -4,8 +4,10 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class ConfigurationCommand extends AbstractCommand { @@ -15,7 +17,7 @@ class ConfigurationCommand extends AbstractCommand * @param string $configuration * @return void */ - public function generate(string $configuration): void + #[NoReturn] public function generate(string $configuration): void { $generator = new Generator( $this->setting->getPackageDirectory(), diff --git a/src/Console/Command/ConsoleCommand.php b/src/Console/Command/ConsoleCommand.php index f6d130a8..bf7c4d30 100644 --- a/src/Console/Command/ConsoleCommand.php +++ b/src/Console/Command/ConsoleCommand.php @@ -4,7 +4,9 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class ConsoleCommand extends AbstractCommand { @@ -14,7 +16,7 @@ class ConsoleCommand extends AbstractCommand * @param string $service * @return void */ - public function generate(string $service): void + #[NoReturn] public function generate(string $service): void { $generator = new Generator( $this->setting->getCommandDirectory(), diff --git a/src/Console/Command/ControllerCommand.php b/src/Console/Command/ControllerCommand.php index 1883136b..264f5e3a 100644 --- a/src/Console/Command/ControllerCommand.php +++ b/src/Console/Command/ControllerCommand.php @@ -4,7 +4,9 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class ControllerCommand extends AbstractCommand { @@ -14,7 +16,7 @@ class ControllerCommand extends AbstractCommand * @param string $controller * @return void */ - public function generate(string $controller): void + #[NoReturn] public function generate(string $controller): void { $generator = new Generator( $this->setting->getControllerDirectory(), diff --git a/src/Console/Command/EventListenerCommand.php b/src/Console/Command/EventListenerCommand.php index 0005d06e..d110c2fa 100644 --- a/src/Console/Command/EventListenerCommand.php +++ b/src/Console/Command/EventListenerCommand.php @@ -4,7 +4,9 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class EventListenerCommand extends AbstractCommand { @@ -14,7 +16,7 @@ class EventListenerCommand extends AbstractCommand * @param string $event * @return void */ - public function generate(string $event): void + #[NoReturn] public function generate(string $event): void { $generator = new Generator( $this->setting->getEventListenerDirectory(), diff --git a/src/Console/Command/ExceptionCommand.php b/src/Console/Command/ExceptionCommand.php index 5c553d6a..0c413b87 100644 --- a/src/Console/Command/ExceptionCommand.php +++ b/src/Console/Command/ExceptionCommand.php @@ -4,17 +4,19 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class ExceptionCommand extends AbstractCommand { /** * Add middleware * - * @param string $middleware + * @param string $exception * @return void */ - public function generate(string $exception): void + #[NoReturn] public function generate(string $exception): void { $generator = new Generator( $this->setting->getExceptionDirectory(), diff --git a/src/Console/Command/GenerateCacheCommand.php b/src/Console/Command/GenerateCacheCommand.php index 788d1235..7f2f0122 100644 --- a/src/Console/Command/GenerateCacheCommand.php +++ b/src/Console/Command/GenerateCacheCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; use Bow\Support\Str; diff --git a/src/Console/Command/GenerateKeyCommand.php b/src/Console/Command/GenerateKeyCommand.php index 30629a2e..ba3a332e 100644 --- a/src/Console/Command/GenerateKeyCommand.php +++ b/src/Console/Command/GenerateKeyCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Exception\ConsoleException; diff --git a/src/Console/Command/GenerateQueueCommand.php b/src/Console/Command/GenerateQueueCommand.php index b12241a3..d7b655df 100644 --- a/src/Console/Command/GenerateQueueCommand.php +++ b/src/Console/Command/GenerateQueueCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; use Bow\Support\Str; diff --git a/src/Console/Command/GenerateResourceControllerCommand.php b/src/Console/Command/GenerateResourceControllerCommand.php index 9aad6831..480d5790 100644 --- a/src/Console/Command/GenerateResourceControllerCommand.php +++ b/src/Console/Command/GenerateResourceControllerCommand.php @@ -4,9 +4,11 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; use Bow\Support\Str; +use JetBrains\PhpStorm\NoReturn; class GenerateResourceControllerCommand extends AbstractCommand { @@ -17,7 +19,7 @@ class GenerateResourceControllerCommand extends AbstractCommand * @return void * @throws */ - public function generate(string $controller): void + #[NoReturn] public function generate(string $controller): void { // We create command generator instance $generator = new Generator( @@ -34,7 +36,7 @@ public function generate(string $controller): void // We create the resource url prefix $prefix = preg_replace("/controller/i", "", strtolower($controller)); $prefix = '/' . trim($prefix, '/'); - $prefix = Str::plurial(Str::snake($prefix)); + $prefix = Str::plural(Str::snake($prefix)); $parameters = $this->arg->getParameters(); diff --git a/src/Console/Command/GenerateSessionCommand.php b/src/Console/Command/GenerateSessionCommand.php index 70db1604..91b98ee0 100644 --- a/src/Console/Command/GenerateSessionCommand.php +++ b/src/Console/Command/GenerateSessionCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; use Bow\Support\Str; diff --git a/src/Console/Command/MiddlewareCommand.php b/src/Console/Command/MiddlewareCommand.php index 34a4c3af..d5cde87c 100644 --- a/src/Console/Command/MiddlewareCommand.php +++ b/src/Console/Command/MiddlewareCommand.php @@ -4,8 +4,10 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class MiddlewareCommand extends AbstractCommand { @@ -15,7 +17,7 @@ class MiddlewareCommand extends AbstractCommand * @param string $middleware * @return void */ - public function generate(string $middleware): void + #[NoReturn] public function generate(string $middleware): void { $generator = new Generator( $this->setting->getMiddlewareDirectory(), diff --git a/src/Console/Command/MigrationCommand.php b/src/Console/Command/MigrationCommand.php index 4c99545f..4cee7f09 100644 --- a/src/Console/Command/MigrationCommand.php +++ b/src/Console/Command/MigrationCommand.php @@ -4,18 +4,22 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; use Bow\Database\Database; +use Bow\Database\Exception\ConnectionException; +use Bow\Database\Exception\QueryBuilderException; use Bow\Database\Migration\SQLGenerator; +use Bow\Database\QueryBuilder; use Bow\Support\Str; +use JetBrains\PhpStorm\NoReturn; class MigrationCommand extends AbstractCommand { /** * Make a migration command * - * @param string $model * @return void * @throws \Exception */ @@ -49,13 +53,11 @@ public function reset(): void /** * Create a migration in both directions * - * @param string $model * @param string $type - * * @return void * @throws \Exception */ - private function factory(string $type) + private function factory(string $type): void { $migrations = []; @@ -67,13 +69,9 @@ private function factory(string $type) // We create the migration database status $this->createMigrationTable(); - try { - $action = 'make' . strtoupper($type); + $action = 'make' . strtoupper($type); - return $this->$action($migrations); - } catch (\Exception $exception) { - throw $exception; - } + $this->$action($migrations); } /** @@ -81,6 +79,8 @@ private function factory(string $type) * * @param array $migrations * @return void + * @throws ConnectionException + * @throws QueryBuilderException */ protected function makeUp(array $migrations): void { @@ -126,6 +126,8 @@ protected function makeUp(array $migrations): void * * @param array $migrations * @return void + * @throws ConnectionException + * @throws QueryBuilderException */ protected function makeRollback(array $migrations): void { @@ -186,6 +188,8 @@ protected function makeRollback(array $migrations): void * * @param array $migrations * @return void + * @throws ConnectionException + * @throws QueryBuilderException */ protected function makeReset(array $migrations): void { @@ -233,7 +237,7 @@ protected function makeReset(array $migrations): void * @param string $migration * @return void */ - private function printExceptionMessage(string $message, string $migration) + #[NoReturn] private function printExceptionMessage(string $message, string $migration): void { $message = Color::red($message); $migration = Color::yellow($migration); @@ -247,7 +251,7 @@ private function printExceptionMessage(string $message, string $migration) * @param \Exception $exception * @param string $migration */ - private function throwMigrationException(\Exception $exception, string $migration) + #[NoReturn] private function throwMigrationException(\Exception $exception, string $migration): void { $this->printExceptionMessage( $exception->getMessage(), @@ -259,8 +263,9 @@ private function throwMigrationException(\Exception $exception, string $migratio * Create the migration status table * * @return void + * @throws ConnectionException */ - private function createMigrationTable() + private function createMigrationTable(): void { $connection = $this->arg->getParameter("--connection", config("database.default")); @@ -287,20 +292,21 @@ private function createMigrationTable() $generator->make() ); - return Database::statement($sql); + Database::statement($sql); } /** * Create migration status * * @param string $migration - * @return int + * @return void + * @throws ConnectionException */ - private function createMigrationStatus(string $migration): int + private function createMigrationStatus(string $migration): void { $table = $this->getMigrationTable(); - return $table->insert([ + $table->insert([ 'migration' => $migration, 'batch' => 1, 'created_at' => date('Y-m-d H:i:s') @@ -312,13 +318,14 @@ private function createMigrationStatus(string $migration): int * * @param string $migration * @param int $batch - * @return int + * @return void + * @throws ConnectionException|QueryBuilderException */ - private function updateMigrationStatus(string $migration, int $batch): int + private function updateMigrationStatus(string $migration, int $batch): void { $table = $this->getMigrationTable(); - return $table->where('migration', $migration)->update([ + $table->where('migration', $migration)->update([ 'migration' => $migration, 'batch' => $batch ]); @@ -329,6 +336,7 @@ private function updateMigrationStatus(string $migration, int $batch): int * * @param string $migration * @return bool + * @throws ConnectionException|QueryBuilderException */ private function checkIfMigrationExist(string $migration): bool { @@ -342,13 +350,14 @@ private function checkIfMigrationExist(string $migration): bool /** * Get migration table * - * @return \Database\Database\QueryBuilder + * @return QueryBuilder + * @throws ConnectionException */ - private function getMigrationTable() + private function getMigrationTable(): QueryBuilder { $migration_status_table = config('database.migration', 'migrations'); - return table($migration_status_table); + return db_table($migration_status_table); } /** @@ -356,7 +365,7 @@ private function getMigrationTable() * * @return array */ - private function getMigrationFiles() + private function getMigrationFiles(): array { $file_pattern = $this->setting->getMigrationDirectory() . strtolower("/*.php"); @@ -371,7 +380,7 @@ private function getMigrationFiles() * @return void * @throws \ErrorException */ - public function generate($model) + public function generate(string $model): void { $create_at = date("YmdHis"); $filename = sprintf("Version%s%s", $create_at, ucfirst(Str::camel($model))); diff --git a/src/Console/Command/ModelCommand.php b/src/Console/Command/ModelCommand.php index 9a609e3b..9a2b305c 100644 --- a/src/Console/Command/ModelCommand.php +++ b/src/Console/Command/ModelCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; @@ -13,9 +14,9 @@ class ModelCommand extends AbstractCommand * Add Model * * @param string $model - * @return mixed + * @return void */ - public function generate(string $model) + public function generate(string $model): void { $generator = new Generator( $this->setting->getModelDirectory(), diff --git a/src/Console/Command/ProducerCommand.php b/src/Console/Command/ProducerCommand.php index c78d4991..ae015f20 100644 --- a/src/Console/Command/ProducerCommand.php +++ b/src/Console/Command/ProducerCommand.php @@ -4,8 +4,10 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; +use JetBrains\PhpStorm\NoReturn; class ProducerCommand extends AbstractCommand { @@ -15,7 +17,7 @@ class ProducerCommand extends AbstractCommand * @param string $producer * @return void */ - public function generate(string $producer): void + #[NoReturn] public function generate(string $producer): void { $generator = new Generator( $this->setting->getProducerDirectory(), diff --git a/src/Console/Command/ReplCommand.php b/src/Console/Command/ReplCommand.php index 0a7da8b5..bbee5ba2 100644 --- a/src/Console/Command/ReplCommand.php +++ b/src/Console/Command/ReplCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; class ReplCommand extends AbstractCommand @@ -11,7 +12,7 @@ class ReplCommand extends AbstractCommand /** * Launch the REPL console * - * @return mixed + * @return void */ public function run(): void { @@ -27,7 +28,7 @@ public function run(): void } if (!class_exists('\Psy\Shell')) { - echo Color::red('Please, insall psy/psysh:@stable'); + echo Color::red('Please, install psy/psysh:@stable'); return; } @@ -35,11 +36,11 @@ public function run(): void $config = new \Psy\Configuration(); $config->setUpdateCheck(\Psy\VersionUpdater\Checker::NEVER); - // Load the custum prompt + // Load the custom prompt $prompt = $this->arg->getParameter('--prompt', '(bow) >>'); $prompt = trim($prompt) . ' '; - $config->setPrompt($prompt); + $config->theme()->setPrompt($prompt); $shell = new \Psy\Shell($config); diff --git a/src/Console/Command/SeederCommand.php b/src/Console/Command/SeederCommand.php index bcca7e8f..49bbb2d9 100644 --- a/src/Console/Command/SeederCommand.php +++ b/src/Console/Command/SeederCommand.php @@ -4,11 +4,14 @@ namespace Bow\Console\Command; -use Bow\Support\Str; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; -use Bow\Database\Database; use Bow\Console\Traits\ConsoleTrait; +use Bow\Database\Database; +use Bow\Support\Str; +use ErrorException; +use JetBrains\PhpStorm\NoReturn; class SeederCommand extends AbstractCommand { @@ -19,9 +22,9 @@ class SeederCommand extends AbstractCommand * * @param string $seeder */ - public function generate(string $seeder): void + #[NoReturn] public function generate(string $seeder): void { - $seeder = Str::plurial($seeder); + $seeder = Str::plural($seeder); $generator = new Generator( $this->setting->getSeederDirectory(), @@ -48,51 +51,48 @@ public function generate(string $seeder): void */ public function all(): void { - $seeds_filenames = glob($this->setting->getSeederDirectory() . '/*.php'); + $seeder = $this->setting->getSeederDirectory() . '/_database.php'; - $this->make($seeds_filenames); + $this->make($seeder); } /** * Launch targeted seeding * - * @param string $table_name + * @param string|null $seeder_name * @return void + * @throws ErrorException */ - public function table(string $seeder_name): void + public function table(?string $seeder_name = null): void { - $seeder_name = trim($seeder_name); - if (is_null($seeder_name)) { $this->throwFailsCommand('Specify the seeder table name', 'help seed'); } + $seeder_name = trim($seeder_name); + if (!file_exists($this->setting->getSeederDirectory() . "/{$seeder_name}.php")) { echo Color::red("Seeder $seeder_name not exists."); exit(1); } - $this->make([ + $this->make( $this->setting->getSeederDirectory() . "/{$seeder_name}.php" - ]); + ); } /** * Make Seeder * - * @param array $seeds_filenames + * @param string $seed_filename * @return void */ - private function make(array $seeds_filenames): void + private function make(string $seed_filename): void { - $seed_collection = []; + $seeds = require $seed_filename; - foreach ($seeds_filenames as $filename) { - $seeds = require $filename; - - $seed_collection = array_merge($seeds, $seed_collection); - } + $seed_collection = array_merge($seeds); // Get the database connexion $connection = $this->arg->getParameters()->get('--connection', config("database.default")); diff --git a/src/Console/Command/ServerCommand.php b/src/Console/Command/ServerCommand.php index 0fe89004..0e73c6d0 100644 --- a/src/Console/Command/ServerCommand.php +++ b/src/Console/Command/ServerCommand.php @@ -4,6 +4,8 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; + class ServerCommand extends AbstractCommand { /** diff --git a/src/Console/Command/ServiceCommand.php b/src/Console/Command/ServiceCommand.php index c76df43e..379978de 100644 --- a/src/Console/Command/ServiceCommand.php +++ b/src/Console/Command/ServiceCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Generator; class ServiceCommand extends AbstractCommand diff --git a/src/Console/Command/ValidationCommand.php b/src/Console/Command/ValidationCommand.php index 3de04301..1d7bb384 100644 --- a/src/Console/Command/ValidationCommand.php +++ b/src/Console/Command/ValidationCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Console\Color; use Bow\Console\Generator; diff --git a/src/Console/Command/WorkerCommand.php b/src/Console/Command/WorkerCommand.php index 69c18305..639efbb3 100644 --- a/src/Console/Command/WorkerCommand.php +++ b/src/Console/Command/WorkerCommand.php @@ -4,6 +4,7 @@ namespace Bow\Console\Command; +use Bow\Console\AbstractCommand; use Bow\Queue\WorkerService; class WorkerCommand extends AbstractCommand diff --git a/src/Console/Console.php b/src/Console/Console.php index 192caa12..6b585472 100644 --- a/src/Console/Console.php +++ b/src/Console/Console.php @@ -67,7 +67,7 @@ class Console /** * The console instance * - * @var Console + * @var ?Console */ private static ?Console $instance = null; @@ -94,9 +94,10 @@ class Console /** * Bow constructor. * - * @param Setting $setting + * @param Setting $setting * * @return void + * @throws \ErrorException */ public function __construct(Setting $setting) { @@ -173,7 +174,7 @@ public function run(): mixed // Get the argument command $command = $this->arg->getCommand(); - // Renaming the incomming command + // Renaming the incoming command if ($command == 'launch') { $command = null; } @@ -195,9 +196,10 @@ public function run(): mixed /** * Calls a command * - * @param string $command + * @param string|null $command * @return mixed - * @throws + * @throws \ErrorException + * @throws \Exception */ public function call(?string $command): mixed { @@ -266,6 +268,7 @@ public static function register(string $command, callable|string $cb): void * * @param string $command * @return mixed + * @throws \Exception */ private function executeCustomCommand(string $command): mixed { @@ -396,9 +399,10 @@ private function launch(): void } /** - * Allows generate a resource on a controller + * Allows to generate a resource on a controller * * @return void + * @throws \ErrorException */ private function generate(): void { @@ -415,6 +419,7 @@ private function generate(): void * Alias of generate * * @return void + * @throws \ErrorException */ private function gen(): void { @@ -444,7 +449,7 @@ private function flush(): void { $action = $this->arg->getAction(); - if (!in_array($action, ['worker'])) { + if ($action != 'worker') { $this->throwFailsCommand('This action is not exists', 'help flush'); } @@ -454,8 +459,9 @@ private function flush(): void /** * Display global help or helper command. * - * @param string|null $command + * @param string|null $command * @return int + * @throws \ErrorException */ private function help(?string $command = null): int { diff --git a/src/Console/Generator.php b/src/Console/Generator.php index 2992c637..1a80b0ad 100644 --- a/src/Console/Generator.php +++ b/src/Console/Generator.php @@ -37,11 +37,11 @@ public function __construct(string $base_directory, string $name) } /** - * Check if filename is valide + * Check if filename is valid * - * @param string $filename + * @param string|null $filename */ - public function filenameIsValide(?string $filename): void + public function filenameIsValid(?string $filename): void { if (is_null($filename)) { echo Color::red('The file name is invalid.'); @@ -57,7 +57,7 @@ public function filenameIsValide(?string $filename): void */ public function fileExists(): bool { - $this->filenameIsValide($this->name); + $this->filenameIsValid($this->name); return file_exists($this->getPath()) || is_dir($this->base_directory . "/" . $this->name); } @@ -79,7 +79,7 @@ public function getPath(): string */ public function exists(): bool { - $this->filenameIsValide($this->name); + $this->filenameIsValid($this->name); return file_exists($this->getPath()); } @@ -144,7 +144,7 @@ public function makeStubContent(string $type, array $data = []): string * * @param string $name */ - public function setName($name): void + public function setName(string $name): void { $this->name = $name; } diff --git a/src/Console/README.md b/src/Console/README.md index 7c6f0186..07eca798 100644 --- a/src/Console/README.md +++ b/src/Console/README.md @@ -8,4 +8,4 @@ Let's show the console guide: php bow help ``` -Is very enjoyful api +Is very joyful api diff --git a/src/Console/Setting.php b/src/Console/Setting.php index cadb0cda..bb398b66 100644 --- a/src/Console/Setting.php +++ b/src/Console/Setting.php @@ -165,7 +165,7 @@ class Setting private string $event_listener_directory; /** - * The namesapces directory + * The namespaces directory * * @var array */ diff --git a/src/Console/Traits/ConsoleTrait.php b/src/Console/Traits/ConsoleTrait.php index 41d4a227..7ba931aa 100644 --- a/src/Console/Traits/ConsoleTrait.php +++ b/src/Console/Traits/ConsoleTrait.php @@ -5,6 +5,7 @@ namespace Bow\Console\Traits; use Bow\Console\Color; +use JetBrains\PhpStorm\NoReturn; trait ConsoleTrait { @@ -12,11 +13,10 @@ trait ConsoleTrait * Throw fails command * * @param string $message - * @param string $command + * @param string|null $command * @return void - * @throws \ErrorException */ - protected function throwFailsCommand(string $message, ?string $command = null): void + #[NoReturn] protected function throwFailsCommand(string $message, ?string $command = null): void { echo Color::red($message) . "\n"; diff --git a/src/Console/stubs/controller/service.stub b/src/Console/stubs/controller/service.stub index 19893c07..78c746c1 100644 --- a/src/Console/stubs/controller/service.stub +++ b/src/Console/stubs/controller/service.stub @@ -21,8 +21,8 @@ class {className} extends Controller * @param {serviceClassName} ${serviceName} * @return mixed */ - public function __construct({serviceClassName} ${serviceName}) - { - $this->{serviceName} = ${serviceName}; + public function __construct( + private {serviceClassName} ${serviceName} + ){ } } diff --git a/src/Console/stubs/model/queue.stub b/src/Console/stubs/model/queue.stub index 02a9bbaf..e6239761 100644 --- a/src/Console/stubs/model/queue.stub +++ b/src/Console/stubs/model/queue.stub @@ -19,7 +19,7 @@ class {className} extends Migration "size" => ["waiting", "processing", "reserved", "failed", "done"], "default" => "waiting", ]); - $table->addDatetime('avalaibled_at'); + $table->addDatetime('available_at'); $table->addDatetime('reserved_at', ["nullable" => true, "default" => null]); $table->addDatetime('created_at'); }); diff --git a/src/Container/Action.php b/src/Container/Action.php index f2922ae8..58fdfe6f 100644 --- a/src/Container/Action.php +++ b/src/Container/Action.php @@ -40,7 +40,7 @@ class Action /** * The Action instance * - * @var Action + * @var ?Action */ private static ?Action $instance = null; @@ -96,7 +96,7 @@ public static function getInstance(): Action /** * Add a middleware to the list * - * @param array|callable $middlewares + * @param array $middlewares * @param bool $end * @return void */ @@ -105,9 +105,9 @@ public function pushMiddleware(array $middlewares, bool $end = false): void $middlewares = (array) $middlewares; if ($end) { - array_merge($this->middlewares, $middlewares); + $this->middlewares = array_merge($this->middlewares, $middlewares); } else { - array_merge($middlewares, $this->middlewares); + $this->middlewares = array_merge($middlewares, $this->middlewares); } } @@ -257,7 +257,7 @@ public function call(callable|string|array $actions, ?array $param = null): mixe */ foreach ($actions as $key => $action) { if (is_string($action)) { - array_push($functions, $this->controller($action)); + $functions[] = $this->controller($action); continue; } if (!is_callable($action)) { @@ -269,7 +269,7 @@ public function call(callable|string|array $actions, ?array $param = null): mixe $injection = $this->injectorForClosure($action); } - array_push($functions, ['action' => $action, 'injection' => $injection]); + $functions[] = ['action' => $action, 'injection' => $injection]; } return $this->dispatchControllers($functions, $param); @@ -350,16 +350,11 @@ public function execute(array|callable|string $function, array $arguments): mixe * Load the controllers defined as string * * @param string $controller_name - * @return array + * @return array|null * @throws ReflectionException */ public function controller(string $controller_name): ?array { - // Retrieving the class and method to launch. - if (is_null($controller_name)) { - return null; - } - $parts = preg_split('/::|@/', $controller_name); if (count($parts) == 1) { @@ -393,7 +388,7 @@ public function controller(string $controller_name): ?array * Load the closure define as action * * @param Closure $closure - * @return array + * @return array|null */ public function closure(Closure $closure): ?array { @@ -482,8 +477,9 @@ private function getInjectParameters(array $parameters): array * * @param ReflectionClass $class * @return ?object + * @throws ReflectionException */ - private function getInjectParameter($class): ?object + private function getInjectParameter(ReflectionClass $class): ?object { $class_name = $class->getName(); @@ -491,7 +487,7 @@ private function getInjectParameter($class): ?object return null; } - if (!class_exists($class_name, true)) { + if (!class_exists($class_name)) { throw new InvalidArgumentException( sprintf('class %s not exists', $class_name) ); diff --git a/src/Container/Capsule.php b/src/Container/Capsule.php index 3c146174..fd41fc8e 100644 --- a/src/Container/Capsule.php +++ b/src/Container/Capsule.php @@ -49,7 +49,7 @@ class Capsule implements ArrayAccess /** * Represents the instance of Capsule * - * @var Capsule + * @var ?Capsule */ private static ?Capsule $instance = null; @@ -134,7 +134,7 @@ public function makeWith(string $key, array $parameters = []): mixed * @param string $key * @param callable $value */ - public function bind(string $key, callable $value) + public function bind(string $key, callable $value): void { $this->key[$key] = true; @@ -148,7 +148,7 @@ public function bind(string $key, callable $value) * @param Closure|callable $value * @return void */ - public function factory($key, Closure|callable $value) + public function factory(string $key, Closure|callable $value): void { $this->factories[$key] = $value; } @@ -178,7 +178,7 @@ public function instance(string $key, mixed $instance): void * @return mixed * @throws */ - private function resolve($key): mixed + private function resolve(string $key): mixed { $reflection = new ReflectionClass($key); diff --git a/src/Container/ContainerConfiguration.php b/src/Container/ContainerConfiguration.php index a65c9f03..d2dc1dbf 100644 --- a/src/Container/ContainerConfiguration.php +++ b/src/Container/ContainerConfiguration.php @@ -4,7 +4,6 @@ namespace Bow\Container; -use Bow\Container\Action; use Bow\Configuration\Configuration; use Bow\Configuration\Loader; diff --git a/src/Contracts/CollectionInterface.php b/src/Contracts/CollectionInterface.php index 6844fced..0b73034f 100644 --- a/src/Contracts/CollectionInterface.php +++ b/src/Contracts/CollectionInterface.php @@ -44,7 +44,7 @@ public function add(string|int $key, mixed $data, bool $next = false): mixed; /** * Delete an entry in the collection * - * @param string $key + * @param string|int $key * @return CollectionInterface */ public function remove(string|int $key): mixed; diff --git a/src/Database/Barry/Builder.php b/src/Database/Barry/Builder.php index 678210ed..26e61056 100644 --- a/src/Database/Barry/Builder.php +++ b/src/Database/Barry/Builder.php @@ -5,6 +5,7 @@ namespace Bow\Database\Barry; use Bow\Database\Collection; +use Bow\Database\Exception\QueryBuilderException; use Bow\Database\QueryBuilder; use Bow\Database\Exception\ModelException; @@ -13,15 +14,15 @@ class Builder extends QueryBuilder /** * The model instance * - * @var string + * @var ?string */ protected ?string $model = null; /** - * Get informations + * Get information * * @param array $columns - * @return Model|Collection + * @return Model|Collection|null */ public function get(array $columns = []): Model|Collection|null { @@ -46,10 +47,10 @@ public function get(array $columns = []): Model|Collection|null /** * Check if rows exists * - * @param string $column + * @param string|null $column * @param mixed $value * @return bool - * @throws + * @throws QueryBuilderException */ public function exists(?string $column = null, mixed $value = null): bool { @@ -57,7 +58,7 @@ public function exists(?string $column = null, mixed $value = null): bool return $this->count() > 0; } - // If value is null and column is define + // If value is null and column is defined // we make the column as value on model primary key name if (!is_null($column) && is_null($value)) { $value = $column; @@ -85,6 +86,7 @@ public function setModel(string $model): Builder * Get model * * @return string + * @throws ModelException */ public function getModel(): string { diff --git a/src/Database/Barry/Concerns/Relationship.php b/src/Database/Barry/Concerns/Relationship.php index 046f8505..456a6a62 100644 --- a/src/Database/Barry/Concerns/Relationship.php +++ b/src/Database/Barry/Concerns/Relationship.php @@ -16,14 +16,14 @@ trait Relationship * * @return string */ - abstract public function getKey(); + abstract public function getKey(): string; /** * The has one relative * * @param string $related - * @param string $foreign_key - * @param string $local_key + * @param string|null $foreign_key + * @param string|null $local_key * @return BelongsTo */ public function belongsTo( @@ -50,8 +50,8 @@ public function belongsTo( * The belongs to many relative * * @param string $related - * @param string $primary_key - * @param string $foreign_key + * @param string|null $primary_key + * @param string|null $foreign_key * @return BelongsToMany */ public function belongsToMany( @@ -77,8 +77,8 @@ public function belongsToMany( * The has many relative * * @param string $related - * @param string $primary_key - * @param string $foreign_key + * @param string|null $primary_key + * @param string|null $foreign_key * @return HasMany */ public function hasMany( @@ -104,8 +104,8 @@ public function hasMany( * The has one relative * * @param string $related - * @param string $foreign_key - * @param string $primary_key + * @param string|null $foreign_key + * @param string|null $primary_key * @return HasOne */ public function hasOne( diff --git a/src/Database/Barry/Model.php b/src/Database/Barry/Model.php index b23ca3f9..6d5b1735 100644 --- a/src/Database/Barry/Model.php +++ b/src/Database/Barry/Model.php @@ -4,6 +4,8 @@ namespace Bow\Database\Barry; +use Bow\Database\Exception\ConnectionException; +use Bow\Database\Exception\QueryBuilderException; use Carbon\Carbon; use Bow\Support\Str; use Bow\Database\Collection; @@ -15,6 +17,13 @@ use Bow\Database\Barry\Traits\SerializableTrait; use Bow\Database\Pagination; +/** + * @method select(array|string[] $select) + * @method whereIn(string $primary_key, array $id) + * @method get() + * @method where(string $column, mixed $value) + * @method orderBy(string $latest, string $string) + */ abstract class Model implements \ArrayAccess, \JsonSerializable { use Relationship; @@ -137,7 +146,7 @@ abstract class Model implements \ArrayAccess, \JsonSerializable /** * The query builder instance * - * @var Builder + * @var ?Builder */ protected static ?Builder $builder = null; @@ -160,10 +169,12 @@ public function __construct(array $attributes = []) * * @param string $name * @return Model + * @throws ConnectionException */ public static function connection(string $name): Model { $model = new static(); + $model->setConnection($name); return $model; @@ -174,9 +185,9 @@ public static function connection(string $name): Model * * @param array $columns * - * @return \Bow\Database\Collection + * @return Collection */ - public static function all(array $columns = []) + public static function all(array $columns = []): Collection { $model = static::query(); @@ -190,7 +201,7 @@ public static function all(array $columns = []) /** * Get first rows * - * @return Model + * @return Model|null */ public static function first(): ?Model { @@ -200,7 +211,7 @@ public static function first(): ?Model /** * Get latest * - * @return Model + * @return Model|null */ public static function latest(): ?Model { @@ -230,9 +241,7 @@ public static function find( return $model->get(); } - $result = $model->first(); - - return $result; + return $model->first(); } /** @@ -265,7 +274,7 @@ public static function findAndDelete( $model = static::find($id, $select); if (is_null($model)) { - return $model; + return null; } if ($model instanceof Collection) { @@ -282,12 +291,12 @@ public static function findAndDelete( * Find information by id or throws an * exception in data box not found * - * @param mixed $id - * @param array|callable $select + * @param mixed $id + * @param array $select * @return Model * @throws NotFoundException */ - public static function findOrFail(int | string $id, $select = ['*']): Model + public static function findOrFail(int | string $id, array $select = ['*']): Model { $result = static::find($id, $select); @@ -315,7 +324,7 @@ public static function create(array $data): Model ]); } - // Check if the primary key existe on updating data + // Check if the primary key exist on updating data if ( !array_key_exists($model->primary_key, $data) && static::$builder->getAdapterName() !== "pgsql" @@ -342,7 +351,7 @@ public static function create(array $data): Model * * @param int $page_number * @param int $current - * @param int $chunk + * @param int|null $chunk * @return Pagination */ public static function paginate(int $page_number, int $current = 0, ?int $chunk = null): Pagination @@ -452,22 +461,18 @@ public static function query(): Builder if (!isset($properties['table']) || $properties['table'] == null) { $parts = explode('\\', static::class); - $table = Str::lower(Str::snake(Str::plurial(end($parts)))); + $table = Str::lower(Str::snake(Str::plural(end($parts)))); } else { $table = $properties['table']; } // Check the connection parameter before apply - if (isset($properties['connection']) && !is_null($properties['connection'])) { + if (isset($properties['connection'])) { DB::connection($properties['connection']); } // Check the prefix parameter before apply - if (isset($properties['prefix']) && !is_null($properties['prefix'])) { - $prefix = $properties['prefix']; - } else { - $prefix = DB::getConnectionAdapter()->getTablePrefix(); - } + $prefix = $properties['prefix'] ?? DB::getConnectionAdapter()->getTablePrefix(); // Set the table prefix $table = $prefix . $table; @@ -482,10 +487,10 @@ public static function query(): Builder /** * Create the new row * - * @param Builder $model + * @param Builder $builder * @return int */ - private function writeRows(Builder $builder) + private function writeRows(Builder $builder): int { // Fire the creating event $this->fireEvent('model.creating'); @@ -505,7 +510,7 @@ private function writeRows(Builder $builder) $primary_key_value = static::$builder->getPdo()->lastInsertId(); } - if (is_null($primary_key_value) || $primary_key_value == 0) { + if ((int) $primary_key_value == 0) { $primary_key_value = $this->attributes[$this->primary_key] ?? null; } @@ -528,7 +533,7 @@ private function writeRows(Builder $builder) * @return int * @throws */ - public function save() + public function save(): int { $builder = static::query(); @@ -550,13 +555,9 @@ public function save() // We set the primary key value $this->original[$this->primary_key] = $primary_key_value; - $update_data = []; - - foreach ($this->attributes as $key => $value) { - if (!array_key_exists($key, $this->original) || $this->original[$key] !== $value) { - $update_data[$key] = $value; - } - } + $update_data = array_filter($this->attributes, function ($value, $key) { + return !array_key_exists($key, $this->original) || $this->original[$key] !== $value; + }, ARRAY_FILTER_USE_BOTH); // When the update data is empty, we load the original data if (count($update_data) == 0) { @@ -578,12 +579,12 @@ public function save() } /** - * Transtype the primary key value + * Trans-type the primary key value * * @param mixed $primary_key_value - * @return mixed + * @return string|int|float */ - private function transtypeKeyValue(mixed $primary_key_value): mixed + private function transtypeKeyValue(mixed $primary_key_value): string|int|float { // Transtype value to the define primary key type if ($this->primary_key_type == 'int') { @@ -621,12 +622,9 @@ public function update(array $attributes): int|bool $data_for_updating = $attributes; if (count($this->original) > 0) { - $data_for_updating = []; - foreach ($attributes as $key => $value) { - if (array_key_exists($key, $this->original) || $this->original[$key] !== $value) { - $data_for_updating[$key] = $value; - } - } + $data_for_updating = array_filter($attributes, function ($value, $key) { + return array_key_exists($key, $this->original) || $this->original[$key] !== $value; + }, ARRAY_FILTER_USE_BOTH); } // Fire the updating event @@ -687,16 +685,15 @@ public function delete(): int * Delete Active Record by column name * * @param string $column - * @param string|int $value + * @param mixed $value * @return int + * @throws QueryBuilderException */ - public static function deleteBy($column, $value): int + public static function deleteBy(string $column, mixed $value): int { $model = static::query(); - $deleted = $model->where($column, $value)->delete(); - - return $deleted; + return $model->where($column, $value)->delete(); } /** @@ -720,7 +717,7 @@ public function getKey(): string } /** - * Retrieves the primary key key + * Retrieves the primary key * * @return string */ @@ -769,15 +766,15 @@ public function setAttribute(string $key, string $value): void * * @param string $name * @return Builder + * @throws ConnectionException */ public function setConnection(string $name): Builder { $this->connection = $name; DB::connection($name); - $builder = static::query(); - return $builder; + return static::query(); } /** @@ -830,15 +827,9 @@ public function getTable(): string */ public function toArray(): array { - $data = []; - - foreach ($this->attributes as $key => $value) { - if (!in_array($key, $this->hidden)) { - $data[$key] = $value; - } - } - - return $data; + return array_filter($this->attributes, function ($key) { + return !in_array($key, $this->hidden); + }, ARRAY_FILTER_USE_KEY); } /** @@ -848,13 +839,9 @@ public function toArray(): array */ public function toJson(): string { - $data = []; - - foreach ($this->attributes as $key => $value) { - if (!in_array($key, $this->hidden)) { - $data[$key] = $value; - } - } + $data = array_filter($this->attributes, function ($key) { + return !in_array($key, $this->hidden); + }, ARRAY_FILTER_USE_KEY); return json_encode($data); } @@ -864,15 +851,9 @@ public function toJson(): string */ public function jsonSerialize(): array { - $data = []; - - foreach ($this->attributes as $key => $value) { - if (!in_array($key, $this->hidden)) { - $data[$key] = $value; - } - } - - return $data; + return array_filter($this->attributes, function ($key) { + return !in_array($key, $this->hidden); + }, ARRAY_FILTER_USE_KEY); } /** @@ -953,9 +934,9 @@ public function __get(string $name): mixed * __set * * @param string $name - * @param $value + * @param mixed $value */ - public function __set($name, $value) + public function __set(string $name, mixed $value) { $this->attributes[$name] = $value; } @@ -973,11 +954,11 @@ public function __toString(): string /** * __call * - * @param string $name + * @param string $name * @param array $arguments * @return mixed */ - public function __call($name, array $arguments) + public function __call(string $name, array $arguments = []) { $model = static::query(); diff --git a/src/Database/Barry/Relation.php b/src/Database/Barry/Relation.php index bcc2f0f1..446028cf 100644 --- a/src/Database/Barry/Relation.php +++ b/src/Database/Barry/Relation.php @@ -59,7 +59,7 @@ abstract class Relation protected static bool $has_pivot = false; /** - * Relation Contructor + * Relation Contractor * * @param Model $related * @param Model $parent @@ -101,10 +101,10 @@ public function getRelated(): Model * _Call * * @param string $method - * @param string $args + * @param array $args * @return mixed */ - public function __call(string $method, array $args) + public function __call(string $method, array $args = []) { $result = call_user_func_array([$this->query, $method], (array) $args); diff --git a/src/Database/Barry/Relations/BelongsTo.php b/src/Database/Barry/Relations/BelongsTo.php index 1e35ff35..9e079cb2 100644 --- a/src/Database/Barry/Relations/BelongsTo.php +++ b/src/Database/Barry/Relations/BelongsTo.php @@ -7,6 +7,7 @@ use Bow\Cache\Cache; use Bow\Database\Barry\Model; use Bow\Database\Barry\Relation; +use Bow\Database\Exception\QueryBuilderException; class BelongsTo extends Relation { @@ -33,9 +34,9 @@ public function __construct( /** * Get the results of the relationship. * - * @return Model + * @return mixed */ - public function getResults(): ?Model + public function getResults(): mixed { $key = $this->query->getTable() . ":belongsto:" . $this->related->getTable() . ":" . $this->foreign_key; @@ -60,6 +61,7 @@ public function getResults(): ?Model * Set the base constraints on the relation query. * * @return void + * @throws QueryBuilderException */ public function addConstraints(): void { diff --git a/src/Database/Barry/Relations/BelongsToMany.php b/src/Database/Barry/Relations/BelongsToMany.php index d123f41f..2c5e752e 100644 --- a/src/Database/Barry/Relations/BelongsToMany.php +++ b/src/Database/Barry/Relations/BelongsToMany.php @@ -7,6 +7,7 @@ use Bow\Database\Collection; use Bow\Database\Barry\Model; use Bow\Database\Barry\Relation; +use Bow\Database\Exception\QueryBuilderException; class BelongsToMany extends Relation { @@ -40,6 +41,7 @@ public function getResults(): Collection * Set the base constraints on the relation query. * * @return void + * @throws QueryBuilderException */ public function addConstraints(): void { diff --git a/src/Database/Barry/Relations/HasMany.php b/src/Database/Barry/Relations/HasMany.php index eb38420d..8e0586e3 100644 --- a/src/Database/Barry/Relations/HasMany.php +++ b/src/Database/Barry/Relations/HasMany.php @@ -7,6 +7,7 @@ use Bow\Database\Collection; use Bow\Database\Barry\Model; use Bow\Database\Barry\Relation; +use Bow\Database\Exception\QueryBuilderException; class HasMany extends Relation { @@ -15,9 +16,9 @@ class HasMany extends Relation * * @param Model $related * @param Model $parent - * @param string $foreign_key - * @param string $local_key - * @param string $relation + * @param string $foreign_key + * @param string $local_key + * @throws QueryBuilderException */ public function __construct(Model $related, Model $parent, string $foreign_key, string $local_key) { diff --git a/src/Database/Barry/Relations/HasOne.php b/src/Database/Barry/Relations/HasOne.php index 32c155ff..461bbc46 100644 --- a/src/Database/Barry/Relations/HasOne.php +++ b/src/Database/Barry/Relations/HasOne.php @@ -7,6 +7,7 @@ use Bow\Cache\Cache; use Bow\Database\Barry\Model; use Bow\Database\Barry\Relation; +use Bow\Database\Exception\QueryBuilderException; class HasOne extends Relation { @@ -29,9 +30,9 @@ public function __construct(Model $related, Model $parent, string $foreign_key, /** * Get the results of the relationship. * - * @return Model + * @return Model|null */ - public function getResults(): ?Model + public function getResults(): mixed { $key = $this->query->getTable() . ":hasone:" . $this->related->getTable() . ":" . $this->foreign_key; @@ -56,6 +57,7 @@ public function getResults(): ?Model * Set the base constraints on the relation query. * * @return void + * @throws QueryBuilderException */ public function addConstraints(): void { diff --git a/src/Database/Barry/Traits/ArrayAccessTrait.php b/src/Database/Barry/Traits/ArrayAccessTrait.php index 6daab364..968e18ae 100644 --- a/src/Database/Barry/Traits/ArrayAccessTrait.php +++ b/src/Database/Barry/Traits/ArrayAccessTrait.php @@ -58,8 +58,6 @@ public function offsetUnset(mixed $offset): void */ public function offsetGet(mixed $offset): mixed { - return isset($this->attributes[$offset]) - ? $this->attributes[$offset] - : null; + return $this->attributes[$offset] ?? null; } } diff --git a/src/Database/Barry/Traits/CanSerialized.php b/src/Database/Barry/Traits/CanSerialized.php index 49895f09..26c2fd41 100644 --- a/src/Database/Barry/Traits/CanSerialized.php +++ b/src/Database/Barry/Traits/CanSerialized.php @@ -6,12 +6,15 @@ use Bow\Database\Barry\Model; +/** + * @method toArray(): array + */ trait CanSerialized { /** * __sleep * - * @return string + * @return array */ public function __sleep(): array { diff --git a/src/Database/Collection.php b/src/Database/Collection.php index 0b2c6be4..977fd44d 100644 --- a/src/Database/Collection.php +++ b/src/Database/Collection.php @@ -18,7 +18,7 @@ public function __construct(array $storage = []) } /** - * Get the first item of starage + * Get the first item of storage * * @return ?Model */ diff --git a/src/Database/Connection/AbstractConnection.php b/src/Database/Connection/AbstractConnection.php index ea94c812..d27638db 100644 --- a/src/Database/Connection/AbstractConnection.php +++ b/src/Database/Connection/AbstractConnection.php @@ -12,7 +12,7 @@ abstract class AbstractConnection /** * The connexion name * - * @var string + * @var ?string */ protected ?string $name = null; diff --git a/src/Database/Connection/Adapter/MysqlAdapter.php b/src/Database/Connection/Adapter/MysqlAdapter.php index 898e0173..cd7dacdc 100644 --- a/src/Database/Connection/Adapter/MysqlAdapter.php +++ b/src/Database/Connection/Adapter/MysqlAdapter.php @@ -14,7 +14,7 @@ class MysqlAdapter extends AbstractConnection /** * The connexion nane * - * @var string + * @var ?string */ protected ?string $name = 'mysql'; @@ -45,7 +45,7 @@ public function __construct(array $config) public function connection(): void { // Build of the mysql dsn - if (isset($this->config['socket']) && !is_null($this->config['socket']) && !empty($this->config['socket'])) { + if (isset($this->config['socket']) && !empty($this->config['socket'])) { $hostname = $this->config['socket']; $port = ''; } else { @@ -64,9 +64,9 @@ public function connection(): void $username = $this->config["username"]; $password = $this->config["password"]; - // Configuration the PDO attributes that we want to setting + // Configuration the PDO attributes that we want to set $options = [ - PDO::ATTR_DEFAULT_FETCH_MODE => isset($this->config['fetch']) ? $this->config['fetch'] : $this->fetch, + PDO::ATTR_DEFAULT_FETCH_MODE => $this->config['fetch'] ?? $this->fetch, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . Str::upper($this->config["charset"]), PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING diff --git a/src/Database/Connection/Adapter/PostgreSQLAdapter.php b/src/Database/Connection/Adapter/PostgreSQLAdapter.php index 6e92cfe7..b7a4662f 100644 --- a/src/Database/Connection/Adapter/PostgreSQLAdapter.php +++ b/src/Database/Connection/Adapter/PostgreSQLAdapter.php @@ -13,7 +13,7 @@ class PostgreSQLAdapter extends AbstractConnection /** * The connexion nane * - * @var string + * @var ?string */ protected ?string $name = 'pgsql'; @@ -87,9 +87,9 @@ public function connection(): void $username = $this->config["username"]; $password = $this->config["password"]; - // Configuration the PDO attributes that we want to setting + // Configuration the PDO attributes that we want to set $options = [ - PDO::ATTR_DEFAULT_FETCH_MODE => isset($this->config['fetch']) ? $this->config['fetch'] : $this->fetch, + PDO::ATTR_DEFAULT_FETCH_MODE => $this->config['fetch'] ?? $this->fetch, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; diff --git a/src/Database/Connection/Adapter/SqliteAdapter.php b/src/Database/Connection/Adapter/SqliteAdapter.php index 8723c978..6fa20ee5 100644 --- a/src/Database/Connection/Adapter/SqliteAdapter.php +++ b/src/Database/Connection/Adapter/SqliteAdapter.php @@ -13,7 +13,7 @@ class SqliteAdapter extends AbstractConnection /** * The connexion name * - * @var string + * @var ?string */ protected ?string $name = 'sqlite'; @@ -48,7 +48,7 @@ public function connection(): void // Set the PDO attributes that we want $this->pdo->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, - isset($this->config['fetch']) ? $this->config['fetch'] : $this->fetch + $this->config['fetch'] ?? $this->fetch ); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); diff --git a/src/Database/Connection/Connection.php b/src/Database/Connection/Connection.php index 60400f83..29402e33 100644 --- a/src/Database/Connection/Connection.php +++ b/src/Database/Connection/Connection.php @@ -38,7 +38,7 @@ public function getAdapter(): AbstractConnection * * @param AbstractConnection $adapter */ - public function setAdapter(AbstractConnection $adapter) + public function setAdapter(AbstractConnection $adapter): void { $this->adapter = $adapter; } diff --git a/src/Database/Database.php b/src/Database/Database.php index 1198b559..ba1fa574 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -4,7 +4,6 @@ namespace Bow\Database; -use PDO; use Bow\Security\Sanitize; use Bow\Database\Exception\DatabaseException; use Bow\Database\Connection\AbstractConnection; @@ -12,7 +11,7 @@ use Bow\Database\Connection\Adapter\MysqlAdapter; use Bow\Database\Connection\Adapter\SqliteAdapter; use Bow\Database\Connection\Adapter\PostgreSQLAdapter; -use ErrorException; +use PDO; class Database { @@ -204,7 +203,7 @@ public static function select(string $sql_statement, array $data = []): mixed * @param array $data * @return mixed|null */ - public static function selectOne(string $sql_statement, array $data = []) + public static function selectOne(string $sql_statement, array $data = []): mixed { static::verifyConnection(); @@ -232,8 +231,8 @@ public static function selectOne(string $sql_statement, array $data = []) /** * Execute an insert query * - * @param $sql_statement - * @param array $data + * @param string $sql_statement + * @param array $data * @return int */ public static function insert(string $sql_statement, array $data = []): int @@ -335,7 +334,6 @@ public static function table(string $table): QueryBuilder /** * Starting the start of a transaction * - * @param callable $callback * @return void */ public static function startTransaction(): void @@ -471,7 +469,7 @@ public static function getPdo(): PDO * * @param PDO $pdo */ - public static function setPdo(PDO $pdo) + public static function setPdo(PDO $pdo): void { static::$adapter->setConnection($pdo); } @@ -481,10 +479,8 @@ public static function setPdo(PDO $pdo) * * @param string $method * @param array $arguments - * - * @throws DatabaseException - * * @return mixed + * @throws DatabaseException|ErrorException */ public function __call(string $method, array $arguments) { diff --git a/src/Database/Migration/Compose/MysqlCompose.php b/src/Database/Migration/Compose/MysqlCompose.php index 3773bfe2..bcb575e4 100644 --- a/src/Database/Migration/Compose/MysqlCompose.php +++ b/src/Database/Migration/Compose/MysqlCompose.php @@ -12,6 +12,7 @@ trait MysqlCompose * @param string $name * @param array $description * @return string + * @throws SQLGeneratorException */ private function composeAddMysqlColumn(string $name, array $description): string { @@ -21,7 +22,7 @@ private function composeAddMysqlColumn(string $name, array $description): string $type = $raw_type; $attribute = $description['attribute']; - if (in_array($type, ['TEXT']) && isset($attribute['default'])) { + if ($type == 'TEXT' && isset($attribute['default'])) { throw new SQLGeneratorException("Cannot define default value for $type type"); } diff --git a/src/Database/Migration/Compose/PgsqlCompose.php b/src/Database/Migration/Compose/PgsqlCompose.php index cad7418a..295d92d2 100644 --- a/src/Database/Migration/Compose/PgsqlCompose.php +++ b/src/Database/Migration/Compose/PgsqlCompose.php @@ -29,6 +29,7 @@ public function getCustomTypeQueries(): array * @param string $name * @param array $description * @return string + * @throws SQLGeneratorException */ private function composeAddPgsqlColumn(string $name, array $description): string { @@ -38,7 +39,7 @@ private function composeAddPgsqlColumn(string $name, array $description): string $type = $raw_type; $attribute = $description['attribute']; - if (in_array($type, ['TEXT']) && isset($attribute['default'])) { + if ($type == 'TEXT' && isset($attribute['default'])) { throw new SQLGeneratorException("Cannot define default value for $type type"); } @@ -151,9 +152,9 @@ private function dropColumnForPgsql(string $name): void * @param string $name * @param string $type * @param array $attribute - * @return void + * @return string */ - private function formatCheckOrEnum($name, $type, $attribute): string + private function formatCheckOrEnum(string $name, string $type, array $attribute): string { if ($type == "ENUM") { $size = (array) $attribute['size']; @@ -171,26 +172,26 @@ private function formatCheckOrEnum($name, $type, $attribute): string } if (count($attribute["check"]) === 3) { - [$column, $comparaison, $value] = $attribute["check"]; + [$column, $comparison, $value] = $attribute["check"]; if (is_array($value)) { $value = "('" . implode("', '", $value) . "')"; } - return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparaison, $value); + return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparison, $value); } [$column, $value] = $attribute["check"]; - $comparaison = "="; + $comparison = "="; if (is_string($value)) { $value = "'" . addcslashes($value, "'") . "'"; - return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparaison, $value); + return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparison, $value); } $value = (array) $value; if (count($value) > 1) { - $comparaison = "IN"; + $comparison = "IN"; foreach ($value as $key => $item) { if (is_string($item)) { @@ -199,11 +200,11 @@ private function formatCheckOrEnum($name, $type, $attribute): string } $value = "(" . implode(", ", $value) . ")"; - return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparaison, $value); + return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparison, $value); } $value = end($value); - return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparaison, $value); + return sprintf('TEXT CHECK ("%s" %s %s)', $column, $comparison, $value); } } diff --git a/src/Database/Migration/Compose/SqliteCompose.php b/src/Database/Migration/Compose/SqliteCompose.php index f23a86bd..eab61a01 100644 --- a/src/Database/Migration/Compose/SqliteCompose.php +++ b/src/Database/Migration/Compose/SqliteCompose.php @@ -13,10 +13,12 @@ trait SqliteCompose * @param string $name * @param array $description * @return string + * @throws SQLGeneratorException */ private function composeAddSqliteColumn(string $name, array $description): string { $type = $this->normalizeOfType($description['type']); + $raw_type = strtoupper($type); if (in_array($raw_type, ['ENUM', 'CHECK'])) { @@ -68,7 +70,7 @@ private function composeAddSqliteColumn(string $name, array $description): strin // Add default value if (!is_null($default)) { - if (in_array($raw_type, ['TEXT'])) { + if ($raw_type == 'TEXT') { $default = "'" . addcslashes($default, "'") . "'"; } elseif (is_bool($default)) { $default = $default ? 'true' : 'false'; @@ -89,8 +91,8 @@ private function composeAddSqliteColumn(string $name, array $description): strin /** * Rename column with sqlite * - * @param string $name - * @param string $new + * @param string $old_name + * @param string $new_name * @return void */ private function renameColumnOnSqlite(string $old_name, string $new_name): void diff --git a/src/Database/Migration/Migration.php b/src/Database/Migration/Migration.php index ecd9bc48..5ac2573d 100644 --- a/src/Database/Migration/Migration.php +++ b/src/Database/Migration/Migration.php @@ -6,6 +6,7 @@ use Bow\Console\Color; use Bow\Database\Database; +use Bow\Database\Exception\ConnectionException; use Bow\Database\Migration\SQLGenerator; use Bow\Database\Exception\MigrationException; use Bow\Database\Connection\AbstractConnection; @@ -48,6 +49,7 @@ abstract public function rollback(): void; * * @param string $name * @return Migration + * @throws ConnectionException */ final public function connection(string $name): Migration { @@ -73,6 +75,7 @@ public function getAdapterName(): string * * @param string $table * @return Migration + * @throws MigrationException */ final public function drop(string $table): Migration { @@ -88,6 +91,7 @@ final public function drop(string $table): Migration * * @param string $table * @return Migration + * @throws MigrationException */ final public function dropIfExists(string $table): Migration { @@ -105,9 +109,10 @@ final public function dropIfExists(string $table): Migration /** * Function of creation of a new table in the database. * - * @param string $table + * @param string $table * @param callable $cb * @return Migration + * @throws MigrationException */ final public function create(string $table, callable $cb): Migration { @@ -147,6 +152,7 @@ final public function create(string $table, callable $cb): Migration * @param string $table * @param callable $cb * @return Migration + * @throws MigrationException */ final public function alter(string $table, callable $cb): Migration { @@ -170,6 +176,7 @@ final public function alter(string $table, callable $cb): Migration * * @param string $sql * @return Migration + * @throws MigrationException */ final public function addSql(string $sql): Migration { @@ -182,6 +189,7 @@ final public function addSql(string $sql): Migration * @param string $table * @param string $to * @return Migration + * @throws MigrationException */ final public function renameTable(string $table, string $to): Migration { @@ -196,6 +204,7 @@ final public function renameTable(string $table, string $to): Migration * @param string $table * @param string $to * @return Migration + * @throws MigrationException */ final public function renameTableIfExists(string $table, string $to): Migration { @@ -212,9 +221,7 @@ final public function renameTableIfExists(string $table, string $to): Migration */ final public function getTablePrefixed(string $table): string { - $table = $this->adapter->getTablePrefix() . $table; - - return $table; + return $this->adapter->getTablePrefix() . $table; } /** @@ -234,6 +241,7 @@ private function executeSqlQuery(string $sql): Migration } echo sprintf("%s %s\n", Color::green("▶"), $sql); + return $this; } } diff --git a/src/Database/Migration/SQLGenerator.php b/src/Database/Migration/SQLGenerator.php index 9f82a22f..8e086f09 100644 --- a/src/Database/Migration/SQLGenerator.php +++ b/src/Database/Migration/SQLGenerator.php @@ -99,7 +99,7 @@ public function make(): string } /** - * Add a raw column definiton + * Add a raw column definition * * @param string $definition * @return SQLGenerator @@ -118,6 +118,7 @@ public function addRaw(string $definition): SQLGenerator * @param string $type * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addColumn(string $name, string $type, array $attribute = []): SQLGenerator { @@ -140,8 +141,9 @@ public function addColumn(string $name, string $type, array $attribute = []): SQ * * @param string $name * @param string $type - * @param array $attributes + * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeColumn(string $name, string $type, array $attribute = []): SQLGenerator { @@ -290,6 +292,7 @@ public function setTable(string $table): string * @param string $name * @param array $description * @return string + * @throws SQLGeneratorException */ private function composeAddColumn(string $name, array $description): string { @@ -298,14 +301,12 @@ private function composeAddColumn(string $name, array $description): string throw new SQLGeneratorException("Cannot define size for $type type"); } - switch ($this->adapter) { - case "sqlite": - return $this->composeAddSqliteColumn($name, $description); - case "mysql": - return $this->composeAddMysqlColumn($name, $description); - case "pgsql": - return $this->composeAddPgsqlColumn($name, $description); - } + return match ($this->adapter) { + "sqlite" => $this->composeAddSqliteColumn($name, $description), + "mysql" => $this->composeAddMysqlColumn($name, $description), + "pgsql" => $this->composeAddPgsqlColumn($name, $description), + default => throw new SQLGeneratorException("Unknown adapter '{$this->adapter}'"), + }; } /** @@ -340,20 +341,14 @@ public function setAdapter(string $adapter): SQLGenerator * @param string $type * @return string */ - public function normalizeOfType(string $type) + public function normalizeOfType(string $type): string { - if (in_array($this->adapter, ["mysql", "pgsql"])) { - return $type; - } - - if (preg_match('/int|float|double/', $type)) { - $type = 'integer'; - } elseif (preg_match('/float|double/', $type)) { - $type = 'real'; - } elseif (preg_match('/^(text|char|string)$/i', $type)) { - $type = 'text'; - } - - return $type; + return match (true) { + (bool) in_array($this->adapter, ["mysql", "pgsql"]) => $type, + (bool) preg_match('/int|float|double/', $type) => 'integer', + (bool) preg_match('/float|double/', $type) => 'real', + (bool) preg_match('/^(text|char|string)$/i', $type) => 'text', + default => $type, + }; } } diff --git a/src/Database/Migration/Shortcut/ConstraintColumn.php b/src/Database/Migration/Shortcut/ConstraintColumn.php index b4d10121..edae02d1 100644 --- a/src/Database/Migration/Shortcut/ConstraintColumn.php +++ b/src/Database/Migration/Shortcut/ConstraintColumn.php @@ -73,9 +73,9 @@ public function addForeign(string $name, array $attributes = []): SQLGenerator } /** - * Drop constraintes column; + * Drop constraints column; * - * @param string $name + * @param string|array $name * @param bool $as_raw * @return SQLGenerator */ diff --git a/src/Database/Migration/Shortcut/DateColumn.php b/src/Database/Migration/Shortcut/DateColumn.php index 4c2c5b5b..a1990eec 100644 --- a/src/Database/Migration/Shortcut/DateColumn.php +++ b/src/Database/Migration/Shortcut/DateColumn.php @@ -4,6 +4,7 @@ namespace Bow\Database\Migration\Shortcut; +use Bow\Database\Exception\SQLGeneratorException; use Bow\Database\Migration\SQLGenerator; trait DateColumn @@ -14,6 +15,7 @@ trait DateColumn * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addDatetime(string $column, array $attribute = []): SQLGenerator { @@ -30,6 +32,7 @@ public function addDatetime(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addDate(string $column, array $attribute = []): SQLGenerator { @@ -42,6 +45,7 @@ public function addDate(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addTime(string $column, array $attribute = []): SQLGenerator { @@ -54,6 +58,7 @@ public function addTime(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addYear(string $column, array $attribute = []): SQLGenerator { @@ -66,6 +71,7 @@ public function addYear(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addTimestamp(string $column, array $attribute = []): SQLGenerator { @@ -76,6 +82,7 @@ public function addTimestamp(string $column, array $attribute = []): SQLGenerato * Add default timestamps * * @return SQLGenerator + * @throws SQLGeneratorException */ public function addTimestamps(): SQLGenerator { @@ -98,6 +105,7 @@ public function addTimestamps(): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeDatetime(string $column, array $attribute = []): SQLGenerator { @@ -114,6 +122,7 @@ public function changeDatetime(string $column, array $attribute = []): SQLGenera * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeDate(string $column, array $attribute = []): SQLGenerator { @@ -126,6 +135,7 @@ public function changeDate(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeTime(string $column, array $attribute = []): SQLGenerator { @@ -138,6 +148,7 @@ public function changeTime(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeYear(string $column, array $attribute = []): SQLGenerator { @@ -150,6 +161,7 @@ public function changeYear(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeTimestamp(string $column, array $attribute = []): SQLGenerator { @@ -160,8 +172,9 @@ public function changeTimestamp(string $column, array $attribute = []): SQLGener * Change default timestamps * * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeTimestamps() + public function changeTimestamps(): SQLGenerator { if ($this->adapter == 'sqlite') { $this->changeColumn('created_at', 'text', ['default' => 'CURRENT_TIMESTAMP']); diff --git a/src/Database/Migration/Shortcut/MixedColumn.php b/src/Database/Migration/Shortcut/MixedColumn.php index e3b9de7b..9d253b9a 100644 --- a/src/Database/Migration/Shortcut/MixedColumn.php +++ b/src/Database/Migration/Shortcut/MixedColumn.php @@ -15,6 +15,7 @@ trait MixedColumn * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addBoolean(string $column, array $attribute = []): SQLGenerator { @@ -27,6 +28,7 @@ public function addBoolean(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addUuid(string $column, array $attribute = []): SQLGenerator { @@ -58,6 +60,7 @@ public function addUuid(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addUuidPrimary(string $column, array $attribute = []): SQLGenerator { @@ -80,6 +83,7 @@ public function addUuidPrimary(string $column, array $attribute = []): SQLGenera * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addBinary(string $column, array $attribute = []): SQLGenerator { @@ -92,6 +96,7 @@ public function addBinary(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addTinyBlob(string $column, array $attribute = []): SQLGenerator { @@ -104,6 +109,7 @@ public function addTinyBlob(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addLongBlob(string $column, array $attribute = []): SQLGenerator { @@ -116,6 +122,7 @@ public function addLongBlob(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addMediumBlob(string $column, array $attribute = []): SQLGenerator { @@ -128,6 +135,7 @@ public function addMediumBlob(string $column, array $attribute = []): SQLGenerat * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addIpAddress(string $column, array $attribute = []): SQLGenerator { @@ -140,6 +148,7 @@ public function addIpAddress(string $column, array $attribute = []): SQLGenerato * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addMacAddress(string $column, array $attribute = []): SQLGenerator { @@ -152,6 +161,7 @@ public function addMacAddress(string $column, array $attribute = []): SQLGenerat * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addEnum(string $column, array $attribute = []): SQLGenerator { @@ -176,24 +186,11 @@ public function addEnum(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addCheck(string $column, array $attribute = []): SQLGenerator { - if (!isset($attribute['check'])) { - throw new SQLGeneratorException("The check values should be define."); - } - - if (!is_array($attribute['check'])) { - throw new SQLGeneratorException("The check values should be array."); - } - - if (count($attribute['check']) === 0) { - throw new SQLGeneratorException("The check values cannot be empty."); - } - - if (count($attribute['check']) === 0) { - throw new SQLGeneratorException("The check values cannot be empty."); - } + $this->verifyCheckAttribute($attribute); return $this->addColumn($column, 'check', $attribute); } @@ -204,6 +201,7 @@ public function addCheck(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeBoolean(string $column, array $attribute = []): SQLGenerator { @@ -216,6 +214,7 @@ public function changeBoolean(string $column, array $attribute = []): SQLGenerat * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeUuid(string $column, array $attribute = []): SQLGenerator { @@ -241,6 +240,7 @@ public function changeUuid(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeBinary(string $column, array $attribute = []): SQLGenerator { @@ -253,6 +253,7 @@ public function changeBinary(string $column, array $attribute = []): SQLGenerato * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeLongBlob(string $column, array $attribute = []): SQLGenerator { @@ -265,6 +266,7 @@ public function changeLongBlob(string $column, array $attribute = []): SQLGenera * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeMediumBlob(string $column, array $attribute = []): SQLGenerator { @@ -277,6 +279,7 @@ public function changeMediumBlob(string $column, array $attribute = []): SQLGene * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeTinyBlob(string $column, array $attribute = []): SQLGenerator { @@ -289,6 +292,7 @@ public function changeTinyBlob(string $column, array $attribute = []): SQLGenera * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeIpAddress(string $column, array $attribute = []): SQLGenerator { @@ -301,6 +305,7 @@ public function changeIpAddress(string $column, array $attribute = []): SQLGener * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeMacAddress(string $column, array $attribute = []): SQLGenerator { @@ -313,6 +318,7 @@ public function changeMacAddress(string $column, array $attribute = []): SQLGene * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeEnum(string $column, array $attribute = []): SQLGenerator { @@ -337,8 +343,19 @@ public function changeEnum(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeCheck(string $column, array $attribute = []): SQLGenerator + { + $this->verifyCheckAttribute($attribute); + + return $this->changeColumn($column, 'check', $attribute); + } + + /** + * @throws SQLGeneratorException + */ + private function verifyCheckAttribute($attribute): void { if (!isset($attribute['check'])) { throw new SQLGeneratorException("The check values should be define."); @@ -355,7 +372,5 @@ public function changeCheck(string $column, array $attribute = []): SQLGenerator if (count($attribute['check']) === 0) { throw new SQLGeneratorException("The check values cannot be empty."); } - - return $this->changeColumn($column, 'check', $attribute); } } diff --git a/src/Database/Migration/Shortcut/NumberColumn.php b/src/Database/Migration/Shortcut/NumberColumn.php index bea6cfba..c032f634 100644 --- a/src/Database/Migration/Shortcut/NumberColumn.php +++ b/src/Database/Migration/Shortcut/NumberColumn.php @@ -4,6 +4,7 @@ namespace Bow\Database\Migration\Shortcut; +use Bow\Database\Exception\SQLGeneratorException; use Bow\Database\Migration\SQLGenerator; trait NumberColumn @@ -14,6 +15,7 @@ trait NumberColumn * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addFloat(string $column, array $attribute = []): SQLGenerator { @@ -26,6 +28,7 @@ public function addFloat(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addDouble(string $column, array $attribute = []): SQLGenerator { @@ -37,6 +40,7 @@ public function addDouble(string $column, array $attribute = []): SQLGenerator * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ public function addDoublePrimary(string $column): SQLGenerator { @@ -48,6 +52,7 @@ public function addDoublePrimary(string $column): SQLGenerator * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ public function addFloatPrimary(string $column): SQLGenerator { @@ -59,6 +64,7 @@ public function addFloatPrimary(string $column): SQLGenerator * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ public function addIncrement(string $column): SQLGenerator { @@ -71,6 +77,7 @@ public function addIncrement(string $column): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addInteger(string $column, array $attribute = []): SQLGenerator { @@ -82,6 +89,7 @@ public function addInteger(string $column, array $attribute = []): SQLGenerator * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ public function addIntegerPrimary(string $column): SQLGenerator { @@ -93,6 +101,7 @@ public function addIntegerPrimary(string $column): SQLGenerator * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ public function addBigIncrement(string $column): SQLGenerator { @@ -105,6 +114,7 @@ public function addBigIncrement(string $column): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addTinyInteger(string $column, array $attribute = []): SQLGenerator { @@ -117,6 +127,7 @@ public function addTinyInteger(string $column, array $attribute = []): SQLGenera * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addBigInteger(string $column, array $attribute = []): SQLGenerator { @@ -129,6 +140,7 @@ public function addBigInteger(string $column, array $attribute = []): SQLGenerat * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addMediumInteger(string $column, array $attribute = []): SQLGenerator { @@ -140,6 +152,7 @@ public function addMediumInteger(string $column, array $attribute = []): SQLGene * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ public function addMediumIncrement(string $column): SQLGenerator { @@ -152,6 +165,7 @@ public function addMediumIncrement(string $column): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addSmallInteger(string $column, array $attribute = []): SQLGenerator { @@ -163,6 +177,7 @@ public function addSmallInteger(string $column, array $attribute = []): SQLGener * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ public function addSmallIntegerIncrement(string $column): SQLGenerator { @@ -175,6 +190,7 @@ public function addSmallIntegerIncrement(string $column): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeFloat(string $column, array $attribute = []): SQLGenerator { @@ -187,6 +203,7 @@ public function changeFloat(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeDouble(string $column, array $attribute = []): SQLGenerator { @@ -198,8 +215,9 @@ public function changeDouble(string $column, array $attribute = []): SQLGenerato * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeDoublePrimary($column) + public function changeDoublePrimary(string $column): SQLGenerator { return $this->changeColumn($column, 'double', ['primary' => true]); } @@ -209,8 +227,9 @@ public function changeDoublePrimary($column) * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeFloatPrimary($column) + public function changeFloatPrimary(string $column): SQLGenerator { return $this->changeColumn($column, 'float', ['primary' => true]); } @@ -220,8 +239,9 @@ public function changeFloatPrimary($column) * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeIncrement(string $column) + public function changeIncrement(string $column): SQLGenerator { return $this->changeColumn($column, 'int', ['primary' => true, 'increment' => true]); } @@ -232,6 +252,7 @@ public function changeIncrement(string $column) * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeInteger(string $column, array $attribute = []): SQLGenerator { @@ -243,8 +264,9 @@ public function changeInteger(string $column, array $attribute = []): SQLGenerat * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeIntegerPrimary(string $column) + public function changeIntegerPrimary(string $column): SQLGenerator { return $this->changeColumn($column, 'int', ['primary' => true]); } @@ -254,8 +276,9 @@ public function changeIntegerPrimary(string $column) * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeBigIncrement(string $column) + public function changeBigIncrement(string $column): SQLGenerator { return $this->changeColumn($column, 'bigint', ['primary' => true, 'increment' => true]); } @@ -266,6 +289,7 @@ public function changeBigIncrement(string $column) * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeTinyInteger(string $column, array $attribute = []): SQLGenerator { @@ -278,6 +302,7 @@ public function changeTinyInteger(string $column, array $attribute = []): SQLGen * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeBigInteger(string $column, array $attribute = []): SQLGenerator { @@ -290,6 +315,7 @@ public function changeBigInteger(string $column, array $attribute = []): SQLGene * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeMediumInteger(string $column, array $attribute = []): SQLGenerator { @@ -301,8 +327,9 @@ public function changeMediumInteger(string $column, array $attribute = []): SQLG * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeMediumIncrement(string $column) + public function changeMediumIncrement(string $column): SQLGenerator { return $this->changeColumn($column, 'mediumint', ['primary' => true, 'increment' => true]); } @@ -313,8 +340,9 @@ public function changeMediumIncrement(string $column) * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeSmallInteger(string $column, array $attribute = []) + public function changeSmallInteger(string $column, array $attribute = []): SQLGenerator { return $this->changeColumn($column, 'smallint', $attribute); } @@ -324,8 +352,9 @@ public function changeSmallInteger(string $column, array $attribute = []) * * @param string $column * @return SQLGenerator + * @throws SQLGeneratorException */ - public function changeSmallIntegerPrimary(string $column) + public function changeSmallIntegerPrimary(string $column): SQLGenerator { return $this->changeColumn($column, 'smallint', ['primary' => true, 'increment' => true]); } diff --git a/src/Database/Migration/Shortcut/TextColumn.php b/src/Database/Migration/Shortcut/TextColumn.php index 27667b3c..4eeeecae 100644 --- a/src/Database/Migration/Shortcut/TextColumn.php +++ b/src/Database/Migration/Shortcut/TextColumn.php @@ -15,6 +15,7 @@ trait TextColumn * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addString(string $column, array $attribute = []): SQLGenerator { @@ -27,6 +28,7 @@ public function addString(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addJson(string $column, array $attribute = []): SQLGenerator { @@ -39,6 +41,7 @@ public function addJson(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addChar(string $column, array $attribute = []): SQLGenerator { @@ -51,6 +54,7 @@ public function addChar(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addLongtext(string $column, array $attribute = []): SQLGenerator { @@ -63,6 +67,7 @@ public function addLongtext(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addText(string $column, array $attribute = []): SQLGenerator { @@ -75,6 +80,7 @@ public function addText(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function addBlob(string $column, array $attribute = []): SQLGenerator { @@ -87,6 +93,7 @@ public function addBlob(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeString(string $column, array $attribute = []): SQLGenerator { @@ -99,6 +106,7 @@ public function changeString(string $column, array $attribute = []): SQLGenerato * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeJson(string $column, array $attribute = []): SQLGenerator { @@ -111,6 +119,7 @@ public function changeJson(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeChar(string $column, array $attribute = []): SQLGenerator { @@ -123,6 +132,7 @@ public function changeChar(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeLongtext(string $column, array $attribute = []): SQLGenerator { @@ -135,6 +145,7 @@ public function changeLongtext(string $column, array $attribute = []): SQLGenera * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeText(string $column, array $attribute = []): SQLGenerator { @@ -147,6 +158,7 @@ public function changeText(string $column, array $attribute = []): SQLGenerator * @param string $column * @param array $attribute * @return SQLGenerator + * @throws SQLGeneratorException */ public function changeBlob(string $column, array $attribute = []): SQLGenerator { diff --git a/src/Database/Pagination.php b/src/Database/Pagination.php index 2f271e43..6041935d 100644 --- a/src/Database/Pagination.php +++ b/src/Database/Pagination.php @@ -8,12 +8,12 @@ class Pagination { public function __construct( - private int $next, - private int $previous, - private int $total, - private int $perPage, - private int $current, - private SupportCollection|DatabaseCollection $data + private readonly int $next, + private readonly int $previous, + private readonly int $total, + private readonly int $perPage, + private readonly int $current, + private readonly SupportCollection|DatabaseCollection $data ) { } diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index 7d16ee86..14d98f55 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -1379,6 +1379,7 @@ public function getPrefix(): string * Modify the prefix * * @param string $prefix + * @return QueryBuilder */ public function setPrefix(string $prefix): QueryBuilder { @@ -1427,9 +1428,9 @@ public function __toString(): string * @param PDOStatement $pdo_statement * @param array $bindings * - * @return PDOStatement + * @return void */ - private function bind(PDOStatement $pdo_statement, array $bindings = []): PDOStatement + private function bind(PDOStatement $pdo_statement, array $bindings = []): void { foreach ($bindings as $key => $value) { if (is_null($value) || strtolower((string) $value) === 'null') { @@ -1471,14 +1472,12 @@ private function bind(PDOStatement $pdo_statement, array $bindings = []): PDOSta $param ); } - - return $pdo_statement; } /** * Utility, allows to validate an operator * - * comparatoram string $comp + * @param mixed $comparator * @return bool */ private static function isComparisonOperator(mixed $comparator): bool diff --git a/src/Database/Redis.php b/src/Database/Redis.php index 3ce09a54..492d856f 100644 --- a/src/Database/Redis.php +++ b/src/Database/Redis.php @@ -14,7 +14,7 @@ class Redis /** * Define the php-redis instance * - * @var Redis + * @var RedisClient */ private static RedisClient $redis; @@ -54,7 +54,7 @@ public function __construct(array $config) $auth[] = $config["password"]; } - if (isset($config["username"]) && !is_null($config["username"])) { + if (isset($config["username"])) { array_unshift($auth, $config["username"]); } @@ -69,6 +69,7 @@ public function __construct(array $config) ]; static::$redis = new RedisClient(); + static::$redis->connect( $config["host"], $config["port"] ?? 6379, @@ -93,7 +94,7 @@ public function __construct(array $config) * * @param ?string $message */ - public static function ping(?string $message = null) + public static function ping(?string $message = null): void { static::$redis->ping($message); } diff --git a/src/Event/Dispatchable.php b/src/Event/Dispatchable.php index 7c18e744..29b18a1b 100644 --- a/src/Event/Dispatchable.php +++ b/src/Event/Dispatchable.php @@ -7,9 +7,9 @@ trait Dispatchable /** * Dispatch the event with the given arguments. * - * @return void + * @return mixed */ - public static function dispatch() + public static function dispatch(): mixed { return event(new static(...func_get_args())); } @@ -17,28 +17,28 @@ public static function dispatch() /** * Dispatch the event with the given arguments if the given truth test passes. * - * @param bool $boolean + * @param bool $boolean * @param mixed ...$arguments * @return void */ - public static function dispatchIf($boolean, ...$arguments) + public static function dispatchIf(bool $boolean, ...$arguments): void { if ($boolean) { - return event(new static(...$arguments)); + event(new static(...$arguments)); } } /** * Dispatch the event with the given arguments unless the given truth test passes. * - * @param bool $boolean + * @param bool $boolean * @param mixed ...$arguments * @return void */ - public static function dispatchUnless($boolean, ...$arguments) + public static function dispatchUnless(bool $boolean, ...$arguments): void { if (! $boolean) { - return event(new static(...$arguments)); + event(new static(...$arguments)); } } } diff --git a/src/Event/Event.php b/src/Event/Event.php index 32430cf5..c352a19f 100644 --- a/src/Event/Event.php +++ b/src/Event/Event.php @@ -14,21 +14,21 @@ class Event * * @var array */ - private static $events = []; + private static array $events = []; /** * The Event instance * - * @var Event + * @var ?Event */ - private static $instance; + private static ?Event $instance = null; /** * Event constructor. * * @return Event */ - public static function getInstance() + public static function getInstance(): Event { if (static::$instance == null) { static::$instance = new Event(); @@ -41,10 +41,10 @@ public static function getInstance() * addEventListener * * @param string $event - * @param callable|array|string $fn + * @param callable|string $fn * @param int $priority */ - public static function on(string $event, callable|string $fn, int $priority = 0) + public static function on(string $event, callable|string $fn, int $priority = 0): void { if (!static::bound($event)) { static::$events[$event] = []; @@ -72,8 +72,9 @@ public static function once(string $event, callable|array|string $fn, int $prior /** * Dispatch event * - * @param string|AppEvent $event - * @return bool + * @param string|AppEvent $event + * @return bool|null + * @throws EventException */ public static function emit(string|AppEvent $event): ?bool { @@ -127,17 +128,18 @@ public static function off(string $event): void */ public static function bound(string $event): bool { - $onces = static::$events['__bow.once.event'] ?? []; + $once = static::$events['__bow.once.event'] ?? []; - return array_key_exists($event, $onces) || array_key_exists($event, static::$events); + return array_key_exists($event, $once) || array_key_exists($event, static::$events); } /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed + * @throws ErrorException */ public function __call(string $name, array $arguments) { diff --git a/src/Event/EventProducer.php b/src/Event/EventProducer.php index 484f3f92..c9830f8a 100644 --- a/src/Event/EventProducer.php +++ b/src/Event/EventProducer.php @@ -14,8 +14,8 @@ class EventProducer extends ProducerService * @param EventListener|EventShouldQueue $event */ public function __construct( - private mixed $event, - private mixed $payload = null, + private readonly mixed $event, + private readonly mixed $payload = null, ) { } diff --git a/src/Http/Client/HttpClient.php b/src/Http/Client/HttpClient.php index 3c65e117..3a9a5cac 100644 --- a/src/Http/Client/HttpClient.php +++ b/src/Http/Client/HttpClient.php @@ -9,7 +9,7 @@ class HttpClient { /** - * The attach file collection + * The attached file collection * * @var array */ @@ -27,12 +27,12 @@ class HttpClient * * @var array */ - private $headers = []; + private array $headers = []; /** * The curl instance * - * @var CurlHandle + * @var ?CurlHandle */ private ?CurlHandle $ch = null; @@ -46,8 +46,7 @@ class HttpClient /** * HttpClient Constructor. * - * @param string $base_url - * @return void + * @param string|null $base_url */ public function __construct(?string $base_url = null) { @@ -72,11 +71,12 @@ public function setBaseUrl(string $url): void } /** - * Make get requete + * Make get requester * * @param string $url * @param array $data * @return Response + * @throws \Exception */ public function get(string $url, array $data = []): Response { @@ -95,11 +95,12 @@ public function get(string $url, array $data = []): Response } /** - * make post requete + * Make post requester * * @param string $url * @param array $data * @return Response + * @throws \Exception */ public function post(string $url, array $data = []): Response { @@ -126,11 +127,12 @@ public function post(string $url, array $data = []): Response } /** - * Make put requete + * Make put requester * * @param string $url * @param array $data * @return Response + * @throws \Exception */ public function put(string $url, array $data = []): Response { @@ -146,11 +148,12 @@ public function put(string $url, array $data = []): Response } /** - * Make put requete + * Make put requester * * @param string $url * @param array $data * @return Response + * @throws \Exception */ public function delete(string $url, array $data = []): Response { @@ -168,7 +171,7 @@ public function delete(string $url, array $data = []): Response /** * Attach new file * - * @param string $attach + * @param string|array $attach * @return HttpClient */ public function addAttach(string|array $attach): HttpClient @@ -179,7 +182,7 @@ public function addAttach(string|array $attach): HttpClient } /** - * Add aditionnal header + * Add additional header * * @param array $headers * @return HttpClient @@ -223,7 +226,7 @@ public function acceptJson(): HttpClient } /** - * Reset alway connection + * Reset always connection * * @param string $url * @return void @@ -300,7 +303,7 @@ private function execute(): string * * @return void */ - private function applyCommonOptions() + private function applyCommonOptions(): void { curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); diff --git a/src/Http/Client/Response.php b/src/Http/Client/Response.php index 2db90300..2b5c3a73 100644 --- a/src/Http/Client/Response.php +++ b/src/Http/Client/Response.php @@ -11,7 +11,7 @@ class Response /** * The error message * - * @var string + * @var ?string */ private ?string $error_message = null; @@ -63,6 +63,7 @@ public function getContent(): ?string /** * Get response content as json * + * @param bool|null $associative * @return object|array */ public function toJson(?bool $associative = null): object|array @@ -183,7 +184,7 @@ public function getDownloadSize(): ?float } /** - * Get the downlad speed + * Get the download speed * * @return ?float */ diff --git a/src/Http/HttpStatus.php b/src/Http/HttpStatus.php index eb58e6ef..02331afe 100644 --- a/src/Http/HttpStatus.php +++ b/src/Http/HttpStatus.php @@ -130,11 +130,11 @@ final class HttpStatus */ public static function getMessage(int $code): string { - if (!isset(static::STATUS[$code])) { + if (!isset(HttpStatus::STATUS[$code])) { throw new InvalidArgumentException("The code {$code} is not exists"); } - return static::STATUS[$code]; + return HttpStatus::STATUS[$code]; } /** @@ -144,6 +144,6 @@ public static function getMessage(int $code): string */ public static function getCodes(): array { - return array_keys(static::STATUS); + return array_keys(HttpStatus::STATUS); } } diff --git a/src/Http/Redirect.php b/src/Http/Redirect.php index 5a7d1d3a..ea9e5929 100644 --- a/src/Http/Redirect.php +++ b/src/Http/Redirect.php @@ -117,7 +117,7 @@ public function to(string $path, int $status = 302): Redirect * @param bool $absolute * @return Redirect */ - public function route(string $name, array $data = [], bool $absolute = false) + public function route(string $name, array $data = [], bool $absolute = false): Redirect { $this->to = route($name, $data, $absolute); @@ -130,7 +130,7 @@ public function route(string $name, array $data = [], bool $absolute = false) * @param int $status * @return Redirect */ - public function back(int $status = 302) + public function back(int $status = 302): Redirect { $this->to($this->request->referer(), $status); diff --git a/src/Http/Request.php b/src/Http/Request.php index 349d5fb6..24ce0b8d 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -54,6 +54,7 @@ class Request * Request constructor * * @return mixed + * @throws BadRequestException */ public function capture() { @@ -72,15 +73,15 @@ public function capture() "The request json payload is invalid: " . $e->getMessage(), ); } - $this->input = array_merge((array) $data, $_GET); } else { $data = $_POST ?? []; if ($this->isPut()) { parse_str(file_get_contents("php://input"), $data); } - $this->input = array_merge((array) $data, $_GET); } + $this->input = array_merge((array) $data, $_GET); + foreach ($this->input as $key => $value) { if (is_string($value) && strlen($value) == 0) { $value = null; @@ -138,7 +139,7 @@ public static function getInstance(): Request } /** - * Check if key is exists + * Check if key is existing * * @param string $key * @return bool @@ -229,7 +230,7 @@ public function time(): string /** * Returns the method of the request. * - * @return string + * @return string|null */ public function method(): ?string { @@ -326,7 +327,7 @@ public function file(string $key): UploadedFile|Collection|null * @param mixed $file * @return bool */ - public static function hasFile($file): bool + public static function hasFile(mixed $file): bool { return isset($_FILES[$file]); } @@ -374,10 +375,10 @@ public function isAjax(): bool /** * Check if a url matches with the pattern * - * @param string $match + * @param string $match * @return bool */ - public function is($match): bool + public function is(string $match): bool { return (bool) preg_match('@' . addcslashes($match, "/*{()}[]$^") . '@', $this->path()); } @@ -385,10 +386,10 @@ public function is($match): bool /** * Check if a url matches with the pattern * - * @param string $match + * @param string $match * @return bool */ - public function isReferer($match): bool + public function isReferer(string $match): bool { return (bool) preg_match('@' . addcslashes($match, "/*{()}[]$^") . '@', $this->referer()); } @@ -406,7 +407,7 @@ public function ip(): ?string /** * Get client port * - * @return string + * @return string|null */ public function port(): ?string { @@ -438,7 +439,7 @@ public function locale(): ?string $tmp = explode(';', $accept_language)[0]; - preg_match('/^([a-z]+(?:-|_)?[a-z]+)/i', $tmp, $match); + preg_match('^([a-z]+)[-_]?/i', $tmp, $match); return end($match); } @@ -446,7 +447,7 @@ public function locale(): ?string /** * Get request lang. * - * @return string + * @return string|null */ public function lang(): ?string { @@ -475,7 +476,7 @@ public function protocol(): string * @param string $protocol * @return mixed */ - public function isProtocol($protocol): bool + public function isProtocol(string $protocol): bool { return $this->scheme() == $protocol; } @@ -493,7 +494,6 @@ public function isSecure(): bool /** * Get Request header * - * @param string $key * @return array */ public function getHeaders(): array @@ -513,10 +513,10 @@ public function getHeaders(): array /** * Get Request header * - * @param string $key + * @param string $key * @return ?string */ - public function getHeader($key): ?string + public function getHeader(string $key): ?string { $key = str_replace('-', '_', strtoupper($key)); @@ -534,10 +534,10 @@ public function getHeader($key): ?string /** * Check if a header exists. * - * @param string $key + * @param string $key * @return bool */ - public function hasHeader($key): bool + public function hasHeader(string $key): bool { return isset($_SERVER[strtoupper($key)]); } @@ -576,10 +576,10 @@ public function user(?string $guard = null): ?Authentication /** * Get cookie * - * @param string $property - * @return mixed + * @param string|null $property + * @return string|array|object|null */ - public function cookie($property = null) + public function cookie(string $property = null): string|array|object|null { return cookie($property); } @@ -587,11 +587,11 @@ public function cookie($property = null) /** * Retrieve a value or a collection of values. * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed|null $default * @return mixed */ - public function get($key, $default = null) + public function get(string $key, mixed $default = null): mixed { $value = $this->input[$key] ?? $default; @@ -608,7 +608,7 @@ public function get($key, $default = null) * @param array $exceptions * @return array */ - public function only($exceptions) + public function only(array $exceptions = []): array { $data = []; @@ -626,9 +626,12 @@ public function only($exceptions) } /** - * @inheritdoc + * Retrieves the rest of values + * + * @param array $ignores + * @return array */ - public function ignore($ignores) + public function ignore(array $ignores = []): array { $data = $this->input; @@ -651,7 +654,7 @@ public function ignore($ignores) * @param array $rule * @return Validate */ - public function validate(array $rule) + public function validate(array $rule): Validate { return Validator::make($this->input, $rule); } @@ -661,9 +664,9 @@ public function validate(array $rule) * * @param string $name * @param mixed $value - * @return mixed + * @return void */ - public function setBag($name, $value) + public function setBag(string $name, mixed $value): void { $this->bags[$name] = $value; } @@ -671,9 +674,10 @@ public function setBag($name, $value) /** * Get the shared value in request bags * + * @param string $name * @return mixed */ - public function getBag(string $name) + public function getBag(string $name): mixed { return $this->bags[$name] ?? null; } @@ -682,9 +686,9 @@ public function getBag(string $name) * Set the shared value in request bags * * @param array $bags - * @return mixed + * @return void */ - public function setBags(array $bags) + public function setBags(array $bags): void { $this->bags = $bags; } @@ -694,7 +698,7 @@ public function setBags(array $bags) * * @return array */ - public function getBags() + public function getBags(): array { return $this->bags; } diff --git a/src/Http/Response.php b/src/Http/Response.php index 6cadc32e..58c22e58 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -10,9 +10,9 @@ class Response implements ResponseInterface { /** - * The Response instamce + * The Response instance * - * @var Response + * @var ?Response */ private static ?Response $instance = null; @@ -21,7 +21,7 @@ class Response implements ResponseInterface * * @var string */ - private ?string $content = ''; + private string $content = ''; /** * The Response code @@ -45,14 +45,14 @@ class Response implements ResponseInterface private bool $download = false; /** - * The downloadable filenme + * The downloadable filename * - * @var string + * @var ?string */ private ?string $download_filename = null; /** - * The override the respons + * The override the response * * @var bool */ @@ -123,7 +123,7 @@ public function getHeaders(): array * @param string $content * @return Response */ - public function setContent($content): Response + public function setContent(string $content): Response { $this->content = $content; @@ -233,7 +233,8 @@ public function status(int $code): Response */ private function buildHttpResponse(): string { - $status_text = static::$status_codes[$this->code] ?? 'Unkdown'; + $status_text = HttpStatus::getMessage($this->code) ?? 'Unknown'; + @header('HTTP/1.1 ' . $this->code . ' ' . $status_text, $this->override, $this->code); foreach ($this->getHeaders() as $key => $header) { @@ -252,11 +253,11 @@ private function buildHttpResponse(): string * JSON response * * @param mixed $data - * @param int $code + * @param int $code * @param array $headers * @return string */ - public function json($data, $code = 200, array $headers = []): string + public function json(mixed $data, int $code = 200, array $headers = []): string { $this->addHeader('Content-Type', 'application/json; charset=UTF-8'); diff --git a/src/Http/ServerAccessControl.php b/src/Http/ServerAccessControl.php index 8380488a..313c999d 100644 --- a/src/Http/ServerAccessControl.php +++ b/src/Http/ServerAccessControl.php @@ -29,10 +29,10 @@ public function __construct(Response $response) * The access control * * @param string $allow - * @param string $excepted + * @param string|null $excepted * @return $this */ - private function push(string $allow, string $excepted): ServerAccessControl + private function push(string $allow, ?string $excepted = null): ServerAccessControl { if ($excepted === null) { $excepted = '*'; diff --git a/src/Mail/Driver/NativeDriver.php b/src/Mail/Driver/NativeDriver.php index db1a2d92..12357fd3 100644 --- a/src/Mail/Driver/NativeDriver.php +++ b/src/Mail/Driver/NativeDriver.php @@ -29,7 +29,6 @@ class NativeDriver implements MailDriverInterface * SimpleMail Constructor * * @param array $config - * @return mixed */ public function __construct(array $config = []) { @@ -45,6 +44,7 @@ public function __construct(array $config = []) * * @param string $from * @return NativeDriver + * @throws MailException */ public function on(string $from): NativeDriver { diff --git a/src/Mail/Driver/SmtpDriver.php b/src/Mail/Driver/SmtpDriver.php index 01a90a76..96336a33 100644 --- a/src/Mail/Driver/SmtpDriver.php +++ b/src/Mail/Driver/SmtpDriver.php @@ -23,21 +23,21 @@ class SmtpDriver implements MailDriverInterface /** * The username * - * @var string + * @var ?string */ private ?string $username; /** * The password * - * @var string + * @var ?string */ private ?string $password; /** * The SMTP server * - * @var string + * @var ?string */ private ?string $url; @@ -159,7 +159,7 @@ public function send(Message $message): bool * @throws ErrorException * @throws SocketException | SmtpException */ - private function connection() + private function connection(): void { $url = $this->url; @@ -217,10 +217,10 @@ private function connection() /** * Disconnection * - * @return mixed + * @return int|string|null * @throws ErrorException */ - private function disconnect() + private function disconnect(): int|string|null { $r = $this->write('QUIT'); @@ -261,11 +261,10 @@ private function read(): int * @param string $command * @param ?int $code * @param ?string $message - * * @throws SmtpException - * @return string|int|null + * @return int|null */ - private function write(string $command, ?int $code = null, ?string $message = null) + private function write(string $command, ?int $code = null, ?string $message = null): ?int { if ($message == null) { $message = $command; @@ -278,7 +277,7 @@ private function write(string $command, ?int $code = null, ?string $message = nu $response = null; if ($code === null) { - return $response; + return null; } $response = $this->read(); diff --git a/src/Mail/Mail.php b/src/Mail/Mail.php index 187bf579..3a6dc7fe 100644 --- a/src/Mail/Mail.php +++ b/src/Mail/Mail.php @@ -32,7 +32,7 @@ class Mail /** * The mail driver instance * - * @var MailDriverInterface + * @var ?MailDriverInterface */ private static ?MailDriverInterface $instance = null; @@ -120,9 +120,14 @@ public static function getInstance(): MailDriverInterface } /** - * @inheritdoc + * The method thad send the configured mail + * + * @param string $view + * @param callable|array $data + * @param callable|null $cb + * @return bool */ - public static function send(string $view, callable|array $data, ?callable $cb = null) + public static function send(string $view, callable|array $data, ?callable $cb = null): bool { if (is_null($cb)) { $cb = $data; @@ -148,7 +153,7 @@ public static function send(string $view, callable|array $data, ?callable $cb = * @param array $headers * @return mixed */ - public static function raw(string|array $to, string $subject, string $data, array $headers = []) + public static function raw(string|array $to, string $subject, string $data, array $headers = []): mixed { $to = (array) $to; @@ -191,7 +196,7 @@ public static function queue(string $template, array $data, callable $cb) * @param callable $cb * @return void */ - public static function queueOn(string $queue, string $template, array $data, callable $cb) + public static function queueOn(string $queue, string $template, array $data, callable $cb): void { $message = new Message(); @@ -213,7 +218,7 @@ public static function queueOn(string $queue, string $template, array $data, cal * @param callable $cb * @return void */ - public static function later(int $delay, string $template, array $data, callable $cb) + public static function later(int $delay, string $template, array $data, callable $cb): void { $message = new Message(); @@ -236,7 +241,7 @@ public static function later(int $delay, string $template, array $data, callable * @param callable $cb * @return void */ - public static function laterOn(int $delay, string $queue, string $template, array $data, callable $cb) + public static function laterOn(int $delay, string $queue, string $template, array $data, callable $cb): void { $message = new Message(); @@ -279,12 +284,12 @@ public static function setDriver(string $driver): MailDriverInterface /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed * @throws \ErrorException */ - public function __call($name, $arguments) + public function __call(string $name, array $arguments = []) { if (method_exists(static::class, $name)) { return call_user_func_array([static::class, $name], $arguments); diff --git a/src/Mail/MailQueueProducer.php b/src/Mail/MailQueueProducer.php index f4ad6af3..85d15088 100644 --- a/src/Mail/MailQueueProducer.php +++ b/src/Mail/MailQueueProducer.php @@ -29,6 +29,8 @@ public function __construct( array $data, Message $message ) { + parent::__construct(); + $this->bags = [ "view" => $view, "data" => $data, @@ -58,7 +60,7 @@ public function process(): void * @param Throwable $e * @return void */ - public function onException(Throwable $e) + public function onException(Throwable $e): void { $this->deleteJob(); } diff --git a/src/Mail/Message.php b/src/Mail/Message.php index 6e067c46..c5e617a8 100644 --- a/src/Mail/Message.php +++ b/src/Mail/Message.php @@ -33,7 +33,7 @@ class Message /** * Define the recipient * - * @var string + * @var ?string */ private ?string $subject = null; @@ -61,7 +61,7 @@ class Message /** * Define the boundary between the contents. * - * @var string + * @var ?string */ private ?string $boundary; @@ -91,7 +91,7 @@ class Message * * @param bool $boundary */ - public function __construct($boundary = true) + public function __construct(bool $boundary = true) { $this->setDefaultHeader(); @@ -122,7 +122,7 @@ public function setDefaultHeader(): void * @param string $key * @param string $value */ - public function addHeader($key, $value): void + public function addHeader(string $key, string $value): void { $this->headers[] = "$key: $value"; } @@ -296,7 +296,7 @@ private function type(string $message, string $type): Message * Adds blind carbon copy * * @param string $mail - * @param ?string $name [optional] + * @param ?string $name * * @return Message */ @@ -313,7 +313,7 @@ public function addBcc(string $mail, ?string $name = null): Message * Add carbon copy * * @param string $mail - * @param ?string $name [optional] + * @param ?string $name * * @return Message */ @@ -331,10 +331,9 @@ public function addCc(string $mail, ?string $name = null): Message * * @param string $mail * @param ?string $name - * * @return Message */ - public function addReplyTo(string $mail, ?string $name = null) + public function addReplyTo(string $mail, ?string $name = null): Message { $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; @@ -390,7 +389,7 @@ public function addPriority(int $priority): Message * @param string $message * @param string $type */ - public function setMessage(string $message, string $type = 'text/html') + public function setMessage(string $message, string $type = 'text/html'): void { $this->type = $type; @@ -402,7 +401,7 @@ public function setMessage(string $message, string $type = 'text/html') * @param string $message * @param string $type */ - public function message(string $message, string $type = 'text/html') + public function message(string $message, string $type = 'text/html'): void { $this->setMessage($message, $type); } @@ -474,7 +473,7 @@ public function getCharset(): ?string */ public function getType(): ?string { - return is_null($this->type) ? 'text/html' : $this->type; + return $this->type ?? 'text/html'; } /** diff --git a/src/Notification/Channel/DatabaseChannel.php b/src/Notification/Channel/DatabaseChannel.php index dff95042..8174ef2e 100644 --- a/src/Notification/Channel/DatabaseChannel.php +++ b/src/Notification/Channel/DatabaseChannel.php @@ -14,6 +14,5 @@ class DatabaseChannel implements ChannelInterface */ public function send(mixed $message) { - } } diff --git a/src/Queue/Adapters/BeanstalkdAdapter.php b/src/Queue/Adapters/BeanstalkdAdapter.php index d11748ae..d2d22a97 100644 --- a/src/Queue/Adapters/BeanstalkdAdapter.php +++ b/src/Queue/Adapters/BeanstalkdAdapter.php @@ -7,8 +7,7 @@ use RuntimeException; use Pheanstalk\Pheanstalk; use Bow\Queue\ProducerService; -use Bow\Queue\Adapters\QueueAdapter; -use Pheanstalk\Contract\PheanstalkInterface; +use Pheanstalk\Contract\PheanstalkPublisherInterface; class BeanstalkdAdapter extends QueueAdapter { @@ -22,23 +21,23 @@ class BeanstalkdAdapter extends QueueAdapter /** * Configure Beanstalkd driver * - * @param array $queue + * @param array $config * @return mixed */ - public function configure(array $queue): BeanstalkdAdapter + public function configure(array $config): BeanstalkdAdapter { if (!class_exists(Pheanstalk::class)) { throw new RuntimeException("Please install the pda/pheanstalk package"); } $this->pheanstalk = Pheanstalk::create( - $queue["hostname"], - $queue["port"], - $queue["timeout"] + $config["hostname"], + $config["port"], + $config["timeout"] ? new \Pheanstalk\Values\Timeout($config["timeout"]) : null, ); - if (isset($queue["queue"])) { - $this->setQueue($queue["queue"]); + if (isset($config["queue"])) { + $this->setQueue($config["queue"]); } return $this; @@ -52,9 +51,9 @@ public function configure(array $queue): BeanstalkdAdapter */ public function size(?string $queue = null): int { - $queue = $this->getQueue($queue); + $queue = new \Pheanstalk\Values\TubeName($this->getQueue($queue)); - return (int) $this->pheanstalk->statsTube($queue)->current_jobs_ready; + return (int) $this->pheanstalk->statsTube($queue)->currentJobsReady; } /** @@ -62,6 +61,7 @@ public function size(?string $queue = null): int * * @param ProducerService $producer * @return void + * @throws \ErrorException */ public function push(ProducerService $producer): void { @@ -73,13 +73,14 @@ public function push(ProducerService $producer): void } $this->pheanstalk - ->useTube($producer->getQueue()) - ->put( - $this->serializeProducer($producer), - $this->getPriority($producer->getPriority()), - $producer->getDelay(), - $producer->getRetry() - ); + ->useTube(new \Pheanstalk\Values\TubeName($producer->getQueue())); + + $this->pheanstalk->put( + $this->serializeProducer($producer), + $this->getPriority($producer->getPriority()), + $producer->getDelay(), + $producer->getRetry() + ); } /** @@ -87,12 +88,13 @@ public function push(ProducerService $producer): void * * @param string|null $queue * @return mixed + * @throws \ErrorException */ public function run(string $queue = null): void { // we want jobs from define queue only. $queue = $this->getQueue($queue); - $this->pheanstalk->watch($queue); + $this->pheanstalk->watch(new \Pheanstalk\Values\TubeName($queue)); // This hangs until a Job is produced. $job = $this->pheanstalk->reserve(); @@ -123,10 +125,10 @@ public function run(string $queue = null): void } // Execute the onException method for notify the producer - // and let developper to decide if the job should be delete + // and let developer decide if the job should be deleted $producer->onException($e); - // Check if the job should be delete + // Check if the job should be deleted if ($producer->jobShouldBeDelete()) { $this->pheanstalk->delete($job); } else { @@ -139,7 +141,9 @@ public function run(string $queue = null): void /** * Flush the queue * + * @param string|null $queue * @return void + * @throws \ErrorException */ public function flush(?string $queue = null): void { @@ -166,15 +170,11 @@ public function flush(?string $queue = null): void */ public function getPriority(int $priority): int { - switch ($priority) { - case $priority > 2: - return 4294967295; - case 1: - return PheanstalkInterface::DEFAULT_PRIORITY; - case 0: - return 0; - default: - return PheanstalkInterface::DEFAULT_PRIORITY; - } + return match ($priority) { + $priority > 2 => 4294967295, + 1 => PheanstalkPublisherInterface::DEFAULT_PRIORITY, + 0 => 0, + default => PheanstalkPublisherInterface::DEFAULT_PRIORITY, + }; } } diff --git a/src/Queue/Adapters/DatabaseAdapter.php b/src/Queue/Adapters/DatabaseAdapter.php index ddd9c27d..a4073d71 100644 --- a/src/Queue/Adapters/DatabaseAdapter.php +++ b/src/Queue/Adapters/DatabaseAdapter.php @@ -18,12 +18,12 @@ class DatabaseAdapter extends QueueAdapter /** * Configure Beanstalkd driver * - * @param array $queue + * @param array $config * @return mixed */ - public function configure(array $queue): DatabaseAdapter + public function configure(array $config): DatabaseAdapter { - $this->table = Database::table($queue["table"] ?? "queue_jobs"); + $this->table = Database::table($config["table"] ?? "queue_jobs"); return $this; } @@ -55,7 +55,7 @@ public function push(ProducerService $producer): void "payload" => base64_encode($this->serializeProducer($producer)), "attempts" => $this->tries, "status" => "waiting", - "avalaibled_at" => date("Y-m-d H:i:s", time() + $producer->getDelay()), + "available_at" => date("Y-m-d H:i:s", time() + $producer->getDelay()), "reserved_at" => null, "created_at" => date("Y-m-d H:i:s"), ]); @@ -84,7 +84,7 @@ public function run(string $queue = null): void foreach ($queues as $job) { try { $producer = $this->unserializeProducer(base64_decode($job->payload)); - if (strtotime($job->avalaibled_at) >= time()) { + if (strtotime($job->available_at) >= time()) { if (!is_null($job->reserved_at) && strtotime($job->reserved_at) < time()) { continue; } @@ -123,7 +123,7 @@ public function run(string $queue = null): void $this->table->where("id", $job->id)->update([ "status" => "reserved", "attempts" => $job->attempts - 1, - "avalaibled_at" => date("Y-m-d H:i:s", time() + $producer->getDelay()), + "available_at" => date("Y-m-d H:i:s", time() + $producer->getDelay()), "reserved_at" => date("Y-m-d H:i:s", time() + $producer->getRetry()) ]); diff --git a/src/Session/Cookie.php b/src/Session/Cookie.php index ece2490c..3c100cb8 100644 --- a/src/Session/Cookie.php +++ b/src/Session/Cookie.php @@ -22,7 +22,7 @@ class Cookie * @param bool $strict * @return bool */ - public static function has($key, $strict = false) + public static function has(string $key, bool $strict = false): bool { $isset = isset($_COOKIE[$key]); @@ -31,7 +31,7 @@ public static function has($key, $strict = false) } if ($isset) { - $isset = $isset && !empty($_COOKIE[$key]); + $isset = !empty($_COOKIE[$key]); } return $isset; @@ -84,23 +84,22 @@ public static function all(): array /** * Add a value to the cookie table. * - * @param string|int $key + * @param int|string $key * @param mixed $data - * @param int $expirate - * + * @param int $expiration * @return bool */ public static function set( - $key, - $data, - $expirate = 3600, - ) { + int|string $key, + mixed $data, + int $expiration = 3600, + ): bool { $data = Crypto::encrypt(json_encode($data)); return setcookie( $key, $data, - time() + $expirate, + time() + $expiration, config('session.path'), config('session.domain'), config('session.secure'), @@ -112,14 +111,14 @@ public static function set( * Delete an entry in the table * * @param string $key - * @return mixed + * @return string|bool|null */ - public static function remove(string $key): mixed + public static function remove(string $key): string|bool|null { $old = null; if (!static::has($key)) { - return $old; + return null; } if (!static::$is_decrypt[$key]) { diff --git a/src/Session/Driver/ArrayDriver.php b/src/Session/Driver/ArrayDriver.php index d8d4b7ad..0ed4ed25 100644 --- a/src/Session/Driver/ArrayDriver.php +++ b/src/Session/Driver/ArrayDriver.php @@ -28,11 +28,13 @@ public function close(): bool /** * Destroy session information * - * @param string $session_id - * @return bool|void + * @param string $id + * @return bool */ - public function destroy(string $session_id): bool + public function destroy(string $id): bool { + unset($this->sessions[$id]); + return true; } @@ -44,9 +46,9 @@ public function destroy(string $session_id): bool */ public function gc(int $max_lifetime): int|false { - foreach ($this->sessions as $session_id => $content) { - if ($this->sessions[$session_id]['time'] <= $this->createTimestamp()) { - $this->destroy($session_id); + foreach ($this->sessions as $id => $content) { + if ($this->sessions[$id]['time'] <= $this->createTimestamp()) { + $this->destroy($id); } } @@ -56,11 +58,11 @@ public function gc(int $max_lifetime): int|false /** * When the session start * - * @param string $save_path - * @param string $session_id + * @param string $path + * @param string $name * @return bool */ - public function open(string $save_path, string $session_id): bool + public function open(string $path, string $name): bool { $this->sessions = []; @@ -70,30 +72,30 @@ public function open(string $save_path, string $session_id): bool /** * Read the session information * - * @param string $session_id + * @param string $id * @return string */ - public function read(string $session_id): string + public function read(string $id): string { - if (!isset($this->sessions[$session_id])) { + if (!isset($this->sessions[$id])) { return ''; } - return $this->sessions[$session_id]['data']; + return $this->sessions[$id]['data']; } /** * Write session information * - * @param string $session_id - * @param string $session_data + * @param string $id + * @param string $data * @return bool */ - public function write(string $session_id, string $session_data): bool + public function write(string $id, string $data): bool { - $this->sessions[$session_id] = [ + $this->sessions[$id] = [ 'time' => $this->createTimestamp(), - 'data' => $session_data + 'data' => $data ]; return true; diff --git a/src/Session/Driver/DatabaseDriver.php b/src/Session/Driver/DatabaseDriver.php index e032f51e..720b1d76 100644 --- a/src/Session/Driver/DatabaseDriver.php +++ b/src/Session/Driver/DatabaseDriver.php @@ -4,8 +4,9 @@ namespace Bow\Session\Driver; +use Bow\Database\Exception\QueryBuilderException; use Bow\Database\QueryBuilder; -use Bow\Database\Database as DB; +use Bow\Database\Database; class DatabaseDriver implements \SessionHandlerInterface { @@ -58,13 +59,14 @@ public function close(): bool /** * Destroy session information * - * @param string $session_id + * @param string $id * @return bool + * @throws QueryBuilderException */ - public function destroy(string $session_id): bool + public function destroy(string $id): bool { $this->sessions() - ->where('id', $session_id)->delete(); + ->where('id', $id)->delete(); return true; } @@ -74,6 +76,7 @@ public function destroy(string $session_id): bool * * @param int $max_lifetime * @return int|false + * @throws QueryBuilderException */ public function gc(int $max_lifetime): int|false { @@ -87,11 +90,11 @@ public function gc(int $max_lifetime): int|false /** * When the session start * - * @param string $save_path + * @param string $path * @param string $name * @return bool */ - public function open(string $save_path, string $name): bool + public function open(string $path, string $name): bool { return true; } @@ -101,11 +104,12 @@ public function open(string $save_path, string $name): bool * * @param string $session_id * @return string + * @throws QueryBuilderException */ - public function read(string $session_id): string + public function read(string $id): string { $session = $this->sessions() - ->where('id', $session_id)->first(); + ->where('id', $id)->first(); if (is_null($session)) { return ''; @@ -117,24 +121,25 @@ public function read(string $session_id): string /** * Write session information * - * @param string $session_id - * @param string $session_data + * @param string $id + * @param string $data * @return bool + * @throws QueryBuilderException */ - public function write(string $session_id, string $session_data): bool + public function write(string $id, string $data): bool { // When create the new session record - if (! $this->sessions()->where('id', $session_id)->exists()) { + if (! $this->sessions()->where('id', $id)->exists()) { $insert = $this->sessions() - ->insert($this->data($session_id, $session_data)); + ->insert($this->data($id, $data)); return (bool) $insert; } // Update the session information - $update = $this->sessions()->where('id', $session_id)->update([ - 'data' => $session_data, - 'id' => $session_id + $update = $this->sessions()->where('id', $id)->update([ + 'data' => $data, + 'id' => $id ]); return (bool) $update; @@ -164,6 +169,6 @@ private function data(string $session_id, string $session_data): array */ private function sessions(): QueryBuilder { - return DB::table($this->table); + return Database::table($this->table); } } diff --git a/src/Session/Driver/DurationTrait.php b/src/Session/Driver/DurationTrait.php index c68f07cc..cd56f772 100644 --- a/src/Session/Driver/DurationTrait.php +++ b/src/Session/Driver/DurationTrait.php @@ -9,7 +9,7 @@ trait DurationTrait /** * Create the timestamp * - * @param int max_lifetime + * @param int|null $max_lifetime * @return string */ private function createTimestamp(?int $max_lifetime = null): string diff --git a/src/Session/Driver/FilesystemDriver.php b/src/Session/Driver/FilesystemDriver.php index 4adc9403..d9af6ae7 100644 --- a/src/Session/Driver/FilesystemDriver.php +++ b/src/Session/Driver/FilesystemDriver.php @@ -38,12 +38,12 @@ public function close(): bool /** * Destroy session information * - * @param string $session_id + * @param string $id * @return bool */ - public function destroy(string $session_id): bool + public function destroy(string $id): bool { - $file = $this->sessionFile($session_id); + $file = $this->sessionFile($id); @unlink($file); @@ -70,11 +70,11 @@ public function gc(int $maxlifetime): int|false /** * When the session start * - * @param string $save_path + * @param string $path * @param string $name * @return bool */ - public function open(string $save_path, string $name): bool + public function open(string $path, string $name): bool { if (!is_dir($this->save_path)) { mkdir($this->save_path, 0777); diff --git a/src/Session/Session.php b/src/Session/Session.php index f4950062..2b2a6264 100644 --- a/src/Session/Session.php +++ b/src/Session/Session.php @@ -39,7 +39,7 @@ class Session implements CollectionInterface /** * The instance of Session * - * @var Session + * @var ?Session */ private static ?Session $instance = null; @@ -54,6 +54,7 @@ class Session implements CollectionInterface * Session constructor. * * @param array $config + * @throws SessionException */ private function __construct(array $config) { @@ -81,6 +82,7 @@ private function __construct(array $config) * * @param array $config * @return Session + * @throws SessionException */ public static function configure(array $config): Session { @@ -105,6 +107,7 @@ public static function getInstance(): ?Session * Session starter. * * @return bool + * @throws SessionException */ public function start(): bool { @@ -121,7 +124,7 @@ public function start(): bool // Boot session $started = $this->boot(); - // Init interne session manager + // Init internet session manager $this->initializeInternalSessionStorage(); return $started; @@ -131,6 +134,7 @@ public function start(): bool * Start session natively * * @return bool + * @throws SessionException */ private function boot(): bool { @@ -145,6 +149,7 @@ private function boot(): bool * Load session driver * * @return void + * @throws SessionException */ private function initializeDriver(): void { @@ -222,7 +227,7 @@ private function initializeInternalSessionStorage(): void * * @return void */ - private function setCookieParameters() + private function setCookieParameters(): void { session_set_cookie_params( $this->config["lifetime"], @@ -238,15 +243,17 @@ private function setCookieParameters() * * @return string */ - private function generateId() + private function generateId(): string { return Crypto::encrypt(uniqid(microtime(false))); } /** * Generate session + * + * @throws SessionException */ - public function regenerate() + public function regenerate(): void { $this->flush(); $this->start(); @@ -257,8 +264,9 @@ public function regenerate() * and those used by the framework. * * @return array + * @throws SessionException */ - private function filter() + private function filter(): array { $arr = []; @@ -279,6 +287,7 @@ private function filter() * @param string|int $key * @param bool $strict * @return bool + * @throws SessionException */ public function has(string|int $key, bool $strict = false): bool { @@ -311,7 +320,7 @@ public function has(string|int $key, bool $strict = false): bool return count((array) $value) > 0; } - if (isset($_SESSION[$key]) && !is_null($_SESSION[$key])) { + if (isset($_SESSION[$key])) { return count((array) $_SESSION[$key]) > 0; } @@ -323,6 +332,7 @@ public function has(string|int $key, bool $strict = false): bool * * @param string $key * @return bool + * @throws SessionException */ public function exists($key): bool { @@ -333,6 +343,7 @@ public function exists($key): bool * Check whether a collection is empty. * * @return bool + * @throws SessionException */ public function isEmpty(): bool { @@ -343,8 +354,9 @@ public function isEmpty(): bool * Retrieves a value or value collection. * * @param string $key - * @param mixed $default + * @param mixed $default * @return mixed + * @throws SessionException */ public function get(mixed $key, mixed $default = null): mixed { @@ -354,7 +366,7 @@ public function get(mixed $key, mixed $default = null): mixed return $content; } - if (is_null($content) && $this->has($key)) { + if ($this->has($key)) { return $_SESSION[$key] ?? null; } @@ -369,19 +381,19 @@ public function get(mixed $key, mixed $default = null): mixed * Add an entry to the collection * * @param string|int $key - * @param mixed $value + * @param mixed $data * @param boolean $next - * @throws InvalidArgumentException * @return mixed + * @throws InvalidArgumentException|SessionException */ - public function add(string|int $key, mixed $value, $next = false): mixed + public function add(string|int $key, mixed $data, bool $next = false): mixed { $this->start(); $_SESSION[static::CORE_SESSION_KEY['cache']][$key] = true; - if ($next == false) { - return $_SESSION[$key] = $value; + if ($next === false) { + return $_SESSION[$key] = $data; } if (! $this->has($key)) { @@ -392,14 +404,15 @@ public function add(string|int $key, mixed $value, $next = false): mixed $_SESSION[$key] = [$_SESSION[$key]]; } - $_SESSION[$key] = array_merge($_SESSION[$key], [$value]); + $_SESSION[$key] = array_merge($_SESSION[$key], [$data]); - return $value; + return $data; } /** * The add alias * + * @throws SessionException * @see \Bow\Session\Session::add */ public function put(string|int $key, mixed $value, $next = false): mixed @@ -411,6 +424,7 @@ public function put(string|int $key, mixed $value, $next = false): mixed * Returns the list of session variables * * @return array + * @throws SessionException */ public function all(): array { @@ -420,9 +434,10 @@ public function all(): array /** * Delete an entry in the collection * - * @param string $key + * @param string|int $key * * @return mixed + * @throws SessionException */ public function remove(string|int $key): mixed { @@ -444,10 +459,11 @@ public function remove(string|int $key): mixed /** * set * - * @param string $key - * @param mixed $value + * @param string|int $key + * @param mixed $value * * @return mixed + * @throws SessionException */ public function set(string|int $key, mixed $value): mixed { @@ -460,7 +476,7 @@ public function set(string|int $key, mixed $value): mixed if (!$this->has($key)) { $_SESSION[$key] = $value; - return $old; + return null; } $old = $_SESSION[$key]; @@ -474,9 +490,10 @@ public function set(string|int $key, mixed $value): mixed * Add flash data * After the data recovery is automatic deleted * - * @param string|int $key - * @param mixed $message + * @param string|int $key + * @param mixed $message * @return mixed + * @throws SessionException */ public function flash(string|int $key, ?string $message = null): mixed { @@ -490,14 +507,11 @@ public function flash(string|int $key, ?string $message = null): mixed $flash = $_SESSION[static::CORE_SESSION_KEY['flash']]; - $content = isset($flash[$key]) ? $flash[$key] : null; - $tmp = []; + $content = $flash[$key] ?? null; - foreach ($flash as $i => $value) { - if ($i != $key) { - $tmp[$i] = $value; - } - } + $tmp = array_filter($flash, function ($i) use ($key) { + return $i != $key; + }, ARRAY_FILTER_USE_KEY); $_SESSION[static::CORE_SESSION_KEY['flash']] = $tmp; @@ -508,6 +522,7 @@ public function flash(string|int $key, ?string $message = null): mixed * Returns the list of session data as a array. * * @return array + * @throws SessionException */ public function toArray(): array { @@ -516,8 +531,9 @@ public function toArray(): array /** * Empty the flash system. + * @throws SessionException */ - public function clearFash(): void + public function clearFlash(): void { $this->start(); @@ -526,6 +542,8 @@ public function clearFash(): void /** * Allows to clear the cache except csrf and __bow.flash + * + * @throws SessionException */ public function clear(): void { @@ -549,7 +567,7 @@ public function flush(): void /** * Returns the list of session data as a toObject. * - * @return array|void + * @return array */ public function toObject(): array { @@ -560,6 +578,7 @@ public function toObject(): array * __toString * * @return string + * @throws SessionException */ public function __toString(): string { diff --git a/src/Storage/Contracts/FilesystemInterface.php b/src/Storage/Contracts/FilesystemInterface.php index c891a67d..781f226a 100644 --- a/src/Storage/Contracts/FilesystemInterface.php +++ b/src/Storage/Contracts/FilesystemInterface.php @@ -12,9 +12,9 @@ interface FilesystemInterface /** * Store directly the upload file * - * @param UploadedFile $file - * @param string $location - * @param array $option + * @param UploadedFile $file + * @param string|null $location + * @param array $option * @return array|bool|string * @throws InvalidArgumentException */ @@ -37,7 +37,7 @@ public function append(string $file, string $content): bool; * @return bool * @throws */ - public function prepend(string $file, string $content); + public function prepend(string $file, string $content): bool; /** * Put other file content in given file @@ -46,7 +46,7 @@ public function prepend(string $file, string $content); * @param string $content * @return bool */ - public function put(string $file, string $content); + public function put(string $file, string $content): bool; /** * Delete file @@ -84,44 +84,44 @@ public function makeDirectory(string $dirname, int $mode = 0777): bool; /** * Get file content * - * @param string $filename + * @param string $file * @return ?string */ - public function get(string $filename): ?string; + public function get(string $file): ?string; /** * Copy the contents of a source file to a target file. * + * @param string $source * @param string $target - * @param string $source * @return bool */ - public function copy(string $target, string $source): bool; + public function copy(string $source, string $target): bool; /** - * Rénme or move a source file to a target file. + * Rename or move a source file to a target file. * - * @param string $target * @param string $source + * @param string $target * @return bool */ - public function move(string $target, string $source): bool; + public function move(string $source, string $target): bool; /** * Check the existence of a file * - * @param string $filename + * @param string $file * @return bool */ - public function exists(string $filename): bool; + public function exists(string $file): bool; /** * isFile alias of is_file. * - * @param string $filename + * @param string $file * @return bool */ - public function isFile(string $filename): bool; + public function isFile(string $file): bool; /** * isDirectory alias of is_dir. @@ -135,8 +135,8 @@ public function isDirectory(string $dirname): bool; * Resolves a path. * Give the absolute path of a path * - * @param string $filename + * @param string $file * @return string */ - public function path(string $filename): string; + public function path(string $file): string; } diff --git a/src/Storage/Service/DiskFilesystemService.php b/src/Storage/Service/DiskFilesystemService.php index 46f00782..cd43c934 100644 --- a/src/Storage/Service/DiskFilesystemService.php +++ b/src/Storage/Service/DiskFilesystemService.php @@ -51,12 +51,11 @@ public function getBaseDirectory(): string /** * Function to upload a file * - * @param UploadedFile $file - * @param string|array $location - * @param array $option + * @param UploadedFile $file + * @param string|array|null $location + * @param array $option * * @return array|bool|string - * @throws InvalidArgumentException */ public function store(UploadedFile $file, string|array $location = null, array $option = []): array|bool|string { @@ -185,9 +184,7 @@ public function files(string $dirname): array */ public function directories(string $dirname): array { - $directory_contents = glob($this->path($dirname) . "/*", GLOB_ONLYDIR); - - return $directory_contents; + return glob($this->path($dirname) . "/*", GLOB_ONLYDIR); } /** @@ -199,17 +196,14 @@ public function directories(string $dirname): array */ public function makeDirectory(string $dirname, int $mode = 0777): bool { - $result = @mkdir($dirname, $mode, true); - - return $result; + return @mkdir($dirname, $mode, true); } /** * Recover the contents of the file * - * @param string $filename - * - * @return int + * @param string $filename + * @return string|null */ public function get(string $filename): ?string { @@ -227,7 +221,6 @@ public function get(string $filename): ?string * * @param string $target * @param string $source - * * @return bool */ public function copy(string $target, string $source): bool @@ -248,7 +241,6 @@ public function copy(string $target, string $source): bool * * @param string $target * @param string $source - * * @return bool */ public function move(string $target, string $source): bool @@ -275,7 +267,7 @@ public function exists(string $filename): bool * The file extension * * @param string $filename - * @return string + * @return string|null */ public function extension(string $filename): ?string { diff --git a/src/Storage/Service/FTPService.php b/src/Storage/Service/FTPService.php index 9eef6d2b..4c814c42 100644 --- a/src/Storage/Service/FTPService.php +++ b/src/Storage/Service/FTPService.php @@ -23,9 +23,9 @@ class FTPService implements ServiceInterface /** * Ftp connection * - * @var FTPConnection + * @var ?FTPConnection */ - private FTPConnection $connection; + private ?FTPConnection $connection; /** * Transfer mode @@ -44,7 +44,7 @@ class FTPService implements ServiceInterface /** * The FTPService Instance * - * @var FTPService + * @var ?FTPService */ private static ?FTPService $instance = null; @@ -89,11 +89,11 @@ public static function configure(array $config): FTPService * @return void * @throws RuntimeException */ - public function connect() + public function connect(): void { $host = $this->config['hostname']; - $port = $this->config['port']; - $timeout = $this->config['timeout']; + $port = (int) $this->config['port']; + $timeout = (int) $this->config['timeout']; if ($this->config['tls']) { $connection = ftp_ssl_connect($host, $port, $timeout); @@ -120,29 +120,25 @@ public function connect() * * @return void */ - public function disconnect() + public function disconnect(): void { - if (is_resource($this->connection)) { - ftp_close($this->connection); - } - $this->connection = null; } /** * Make FTP Login. * - * @return bool + * @return void * @throws RuntimeException */ - private function login(): bool + private function login(): void { ['username' => $username, 'password' => $password] = $this->config; $is_logged_in = ftp_login($this->connection, $username, $password); if ($is_logged_in) { - return true; + return; } $this->disconnect(); @@ -160,10 +156,10 @@ private function login(): bool /** * Change path. * - * @param string $path + * @param string|null $path * @return void */ - public function changePath(?string $path = null) + public function changePath(?string $path = null): void { $base_path = $path ?: $this->config['root']; @@ -175,7 +171,7 @@ public function changePath(?string $path = null) } /** - * Get ftp connextion + * Get ftp connection * * @return FTPConnection */ @@ -189,7 +185,7 @@ public function getConnection(): FTPConnection * * @return mixed */ - public function getCurrentDirectory() + public function getCurrentDirectory(): mixed { $path = pathinfo(ftp_pwd($this->connection)); @@ -199,14 +195,13 @@ public function getCurrentDirectory() /** * Store directly the upload file * - * @param UploadedFile $file - * @param string $location - * @param array $option + * @param UploadedFile $file + * @param string|null $location + * @param array $option * - * @return array|bool|string - * @throws InvalidArgumentException + * @return bool */ - public function store(UploadedFile $file, ?string $location = null, array $option = []): array|bool|string + public function store(UploadedFile $file, ?string $location = null, array $option = []): bool { if (is_null($location)) { throw new InvalidArgumentException("Please define the store location"); @@ -223,15 +218,9 @@ public function store(UploadedFile $file, ?string $location = null, array $optio fwrite($stream, $content); rewind($stream); - // $result = $this->writeStream($location, $stream); - fclose($stream); - if ($result === false) { - return false; - } - - $result['content'] = $content; + fclose($stream); return $result; } @@ -262,12 +251,12 @@ public function append(string $file, string $content): bool /** * Write to the beginning of a file specify * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool - * @throws + * @throws ResourceException */ - public function prepend($file, $content) + public function prepend(string $file, string $content): bool { $remote_file_content = $this->get($file); @@ -283,26 +272,34 @@ public function prepend($file, $content) fclose($stream); - return $result; + return (bool) $result; } /** * Put other file content in given file * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool + * @throws ResourceException */ - public function put($file, $content) + public function put(string $file, string $content): bool { $stream = $this->readStream($file); + + if (!$stream) { + return false; + } + fwrite($stream, $content); + rewind($stream); $result = $this->writeStream($file, $stream); + fclose($stream); - return $result; + return (bool) $result; } /** @@ -340,7 +337,6 @@ public function directories(string $dirname = '.'): array * * @param string $dirname * @param int $mode - * * @return boolean */ public function makeDirectory(string $dirname, int $mode = 0777): bool @@ -379,7 +375,6 @@ protected function makeActualDirectory(string $directory): bool return preg_match('~^\./.*~', $dir_name) ? substr($dir_name, 2) : $dir_name; }); - // Skip directory creation if it already exists if (in_array($directory, $directories, true)) { return true; @@ -391,12 +386,13 @@ protected function makeActualDirectory(string $directory): bool /** * Get file content * - * @param string $filename + * @param string $file * @return ?string + * @throws ResourceException */ - public function get(string $filename): ?string + public function get(string $file): ?string { - if (!$stream = $this->readStream($filename)) { + if (!$stream = $this->readStream($file)) { return null; } @@ -410,44 +406,46 @@ public function get(string $filename): ?string /** * Copy the contents of a source file to a target file. * - * @param string $target - * @param string $source + * @param string $source + * @param string $target * @return bool + * @throws ResourceException */ - public function copy(string $target, string $source): bool + public function copy(string $source, string $target): bool { $source_stream = $this->readStream($source); + $result = $this->writeStream($target, $source_stream); fclose($source_stream); - return true; + return $result; } /** * Rename or move a source file to a target file. * - * @param string $target * @param string $source + * @param string $target * @return bool */ - public function move(string $target, string $source): bool + public function move(string $source, string $target): bool { - return ftp_rename($this->getConnection(), $target, $source); + return ftp_rename($this->getConnection(), $source, $target); } /** * Check that a file exists * - * @param string $filename + * @param string $file * @return bool */ - public function exists(string $filename): bool + public function exists(string $file): bool { $listing = $this->listDirectoryContents(); - $dirname_info = array_filter($listing, function ($item) use ($filename) { - return $item['name'] === $filename; + $dirname_info = array_filter($listing, function ($item) use ($file) { + return $item['name'] === $file; }); return count($dirname_info) !== 0; @@ -456,15 +454,15 @@ public function exists(string $filename): bool /** * isFile alias of is_file. * - * @param string $filename + * @param string $file * @return bool */ - public function isFile(string $filename): bool + public function isFile(string $file): bool { $listing = $this->listDirectoryContents(); - $dirname_info = array_filter($listing, function ($item) use ($filename) { - return $item['type'] === 'file' && $item['name'] === $filename; + $dirname_info = array_filter($listing, function ($item) use ($file) { + return $item['type'] === 'file' && $item['name'] === $file; }); return count($dirname_info) !== 0; @@ -496,16 +494,16 @@ public function isDirectory(string $dirname): bool * Resolves a path. * Give the absolute path of a path * - * @param string $filename + * @param string $file * @return string */ - public function path(string $filename): string + public function path(string $file): string { - if ($this->exists($filename)) { - return $filename; + if ($this->exists($file)) { + return $file; } - return $filename; + return $file; } /** @@ -516,49 +514,31 @@ public function path(string $filename): string */ public function delete(string $file): bool { - $paths = is_array($file) ? $file : func_get_args(); - - $success = true; - - foreach ($paths as $path) { - if (!ftp_delete($this->getConnection(), $path)) { - $success = false; - break; - } - } - - return $success; + return ftp_delete($this->getConnection(), $file); } /** * Write stream * - * @param string $path + * @param string $file * @param resource $resource * - * @return array|bool + * @return bool */ - private function writeStream(string $path, mixed $resource): array|bool + private function writeStream(string $file, mixed $resource): bool { - if (!ftp_fput($this->getConnection(), $path, $resource, $this->transfer_mode)) { - return false; - } - - $type = 'file'; - - return compact('type', 'path'); + return ftp_fput($this->getConnection(), $file, $resource, $this->transfer_mode); } - /** * List the directory content * * @param string $directory * @return array */ - protected function listDirectoryContents($directory = '.') + protected function listDirectoryContents(string $directory = '.'): array { - if ($directory && strpos($directory, '.') !== 0) { + if ($directory && (strpos($directory, '.') !== 0)) { ftp_chdir($this->getConnection(), $directory); } @@ -608,14 +588,20 @@ private function normalizeDirectoryListing(array $listing): array * Read stream * * @param string $path + * @return mixed * @throws ResourceException - * @return resource|bool */ private function readStream(string $path): mixed { try { $stream = fopen('php://temp', 'w+b'); + + if (!$stream) { + return false; + } + $result = ftp_fget($this->getConnection(), $stream, $path, $this->transfer_mode); + rewind($stream); if ($result) { @@ -635,7 +621,7 @@ private function readStream(string $path): mixed * * @throws RuntimeException */ - private function activePassiveMode() + private function activePassiveMode(): void { @ftp_set_option($this->connection, FTP_USEPASVADDRESS, false); diff --git a/src/Storage/Service/S3Service.php b/src/Storage/Service/S3Service.php index fd0f334f..6b4acd43 100644 --- a/src/Storage/Service/S3Service.php +++ b/src/Storage/Service/S3Service.php @@ -13,7 +13,7 @@ class S3Service implements ServiceInterface /** * The S3Service instance * - * @var S3Service + * @var ?S3Service */ private static ?S3Service $instance = null; @@ -73,9 +73,9 @@ public static function getInstance(): S3Service /** * Function to upload a file * - * @param UploadedFile $file - * @param string $location - * @param array $option + * @param UploadedFile $file + * @param string|null $location + * @param array $option * @return array|bool|string */ public function store(UploadedFile $file, ?string $location = null, array $option = []): array|bool|string @@ -88,15 +88,15 @@ public function store(UploadedFile $file, ?string $location = null, array $optio /** * Add content after the contents of the file * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool */ - public function append(string $filename, string $content): bool + public function append(string $file, string $content): bool { - $result = $this->get($filename); + $result = $this->get($file); $new_content = $result . PHP_EOL . $content; - $this->put($filename, $new_content); + $this->put($file, $new_content); return isset($result["Location"]); } @@ -109,11 +109,11 @@ public function append(string $filename, string $content): bool * @return bool * @throws */ - public function prepend(string $filename, string $content): bool + public function prepend(string $file, string $content): bool { - $result = $this->get($filename); + $result = $this->get($file); $new_content = $content . PHP_EOL . $result; - $this->put($filename, $new_content); + $this->put($file, $new_content); return true; } @@ -125,48 +125,34 @@ public function prepend(string $filename, string $content): bool * @param string $content * @param array $options * - * @return mixed + * @return bool */ - public function put(string $file, string $content, array $options = []): mixed + public function put(string $file, string $content, array $options = []): bool { $options = is_string($options) ? ['visibility' => $options] : (array) $options; - $result = $this->client->putObject([ + return (bool) $this->client->putObject([ 'Bucket' => $this->config['bucket'], 'Key' => $file, 'Body' => $content, "Visibility" => $options["visibility"] ?? 'public' ]); - - return $result; } /** * Delete file or directory * - * @param string $filename + * @param string $file * @return bool */ - public function delete(string|array $filename): bool + public function delete(string $file): bool { - $paths = is_array($filename) ? $filename : func_get_args(); - - $success = true; - - foreach ($paths as $path) { - try { - $this->client->deleteObject([ - 'Bucket' => $this->config['bucket'], - 'Key' => $path - ]); - } catch (\Exception $e) { - $success = false; - } - } - - return $success; + return (bool) $this->client->deleteObject([ + 'Bucket' => $this->config['bucket'], + 'Key' => $file + ]); } /** @@ -177,11 +163,11 @@ public function delete(string|array $filename): bool */ public function files(string $dirname): array { - $results = $this->client->listObjects([ + $result = $this->client->listObjects([ "Bucket" => $dirname ]); - return array_map(fn($file) => $file["Key"], $results["Contents"]); + return array_map(fn($file) => $file["Key"], $result["Contents"]); } /** @@ -200,16 +186,15 @@ public function directories(string $dirname): array /** * Create a directory * - * @param string $bucket - * @param int $mode - * @param bool $recursive - * @param array $option + * @param string $dirname + * @param int $mode + * @param array $option * @return bool */ - public function makeDirectory(string $bucket, int $mode = 0777, array $option = []): bool + public function makeDirectory(string $dirname, int $mode = 0777, array $option = []): bool { $result = $this->client->createBucket([ - "Bucket" => $bucket + "Bucket" => $dirname ]); return isset($result["Location"]); @@ -218,14 +203,14 @@ public function makeDirectory(string $bucket, int $mode = 0777, array $option = /** * Recover the contents of the file * - * @param string $filename + * @param string $file * @return ?string */ - public function get(string $filename): ?string + public function get(string $file): ?string { $result = $this->client->getObject([ 'Bucket' => $this->config['bucket'], - 'Key' => $filename + 'Key' => $file ]); if (isset($result["Body"])) { @@ -238,8 +223,8 @@ public function get(string $filename): ?string /** * Copy the contents of a source file to a target file. * - * @param string $source - * @param string $target + * @param string $source + * @param string $target * @return bool */ public function copy(string $source, string $target): bool @@ -254,8 +239,9 @@ public function copy(string $source, string $target): bool /** * Renames or moves a source file to a target file. * - * @param $source - * @param $target + * @param string $source + * @param string $target + * @return bool */ public function move(string $source, string $target): bool { @@ -269,25 +255,23 @@ public function move(string $source, string $target): bool /** * Check the existence of a file * - * @param $filename + * @param string $file * @return bool */ - public function exists(string $filename): bool + public function exists(string $file): bool { - $result = (bool) $this->get($filename); - - return $result; + return (bool) $this->get($file); } /** * isFile alias of is_file. * - * @param $filename + * @param string $file * @return bool */ - public function isFile(string $filename): bool + public function isFile(string $file): bool { - $result = $this->get($filename); + $result = $this->get($file); return strlen($result) > -1; } @@ -295,7 +279,7 @@ public function isFile(string $filename): bool /** * isDirectory alias of is_dir. * - * @param $dirname + * @param string $dirname * @return bool */ public function isDirectory(string $dirname): bool @@ -309,13 +293,11 @@ public function isDirectory(string $dirname): bool * Resolves file path. * Give the absolute path of a path * - * @param $filename + * @param string $file * @return string */ - public function path(string $filename): string + public function path(string $file): string { - $result = $this->client->getObjectUrl($this->config["bucket"], $filename); - - return $result; + return $this->client->getObjectUrl($this->config["bucket"], $file); } } diff --git a/src/Storage/Storage.php b/src/Storage/Storage.php index b401b8e1..7eea973b 100644 --- a/src/Storage/Storage.php +++ b/src/Storage/Storage.php @@ -27,7 +27,7 @@ class Storage /** * The disk mounting * - * @var DiskFilesystemService + * @var ?DiskFilesystemService */ private static ?DiskFilesystemService $disk = null; @@ -36,7 +36,7 @@ class Storage * * @var array */ - private static array $available_services_driviers = [ + private static array $available_services_drivers = [ 'ftp' => FTPService::class, 's3' => S3Service::class, ]; @@ -44,7 +44,7 @@ class Storage /** * Mount disk * - * @param string $disk + * @param string|null $disk * * @return DiskFilesystemService * @throws DiskNotFoundException @@ -77,7 +77,7 @@ public static function disk(?string $disk = null): DiskFilesystemService * @throws ServiceConfigurationNotFoundException * @throws ServiceNotFoundException */ - public static function service(string $service) + public static function service(string $service): S3Service|FTPService { $config = static::$config['services'][$service] ?? null; @@ -97,14 +97,14 @@ public static function service(string $service) )))->setService($service); } - if (!array_key_exists($driver, self::$available_services_driviers)) { + if (!array_key_exists($driver, self::$available_services_drivers)) { throw (new ServiceNotFoundException(sprintf( '"%s" is not registered as a service.', $driver )))->setService($service); } - $service_class = static::$available_services_driviers[$driver]; + $service_class = static::$available_services_drivers[$driver]; return $service_class::configure($config); } @@ -115,14 +115,14 @@ public static function service(string $service) * * @param array $drivers */ - public static function pushService(array $drivers) + public static function pushService(array $drivers): void { - foreach ($drivers as $driver => $hanlder) { - if (isset(static::$available_services_driviers[$driver])) { + foreach ($drivers as $driver => $handler) { + if (isset(static::$available_services_drivers[$driver])) { throw new InvalidArgumentException("The $driver is already define"); } - static::$available_services_driviers[$driver] = $hanlder; + static::$available_services_drivers[$driver] = $handler; } } @@ -147,11 +147,12 @@ public static function configure(array $config): FilesystemInterface /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed + * @throws ErrorException */ - public function __call($name, array $arguments) + public function __call(string $name, array $arguments = []) { if (is_null(static::$disk)) { throw new ErrorException( @@ -169,11 +170,12 @@ public function __call($name, array $arguments) /** * __callStatic * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed + * @throws ErrorException */ - public static function __callStatic($name, array $arguments) + public static function __callStatic(string $name, array $arguments) { if (is_null(static::$disk)) { throw new ErrorException( diff --git a/src/Storage/Temporary.php b/src/Storage/Temporary.php index 10e3ecd1..5cfdd9e3 100644 --- a/src/Storage/Temporary.php +++ b/src/Storage/Temporary.php @@ -27,8 +27,9 @@ class Temporary * * @param string $lock_filename * @return void + * @throws ResourceException */ - public function __construct($lock_filename = 'php://temp') + public function __construct(string $lock_filename = 'php://temp') { $this->lock_filename = $lock_filename; @@ -49,6 +50,7 @@ public function isOpen(): bool * Open the streaming * * @return void + * @throws ResourceException */ public function open(): void { @@ -67,6 +69,7 @@ public function open(): void * @param string $lock_filename * * @return void + * @throws ResourceException */ public function lockFile(string $lock_filename): void { @@ -94,9 +97,10 @@ public function close(): void * * @param string $content * - * @return mixed + * @return int|bool + * @throws ResourceException */ - public function write($content): mixed + public function write(string $content): int|bool { if (!$this->isOpen()) { $this->open(); @@ -108,7 +112,8 @@ public function write($content): mixed /** * Read content of temp * - * @return string|null + * @return string + * @throws ResourceException */ public function read(): string { diff --git a/src/Support/Arraydotify.php b/src/Support/Arraydotify.php index 3bc1522c..2c4bd1a4 100644 --- a/src/Support/Arraydotify.php +++ b/src/Support/Arraydotify.php @@ -90,9 +90,9 @@ private function dotify(array $items, string $prepend = ''): array * @param mixed $array * @param string $key * @param mixed $value - * @return array + * @return void */ - private function dataSet(mixed &$array, string $key, mixed $value): array + private function dataSet(mixed &$array, string $key, mixed $value): void { $keys = explode('.', $key); @@ -107,8 +107,6 @@ private function dataSet(mixed &$array, string $key, mixed $value): array } $array[array_shift($keys)] = $value; - - return $array; } /** @@ -130,10 +128,6 @@ private function find(array $origin, string $segment): ?array return null; } - if (is_array($array) && isset($array[$part]) && is_null($array[$part])) { - return null; - } - if (isset($array[$part]) && is_array($array[$part])) { $array = &$array[$part]; } @@ -141,7 +135,7 @@ private function find(array $origin, string $segment): ?array continue; } - if (!isset($origin[$part]) || is_null($origin[$part])) { + if (!isset($origin[$part])) { return null; } @@ -178,9 +172,7 @@ public function offsetGet($offset): mixed return null; } - return isset($this->items[$offset]) - ? $this->items[$offset] - : $this->find($this->origin, $offset); + return $this->items[$offset] ?? $this->find($this->origin, $offset); } /** diff --git a/src/Support/Collection.php b/src/Support/Collection.php index b0c20135..2882f43e 100644 --- a/src/Support/Collection.php +++ b/src/Support/Collection.php @@ -4,6 +4,7 @@ namespace Bow\Support; +use ErrorException; use Generator as PHPGenerator; class Collection implements \Countable, \JsonSerializable, \IteratorAggregate, \ArrayAccess @@ -18,7 +19,7 @@ class Collection implements \Countable, \JsonSerializable, \IteratorAggregate, \ /** * Collection constructor * - * @param array $arr + * @param array $storage */ public function __construct(array $storage = []) { @@ -62,9 +63,7 @@ public function has(int|string $key, bool $strict = false): bool $isset = isset($this->storage[$key]); if ($isset) { - if ($strict === true) { - $isset = $isset && !empty($this->storage[$key]); - } + $isset = !($strict === true) || !empty($this->storage[$key]); } return $isset; @@ -93,11 +92,11 @@ public function isEmpty(): bool /** * Allows to recover a value or value collection. * - * @param int|string $key - * @param mixed $default + * @param int|string|null $key + * @param mixed $default * @return mixed */ - public function get(int|string $key = null, mixed $default = null) + public function get(int|string $key = null, mixed $default = null): mixed { if (is_null($key)) { return $this->storage; @@ -130,7 +129,7 @@ public function values(): Collection $r = []; foreach ($this->storage as $value) { - array_push($r, $value); + $r[] = $value; } return new Collection($r); @@ -146,7 +145,7 @@ public function keys(): Collection $r = []; foreach ($this->storage as $key => $value) { - array_push($r, $key); + $r[] = $key; } return new Collection($r); @@ -165,8 +164,8 @@ public function count(): int /** * Chunk the storage content * - * @param int $count - * @return int + * @param int $chunk + * @return Collection */ public function chunk(int $chunk): Collection { @@ -174,7 +173,7 @@ public function chunk(int $chunk): Collection } /** - * To retrieve a value or value collection form d'instance de collection. + * To retrieve a value or value collection form instance of collection. * * @param string $key * @return Collection @@ -244,7 +243,7 @@ public function each(callable $cb): void * * @param Collection|array $array * @return Collection - * @throws \ErrorException + * @throws ErrorException */ public function merge(Collection|array $array): Collection { @@ -259,7 +258,7 @@ public function merge(Collection|array $array): Collection $array->toArray() ); } else { - throw new \ErrorException( + throw new ErrorException( 'Must be take 1 parameter to be array or Collection', E_ERROR ); @@ -313,7 +312,7 @@ public function filter(callable $cb): Collection * @param int $offset * @return array */ - public function fill(mixed $data, int $offset): mixed + public function fill(mixed $data, int $offset): array { $old = $this->storage; @@ -330,10 +329,10 @@ public function fill(mixed $data, int $offset): mixed * Reduce * * @param callable $cb - * @param mixed $next + * @param mixed|null $next * @return Collection */ - public function reduce(callable $cb, $next = null): Collection + public function reduce(callable $cb, mixed $next = null): Collection { foreach ($this->storage as $key => $current) { $next = call_user_func_array($cb, [ @@ -358,10 +357,10 @@ public function implode(string $sep): string /** * Sum * - * @param callable $cb + * @param callable|null $cb * @return int|float */ - public function sum(callable $cb = null): int|float + public function sum(?callable $cb = null): int|float { $sum = 0; @@ -398,7 +397,7 @@ public function max(?callable $cb = null): int|float * @param ?callable $cb * @return int|float */ - public function min(?callable $cb = null) + public function min(?callable $cb = null): float|int { return $this->aggregate('min', $cb); } @@ -406,11 +405,11 @@ public function min(?callable $cb = null) /** * Aggregate Execute max|min * - * @param callable $cb - * @param string $type + * @param callable|null $cb + * @param string $type * @return int|float */ - private function aggregate($type, $cb = null) + private function aggregate(string $type, ?callable $cb = null): float|int { $data = []; @@ -637,7 +636,7 @@ public function push(mixed $value, mixed $key = null): Collection * @param array $data * @param callable $cb */ - private function recursive(array $data, callable $cb) + private function recursive(array $data, callable $cb): void { foreach ($data as $key => $value) { if (is_array($value) || is_object($value)) { @@ -654,7 +653,7 @@ private function recursive(array $data, callable $cb) * @param mixed $name * @return mixed */ - public function __get($name) + public function __get(mixed $name) { return $this->get($name); } @@ -666,7 +665,7 @@ public function __get($name) * @param mixed $value * @return void */ - public function __set($name, $value) + public function __set(mixed $name, mixed $value) { $this->storage[$name] = $value; } @@ -677,7 +676,7 @@ public function __set($name, $value) * @param mixed $name * @return bool */ - public function __isset($name) + public function __isset(mixed $name) { return $this->has($name); } @@ -688,7 +687,7 @@ public function __isset($name) * @param mixed $name * @return void */ - public function __unset($name) + public function __unset(mixed $name) { $this->delete($name); } @@ -706,9 +705,9 @@ public function __toString() /** * jsonSerialize * - * @return mixed + * @return array */ - public function jsonSerialize(): mixed + public function jsonSerialize(): array { return $this->storage; } @@ -729,7 +728,7 @@ public function getIterator(): \ArrayIterator * @param mixed $offset * @return bool */ - public function offsetExists($offset): bool + public function offsetExists(mixed $offset): bool { return $this->has($offset); } @@ -740,7 +739,7 @@ public function offsetExists($offset): bool * @param mixed $offset * @return mixed */ - public function offsetGet($offset): mixed + public function offsetGet(mixed $offset): mixed { return $this->get($offset); } @@ -752,7 +751,7 @@ public function offsetGet($offset): mixed * @param mixed $value * @return void */ - public function offsetSet($offset, $value): void + public function offsetSet(mixed $offset, mixed $value): void { $this->set($offset, $value); } @@ -763,7 +762,7 @@ public function offsetSet($offset, $value): void * @param mixed $offset * @return void */ - public function offsetUnset($offset): void + public function offsetUnset(mixed $offset): void { unset($this->storage[$offset]); } diff --git a/src/Support/Env.php b/src/Support/Env.php index a2f7ad2b..910470d7 100644 --- a/src/Support/Env.php +++ b/src/Support/Env.php @@ -11,7 +11,7 @@ class Env /** * The env collection * - * @var array + * @var bool */ private static bool $loaded = false; @@ -27,7 +27,7 @@ class Env * * @return bool */ - public static function isLoaded() + public static function isLoaded(): bool { return static::$loaded; } @@ -39,7 +39,7 @@ public static function isLoaded() * @return void * @throws */ - public static function load(string $filename) + public static function load(string $filename): void { if (static::$loaded) { return; @@ -58,7 +58,7 @@ public static function load(string $filename) if (json_last_error()) { throw new ApplicationException( - json_last_error_msg() . ": check your env json and synthax please." + json_last_error_msg() . ": check your env json and syntax please." ); } @@ -95,6 +95,7 @@ public static function load(string $filename) public static function get(string $key, mixed $default = null): mixed { $key = Str::upper(trim($key)); + $value = static::$envs[$key] ?? getenv($key); if ($value === false) { diff --git a/src/Support/Log.php b/src/Support/Log.php index 568ebac1..8783d995 100644 --- a/src/Support/Log.php +++ b/src/Support/Log.php @@ -19,8 +19,10 @@ class Log * @param array $arguments * @return void */ - public static function __callStatic($name, $arguments) + public static function __callStatic(string $name, array $arguments = []) { - call_user_func_array([app("logger"), $name], $arguments); + $instance = app("logger"); + + call_user_func_array([$instance, $name], $arguments); } } diff --git a/src/Support/LoggerService.php b/src/Support/LoggerService.php index be0db4f7..eb74e2e3 100644 --- a/src/Support/LoggerService.php +++ b/src/Support/LoggerService.php @@ -9,9 +9,9 @@ class LoggerService * * @param string $message * @param array $context - * @return mixed + * @return void */ - public function error(string $message, array $context = []) + public function error(string $message, array $context = []): void { app('logger')->error($message, $context); } @@ -21,9 +21,9 @@ public function error(string $message, array $context = []) * * @param string $message * @param array $context - * @return mixed + * @return void */ - public function info(string $message, array $context = []) + public function info(string $message, array $context = []): void { app('logger')->info($message, $context); } @@ -33,9 +33,9 @@ public function info(string $message, array $context = []) * * @param string $message * @param array $context - * @return mixed + * @return void */ - public function warning(string $message, array $context = []) + public function warning(string $message, array $context = []): void { app('logger')->warning($message, $context); } @@ -45,9 +45,9 @@ public function warning(string $message, array $context = []) * * @param string $message * @param array $context - * @return mixed + * @return void */ - public function alert(string $message, array $context = []) + public function alert(string $message, array $context = []): void { app('logger')->alert($message, $context); } @@ -57,9 +57,9 @@ public function alert(string $message, array $context = []) * * @param string $message * @param array $context - * @return mixed + * @return void */ - public function critical(string $message, array $context = []) + public function critical(string $message, array $context = []): void { app('logger')->critical($message, $context); } @@ -69,9 +69,9 @@ public function critical(string $message, array $context = []) * * @param string $message * @param array $context - * @return mixed + * @return void */ - public function emergency(string $message, array $context = []) + public function emergency(string $message, array $context = []): void { app('logger')->emergency($message, $context); } diff --git a/src/Support/Serializes.php b/src/Support/Serializes.php index b9e5506a..32c2ebbe 100644 --- a/src/Support/Serializes.php +++ b/src/Support/Serializes.php @@ -25,12 +25,12 @@ public function __serialize() continue; } - $property->setAccessible(true); if (!$property->isInitialized($this)) { continue; } $value = $this->getPropertyValue($property); + if ($property->hasDefaultValue() && $value === $property->getDefaultValue()) { continue; } @@ -55,7 +55,7 @@ public function __serialize() * @param array $values * @return void */ - public function __unserialize(array $values) + public function __unserialize(array $values): void { $properties = (new ReflectionClass($this))->getProperties(); @@ -78,8 +78,6 @@ public function __unserialize(array $values) continue; } - $property->setAccessible(true); - $property->setValue( $this, $values[$name] @@ -95,9 +93,7 @@ public function __unserialize(array $values) */ protected function getPropertyValue( ReflectionProperty $property - ) { - $property->setAccessible(true); - + ): mixed { return $property->getValue($this); } } diff --git a/src/Support/Str.php b/src/Support/Str.php index ab6c7c50..5ac28329 100644 --- a/src/Support/Str.php +++ b/src/Support/Str.php @@ -13,27 +13,23 @@ class Str /** * upper case * - * @param string $str - * @return array|string + * @param string $str + * @return string */ public static function upper(string $str): string { - $str = mb_strtoupper($str, 'UTF-8'); - - return $str; + return mb_strtoupper($str, 'UTF-8'); } /** * lower case * - * @param string $str - * @return array|string + * @param string $str + * @return string */ public static function lower(string $str): string { - $str = mb_strtolower($str, 'UTF-8'); - - return $str; + return mb_strtolower($str, 'UTF-8'); } /** @@ -65,9 +61,9 @@ public static function camel(string $str): string * * @param string $str * @param string $delimiter - * @return mixed + * @return string */ - public static function snake(string $str, string $delimiter = '_') + public static function snake(string $str, string $delimiter = '_'): string { $str = preg_replace('/\s+/u', $delimiter, $str); @@ -79,20 +75,20 @@ public static function snake(string $str, string $delimiter = '_') } /** - * Get str plurial + * Get str plural * * @param string $str * @return string */ - public static function plurial(string $str): string + public static function plural(string $str): string { - if (preg_match('/y$/', $str)) { + if (str_ends_with($str, 'y')) { $str = static::slice($str, 0, static::len($str) - 1); return $str . 'ies'; } - preg_match('/s$/', $str) ?: $str = $str . 's'; + str_ends_with($str, 's') ?: $str = $str . 's'; return $str; } @@ -100,26 +96,24 @@ public static function plurial(string $str): string /** * slice * - * @param string $str - * @param int $start - * @param int $length + * @param string $str + * @param int $start + * @param int|null $length * @return string */ - public static function slice(string $str, int $start, ?int $length = null) + public static function slice(string $str, int $start, ?int $length = null): string { - $sliceStr = ''; + $slice_str = ''; - if (is_string($str)) { - if ($length === null) { - $length = static::len($str); - } + if ($length === null) { + $length = static::len($str); + } - if ($start < $length) { - $sliceStr = mb_substr($str, $start, $length, 'UTF-8'); - } + if ($start < $length) { + $slice_str = mb_substr($str, $start, $length, 'UTF-8'); } - return $sliceStr; + return $slice_str; } /** @@ -200,13 +194,13 @@ public static function len(string $str): int } /** - * Wordify + * Wordily * * @param string $str * @param string $sep * @return array */ - public static function wordify(string $str, string $sep = ' '): array + public static function wordily(string $str, string $sep = ' '): array { return static::split($sep, $str, static::count($sep, $str)); } @@ -235,7 +229,7 @@ public static function random(int $size = 16): string } /** - * Get rondom uuid + * Get random uuid * * @return string */ @@ -276,7 +270,7 @@ public static function slug(string $str, string $delimiter = '-'): string } /** - * unslugify, Lets you undo a slug + * un-slugify, Lets you undo a slug * * @param string $str * @return string @@ -287,7 +281,7 @@ public static function unSlugify(string $str): string } /** - * Alias of unslugify + * Alias of un-slugify * * @param string $str * @return string @@ -309,7 +303,7 @@ public static function isMail(string $email): bool { $parts = explode('@', $email); - if (!is_string($email) || count($parts) != 2) { + if (count($parts) != 2) { return false; } @@ -319,19 +313,14 @@ public static function isMail(string $email): bool /** * Check if the string is a domain * - * eg: http://exemple.com => true - * eg: http:/exemple.com => false + * eg: http://example.com => true + * eg: http:/example.com => false * * @param string $domain * @return bool - * @throws ErrorException */ public static function isDomain(string $domain): bool { - if (!is_string($domain)) { - throw new ErrorException('Accept string ' . gettype($domain) . ' given'); - } - return (bool) preg_match( '/^((https?|ftps?|ssl|url|git):\/\/)?[a-zA-Z0-9-_.]+\.[a-z]{2,6}$/', $domain @@ -343,14 +332,9 @@ public static function isDomain(string $domain): bool * * @param string $str * @return bool - * @throws ErrorException */ public static function isAlphaNum(string $str): bool { - if (!is_string($str)) { - throw new ErrorException('Accept string ' . gettype($str) . ' given'); - } - return (bool) preg_match('/^[a-zA-Z0-9]+$/', $str); } @@ -359,14 +343,9 @@ public static function isAlphaNum(string $str): bool * * @param string $str * @return bool - * @throws ErrorException */ public static function isNumeric(string $str): bool { - if (!is_string($str)) { - throw new ErrorException('Accept string ' . gettype($str) . ' given'); - } - return (bool) preg_match('/^[0-9]+(\.[0-9]+)?$/', $str); } @@ -375,14 +354,9 @@ public static function isNumeric(string $str): bool * * @param string $str * @return bool - * @throws ErrorException */ public static function isAlpha(string $str): bool { - if (!is_string($str)) { - throw new ErrorException('Accept string ' . gettype($str) . ' given'); - } - return (bool) preg_match('/^[a-zA-Z]+$/', $str); } @@ -391,14 +365,9 @@ public static function isAlpha(string $str): bool * * @param string $str * @return bool - * @throws ErrorException */ public static function isSlug(string $str): bool { - if (!is_string($str)) { - throw new ErrorException('Accept string ' . gettype($str) . ' given'); - } - return (bool) preg_match('/^[a-z0-9-]+[a-z0-9]+$/', $str); } @@ -511,19 +480,17 @@ public static function forceInUTF8(): void */ public static function fixUTF8(string $garbled_utf8_string): string { - $utf8_string = Encoding::fixUTF8($garbled_utf8_string); - - return $utf8_string; + return Encoding::fixUTF8($garbled_utf8_string); } /** * __call * - * @param string $method + * @param string $method * @param array $arguments * @return mixed */ - public function __call($method, $arguments) + public function __call(string $method, array $arguments = []) { return call_user_func_array([static::class, $method], $arguments); } diff --git a/src/Support/Util.php b/src/Support/Util.php index db6d89d8..333c8ffc 100644 --- a/src/Support/Util.php +++ b/src/Support/Util.php @@ -4,6 +4,7 @@ namespace Bow\Support; +use JetBrains\PhpStorm\NoReturn; use Symfony\Component\VarDumper\Cloner\VarCloner; use Symfony\Component\VarDumper\Dumper\CliDumper; use Symfony\Component\VarDumper\Dumper\HtmlDumper; @@ -15,14 +16,14 @@ class Util * * @var string */ - private static $sep; + private static string $sep; /** * Run a var_dump on the variables passed in parameter. * * @return void */ - public static function debug() + public static function debug(): void { $vars = func_get_args(); @@ -67,7 +68,7 @@ public static function debug() * * @return void */ - public static function dd(mixed $var) + #[NoReturn] public static function dd(mixed $var): void { call_user_func_array([static::class, 'debug'], func_get_args()); @@ -88,7 +89,7 @@ public static function sep(): string if (defined('PHP_EOL')) { static::$sep = PHP_EOL; } else { - static::$sep = (strpos(PHP_OS, 'WIN') === false) ? '\n' : '\r\n'; + static::$sep = (!str_contains(PHP_OS, 'WIN')) ? '\n' : '\r\n'; } return static::$sep; diff --git a/src/Support/helpers.php b/src/Support/helpers.php index 496de7bf..430a5a0c 100644 --- a/src/Support/helpers.php +++ b/src/Support/helpers.php @@ -1,7 +1,14 @@ url(), '/'); @@ -631,7 +642,7 @@ function set_pdo(PDO $pdo): PDO if (!function_exists('collect')) { /** - * Create new Ccollection instance + * Create new Collection instance * * @param array $data * @return Collection @@ -672,7 +683,7 @@ function decrypt(string $data): string /** * Start Database transaction * - * @param callable $cb + * @param callable|null $cb * @return void */ function db_transaction(callable $cb = null): void @@ -719,7 +730,7 @@ function db_commit(): void if (!function_exists('event')) { /** - * Event event + * Event * * @return mixed */ @@ -745,7 +756,7 @@ function event(): mixed * @param string $message * @return mixed */ - function flash(string $key, string $message) + function flash(string $key, string $message): mixed { return Session::getInstance() ->flash($key, $message); @@ -757,10 +768,9 @@ function flash(string $key, string $message) * Send email * * @param null|string $view - * @param array $data - * @param callable $cb + * @param array $data + * @param callable|null $cb * @return MailDriverInterface|bool - * @throws */ function email( string $view = null, @@ -779,10 +789,10 @@ function email( /** * Send raw email * - * @param array $to - * @param string $subject - * @param string $message - * @param array $headers + * @param string $to + * @param string $subject + * @param string $message + * @param array $headers * @return bool */ function raw_email(string $to, string $subject, string $message, array $headers = []): bool @@ -795,7 +805,7 @@ function raw_email(string $to, string $subject, string $message, array $headers /** * Session help * - * @param array|string $value + * @param array|string|null $value * @param mixed $default * @return mixed */ @@ -822,33 +832,25 @@ function session(array|string $value = null, mixed $default = null): mixed /** * Cooke alias * - * @param string $key - * @param mixed $data - * @param int $expirate - * @param string $path - * @param string $domain - * @param bool $secure - * @param bool $http - * @return null|string + * @param string|null $key + * @param mixed $data + * @param int $expiration + * @return string|array|object|null */ function cookie( string $key = null, mixed $data = null, - int $expirate = 3600 - ) { + int $expiration = 3600 + ): string|array|object|null { if ($key === null) { return Cookie::all(); } - if ($key !== null && $data == null) { + if ($data == null) { return Cookie::get($key); } - if ($key !== null && $data !== null) { - return Cookie::set($key, $data, $expirate); - } - - return null; + return Cookie::set($key, $data, $expiration); } } @@ -876,7 +878,7 @@ function validator(array $inputs, array $rules, array $messages = []): Validate * @param bool $absolute * @return string */ - function route(string $name, bool|array $data = [], bool $absolute = false) + function route(string $name, bool|array $data = [], bool $absolute = false): string { if (is_bool($data)) { $absolute = $data; @@ -892,13 +894,13 @@ function route(string $name, bool|array $data = [], bool $absolute = false) ); } - if (preg_match_all('/(?::([a-zA-Z0-9_]+\??))/', $url, $matches)) { + if (preg_match_all('/:([a-zA-Z0-9_]+\??)/', $url, $matches)) { $keys = end($matches); foreach ($keys as $key) { if (preg_match("/\?$/", $key)) { - $valide_key = trim($key, "?"); - $value = $data[$valide_key] ?? ""; - unset($data[$valide_key]); + $valid_key = trim($key, "?"); + $value = $data[$valid_key] ?? ""; + unset($data[$valid_key]); } else { if (!isset($data[$key])) { throw new InvalidArgumentException("Route: The $key key is not provide"); @@ -942,9 +944,12 @@ function e(?string $value = null): string /** * Service loader * - * @return \Bow\Storage\Service\FTPService|\Bow\Storage\Service\S3Service + * @param string $service + * @return FTPService|S3Service + * @throws ServiceConfigurationNotFoundException + * @throws ServiceNotFoundException */ - function storage_service(string $service) + function storage_service(string $service): S3Service|FTPService { return Storage::service($service); } @@ -956,7 +961,7 @@ function storage_service(string $service) * * @param string $disk * @return DiskFilesystemService - * @throws ResourceException + * @throws DiskNotFoundException */ function app_file_system(string $disk): DiskFilesystemService { @@ -969,21 +974,24 @@ function app_file_system(string $disk): DiskFilesystemService * Cache help * * @param ?string $key - * @param ?mixed $value - * @param ?int $ttl + * @param ?mixed $value + * @param ?int $ttl * @return mixed + * @throws ErrorException */ - function cache(string $key = null, mixed $value = null, int $ttl = null) + function cache(string $key = null, mixed $value = null, int $ttl = null): mixed { + $instance = \Bow\Cache\Cache::getInstance(); + if ($key === null) { - return \Bow\Cache\Cache::getInstance(); + return $instance; } - if ($key !== null && $value === null) { - return \Bow\Cache\Cache::get($key); + if ($value === null) { + return $instance->get($key); } - return \Bow\Cache\Cache::add($key, $value, $ttl); + return $instance->add($key, $value, $ttl); } } @@ -1049,7 +1057,7 @@ function bow_hash(string $data, string $hash_value = null): bool|string /** * Make translation * - * @param string $key + * @param string|null $key * @param array $data * @param bool $choose * @return string|Translator @@ -1076,10 +1084,10 @@ function app_trans( /** * Alias of trans * - * @param string $key - * @param array $data - * @param bool $choose - * @return string + * @param string $key + * @param array $data + * @param bool $choose + * @return string|Translator */ function t( string $key, @@ -1094,10 +1102,10 @@ function t( /** * Alias of trans * - * @param $key - * @param $data - * @param bool $choose - * @return string + * @param string $key + * @param array $data + * @param bool $choose + * @return string|Translator */ function __( string $key, @@ -1110,13 +1118,13 @@ function __( if (!function_exists('app_env')) { /** - * Gets the app environement variable + * Gets the app environment variable * * @param string $key * @param mixed $default - * @return string + * @return ?string */ - function app_env(string $key, mixed $default = null) + function app_env(string $key, mixed $default = null): ?string { if (Env::isLoaded()) { return Env::get($key, $default); @@ -1148,7 +1156,7 @@ function app_assets(string $filename): string * @return Response * @throws HttpException */ - function app_abort(int $code = 500, string $message = '') + function app_abort(int $code = 500, string $message = ''): Response { if (strlen($message) == 0) { $message = HttpStatus::getMessage($code); @@ -1160,12 +1168,13 @@ function app_abort(int $code = 500, string $message = '') if (!function_exists('app_abort_if')) { /** - * Abort bow execution if condiction is true + * Abort bow execution if condition is true * * @param boolean $boolean * @param int $code * @param string $message * @return Response|null + * @throws HttpException */ function app_abort_if( bool $boolean, @@ -1182,7 +1191,7 @@ function app_abort_if( if (!function_exists('app_mode')) { /** - * Get app enviroment mode + * Get app environment mode * * @return string */ @@ -1194,7 +1203,7 @@ function app_mode(): string if (!function_exists('app_in_debug')) { /** - * Get app enviroment mode + * Get app environment mode * * @return bool */ @@ -1218,7 +1227,7 @@ function client_locale(): string if (!function_exists('old')) { /** - * Get old request valude + * Get old request value * * @param string $key * @param mixed $fullback @@ -1234,9 +1243,8 @@ function old(string $key, mixed $fullback = null): mixed /** * Recovery of the guard * - * @param string $guard + * @param string|null $guard * @return GuardContract - * @throws */ function auth(string $guard = null): GuardContract { @@ -1320,8 +1328,8 @@ function str_is_domain(string $domain): bool * Check if string is slug * * @param string $slug - * @return bool - * @throws + * @return string + * @throws ErrorException */ function str_is_slug(string $slug): string { @@ -1406,7 +1414,7 @@ function str_shuffle_words(string $words): string */ function str_wordify(string $words, string $sep = ''): array { - return Str::wordify($words, $sep); + return Str::wordily($words, $sep); } } @@ -1419,7 +1427,7 @@ function str_wordify(string $words, string $sep = ''): array */ function str_plurial(string $slug): string { - return Str::plurial($slug); + return Str::plural($slug); } } @@ -1451,7 +1459,7 @@ function str_snake(string $slug): string if (!function_exists('str_contains')) { /** - * Check if string contain an other string + * Check if string contain another string * * @param string $search * @param string $string @@ -1520,9 +1528,10 @@ function str_fix_utf8(string $string): string * * @param string $name * @param array $data - * @return mixed + * @return int|array + * @throws ErrorException */ - function db_seed(string $name, array $data = []): mixed + function db_seed(string $name, array $data = []): int|array { if (class_exists($name, true)) { $instance = app($name); diff --git a/src/Testing/Features/SeedingHelper.php b/src/Testing/Features/SeedingHelper.php index 557db6fc..92146d1a 100644 --- a/src/Testing/Features/SeedingHelper.php +++ b/src/Testing/Features/SeedingHelper.php @@ -12,6 +12,7 @@ trait SeedingHelper * @param string $seeder * @param array $data * @return int + * @throws \ErrorException */ public function seed(string $seeder, array $data = []): int { diff --git a/src/Testing/Response.php b/src/Testing/Response.php index c91a08f1..87427608 100644 --- a/src/Testing/Response.php +++ b/src/Testing/Response.php @@ -24,7 +24,7 @@ class Response private string $content; /** - * Behovior constructor. + * Behavior constructor. * * @param HttpClientResponse $http_response */ @@ -69,7 +69,7 @@ public function assertExactJson(array $data, string $message = ''): Response } /** - * Check if the content is some of parse data + * Check if the content is some parse data * * @param string $data * @param string $message diff --git a/src/Testing/TestCase.php b/src/Testing/TestCase.php index 4727c083..d9899841 100644 --- a/src/Testing/TestCase.php +++ b/src/Testing/TestCase.php @@ -19,12 +19,12 @@ class TestCase extends PHPUnitTestCase /** * The base url * - * @var string + * @var ?string */ protected ?string $url = null; /** - * The list of additionnal header + * The list of additional header * * @var array */ @@ -37,18 +37,14 @@ class TestCase extends PHPUnitTestCase */ private function getBaseUrl(): string { - if (is_null($this->url)) { - return rtrim(app_env('APP_URL', 'http://127.0.0.1:5000')); - } - - return $this->url ?? 'http://127.0.0.1:5000'; + return $this->url ?? rtrim(app_env('APP_URL', 'http://127.0.0.1:5000')); } /** * Add attachment * * @param array $attach - * @return Response + * @return TestCase */ public function attach(array $attach): TestCase { @@ -58,7 +54,7 @@ public function attach(array $attach): TestCase } /** - * Specify the additionnal headers + * Specify the additional headers * * @param array $headers * @return TestCase @@ -71,9 +67,10 @@ public function withHeaders(array $headers): TestCase } /** - * Specify the additionnal header + * Specify the additional header * - * @param array $headers + * @param string $key + * @param string $value * @return TestCase */ public function withHeader(string $key, string $value): TestCase @@ -89,6 +86,7 @@ public function withHeader(string $key, string $value): TestCase * @param string $url * @param array $param * @return Response + * @throws \Exception */ public function get(string $url, array $param = []): Response { @@ -105,6 +103,7 @@ public function get(string $url, array $param = []): Response * @param string $url * @param array $param * @return Response + * @throws \Exception */ public function post(string $url, array $param = []): Response { @@ -125,6 +124,7 @@ public function post(string $url, array $param = []): Response * @param string $url * @param array $param * @return Response + * @throws \Exception */ public function put(string $url, array $param = []): Response { @@ -141,6 +141,7 @@ public function put(string $url, array $param = []): Response * @param string $url * @param array $param * @return Response + * @throws \Exception */ public function delete(string $url, array $param = []): Response { @@ -157,8 +158,9 @@ public function delete(string $url, array $param = []): Response * @param string $url * @param array $param * @return Response + * @throws \Exception */ - public function patch(string $url, array $param = []) + public function patch(string $url, array $param = []): Response { $param = array_merge([ '_method' => 'PATCH' @@ -168,7 +170,7 @@ public function patch(string $url, array $param = []) } /** - * Initilalize Response action + * Initialize Response action * * @param string $method * @param string $url diff --git a/src/Translate/Translator.php b/src/Translate/Translator.php index dc98ffd8..4952bfbb 100644 --- a/src/Translate/Translator.php +++ b/src/Translate/Translator.php @@ -10,7 +10,7 @@ class Translator { /** - * The define langue + * The define language * * @var string */ @@ -26,7 +26,7 @@ class Translator /** * The Translator instance * - * @var Translator + * @var ?Translator */ private static ?Translator $instance = null; @@ -96,26 +96,18 @@ public static function isLocale(string $locale): bool * * @param string $key * @param array $data - * @param bool $plurial + * @param bool $plural * * @return string */ - public static function translate(string $key, array $data = [], bool $plurial = false): string + public static function translate(string $key, array $data = [], bool $plural = false): string { - if (!is_string($key)) { - throw new \InvalidArgumentException( - 'The first parameter must be a string.', - E_USER_ERROR - ); - } - $map = explode('.', $key); if (count($map) == 1) { return $key; } - // Formatage du path de fichier de la translation $translation_filename = static::$directory . '/' . static::$lang . '/' . current($map) . '.php'; if (!file_exists($translation_filename)) { @@ -141,7 +133,7 @@ public static function translate(string $key, array $data = [], bool $plurial = $value = $translations[$key]; $parts = explode('|', $value); - if ($plurial === true) { + if ($plural === true) { if (!isset($parts[1])) { return $key; } @@ -168,19 +160,19 @@ public static function single(string $key, array $data = []): string } /** - * Make plurial translation + * Make plural translation * - * @param $key + * @param string $key * @param array $data * @return string */ - public static function plurial(string $key, array $data = []): string + public static function plural(string $key, array $data = []): string { return static::translate($key, $data, true); } /** - * Permet de formater + * Str formatter * * @param string $str * @param array $values diff --git a/src/Validation/README.md b/src/Validation/README.md index 984d2cec..9d49e50c 100644 --- a/src/Validation/README.md +++ b/src/Validation/README.md @@ -2,7 +2,7 @@ Bow Framework's validator system help developer to make data validation delightful. -Let's show a little exemple: +Let's show a little example: ```php $data = ["name" => "Franck DAKIA"]; diff --git a/src/Validation/RequestValidation.php b/src/Validation/RequestValidation.php index c8c09351..8e41deba 100644 --- a/src/Validation/RequestValidation.php +++ b/src/Validation/RequestValidation.php @@ -35,7 +35,6 @@ abstract class RequestValidation /** * TodoValidation constructor. * - * @return mixed * @throws */ public function __construct() @@ -68,7 +67,7 @@ public function __construct() * * @return array */ - protected function rules() + protected function rules(): array { return [ // Your rules @@ -80,7 +79,7 @@ protected function rules() * * @return array */ - protected function keys() + protected function keys(): array { return [ '*' @@ -92,7 +91,7 @@ protected function keys() * * @return bool */ - protected function authorize() + protected function authorize(): bool { return true; } @@ -102,7 +101,7 @@ protected function authorize() * * @return array */ - protected function messages() + protected function messages(): array { return []; } @@ -131,9 +130,9 @@ protected function authorizationFailAction() } /** - * When user have not authorize to launch a request + * When user have not authorized to launch a request * This is hook the method that can watch them for make an action - * This method permet to custom fail exception + * This method able to custom fail exception * * @throws AuthorizationException */ @@ -157,7 +156,7 @@ protected function fails() * * @return Validate */ - protected function getValidationInstance() + protected function getValidationInstance(): Validate { return $this->validate; } @@ -167,7 +166,7 @@ protected function getValidationInstance() * * @return string */ - protected function getMessage() + protected function getMessage(): string { return $this->validate->getLastMessage(); } @@ -187,7 +186,7 @@ protected function getMessages() * * @return array */ - protected function getValidationData() + protected function getValidationData(): array { return $this->data; } @@ -197,7 +196,7 @@ protected function getValidationData() * * @return Request */ - protected function getRequest() + protected function getRequest(): Request { return $this->request; } @@ -207,7 +206,7 @@ protected function getRequest() * * @throws ValidationException; */ - protected function throwError() + protected function throwError(): void { $this->validate->throwError(); } @@ -215,11 +214,11 @@ protected function throwError() /** * __call * - * @param string $name + * @param string $name * @param array $arguments * @return Request */ - public function __call($name, array $arguments) + public function __call(string $name, array $arguments) { if (method_exists($this->request, $name)) { return call_user_func_array([$this->request, $name], $arguments); @@ -233,10 +232,10 @@ public function __call($name, array $arguments) /** * __get * - * @param string $name + * @param string $name * @return string */ - public function __get($name) + public function __get(string $name) { return $this->request->$name; } diff --git a/src/Validation/Rules/DatabaseRule.php b/src/Validation/Rules/DatabaseRule.php index 613b2853..5c9d756e 100644 --- a/src/Validation/Rules/DatabaseRule.php +++ b/src/Validation/Rules/DatabaseRule.php @@ -5,6 +5,7 @@ namespace Bow\Validation\Rules; use Bow\Database\Database; +use Bow\Database\Exception\QueryBuilderException; trait DatabaseRule { @@ -16,6 +17,7 @@ trait DatabaseRule * @param string $key * @param string $masque * @return void + * @throws QueryBuilderException */ protected function compileExists(string $key, string $masque): void { @@ -26,13 +28,11 @@ protected function compileExists(string $key, string $masque): void $catch = end($match); $parts = explode(',', $catch); - if (count($parts) == 1) { - $exists = Database::table($parts[0]) - ->where($key, $this->inputs[$key])->exists(); - } else { - $exists = Database::table($parts[0]) + $exists = count($parts) == 1 + ? Database::table($parts[0]) + ->where($key, $this->inputs[$key])->exists() + : Database::table($parts[0]) ->where($parts[1], $this->inputs[$key])->exists(); - } if (!$exists) { $this->last_message = $this->lexical('exists', $key); @@ -54,6 +54,7 @@ protected function compileExists(string $key, string $masque): void * @param string $key * @param string $masque * @return void + * @throws QueryBuilderException */ protected function compileNotExists(string $key, string $masque): void { @@ -64,13 +65,11 @@ protected function compileNotExists(string $key, string $masque): void $catch = end($match); $parts = explode(',', $catch); - if (count($parts) == 1) { - $exists = Database::table($parts[0]) - ->where($key, $this->inputs[$key])->exists(); - } else { - $exists = Database::table($parts[0]) + $exists = count($parts) == 1 + ? Database::table($parts[0]) + ->where($key, $this->inputs[$key])->exists() + : Database::table($parts[0]) ->where($parts[1], $this->inputs[$key])->exists(); - } if ($exists) { $this->last_message = $this->lexical('not_exists', $key); @@ -92,6 +91,7 @@ protected function compileNotExists(string $key, string $masque): void * @param string $key * @param string $masque * @return void + * @throws QueryBuilderException */ protected function compileUnique(string $key, string $masque): void { diff --git a/src/Validation/Rules/EmailRule.php b/src/Validation/Rules/EmailRule.php index 6bcfd2f3..55c81912 100644 --- a/src/Validation/Rules/EmailRule.php +++ b/src/Validation/Rules/EmailRule.php @@ -17,7 +17,7 @@ trait EmailRule * @param string $masque * @return void */ - protected function compileEmail(string $key, string $masque) + protected function compileEmail(string $key, string $masque): void { if (!preg_match("/^email$/", $masque, $match)) { return; diff --git a/src/Validation/Rules/StringRule.php b/src/Validation/Rules/StringRule.php index f0339983..bcbbe86e 100644 --- a/src/Validation/Rules/StringRule.php +++ b/src/Validation/Rules/StringRule.php @@ -50,6 +50,7 @@ protected function compileRequired(string $key, string $masque): void * @param string $key * @param string $masque * @return void + * @throws ValidationException */ protected function compileRequiredIf(string $key, string $masque): void { @@ -67,8 +68,8 @@ protected function compileRequiredIf(string $key, string $masque): void $exists = false; $fields = explode(",", $match[0]); - foreach ($fields as $key => $field) { - if ($key == 0) { + foreach ($fields as $field_key => $field) { + if ($field_key == 0) { $exists = isset($this->inputs[$field]); } else { $exists = $exists && isset($this->inputs[$field]); @@ -127,7 +128,7 @@ protected function compileEmpty(string $key, string $masque): void */ protected function compileAlphaNum(string $key, string $masque): void { - if (!preg_match("/^alphanum$/", $masque)) { + if (!($masque === "alphanum")) { return; } @@ -229,7 +230,7 @@ protected function compileSize(string $key, string $masque): void */ protected function compileLower(string $key, string $masque): void { - if (!preg_match("/^lower/", $masque)) { + if (!str_starts_with($masque, "lower")) { return; } @@ -258,7 +259,7 @@ protected function compileLower(string $key, string $masque): void */ protected function compileUpper(string $key, string $masque): void { - if (!preg_match("/^upper/", $masque)) { + if (!str_starts_with($masque, "upper")) { return; } @@ -287,7 +288,7 @@ protected function compileUpper(string $key, string $masque): void */ protected function compileAlpha(string $key, string $masque): void { - if (!preg_match("/^alpha$/", $masque)) { + if (!($masque === "alpha")) { return; } diff --git a/src/Validation/Validate.php b/src/Validation/Validate.php index a50d7353..e1571e69 100644 --- a/src/Validation/Validate.php +++ b/src/Validation/Validate.php @@ -18,7 +18,7 @@ class Validate /** * The last message * - * @var string + * @var ?string */ private ?string $last_message = null; diff --git a/src/Validation/Validator.php b/src/Validation/Validator.php index e83fcaf2..0bfd96b1 100644 --- a/src/Validation/Validator.php +++ b/src/Validation/Validator.php @@ -32,7 +32,7 @@ class Validator /** * The last name * - * @var string + * @var ?string */ protected ?string $last_message = null; diff --git a/src/View/Engine/PHPEngine.php b/src/View/Engine/PHPEngine.php index 3468802d..eb57d586 100644 --- a/src/View/Engine/PHPEngine.php +++ b/src/View/Engine/PHPEngine.php @@ -4,7 +4,6 @@ namespace Bow\View\Engine; -use Bow\Configuration\Loader; use Bow\View\EngineAbstract; use RuntimeException; diff --git a/src/View/Engine/TwigEngine.php b/src/View/Engine/TwigEngine.php index e4945eaa..598dd0ed 100644 --- a/src/View/Engine/TwigEngine.php +++ b/src/View/Engine/TwigEngine.php @@ -4,6 +4,7 @@ namespace Bow\View\Engine; +use Bow\Application\Exception\ApplicationException; use Bow\Configuration\Loader as ConfigurationLoader; use Bow\View\EngineAbstract; @@ -27,7 +28,8 @@ class TwigEngine extends EngineAbstract * TwigEngine constructor. * * @param array $config - * @return void + * @return \Twig\Environment + * @throws ApplicationException */ public function __construct(array $config) { @@ -35,7 +37,7 @@ public function __construct(array $config) $loader = new \Twig\Loader\FilesystemLoader($config['path']); - $aditionnals = $config['aditionnal_options'] ?? []; + $additional_options = $config['additional_options'] ?? []; $env = [ 'auto_reload' => true, @@ -43,9 +45,9 @@ public function __construct(array $config) 'cache' => $config['cache'] ]; - if (is_array($aditionnals)) { - foreach ($aditionnals as $key => $aditionnal) { - $env[$key] = $aditionnal; + if (is_array($additional_options)) { + foreach ($additional_options as $key => $additional_option) { + $env[$key] = $additional_option; } } @@ -62,8 +64,6 @@ public function __construct(array $config) new \Twig\TwigFunction($helper, $helper) ); } - - return $this->template; } /** diff --git a/src/View/EngineAbstract.php b/src/View/EngineAbstract.php index cacf5829..f1b8bb0c 100644 --- a/src/View/EngineAbstract.php +++ b/src/View/EngineAbstract.php @@ -4,7 +4,6 @@ namespace Bow\View; -use Bow\Configuration\Loader as ConfigurationLoader; use Bow\View\Exception\ViewException; abstract class EngineAbstract @@ -93,7 +92,7 @@ protected function checkParseFile(string $filename, bool $extended = true): stri { $normalized_filename = $this->normalizeFilename($filename); - // Vérification de l'existance du fichier + // Check if file exists if ($this->config['path'] !== null && !file_exists($this->config['path'] . '/' . $normalized_filename)) { throw new ViewException( sprintf( @@ -139,6 +138,6 @@ public function fileExists(string $filename): bool */ private function normalizeFilename(string $filename): string { - return preg_replace('/@|\./', '/', $filename) . $this->config['extension']; + return preg_replace('/@|\./', '/', $filename) . '.' . trim($this->config['extension'], '.'); } } diff --git a/src/View/View.php b/src/View/View.php index 3ad2a0b8..b8e75872 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -6,7 +6,6 @@ use Tintin\Tintin; use BadMethodCallException; -use Bow\View\EngineAbstract; use Bow\Contracts\ResponseInterface; use Bow\View\Exception\ViewException; @@ -51,13 +50,6 @@ class View implements ResponseInterface 'php' => \Bow\View\Engine\PHPEngine::class, ]; - /** - * The cachabled flash for twig - * - * @var boolean - */ - private bool $cachabled = false; - /** * View constructor. * @@ -145,7 +137,7 @@ public function getTemplate() * * @return Tintin|\Twig\Environment */ - public function getEngine() + public function getEngine(): \Twig\Environment|Tintin { return static::$template->getEngine(); } @@ -190,11 +182,10 @@ public function setExtension(string $extension): View } /** - * Ajouter un moteur de template - * - * @param $name - * @param $engine + * Add a template engine * + * @param string $name + * @param string $engine * @return bool * @throws ViewException */ @@ -228,7 +219,7 @@ public function getContent(): string /** * Send Response * - * @return mixed + * @return void */ public function sendContent(): void { diff --git a/src/View/ViewConfiguration.php b/src/View/ViewConfiguration.php index 53e2bbd0..507a47cf 100644 --- a/src/View/ViewConfiguration.php +++ b/src/View/ViewConfiguration.php @@ -14,9 +14,6 @@ class ViewConfiguration extends Configuration */ public function create(Loader $config): void { - /** - * Configuration of view - */ $this->container->bind('view', function () use ($config) { View::configure($config["view"]); diff --git a/tests/Auth/AuthenticationTest.php b/tests/Auth/AuthenticationTest.php index e233abaa..da9b06ea 100644 --- a/tests/Auth/AuthenticationTest.php +++ b/tests/Auth/AuthenticationTest.php @@ -23,6 +23,7 @@ public static function setUpBeforeClass(): void $config = TestingConfiguration::getConfig(); Auth::configure($config["auth"]); + Policier::configure($config["policier"]); // Configuration database Database::configure($config["database"]); @@ -32,7 +33,6 @@ public static function setUpBeforeClass(): void 'password' => Hash::make("password"), 'username' => 'papac' ]); - Policier::configure($config["policier"]); } public static function tearDownAfterClass(): void @@ -92,6 +92,7 @@ public function test_fail_get_user_id_with_session() public function test_attempt_login_with_jwt_provider() { $auth = Auth::guard('api'); + $result = $auth->attempts([ "username" => "papac", "password" => "password" diff --git a/tests/Config/stubs/policier.php b/tests/Config/stubs/policier.php index ded1be3c..c5b7a69a 100644 --- a/tests/Config/stubs/policier.php +++ b/tests/Config/stubs/policier.php @@ -28,16 +28,6 @@ */ "iat" => 60, - /** - * Configures the issuer - */ - "iss" => "localhost", - - /** - * Configures the audience - */ - "aud" => "localhost", - /** * The type of the token, which is JWT */ diff --git a/tests/Console/Stubs/CustomCommand.php b/tests/Console/Stubs/CustomCommand.php index 586f1c1d..3053aad1 100644 --- a/tests/Console/Stubs/CustomCommand.php +++ b/tests/Console/Stubs/CustomCommand.php @@ -2,7 +2,7 @@ namespace Bow\Tests\Console\Stubs; -use Bow\Console\Command\AbstractCommand as ConsoleCommand; +use Bow\Console\AbstractCommand as ConsoleCommand; class CustomCommand extends ConsoleCommand { diff --git a/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_queue_migration_stubs__1.txt b/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_queue_migration_stubs__1.txt index 0c85a498..698f3cbd 100644 --- a/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_queue_migration_stubs__1.txt +++ b/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_queue_migration_stubs__1.txt @@ -19,7 +19,7 @@ class QueueTableMigration extends Migration "size" => ["waiting", "processing", "reserved", "failed", "done"], "default" => "waiting", ]); - $table->addDatetime('avalaibled_at'); + $table->addDatetime('available_at'); $table->addDatetime('reserved_at', ["nullable" => true, "default" => null]); $table->addDatetime('created_at'); }); diff --git a/tests/Container/CapsuleTest.php b/tests/Container/CapsuleTest.php index 43dd633e..d9f0aa51 100644 --- a/tests/Container/CapsuleTest.php +++ b/tests/Container/CapsuleTest.php @@ -4,7 +4,7 @@ use StdClass; use Bow\Container\Capsule; -use Bow\Tests\Stubs\Container\MyClass; +use Bow\Tests\Container\Stubs\MyClass; class CapsuleTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Container/Stubs/MyClass.php b/tests/Container/Stubs/MyClass.php index 9b2c1cd6..7a3c1be7 100644 --- a/tests/Container/Stubs/MyClass.php +++ b/tests/Container/Stubs/MyClass.php @@ -1,6 +1,6 @@ createFile($this->ftp_service, $file_name, $file_content); - $this->assertIsArray($result); - $this->assertEquals($result['content'], $file_content); - $this->assertEquals($result['path'], $file_name); + $this->assertIsBool($result); + $this->assertTrue($result); } public function test_file_should_not_be_existe() @@ -91,6 +90,8 @@ public function test_rename_file() public function test_copy_file_and_the_contents() { + $this->createFile($this->ftp_service, 'file-copy.txt', 'something'); + $result = $this->ftp_service->copy('file-copy.txt', 'test.txt'); $this->assertTrue($result); @@ -180,13 +181,13 @@ public function test_put_content_into_file() private function createFile(FTPService $ftp_service, $filename, $content = '') { - $uploadedFile = $this->getMockBuilder(\Bow\Http\UploadedFile::class) + $uploaded_file = $this->getMockBuilder(\Bow\Http\UploadedFile::class) ->disableOriginalConstructor() ->getMock(); - $uploadedFile->method('getContent')->willReturn($content); - $uploadedFile->method('getFilename')->willReturn($filename); + $uploaded_file->method('getContent')->willReturn($content); + $uploaded_file->method('getFilename')->willReturn($filename); - return $ftp_service->store($uploadedFile, $filename); + return $ftp_service->store($uploaded_file, $filename); } } diff --git a/tests/Hashing/SecurityTest.php b/tests/Hashing/SecurityTest.php index 980439dd..c3bd3261 100644 --- a/tests/Hashing/SecurityTest.php +++ b/tests/Hashing/SecurityTest.php @@ -2,14 +2,23 @@ namespace Bow\Tests\Hashing; +use Bow\Auth\Auth; +use Bow\Database\Database; use Bow\Security\Hash; use Bow\Security\Crypto; +use Bow\Tests\Config\TestingConfiguration; class SecurityTest extends \PHPUnit\Framework\TestCase { + public static function setUpBeforeClass(): void + { + TestingConfiguration::getConfig(); + } + public function test_should_decrypt_data() { Crypto::setkey(file_get_contents(__DIR__ . '/stubs/.key'), 'AES-256-CBC'); + $encrypted = Crypto::encrypt('bow'); $this->assertEquals(Crypto::decrypt($encrypted), 'bow'); diff --git a/tests/Queue/MailQueueTest.php b/tests/Queue/MailQueueTest.php index 52a14bab..16b2e26f 100644 --- a/tests/Queue/MailQueueTest.php +++ b/tests/Queue/MailQueueTest.php @@ -41,6 +41,7 @@ public function testQueueMail() $adapter = static::$connection->setConnection("beanstalkd")->getAdapter(); $adapter->push($producer); + $adapter->run(); } } diff --git a/tests/Queue/QueueTest.php b/tests/Queue/QueueTest.php index 6f26248a..1a87786f 100644 --- a/tests/Queue/QueueTest.php +++ b/tests/Queue/QueueTest.php @@ -46,7 +46,7 @@ public static function setUpBeforeClass(): void payload text, status varchar(100), attempts int, - avalaibled_at datetime null default null, + available_at datetime null default null, reserved_at datetime null default null, created_at datetime )'); diff --git a/tests/Translate/TranslationTest.php b/tests/Translate/TranslationTest.php index 4f3f8a18..c92ccea0 100644 --- a/tests/Translate/TranslationTest.php +++ b/tests/Translate/TranslationTest.php @@ -25,7 +25,7 @@ public function test_fr_user_name() public function test_fr_plurial() { - $this->assertEquals(Translator::plurial('welcome.plurial'), 'Utilisateurs'); + $this->assertEquals(Translator::plural('welcome.plurial'), 'Utilisateurs'); } public function test_fr_single() @@ -53,7 +53,7 @@ public function test_en_user_name() public function test_en_plurial() { Translator::setLocale("en"); - $this->assertEquals(Translator::plurial('welcome.plurial'), 'Users'); + $this->assertEquals(Translator::plural('welcome.plurial'), 'Users'); } public function test_en_single()