From 66b2daf460ce7fc6be74d0883d906a55eb2072bf Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sat, 25 Jan 2025 23:38:58 +0000 Subject: [PATCH 01/10] feat: refactoring mail and messaging --- src/Console/stubs/messaging.stub | 7 +- src/Mail/Contracts/MailDriverInterface.php | 6 +- src/Mail/Driver/NativeDriver.php | 28 ++-- src/Mail/Driver/SesDriver.php | 24 +-- src/Mail/Driver/SmtpDriver.php | 37 +++-- src/Mail/{Message.php => Envelop.php} | 58 +++---- src/Mail/Mail.php | 44 ++--- src/Mail/MailQueueProducer.php | 12 +- src/Messaging/Channel/DatabaseChannel.php | 8 +- src/Messaging/Channel/MailChannel.php | 12 +- src/Messaging/Messaging.php | 30 ++-- src/Messaging/MessagingQueueProducer.php | 8 +- tests/Messaging/MessagingTest.php | 150 ++++++++++++++++++ tests/Messaging/Stubs/TestMessage.php | 33 ++++ tests/Messaging/Stubs/TestNotifiableModel.php | 11 ++ 15 files changed, 331 insertions(+), 137 deletions(-) rename src/Mail/{Message.php => Envelop.php} (89%) create mode 100644 tests/Messaging/MessagingTest.php create mode 100644 tests/Messaging/Stubs/TestMessage.php create mode 100644 tests/Messaging/Stubs/TestNotifiableModel.php diff --git a/src/Console/stubs/messaging.stub b/src/Console/stubs/messaging.stub index cae21c56..55e63f84 100644 --- a/src/Console/stubs/messaging.stub +++ b/src/Console/stubs/messaging.stub @@ -3,6 +3,7 @@ namespace {baseNamespace}{namespace}; use Bow\Database\Barry\Model; +use Bow\Mail\Envelop; use Bow\Messaging\Messaging; class {className} extends Messaging @@ -22,11 +23,11 @@ class {className} extends Messaging * Send notification to mail * * @param Model $notifiable - * @return Message|null + * @return Envelop|null */ - public function toMail(Model $notifiable): ?Message + public function toMail(Model $notifiable): ?Envelop { - return (new Message()); + return (new Envelop()); } /** diff --git a/src/Mail/Contracts/MailDriverInterface.php b/src/Mail/Contracts/MailDriverInterface.php index e3640aef..99eacde0 100644 --- a/src/Mail/Contracts/MailDriverInterface.php +++ b/src/Mail/Contracts/MailDriverInterface.php @@ -4,15 +4,15 @@ namespace Bow\Mail\Contracts; -use Bow\Mail\Message; +use Bow\Mail\Envelop; interface MailDriverInterface { /** * Send mail by any driver * - * @param Message $message + * @param Envelop $envelop * @return bool */ - public function send(Message $message): bool; + public function send(Envelop $envelop): bool; } diff --git a/src/Mail/Driver/NativeDriver.php b/src/Mail/Driver/NativeDriver.php index 1732ab35..1c2e6e36 100644 --- a/src/Mail/Driver/NativeDriver.php +++ b/src/Mail/Driver/NativeDriver.php @@ -6,7 +6,7 @@ use Bow\Mail\Contracts\MailDriverInterface; use Bow\Mail\Exception\MailException; -use Bow\Mail\Message; +use Bow\Mail\Envelop; use InvalidArgumentException; class NativeDriver implements MailDriverInterface @@ -35,7 +35,7 @@ public function __construct(array $config = []) $this->config = $config; if (count($config) > 0) { - $this->from = $this->config["froms"][$config["default"]]; + $this->from = $this->config["from"][$config["default"]]; } } @@ -63,30 +63,30 @@ public function on(string $from): NativeDriver /** * Implement send email * - * @param Message $message + * @param Envelop $envelop * @return bool * @throws InvalidArgumentException */ - public function send(Message $message): bool + public function send(Envelop $envelop): bool { - if (empty($message->getTo()) || empty($message->getSubject()) || empty($message->getMessage())) { + if (empty($envelop->getTo()) || empty($envelop->getSubject()) || empty($envelop->getMessage())) { throw new InvalidArgumentException( - "An error has occurred. The sender or the message or object omits.", + "An error has occurred. The sender or the env$envelop or object omits.", E_USER_ERROR ); } - if (!$message->fromIsDefined()) { + if (!$envelop->fromIsDefined()) { if (isset($this->from["address"])) { - $message->from($this->from["address"], $this->from["name"] ?? null); + $envelop->from($this->from["address"], $this->from["name"] ?? null); } } $to = ''; - $message->setDefaultHeader(); + $envelop->setDefaultHeader(); - foreach ($message->getTo() as $value) { + foreach ($envelop->getTo() as $value) { if ($value[0] !== null) { $to .= $value[0] . ' <' . $value[1] . '>'; } else { @@ -94,13 +94,13 @@ public function send(Message $message): bool } } - $headers = $message->compileHeaders(); + $headers = $envelop->compileHeaders(); - $headers .= 'Content-Type: ' . $message->getType() . '; charset=' . $message->getCharset() . Message::END; - $headers .= 'Content-Transfer-Encoding: 8bit' . Message::END; + $headers .= 'Content-Type: ' . $envelop->getType() . '; charset=' . $envelop->getCharset() . Envelop::END; + $headers .= 'Content-Transfer-Encoding: 8bit' . Envelop::END; // Send email use the php native function - $status = @mail($to, $message->getSubject(), $message->getMessage(), $headers); + $status = @mail($to, $envelop->getSubject(), $envelop->getMessage(), $headers); return (bool)$status; } diff --git a/src/Mail/Driver/SesDriver.php b/src/Mail/Driver/SesDriver.php index f1cd05ef..53c6b184 100644 --- a/src/Mail/Driver/SesDriver.php +++ b/src/Mail/Driver/SesDriver.php @@ -6,7 +6,7 @@ use Aws\Ses\SesClient; use Bow\Mail\Contracts\MailDriverInterface; -use Bow\Mail\Message; +use Bow\Mail\Envelop; class SesDriver implements MailDriverInterface { @@ -52,37 +52,37 @@ public function initializeSesClient(): SesClient } /** - * Send message + * Send env$envelop * - * @param Message $message + * @param Envelop $envelop * @return bool */ - public function send(Message $message): bool + public function send(Envelop $envelop): bool { $body = []; - if ($message->getType() == "text/html") { + if ($envelop->getType() == "text/html") { $type = "Html"; } else { $type = "Text"; } $body[$type] = [ - 'Charset' => $message->getCharset(), - 'Data' => $message->getMessage(), + 'Charset' => $envelop->getCharset(), + 'Data' => $envelop->getMessage(), ]; $subject = [ - 'Charset' => $message->getCharset(), - 'Data' => $message->getSubject(), + 'Charset' => $envelop->getCharset(), + 'Data' => $envelop->getSubject(), ]; $email = [ 'Destination' => [ - 'ToAddresses' => $message->getTo(), + 'ToAddresses' => $envelop->getTo(), ], - 'Source' => $message->getFrom(), - 'Message' => [ + 'Source' => $envelop->getFrom(), + 'Envelop' => [ 'Body' => $body, 'Subject' => $subject, ], diff --git a/src/Mail/Driver/SmtpDriver.php b/src/Mail/Driver/SmtpDriver.php index 550faf3c..1b553cb0 100644 --- a/src/Mail/Driver/SmtpDriver.php +++ b/src/Mail/Driver/SmtpDriver.php @@ -7,9 +7,8 @@ use Bow\Mail\Contracts\MailDriverInterface; use Bow\Mail\Exception\SmtpException; use Bow\Mail\Exception\SocketException; -use Bow\Mail\Message; +use Bow\Mail\Envelop; use ErrorException; -use resource; class SmtpDriver implements MailDriverInterface { @@ -96,25 +95,25 @@ public function __construct(array $config) /** * Start sending mail * - * @param Message $message + * @param Envelop $envelop * @return bool * @throws SocketException * @throws ErrorException */ - public function send(Message $message): bool + public function send(Envelop $envelop): bool { $this->connection(); $error = true; // SMTP command - if ($message->getFrom() !== null) { - $this->write('MAIL FROM: <' . $message->getFrom() . '>', 250); + if ($envelop->getFrom() !== null) { + $this->write('MAIL FROM: <' . $envelop->getFrom() . '>', 250); } elseif ($this->username !== null) { $this->write('MAIL FROM: <' . $this->username . '>', 250); } - foreach ($message->getTo() as $value) { + foreach ($envelop->getTo() as $value) { if ($value[0] !== null) { $to = $value[0] . '<' . $value[1] . '>'; } else { @@ -124,15 +123,15 @@ public function send(Message $message): bool $this->write('RCPT TO: ' . $to, 250); } - $message->setDefaultHeader(); + $envelop->setDefaultHeader(); $this->write('DATA', 354); - $data = 'Subject: ' . $message->getSubject() . Message::END; - $data .= $message->compileHeaders(); - $data .= 'Content-Type: ' . $message->getType() . '; charset=' . $message->getCharset() . Message::END; - $data .= 'Content-Transfer-Encoding: 8bit' . Message::END; - $data .= Message::END . $message->getMessage() . Message::END; + $data = 'Subject: ' . $envelop->getSubject() . Envelop::END; + $data .= $envelop->compileHeaders(); + $data .= 'Content-Type: ' . $envelop->getType() . '; charset=' . $envelop->getCharset() . Envelop::END; + $data .= 'Content-Transfer-Encoding: 8bit' . Envelop::END; + $data .= Envelop::END . $envelop->getMessage() . Envelop::END; $this->write($data); @@ -243,17 +242,17 @@ private function read(): int * * @param string $command * @param ?int $code - * @param ?string $message + * @param ?string $envelop * @return int|null * @throws SmtpException */ - private function write(string $command, ?int $code = null, ?string $message = null): ?int + private function write(string $command, ?int $code = null, ?string $envelop = null): ?int { - if ($message == null) { - $message = $command; + if ($envelop == null) { + $envelop = $command; } - $command = $command . Message::END; + $command = $command . Envelop::END; fwrite($this->sock, $command, strlen($command)); @@ -267,7 +266,7 @@ private function write(string $command, ?int $code = null, ?string $message = nu if (!in_array($response, (array)$code)) { throw new SmtpException( - sprintf('SMTP server did not accept %s with code [%s]', $message, $response), + sprintf('SMTP server did not accept %s with code [%s]', $envelop, $response), E_ERROR ); } diff --git a/src/Mail/Message.php b/src/Mail/Envelop.php similarity index 89% rename from src/Mail/Message.php rename to src/Mail/Envelop.php index ab32aaaa..0f602f8c 100644 --- a/src/Mail/Message.php +++ b/src/Mail/Envelop.php @@ -8,7 +8,7 @@ use Bow\Support\Str; use InvalidArgumentException; -class Message +class Envelop { /** * The mail end of line @@ -88,7 +88,7 @@ class Message private bool $fromDefined = false; /** - * Message Constructor. + * Envelop Constructor. * * @param bool $boundary */ @@ -144,9 +144,9 @@ public function addHeader(string $key, string $value): void * @param string $to * @param ?string $name * - * @return Message + * @return Envelop */ - public function to(string $to, ?string $name = null): Message + public function to(string $to, ?string $name = null): Envelop { $this->to[] = $this->formatEmail($to, $name); @@ -184,7 +184,7 @@ private function formatEmail(string $email, ?string $name = null): array * @param array $recipients * @return $this */ - public function toList(array $recipients): Message + public function toList(array $recipients): Envelop { foreach ($recipients as $name => $to) { $this->to[] = $this->formatEmail($to, !is_int($name) ? $name : null); @@ -197,10 +197,10 @@ public function toList(array $recipients): Message * Add an attachment file * * @param string $file - * @return Message + * @return Envelop * @throws MailException */ - public function addFile(string $file): Message + public function addFile(string $file): Envelop { if (!is_file($file)) { throw new MailException("The $file file was not found.", E_USER_ERROR); @@ -240,9 +240,9 @@ public function compileHeaders(): string * Define the subject of the mail * * @param string $subject - * @return Message + * @return Envelop */ - public function subject(string $subject): Message + public function subject(string $subject): Envelop { $this->subject = $subject; @@ -254,9 +254,9 @@ public function subject(string $subject): Message * * @param string $from * @param ?string $name - * @return Message + * @return Envelop */ - public function from(string $from, ?string $name = null): Message + public function from(string $from, ?string $name = null): Envelop { $this->from = ($name !== null) ? (ucwords($name) . " <{$from}>") : $from; @@ -267,9 +267,9 @@ public function from(string $from, ?string $name = null): Message * Define the type of content in text/html * * @param string $html - * @return Message + * @return Envelop */ - public function html(string $html): Message + public function html(string $html): Envelop { return $this->type($html, "text/html"); } @@ -279,9 +279,9 @@ public function html(string $html): Message * * @param string $message * @param string $type - * @return Message + * @return Envelop */ - private function type(string $message, string $type): Message + private function type(string $message, string $type): Envelop { $this->type = $type; @@ -294,9 +294,9 @@ private function type(string $message, string $type): Message * Add message body * * @param string $text - * @return Message + * @return Envelop */ - public function text(string $text): Message + public function text(string $text): Envelop { $this->type($text, "text/plain"); @@ -309,9 +309,9 @@ public function text(string $text): Message * @param string $mail * @param ?string $name * - * @return Message + * @return Envelop */ - public function addBcc(string $mail, ?string $name = null): Message + public function addBcc(string $mail, ?string $name = null): Envelop { $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; @@ -326,9 +326,9 @@ public function addBcc(string $mail, ?string $name = null): Message * @param string $mail * @param ?string $name * - * @return Message + * @return Envelop */ - public function addCc(string $mail, ?string $name = null): Message + public function addCc(string $mail, ?string $name = null): Envelop { $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; @@ -342,9 +342,9 @@ public function addCc(string $mail, ?string $name = null): Message * * @param string $mail * @param ?string $name - * @return Message + * @return Envelop */ - public function addReplyTo(string $mail, ?string $name = null): Message + public function addReplyTo(string $mail, ?string $name = null): Envelop { $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; @@ -359,9 +359,9 @@ public function addReplyTo(string $mail, ?string $name = null): Message * @param string $mail * @param ?string $name = null * - * @return Message + * @return Envelop */ - public function addReturnPath(string $mail, ?string $name = null): Message + public function addReturnPath(string $mail, ?string $name = null): Envelop { $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; @@ -375,9 +375,9 @@ public function addReturnPath(string $mail, ?string $name = null): Message * * @param int $priority * - * @return Message + * @return Envelop */ - public function addPriority(int $priority): Message + public function addPriority(int $priority): Envelop { $this->headers[] = "X-Priority: " . (int)$priority; @@ -387,7 +387,7 @@ public function addPriority(int $priority): Message /** * @param string $message * @param string $type - * @see setMessage + * @see setEnvelop */ public function message(string $message, string $type = 'text/html'): void { @@ -494,7 +494,7 @@ public function fromIsDefined(): bool * @param array $data * @return $this */ - public function view(string $view, array $data = []): Message + public function view(string $view, array $data = []): Envelop { $this->message(view($view, $data)->getContent()); diff --git a/src/Mail/Mail.php b/src/Mail/Mail.php index 635f502d..64197c8c 100644 --- a/src/Mail/Mail.php +++ b/src/Mail/Mail.php @@ -117,15 +117,15 @@ public static function raw(string|array $to, string $subject, string $data, arra { $to = (array)$to; - $message = new Message(); + $envelop = new Envelop(); - $message->toList($to)->subject($subject)->setMessage($data); + $envelop->toList($to)->subject($subject)->setMessage($data); foreach ($headers as $key => $value) { - $message->addHeader($key, $value); + $envelop->addHeader($key, $value); } - return static::$instance->send($message); + return static::$instance->send($envelop); } /** @@ -145,16 +145,16 @@ public static function send(string $view, callable|array $data, ?callable $cb = $content = View::parse($view, $data)->getContent(); - $message = new Message(); - $message->setMessage($content); + $envelop = new Envelop(); + $envelop->setMessage($content); - call_user_func_array($cb, [$message]); + call_user_func_array($cb, [$envelop]); - return static::$instance->send($message); + return static::$instance->send($envelop); } /** - * Send message on queue + * Send env on queue * * @param string $template * @param array $data @@ -163,17 +163,17 @@ public static function send(string $view, callable|array $data, ?callable $cb = */ public static function queue(string $template, array $data, callable $cb): void { - $message = new Message(); + $envelop = new Envelop(); - call_user_func_array($cb, [$message]); + call_user_func_array($cb, [$envelop]); - $producer = new MailQueueProducer($template, $data, $message); + $producer = new MailQueueProducer($template, $data, $envelop); queue($producer); } /** - * Send message on specific queue + * Send env on specific queue * * @param string $queue * @param string $template @@ -183,11 +183,11 @@ public static function queue(string $template, array $data, callable $cb): void */ public static function queueOn(string $queue, string $template, array $data, callable $cb): void { - $message = new Message(); + $envelop = new Envelop(); - call_user_func_array($cb, [$message]); + call_user_func_array($cb, [$envelop]); - $producer = new MailQueueProducer($template, $data, $message); + $producer = new MailQueueProducer($template, $data, $envelop); $producer->setQueue($queue); @@ -205,11 +205,11 @@ public static function queueOn(string $queue, string $template, array $data, cal */ public static function later(int $delay, string $template, array $data, callable $cb): void { - $message = new Message(); + $envelop = new Envelop(); - call_user_func_array($cb, [$message]); + call_user_func_array($cb, [$envelop]); - $producer = new MailQueueProducer($template, $data, $message); + $producer = new MailQueueProducer($template, $data, $envelop); $producer->setDelay($delay); @@ -228,11 +228,11 @@ public static function later(int $delay, string $template, array $data, callable */ public static function laterOn(int $delay, string $queue, string $template, array $data, callable $cb): void { - $message = new Message(); + $envelop = new Envelop(); - call_user_func_array($cb, [$message]); + call_user_func_array($cb, [$envelop]); - $producer = new MailQueueProducer($template, $data, $message); + $producer = new MailQueueProducer($template, $data, $envelop); $producer->setQueue($queue); $producer->setDelay($delay); diff --git a/src/Mail/MailQueueProducer.php b/src/Mail/MailQueueProducer.php index 7e3f9ada..ba061b94 100644 --- a/src/Mail/MailQueueProducer.php +++ b/src/Mail/MailQueueProducer.php @@ -20,19 +20,19 @@ class MailQueueProducer extends ProducerService * * @param string $view * @param array $data - * @param Message $message + * @param Envelop $message */ public function __construct( string $view, array $data, - Message $message + Envelop $envelop ) { parent::__construct(); $this->bags = [ "view" => $view, "data" => $data, - "message" => $message, + "envelop" => $envelop, ]; } @@ -43,13 +43,13 @@ public function __construct( */ public function process(): void { - $message = $this->bags["message"]; + $envelop = $this->bags["envelop"]; - $message->setMessage( + $envelop->setMessage( View::parse($this->bags["view"], $this->bags["data"])->getContent() ); - Mail::getInstance()->send($message); + Mail::getInstance()->send($envelop); } /** diff --git a/src/Messaging/Channel/DatabaseChannel.php b/src/Messaging/Channel/DatabaseChannel.php index 46ce8ed9..ac1bc25c 100644 --- a/src/Messaging/Channel/DatabaseChannel.php +++ b/src/Messaging/Channel/DatabaseChannel.php @@ -16,16 +16,16 @@ public function __construct( /** * Send the notification to database * - * @param Model $notifiable + * @param Model $context * @return void */ - public function send(Model $notifiable): void + public function send(Model $context): void { Database::table('notifications')->insert([ 'id' => str_uuid(), 'data' => $this->database['data'], - 'concern_id' => $notifiable->getKey(), - 'concern_type' => get_class($notifiable), + 'concern_id' => $context->getKey(), + 'concern_type' => get_class($context), 'type' => $this->database['type'], ]); } diff --git a/src/Messaging/Channel/MailChannel.php b/src/Messaging/Channel/MailChannel.php index b7afa4af..59f3638b 100644 --- a/src/Messaging/Channel/MailChannel.php +++ b/src/Messaging/Channel/MailChannel.php @@ -4,7 +4,7 @@ use Bow\Database\Barry\Model; use Bow\Mail\Mail; -use Bow\Mail\Message; +use Bow\Mail\Envelop; use Bow\Messaging\Contracts\ChannelInterface; class MailChannel implements ChannelInterface @@ -12,22 +12,22 @@ class MailChannel implements ChannelInterface /** * Set the configured message * - * @param Message $message + * @param Envelop $envelop * @return void */ public function __construct( - private readonly Message $message + private readonly Envelop $envelop ) { } /** * Send the notification to mail * - * @param Model $notifiable + * @param Model $context * @return void */ - public function send(Model $notifiable): void + public function send(Model $context): void { - Mail::getInstance()->send($this->message); + Mail::getInstance()->send($this->envelop); } } diff --git a/src/Messaging/Messaging.php b/src/Messaging/Messaging.php index ec88e539..7382bb68 100644 --- a/src/Messaging/Messaging.php +++ b/src/Messaging/Messaging.php @@ -3,7 +3,7 @@ namespace Bow\Messaging; use Bow\Database\Barry\Model; -use Bow\Mail\Message; +use Bow\Mail\Envelop; use Bow\Messaging\Channel\DatabaseChannel; use Bow\Messaging\Channel\MailChannel; @@ -22,21 +22,21 @@ abstract class Messaging /** * Send notification to mail * - * @param Model $notifiable + * @param Model $context * @return Message|null */ - public function toMail(Model $notifiable): ?Message + public function toMail(Model $context): ?Envelop { - return new Message(); + return null; } /** * Send notification to database * - * @param Model $notifiable + * @param Model $context * @return array */ - public function toDatabase(Model $notifiable): array + public function toDatabase(Model $context): array { return []; } @@ -44,28 +44,28 @@ public function toDatabase(Model $notifiable): array /** * Send notification to sms * - * @param Model $notifiable + * @param Model $context * @return array */ - public function toSms(Model $notifiable): array + public function toSms(Model $context): array { return []; } /** * Process the notification - * @param Model $notifiable + * @param Model $context * @return void */ - final function process(Model $notifiable): void + final function process(Model $context): void { - $channels = $this->channels($notifiable); + $channels = $this->channels($context); foreach ($channels as $channel) { if (array_key_exists($channel, $this->channels)) { - $result = $this->{"to" . ucfirst($channel)}($notifiable); + $result = $this->{"to" . ucfirst($channel)}($context); $target_channel = new $this->channels[$channel]($result); - $target_channel->send($notifiable); + $target_channel->send($context); } } } @@ -73,8 +73,8 @@ final function process(Model $notifiable): void /** * Returns the available channels to be used * - * @param Model $notifiable + * @param Model $context * @return array */ - abstract public function channels(Model $notifiable): array; + abstract public function channels(Model $context): array; } diff --git a/src/Messaging/MessagingQueueProducer.php b/src/Messaging/MessagingQueueProducer.php index 83683a45..a4610d98 100644 --- a/src/Messaging/MessagingQueueProducer.php +++ b/src/Messaging/MessagingQueueProducer.php @@ -18,18 +18,18 @@ class MessagingQueueProducer extends ProducerService /** * MessagingQueueProducer constructor * - * @param Model $notifiable + * @param Model $context * @param Messaging $message */ public function __construct( - Model $notifiable, + Model $context, Messaging $message, ) { parent::__construct(); $this->bags = [ "message" => $message, - "notifiable" => $notifiable, + "context" => $context, ]; } @@ -41,7 +41,7 @@ public function __construct( public function process(): void { $message = $this->bags['message']; - $message->process($this->bags['notifiable']); + $message->process($this->bags['context']); } /** diff --git a/tests/Messaging/MessagingTest.php b/tests/Messaging/MessagingTest.php new file mode 100644 index 00000000..879fd08c --- /dev/null +++ b/tests/Messaging/MessagingTest.php @@ -0,0 +1,150 @@ + 'sync', + 'connections' => [ + 'sync' => [ + 'driver' => 'sync' + ] + ] + ]); + } + + protected function setUp(): void + { + parent::setUp(); + + $this->context = $this->createMock(TestNotifiableModel::class); + $this->message = $this->createMock(TestMessage::class); + } + + public function test_can_send_message_synchronously(): void + { + $this->message->expects($this->once()) + ->method('process') + ->with($this->context); + + $this->context->sendMessage($this->message); + } + + public function test_can_send_message_to_queue(): void + { + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to queue and verify + static::$queueConnection->getAdapter()->push($producer); + + $this->context->setMessageQueue($this->message); + } + + public function test_can_send_message_to_specific_queue(): void + { + $queue = 'high-priority'; + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to specific queue and verify + $adapter = static::$queueConnection->getAdapter(); + $adapter->setQueue($queue); + $adapter->push($producer); + + $this->context->sendMessageQueueOn($queue, $this->message); + } + + public function test_can_send_message_with_delay(): void + { + $delay = 3600; + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to queue and verify + $adapter = static::$queueConnection->getAdapter(); + $adapter->setSleep($delay); + $adapter->push($producer); + + $this->context->sendMessageLater($delay, $this->message); + } + + public function test_can_send_message_with_delay_on_specific_queue(): void + { + $delay = 3600; + $queue = 'delayed-notifications'; + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to specific queue with delay and verify + $adapter = static::$queueConnection->getAdapter(); + $adapter->setQueue($queue); + $adapter->setSleep($delay); + $adapter->push($producer); + + $this->context->sendMessageLaterOn($delay, $queue, $this->message); + } + + public function test_message_sends_to_correct_channels(): void + { + $context = new TestNotifiableModel(); + $message = new TestMessage(); + + $channels = $message->channels($context); + + $this->assertEquals(['mail', 'database'], $channels); + } + + public function test_message_can_send_to_mail(): void + { + $context = new TestNotifiableModel(); + $message = new TestMessage(); + + $mailMessage = $message->toMail($context); + + $this->assertInstanceOf(Envelop::class, $mailMessage); + $this->assertEquals('test@example.com', $mailMessage->getTo()); + $this->assertEquals('Test Message', $mailMessage->getSubject()); + } + + public function test_message_can_send_to_database(): void + { + $context = new TestNotifiableModel(); + $message = new TestMessage(); + + $data = $message->toDatabase($context); + + $this->assertIsArray($data); + $this->assertArrayHasKey('type', $data); + $this->assertArrayHasKey('data', $data); + $this->assertEquals('test_message', $data['type']); + $this->assertEquals('Test message content', $data['data']['message']); + } +} diff --git a/tests/Messaging/Stubs/TestMessage.php b/tests/Messaging/Stubs/TestMessage.php new file mode 100644 index 00000000..fbb54b4e --- /dev/null +++ b/tests/Messaging/Stubs/TestMessage.php @@ -0,0 +1,33 @@ +to('test@example.com') + ->subject('Test Message') + ->view('test-view'); + } + + public function toDatabase(Model $context): array + { + return [ + 'type' => 'test_message', + 'data' => [ + 'message' => 'Test message content' + ] + ]; + } +} diff --git a/tests/Messaging/Stubs/TestNotifiableModel.php b/tests/Messaging/Stubs/TestNotifiableModel.php new file mode 100644 index 00000000..290d0330 --- /dev/null +++ b/tests/Messaging/Stubs/TestNotifiableModel.php @@ -0,0 +1,11 @@ + Date: Sun, 26 Jan 2025 00:15:13 +0000 Subject: [PATCH 02/10] feat: add log mail driver and memcached --- src/Mail/Driver/LogDriver.php | 65 ++++++++ src/Mail/Driver/SmtpDriver.php | 45 +++++- src/Mail/Security/DkimSigner.php | 146 ++++++++++++++++++ src/Mail/Security/SpfChecker.php | 255 +++++++++++++++++++++++++++++++ 4 files changed, 510 insertions(+), 1 deletion(-) create mode 100644 src/Mail/Driver/LogDriver.php create mode 100644 src/Mail/Security/DkimSigner.php create mode 100644 src/Mail/Security/SpfChecker.php diff --git a/src/Mail/Driver/LogDriver.php b/src/Mail/Driver/LogDriver.php new file mode 100644 index 00000000..d3f2f6c6 --- /dev/null +++ b/src/Mail/Driver/LogDriver.php @@ -0,0 +1,65 @@ +config = $config; + $this->path = $config['path']; + + if (!is_dir($this->path)) { + mkdir($this->path, 0755, true); + } + } + + /** + * Implement send email + * + * @param Envelop $envelop + * @return bool + */ + public function send(Envelop $envelop): bool + { + $filename = date('Y-m-d_H-i-s') . '_' . Str::random(6) . '.eml'; + $filepath = $this->path . '/' . $filename; + + $content = "Date: " . date('r') . "\n"; + $content .= $envelop->compileHeaders(); + + $content .= "To: " . implode(', ', array_map(function($to) { + return $to[0] ? "{$to[0]} <{$to[1]}>" : $to[1]; + }, $envelop->getTo())) . "\n"; + + $content .= "Subject: " . $envelop->getSubject() . "\n"; + $content .= $envelop->getMessage(); + + return (bool) file_put_contents($filepath, $content); + } +} diff --git a/src/Mail/Driver/SmtpDriver.php b/src/Mail/Driver/SmtpDriver.php index 1b553cb0..6963954b 100644 --- a/src/Mail/Driver/SmtpDriver.php +++ b/src/Mail/Driver/SmtpDriver.php @@ -9,6 +9,9 @@ use Bow\Mail\Exception\SocketException; use Bow\Mail\Envelop; use ErrorException; +use Bow\Mail\Security\DkimSigner; +use Bow\Mail\Security\SpfChecker; +use Bow\Mail\Exception\MailException; class SmtpDriver implements MailDriverInterface { @@ -68,6 +71,20 @@ class SmtpDriver implements MailDriverInterface */ private int $port = 25; + /** + * The DKIM signer + * + * @var ?DkimSigner + */ + private ?DkimSigner $dkimSigner = null; + + /** + * The SPF checker + * + * @var ?SpfChecker + */ + private ?SpfChecker $spfChecker = null; + /** * Smtp Constructor * @@ -90,6 +107,14 @@ public function __construct(array $config) $this->tls = (bool)$config['tls']; $this->timeout = (int)$config['timeout']; $this->port = (int)$config['port']; + + if (isset($config['dkim']) && $config['dkim']['enabled']) { + $this->dkimSigner = new DkimSigner($config['dkim']); + } + + if (isset($config['spf']) && $config['spf']['enabled']) { + $this->spfChecker = new SpfChecker($config['spf']); + } } /** @@ -102,6 +127,24 @@ public function __construct(array $config) */ public function send(Envelop $envelop): bool { + // Validate SPF if enabled + if ($this->spfChecker !== null) { + $senderIp = $_SERVER['REMOTE_ADDR'] ?? ''; + $senderEmail = $envelop->getFrom()[0][1] ?? ''; + $senderHelo = gethostname(); + + $spfResult = $this->spfChecker->verify($senderIp, $senderEmail, $senderHelo); + if ($spfResult === 'fail') { + throw new MailException('SPF verification failed'); + } + } + + // Add DKIM signature if enabled + if ($this->dkimSigner !== null) { + $dkimHeader = $this->dkimSigner->sign($envelop); + $envelop->addHeader('DKIM-Signature', $dkimHeader); + } + $this->connection(); $error = true; @@ -182,7 +225,7 @@ private function connection(): void // The client sends this command to the SMTP server to identify // itself and initiate the SMTP conversation. // The domain name or IP address of the SMTP client is usually sent as an argument - // together with the command (e.g. “EHLO client.example.com”). + // together with the command (e.g. "EHLO client.example.com"). $client_host = isset($_SERVER['HTTP_HOST']) && preg_match('/^[\w.-]+\z/', $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'; diff --git a/src/Mail/Security/DkimSigner.php b/src/Mail/Security/DkimSigner.php new file mode 100644 index 00000000..9208e47e --- /dev/null +++ b/src/Mail/Security/DkimSigner.php @@ -0,0 +1,146 @@ +config = $config; + } + + /** + * Sign the email with DKIM + * + * @param Envelop $envelop + * @return string + */ + public function sign(Envelop $envelop): string + { + $privateKey = $this->loadPrivateKey(); + $headers = $this->getHeadersToSign($envelop); + $bodyHash = $this->hashBody($envelop->getMessage()); + + $stringToSign = $this->buildSignatureString($headers, $bodyHash); + $signature = ''; + + openssl_sign($stringToSign, $signature, $privateKey, OPENSSL_ALGO_SHA256); + $signature = base64_encode($signature); + + return $this->buildDkimHeader($headers, $signature, $bodyHash); + } + + /** + * Load the private key + * + * @return mixed + */ + private function loadPrivateKey() + { + $keyPath = $this->config['private_key']; + $privateKey = file_get_contents($keyPath); + return openssl_pkey_get_private($privateKey); + } + + /** + * Get headers to sign + * + * @param Envelop $envelop + * @return array + */ + private function getHeadersToSign(Envelop $envelop): array + { + $headers = [ + 'From' => $envelop->getFrom(), + 'To' => $this->formatAddresses($envelop->getTo()), + 'Subject' => $envelop->getSubject(), + 'Date' => date('r'), + 'MIME-Version' => '1.0', + 'Content-Type' => $envelop->getType() . '; charset=' . $envelop->getCharset() + ]; + + return $headers; + } + + /** + * Format email addresses + * + * @param array $addresses + * @return string + */ + private function formatAddresses(array $addresses): string + { + return implode(', ', array_map(function($address) { + return $address[0] ? "{$address[0]} <{$address[1]}>" : $address[1]; + }, $addresses)); + } + + /** + * Hash the message body + * + * @param string $body + * @return string + */ + private function hashBody(string $body): string + { + // Canonicalize body according to DKIM rules + $body = preg_replace('/\r\n\s+/', ' ', $body); + $body = trim($body) . "\r\n"; + + return base64_encode(hash('sha256', $body, true)); + } + + /** + * Build the string to sign + * + * @param array $headers + * @param string $bodyHash + * @return string + */ + private function buildSignatureString(array $headers, string $bodyHash): string + { + $signedHeaderFields = array_keys($headers); + $dkimHeaders = []; + + foreach ($signedHeaderFields as $field) { + $dkimHeaders[] = strtolower($field) . ': ' . $headers[$field]; + } + + return implode("\r\n", $dkimHeaders) . "\r\n" . $bodyHash; + } + + /** + * Build the DKIM header + * + * @param array $headers + * @param string $signature + * @param string $bodyHash + * @return string + */ + private function buildDkimHeader(array $headers, string $signature, string $bodyHash): string + { + $domain = $this->config['domain']; + $selector = $this->config['selector']; + $signedHeaders = implode(':', array_map('strtolower', array_keys($headers))); + + return "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d={$domain}; s={$selector};\r\n" . + "\tt=". time() . "; bh={$bodyHash};\r\n" . + "\th={$signedHeaders}; b={$signature};"; + } +} diff --git a/src/Mail/Security/SpfChecker.php b/src/Mail/Security/SpfChecker.php new file mode 100644 index 00000000..24c73203 --- /dev/null +++ b/src/Mail/Security/SpfChecker.php @@ -0,0 +1,255 @@ +config = $config; + } + + /** + * Verify SPF record for a sender + * + * @param string $ip + * @param string $sender + * @param string $helo + * @return string + */ + public function verify(string $ip, string $sender, string $helo): string + { + $domain = $this->extractDomain($sender); + $spfRecord = $this->getSpfRecord($domain); + + if (!$spfRecord) { + return 'none'; + } + + $result = $this->evaluateSpf($spfRecord, $ip, $domain, $helo); + + return $result; + } + + /** + * Extract domain from email address + * + * @param string $email + * @return string + */ + private function extractDomain(string $email): string + { + return substr(strrchr($email, "@"), 1) ?: $email; + } + + /** + * Get SPF record for domain + * + * @param string $domain + * @return string|null + */ + private function getSpfRecord(string $domain): ?string + { + $records = dns_get_record($domain, DNS_TXT); + + foreach ($records as $record) { + if (strpos($record['txt'] ?? '', 'v=spf1') === 0) { + return $record['txt']; + } + } + + return null; + } + + /** + * Evaluate SPF record + * + * @param string $spfRecord + * @param string $ip + * @param string $domain + * @param string $helo + * @return string + */ + private function evaluateSpf(string $spfRecord, string $ip, string $domain, string $helo): string + { + $mechanisms = explode(' ', $spfRecord); + array_shift($mechanisms); // Remove v=spf1 + + foreach ($mechanisms as $mechanism) { + $result = $this->checkMechanism($mechanism, $ip, $domain, $helo); + if ($result !== null) { + return $result; + } + } + + return 'neutral'; + } + + /** + * Check SPF mechanism + * + * @param string $mechanism + * @param string $ip + * @param string $domain + * @param string $helo + * @return string|null + */ + private function checkMechanism(string $mechanism, string $ip, string $domain, string $helo): ?string + { + $qualifier = substr($mechanism, 0, 1); + if (in_array($qualifier, ['+', '-', '~', '?'])) { + $mechanism = substr($mechanism, 1); + } else { + $qualifier = '+'; + } + + if (str_starts_with($mechanism, 'ip4:')) { + return $this->checkIp4($mechanism, $ip, $qualifier); + } + + if (str_starts_with($mechanism, 'ip6:')) { + return $this->checkIp6($mechanism, $ip, $qualifier); + } + + if (str_starts_with($mechanism, 'a')) { + return $this->checkA($mechanism, $ip, $domain, $qualifier); + } + + if (str_starts_with($mechanism, 'mx')) { + return $this->checkMx($mechanism, $ip, $domain, $qualifier); + } + + if ($mechanism === 'all') { + return $this->getQualifierResult($qualifier); + } + + return null; + } + + /** + * Check IPv4 mechanism + * + * @param string $mechanism + * @param string $ip + * @param string $qualifier + * @return string|null + */ + private function checkIp4(string $mechanism, string $ip, string $qualifier): ?string + { + $range = substr($mechanism, 4); + if ($this->ipInRange($ip, $range)) { + return $this->getQualifierResult($qualifier); + } + return null; + } + + /** + * Check IPv6 mechanism + * + * @param string $mechanism + * @param string $ip + * @param string $qualifier + * @return string|null + */ + private function checkIp6(string $mechanism, string $ip, string $qualifier): ?string + { + $range = substr($mechanism, 4); + if ($this->ipInRange($ip, $range)) { + return $this->getQualifierResult($qualifier); + } + return null; + } + + /** + * Check if IP is in range + * + * @param string $ip + * @param string $range + * @return bool + */ + private function ipInRange(string $ip, string $range): bool + { + if (str_contains($range, '/')) { + [$subnet, $bits] = explode('/', $range); + $ip2long = ip2long($ip); + $subnet2long = ip2long($subnet); + $mask = -1 << (32 - $bits); + return ($ip2long & $mask) === ($subnet2long & $mask); + } + return $ip === $range; + } + + /** + * Check A record mechanism + * + * @param string $mechanism + * @param string $ip + * @param string $domain + * @param string $qualifier + * @return string|null + */ + private function checkA(string $mechanism, string $ip, string $domain, string $qualifier): ?string + { + $records = dns_get_record($domain, DNS_A); + foreach ($records as $record) { + if ($record['ip'] === $ip) { + return $this->getQualifierResult($qualifier); + } + } + return null; + } + + /** + * Check MX record mechanism + * + * @param string $mechanism + * @param string $ip + * @param string $domain + * @param string $qualifier + * @return string|null + */ + private function checkMx(string $mechanism, string $ip, string $domain, string $qualifier): ?string + { + $records = dns_get_record($domain, DNS_MX); + foreach ($records as $record) { + $aRecords = dns_get_record($record['target'], DNS_A); + foreach ($aRecords as $aRecord) { + if ($aRecord['ip'] === $ip) { + return $this->getQualifierResult($qualifier); + } + } + } + return null; + } + + /** + * Get result based on qualifier + * + * @param string $qualifier + * @return string + */ + private function getQualifierResult(string $qualifier): string + { + return match($qualifier) { + '+' => 'pass', + '-' => 'fail', + '~' => 'softfail', + '?' => 'neutral', + default => 'neutral' + }; + } +} From fdd525cfde2aaf6840e639bfbdb5a26baae6b09e Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sun, 26 Jan 2025 01:06:16 +0000 Subject: [PATCH 03/10] refactor: update the messaging sending approach --- composer.json | 3 +- src/Mail/Driver/LogDriver.php | 6 +- src/Mail/Security/DkimSigner.php | 14 +-- src/Mail/Security/SpfChecker.php | 6 +- src/Messaging/Channel/DatabaseChannel.php | 17 ++- src/Messaging/Channel/MailChannel.php | 25 ++--- src/Messaging/Channel/SlackChannel.php | 50 +++++++++ src/Messaging/Channel/SmsChannel.php | 90 ++++++++++++++++ src/Messaging/Channel/TelegramChannel.php | 65 ++++++++++++ src/Messaging/Contracts/ChannelInterface.php | 8 +- src/Messaging/Messaging.php | 56 ++++++++-- src/Messaging/README.md | 100 ++++++++++++++++++ tests/Messaging/MessagingTest.php | 70 +++++++++--- tests/Messaging/Stubs/TestMessage.php | 31 +++++- tests/Messaging/Stubs/TestNotifiableModel.php | 2 +- 15 files changed, 483 insertions(+), 60 deletions(-) create mode 100644 src/Messaging/Channel/SlackChannel.php create mode 100644 src/Messaging/Channel/SmsChannel.php create mode 100644 src/Messaging/Channel/TelegramChannel.php create mode 100644 src/Messaging/README.md diff --git a/composer.json b/composer.json index 6ceecc82..5335f4f9 100644 --- a/composer.json +++ b/composer.json @@ -34,7 +34,8 @@ "bowphp/policier": "^3.0", "mockery/mockery": "^1.5", "spatie/phpunit-snapshot-assertions": "^4.2", - "predis/predis": "^2.1" + "predis/predis": "^2.1", + "twilio/sdk": "^8.3" }, "authors": [ { diff --git a/src/Mail/Driver/LogDriver.php b/src/Mail/Driver/LogDriver.php index d3f2f6c6..63a47149 100644 --- a/src/Mail/Driver/LogDriver.php +++ b/src/Mail/Driver/LogDriver.php @@ -52,8 +52,8 @@ public function send(Envelop $envelop): bool $content = "Date: " . date('r') . "\n"; $content .= $envelop->compileHeaders(); - - $content .= "To: " . implode(', ', array_map(function($to) { + + $content .= "To: " . implode(', ', array_map(function ($to) { return $to[0] ? "{$to[0]} <{$to[1]}>" : $to[1]; }, $envelop->getTo())) . "\n"; @@ -62,4 +62,4 @@ public function send(Envelop $envelop): bool return (bool) file_put_contents($filepath, $content); } -} +} diff --git a/src/Mail/Security/DkimSigner.php b/src/Mail/Security/DkimSigner.php index 9208e47e..cac1b3cf 100644 --- a/src/Mail/Security/DkimSigner.php +++ b/src/Mail/Security/DkimSigner.php @@ -36,13 +36,13 @@ public function sign(Envelop $envelop): string $privateKey = $this->loadPrivateKey(); $headers = $this->getHeadersToSign($envelop); $bodyHash = $this->hashBody($envelop->getMessage()); - + $stringToSign = $this->buildSignatureString($headers, $bodyHash); $signature = ''; - + openssl_sign($stringToSign, $signature, $privateKey, OPENSSL_ALGO_SHA256); $signature = base64_encode($signature); - + return $this->buildDkimHeader($headers, $signature, $bodyHash); } @@ -86,7 +86,7 @@ private function getHeadersToSign(Envelop $envelop): array */ private function formatAddresses(array $addresses): string { - return implode(', ', array_map(function($address) { + return implode(', ', array_map(function ($address) { return $address[0] ? "{$address[0]} <{$address[1]}>" : $address[1]; }, $addresses)); } @@ -102,7 +102,7 @@ private function hashBody(string $body): string // Canonicalize body according to DKIM rules $body = preg_replace('/\r\n\s+/', ' ', $body); $body = trim($body) . "\r\n"; - + return base64_encode(hash('sha256', $body, true)); } @@ -140,7 +140,7 @@ private function buildDkimHeader(array $headers, string $signature, string $body $signedHeaders = implode(':', array_map('strtolower', array_keys($headers))); return "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d={$domain}; s={$selector};\r\n" . - "\tt=". time() . "; bh={$bodyHash};\r\n" . + "\tt=" . time() . "; bh={$bodyHash};\r\n" . "\th={$signedHeaders}; b={$signature};"; } -} +} diff --git a/src/Mail/Security/SpfChecker.php b/src/Mail/Security/SpfChecker.php index 24c73203..32b2e602 100644 --- a/src/Mail/Security/SpfChecker.php +++ b/src/Mail/Security/SpfChecker.php @@ -65,7 +65,7 @@ private function extractDomain(string $email): string private function getSpfRecord(string $domain): ?string { $records = dns_get_record($domain, DNS_TXT); - + foreach ($records as $record) { if (strpos($record['txt'] ?? '', 'v=spf1') === 0) { return $record['txt']; @@ -244,7 +244,7 @@ private function checkMx(string $mechanism, string $ip, string $domain, string $ */ private function getQualifierResult(string $qualifier): string { - return match($qualifier) { + return match ($qualifier) { '+' => 'pass', '-' => 'fail', '~' => 'softfail', @@ -252,4 +252,4 @@ private function getQualifierResult(string $qualifier): string default => 'neutral' }; } -} +} diff --git a/src/Messaging/Channel/DatabaseChannel.php b/src/Messaging/Channel/DatabaseChannel.php index ac1bc25c..03ace22a 100644 --- a/src/Messaging/Channel/DatabaseChannel.php +++ b/src/Messaging/Channel/DatabaseChannel.php @@ -2,8 +2,9 @@ namespace Bow\Messaging\Channel; -use Bow\Database\Barry\Model; use Bow\Database\Database; +use Bow\Messaging\Messaging; +use Bow\Database\Barry\Model; use Bow\Messaging\Contracts\ChannelInterface; class DatabaseChannel implements ChannelInterface @@ -17,16 +18,22 @@ public function __construct( * Send the notification to database * * @param Model $context - * @return void + * @param Messaging $message */ - public function send(Model $context): void + public function send(Model $context, Messaging $message): void { + if (!method_exists($message, 'toDatabase')) { + return; + } + + $database = $message->toDatabase($context); + Database::table('notifications')->insert([ 'id' => str_uuid(), - 'data' => $this->database['data'], + 'data' => $database['data'], 'concern_id' => $context->getKey(), 'concern_type' => get_class($context), - 'type' => $this->database['type'], + 'type' => $database['type'], ]); } } diff --git a/src/Messaging/Channel/MailChannel.php b/src/Messaging/Channel/MailChannel.php index 59f3638b..febf8902 100644 --- a/src/Messaging/Channel/MailChannel.php +++ b/src/Messaging/Channel/MailChannel.php @@ -2,32 +2,29 @@ namespace Bow\Messaging\Channel; -use Bow\Database\Barry\Model; use Bow\Mail\Mail; use Bow\Mail\Envelop; +use Bow\Messaging\Messaging; +use Bow\Database\Barry\Model; use Bow\Messaging\Contracts\ChannelInterface; class MailChannel implements ChannelInterface { - /** - * Set the configured message - * - * @param Envelop $envelop - * @return void - */ - public function __construct( - private readonly Envelop $envelop - ) { - } - /** * Send the notification to mail * * @param Model $context + * @param Messaging $message * @return void */ - public function send(Model $context): void + public function send(Model $context, Messaging $message): void { - Mail::getInstance()->send($this->envelop); + if (!method_exists($message, 'toMail')) { + return; + } + + $envelop = $message->toMail($context); + + Mail::getInstance()->send($envelop); } } diff --git a/src/Messaging/Channel/SlackChannel.php b/src/Messaging/Channel/SlackChannel.php new file mode 100644 index 00000000..2157575a --- /dev/null +++ b/src/Messaging/Channel/SlackChannel.php @@ -0,0 +1,50 @@ +toSlack($context); + + if (!isset($data['content'])) { + throw new \InvalidArgumentException('The content are required for Slack'); + } + + $webhook_url = $data['webhook_url'] ?? config('messaging.slack.webhook_url'); + + if (empty($webhook_url)) { + throw new \InvalidArgumentException('The webhook URL is required for Slack'); + } + + $client = new Client(); + + try { + $client->post($webhook_url, [ + 'json' => $data['content'], + 'headers' => [ + 'Content-Type' => 'application/json' + ] + ]); + } catch (\Exception $e) { + throw new \RuntimeException('Error while sending Slack message: ' . $e->getMessage()); + } + } +} diff --git a/src/Messaging/Channel/SmsChannel.php b/src/Messaging/Channel/SmsChannel.php new file mode 100644 index 00000000..c424414d --- /dev/null +++ b/src/Messaging/Channel/SmsChannel.php @@ -0,0 +1,90 @@ +from_number = config('messaging.twilio.from'); + + if (!$account_sid || !$auth_token || !$this->from_number) { + throw new \InvalidArgumentException('Twilio credentials are required'); + } + + $this->client = new Client($account_sid, $auth_token); + } + + /** + * Send message via SMS + * + * @param Model $context + * @param Messaging $message + * @return void + */ + public function send(Model $context, Messaging $message): void + { + if (!method_exists($message, 'toSms')) { + return; + } + + $this->sendWithTwilio($context, $message); + } + + /** + * Send the message via SMS using Twilio + * + * @param Model $context + * @param Messaging $message + * @return void + */ + private function sendWithTwilio(Model $context, Messaging $message): void + { + $data = $message->toSms($context); + + $account_sid = config('messaging.twilio.account_sid'); + $auth_token = config('messaging.twilio.auth_token'); + $this->from_number = config('messaging.twilio.from'); + + if (!$account_sid || !$auth_token || !$this->from_number) { + throw new \InvalidArgumentException('Twilio credentials are required'); + } + + $this->client = new Client($account_sid, $auth_token); + + if (!isset($data['to']) || !isset($data['message'])) { + throw new \InvalidArgumentException('The phone number and message are required'); + } + + try { + $this->client->messages->create($data['to'], [ + 'from' => $this->from_number, + 'body' => $data['message'] + ]); + } catch (\Exception $e) { + throw new \RuntimeException('Error while sending SMS: ' . $e->getMessage()); + } + } +} diff --git a/src/Messaging/Channel/TelegramChannel.php b/src/Messaging/Channel/TelegramChannel.php new file mode 100644 index 00000000..e3f60d35 --- /dev/null +++ b/src/Messaging/Channel/TelegramChannel.php @@ -0,0 +1,65 @@ +botToken = config('messaging.telegram.bot_token'); + + if (!$this->botToken) { + throw new \InvalidArgumentException('The Telegram bot token is required'); + } + } + + /** + * Envoyer le message via Telegram + * + * @param Model $context + * @param Messaging $message + * @return void + */ + public function send(Model $context, Messaging $message): void + { + if (!method_exists($message, 'toTelegram')) { + return; + } + + $data = $message->toTelegram($context); + + if (!isset($data['chat_id']) || !isset($data['message'])) { + throw new \InvalidArgumentException('The chat ID and message are required for Telegram'); + } + + $client = new Client(); + $endpoint = "https://api.telegram.org/bot{$this->botToken}/sendMessage"; + + try { + $client->post($endpoint, [ + 'json' => [ + 'chat_id' => $data['chat_id'], + 'text' => $data['message'], + 'parse_mode' => $data['parse_mode'] ?? 'HTML' + ] + ]); + } catch (\Exception $e) { + throw new \RuntimeException('Error while sending Telegram message: ' . $e->getMessage()); + } + } +} diff --git a/src/Messaging/Contracts/ChannelInterface.php b/src/Messaging/Contracts/ChannelInterface.php index 80c504d7..e41ab325 100644 --- a/src/Messaging/Contracts/ChannelInterface.php +++ b/src/Messaging/Contracts/ChannelInterface.php @@ -2,15 +2,17 @@ namespace Bow\Messaging\Contracts; +use Bow\Messaging\Messaging; use Bow\Database\Barry\Model; interface ChannelInterface { /** - * Send the notification + * Send a message through the channel * - * @param Model $notifiable + * @param Model $context + * @param Messaging $message * @return void */ - public function send(Model $notifiable): void; + public function send(Model $context, Messaging $message): void; } diff --git a/src/Messaging/Messaging.php b/src/Messaging/Messaging.php index 7382bb68..7172028a 100644 --- a/src/Messaging/Messaging.php +++ b/src/Messaging/Messaging.php @@ -2,10 +2,13 @@ namespace Bow\Messaging; -use Bow\Database\Barry\Model; use Bow\Mail\Envelop; -use Bow\Messaging\Channel\DatabaseChannel; +use Bow\Database\Barry\Model; +use Bow\Messaging\Channel\SmsChannel; use Bow\Messaging\Channel\MailChannel; +use Bow\Messaging\Channel\SlackChannel; +use Bow\Messaging\Channel\DatabaseChannel; +use Bow\Messaging\Channel\TelegramChannel; abstract class Messaging { @@ -14,16 +17,32 @@ abstract class Messaging * * @var array */ - private array $channels = [ + private static array $channels = [ "mail" => MailChannel::class, "database" => DatabaseChannel::class, + "telegram" => TelegramChannel::class, + "slack" => SlackChannel::class, + "sms" => SmsChannel::class, ]; + /** + * Push channels to the messaging + * + * @param array $channels + * @return array + */ + public static function pushChannels(array $channels): array + { + static::$channels = array_merge(static::$channels, $channels); + + return self::$channels; + } + /** * Send notification to mail * * @param Model $context - * @return Message|null + * @return Envelop|null */ public function toMail(Model $context): ?Envelop { @@ -45,13 +64,35 @@ public function toDatabase(Model $context): array * Send notification to sms * * @param Model $context - * @return array + * @return array{to: string, message: string} */ public function toSms(Model $context): array { return []; } + /** + * Send notification to slack + * + * @param Model $context + * @return array{webhook_url: ?string, content: array} + */ + public function toSlack(Model $context): array + { + return []; + } + + /** + * Send notification to telegram + * + * @param Model $context + * @return array{message: string, chat_id: string, parse_mode: string} + */ + public function toTelegram(Model $context): array + { + return []; + } + /** * Process the notification * @param Model $context @@ -62,9 +103,8 @@ final function process(Model $context): void $channels = $this->channels($context); foreach ($channels as $channel) { - if (array_key_exists($channel, $this->channels)) { - $result = $this->{"to" . ucfirst($channel)}($context); - $target_channel = new $this->channels[$channel]($result); + if (array_key_exists($channel, static::$channels)) { + $target_channel = new static::$channels[$channel](); $target_channel->send($context); } } diff --git a/src/Messaging/README.md b/src/Messaging/README.md new file mode 100644 index 00000000..92943bfa --- /dev/null +++ b/src/Messaging/README.md @@ -0,0 +1,100 @@ +# Bow Framework - Messaging System + +Le système de messaging de Bow Framework permet d'envoyer des notifications à travers différents canaux (email, base de données, etc.) de manière simple et flexible. + +## Utilisation basique + +### 1. Créer un Message + +```php +to($context->email) + ->subject('Bienvenue sur notre plateforme') + ->view('emails.welcome', [ + 'user' => $context + ]); + } + + /** + * Configuration du message pour la sauvegarde en base de données + */ + public function toDatabase(Model $context): array + { + return [ + 'type' => 'welcome_message', + 'data' => [ + 'user_id' => $context->id, + 'message' => 'Bienvenue sur notre plateforme !' + ] + ]; + } +} +``` + +### 2. Envoyer un Message + +```php +// Envoi synchrone +$user->sendMessage(new WelcomeMessage()); + +// Envoi asynchrone (file d'attente) +$user->setMessageQueue(new WelcomeMessage()); + +// Envoi différé +$user->sendMessageLater(3600, new WelcomeMessage()); // Délai en secondes + +// Envoi sur une file d'attente spécifique +$user->sendMessageQueueOn('high-priority', new WelcomeMessage()); +``` + +## Configuration + +Pour utiliser le système de messaging, assurez-vous que votre modèle implémente le trait `CanSendMessage` : + +```php +use Bow\Messaging\Message; +use Bow\Database\Barry\Model; + +class User extends Model +{ + use CanSendMessage; + + // ... +} +``` + +## Canaux disponibles + +- `mail` : Envoi par email +- `database` : Stockage en base de données +- Possibilité d'ajouter des canaux personnalisés + +## Bonnes pratiques + +1. Créez un message par type de notification +2. Utilisez les files d'attente pour les notifications non urgentes +3. Personnalisez les canaux en fonction du contexte +4. Utilisez les vues pour les templates d'emails diff --git a/tests/Messaging/MessagingTest.php b/tests/Messaging/MessagingTest.php index 879fd08c..e283961c 100644 --- a/tests/Messaging/MessagingTest.php +++ b/tests/Messaging/MessagingTest.php @@ -52,13 +52,13 @@ public function test_can_send_message_synchronously(): void public function test_can_send_message_to_queue(): void { $producer = new MessagingQueueProducer($this->context, $this->message); - + // Verify that the producer is created with correct parameters $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - + // Push to queue and verify static::$queueConnection->getAdapter()->push($producer); - + $this->context->setMessageQueue($this->message); } @@ -66,15 +66,15 @@ public function test_can_send_message_to_specific_queue(): void { $queue = 'high-priority'; $producer = new MessagingQueueProducer($this->context, $this->message); - + // Verify that the producer is created with correct parameters $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - + // Push to specific queue and verify $adapter = static::$queueConnection->getAdapter(); $adapter->setQueue($queue); $adapter->push($producer); - + $this->context->sendMessageQueueOn($queue, $this->message); } @@ -82,15 +82,15 @@ public function test_can_send_message_with_delay(): void { $delay = 3600; $producer = new MessagingQueueProducer($this->context, $this->message); - + // Verify that the producer is created with correct parameters $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - + // Push to queue and verify $adapter = static::$queueConnection->getAdapter(); $adapter->setSleep($delay); $adapter->push($producer); - + $this->context->sendMessageLater($delay, $this->message); } @@ -99,16 +99,16 @@ public function test_can_send_message_with_delay_on_specific_queue(): void $delay = 3600; $queue = 'delayed-notifications'; $producer = new MessagingQueueProducer($this->context, $this->message); - + // Verify that the producer is created with correct parameters $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - + // Push to specific queue with delay and verify $adapter = static::$queueConnection->getAdapter(); $adapter->setQueue($queue); $adapter->setSleep($delay); $adapter->push($producer); - + $this->context->sendMessageLaterOn($delay, $queue, $this->message); } @@ -119,7 +119,7 @@ public function test_message_sends_to_correct_channels(): void $channels = $message->channels($context); - $this->assertEquals(['mail', 'database'], $channels); + $this->assertEquals(['mail', 'database', 'slack', 'sms', 'telegram'], $channels); } public function test_message_can_send_to_mail(): void @@ -147,4 +147,48 @@ public function test_message_can_send_to_database(): void $this->assertEquals('test_message', $data['type']); $this->assertEquals('Test message content', $data['data']['message']); } + + public function test_message_can_send_to_slack(): void + { + $context = new TestNotifiableModel(); + $message = new TestMessage(); + + $data = $message->toSlack($context); + + $this->assertIsArray($data); + $this->assertArrayHasKey('webhook_url', $data); + $this->assertArrayHasKey('content', $data); + $this->assertEquals('https://hooks.slack.com/services/test', $data['webhook_url']); + $this->assertEquals('Test message for Slack', $data['content']['text']); + } + + public function test_message_can_send_to_sms(): void + { + $context = new TestNotifiableModel(); + $message = new TestMessage(); + + $data = $message->toSms($context); + + $this->assertIsArray($data); + $this->assertArrayHasKey('to', $data); + $this->assertArrayHasKey('message', $data); + $this->assertEquals('+1234567890', $data['to']); + $this->assertEquals('Test SMS message', $data['message']); + } + + public function test_message_can_send_to_telegram(): void + { + $context = new TestNotifiableModel(); + $message = new TestMessage(); + + $data = $message->toTelegram($context); + + $this->assertIsArray($data); + $this->assertArrayHasKey('chat_id', $data); + $this->assertArrayHasKey('message', $data); + $this->assertArrayHasKey('parse_mode', $data); + $this->assertEquals('123456789', $data['chat_id']); + $this->assertEquals('Test Telegram message', $data['message']); + $this->assertEquals('HTML', $data['parse_mode']); + } } diff --git a/tests/Messaging/Stubs/TestMessage.php b/tests/Messaging/Stubs/TestMessage.php index fbb54b4e..e3cef600 100644 --- a/tests/Messaging/Stubs/TestMessage.php +++ b/tests/Messaging/Stubs/TestMessage.php @@ -10,7 +10,7 @@ class TestMessage extends Messaging { public function channels(Model $context): array { - return ['mail', 'database']; + return ['mail', 'database', 'slack', 'sms', 'telegram']; } public function toMail(Model $context): Envelop @@ -30,4 +30,31 @@ public function toDatabase(Model $context): array ] ]; } -} + + public function toSlack(Model $context): array + { + return [ + 'webhook_url' => 'https://hooks.slack.com/services/test', + 'content' => [ + 'text' => 'Test message for Slack' + ] + ]; + } + + public function toSms(Model $context): array + { + return [ + 'to' => '+1234567890', + 'message' => 'Test SMS message' + ]; + } + + public function toTelegram(Model $context): array + { + return [ + 'chat_id' => '123456789', + 'message' => 'Test Telegram message', + 'parse_mode' => 'HTML' + ]; + } +} diff --git a/tests/Messaging/Stubs/TestNotifiableModel.php b/tests/Messaging/Stubs/TestNotifiableModel.php index 290d0330..a871ec27 100644 --- a/tests/Messaging/Stubs/TestNotifiableModel.php +++ b/tests/Messaging/Stubs/TestNotifiableModel.php @@ -8,4 +8,4 @@ class TestNotifiableModel extends Model { use CanSendMessage; -} +} From 89c076fd0d0004111bf2987a12d879c5213958b5 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sun, 26 Jan 2025 01:12:54 +0000 Subject: [PATCH 04/10] refactor: optimisation of codebase --- src/Auth/README.md | 2 +- src/Database/Database.php | 6 +++--- src/Mail/Driver/NativeDriver.php | 2 +- src/Mail/Driver/SmtpDriver.php | 6 +++--- src/Messaging/Channel/DatabaseChannel.php | 9 ++------- src/Messaging/Channel/MailChannel.php | 5 ++--- src/Messaging/Channel/SlackChannel.php | 6 ++++-- src/Messaging/Channel/SmsChannel.php | 14 ++++++++------ src/Messaging/Channel/TelegramChannel.php | 19 ++++++++++++------- src/Messaging/Contracts/ChannelInterface.php | 2 +- src/Messaging/Messaging.php | 6 +++--- tests/Application/ApplicationTest.php | 8 ++++---- tests/Auth/AuthenticationTest.php | 10 +++++----- tests/Console/CustomCommandTest.php | 1 - tests/Container/CapsuleTest.php | 2 +- tests/Database/ConnectionTest.php | 6 +++--- tests/Database/PaginationTest.php | 2 +- .../Relation/BelongsToRelationQueryTest.php | 4 ++-- tests/Database/Stubs/PetMasterModelStub.php | 1 - .../Database/Stubs/PetWithMasterModelStub.php | 1 - tests/Events/EventTest.php | 6 +++--- tests/Events/Stubs/UserEventStub.php | 2 +- tests/Hashing/SecurityTest.php | 4 +--- tests/Messaging/MessagingTest.php | 2 +- tests/Queue/QueueTest.php | 7 +++---- tests/Queue/Stubs/MixedProducerStub.php | 1 - tests/Queue/Stubs/ModelProducerStub.php | 1 - tests/Support/EnvTest.php | 1 - tests/Translate/TranslationTest.php | 2 +- tests/Validation/ValidationTest.php | 2 +- 30 files changed, 67 insertions(+), 73 deletions(-) diff --git a/src/Auth/README.md b/src/Auth/README.md index 854d4978..0d2a38f0 100644 --- a/src/Auth/README.md +++ b/src/Auth/README.md @@ -5,7 +5,7 @@ Bow Framework auth is a native authentification system ```php use Bow\Http\Exception\UnauthorizedException; -$auth = auth(); +$auth = app_auth(); $logged = $auth->attempts(["username" => "name@example.com", "password" => "password"]); diff --git a/src/Database/Database.php b/src/Database/Database.php index 124191b5..56c0e3cd 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -26,7 +26,7 @@ class Database /** * The singleton Database instance * - * @var Database + * @var ?Database */ private static ?Database $instance = null; @@ -40,7 +40,7 @@ class Database /** * Configuration * - * @var string + * @var ?string */ private static ?string $name = null; @@ -331,7 +331,7 @@ public static function statement(string $sql_statement): bool /** * Execute a delete request * - * @param $sql_statement + * @param string $sql_statement * @param array $data * @return int */ diff --git a/src/Mail/Driver/NativeDriver.php b/src/Mail/Driver/NativeDriver.php index 1c2e6e36..b640cfec 100644 --- a/src/Mail/Driver/NativeDriver.php +++ b/src/Mail/Driver/NativeDriver.php @@ -5,8 +5,8 @@ namespace Bow\Mail\Driver; use Bow\Mail\Contracts\MailDriverInterface; -use Bow\Mail\Exception\MailException; use Bow\Mail\Envelop; +use Bow\Mail\Exception\MailException; use InvalidArgumentException; class NativeDriver implements MailDriverInterface diff --git a/src/Mail/Driver/SmtpDriver.php b/src/Mail/Driver/SmtpDriver.php index 6963954b..2d3971cf 100644 --- a/src/Mail/Driver/SmtpDriver.php +++ b/src/Mail/Driver/SmtpDriver.php @@ -5,13 +5,13 @@ namespace Bow\Mail\Driver; use Bow\Mail\Contracts\MailDriverInterface; +use Bow\Mail\Envelop; +use Bow\Mail\Exception\MailException; use Bow\Mail\Exception\SmtpException; use Bow\Mail\Exception\SocketException; -use Bow\Mail\Envelop; -use ErrorException; use Bow\Mail\Security\DkimSigner; use Bow\Mail\Security\SpfChecker; -use Bow\Mail\Exception\MailException; +use ErrorException; class SmtpDriver implements MailDriverInterface { diff --git a/src/Messaging/Channel/DatabaseChannel.php b/src/Messaging/Channel/DatabaseChannel.php index 03ace22a..c3fb04c9 100644 --- a/src/Messaging/Channel/DatabaseChannel.php +++ b/src/Messaging/Channel/DatabaseChannel.php @@ -2,18 +2,13 @@ namespace Bow\Messaging\Channel; -use Bow\Database\Database; -use Bow\Messaging\Messaging; use Bow\Database\Barry\Model; +use Bow\Database\Database; use Bow\Messaging\Contracts\ChannelInterface; +use Bow\Messaging\Messaging; class DatabaseChannel implements ChannelInterface { - public function __construct( - private readonly array $database - ) { - } - /** * Send the notification to database * diff --git a/src/Messaging/Channel/MailChannel.php b/src/Messaging/Channel/MailChannel.php index febf8902..cccbdacb 100644 --- a/src/Messaging/Channel/MailChannel.php +++ b/src/Messaging/Channel/MailChannel.php @@ -2,11 +2,10 @@ namespace Bow\Messaging\Channel; -use Bow\Mail\Mail; -use Bow\Mail\Envelop; -use Bow\Messaging\Messaging; use Bow\Database\Barry\Model; +use Bow\Mail\Mail; use Bow\Messaging\Contracts\ChannelInterface; +use Bow\Messaging\Messaging; class MailChannel implements ChannelInterface { diff --git a/src/Messaging/Channel/SlackChannel.php b/src/Messaging/Channel/SlackChannel.php index 2157575a..88344a83 100644 --- a/src/Messaging/Channel/SlackChannel.php +++ b/src/Messaging/Channel/SlackChannel.php @@ -2,10 +2,11 @@ namespace Bow\Messaging\Channel; -use GuzzleHttp\Client; -use Bow\Messaging\Messaging; use Bow\Database\Barry\Model; use Bow\Messaging\Contracts\ChannelInterface; +use Bow\Messaging\Messaging; +use GuzzleHttp\Client; +use GuzzleHttp\Exception\GuzzleException; class SlackChannel implements ChannelInterface { @@ -15,6 +16,7 @@ class SlackChannel implements ChannelInterface * @param Model $context * @param Messaging $message * @return void + * @throws GuzzleException */ public function send(Model $context, Messaging $message): void { diff --git a/src/Messaging/Channel/SmsChannel.php b/src/Messaging/Channel/SmsChannel.php index c424414d..01cf0b3d 100644 --- a/src/Messaging/Channel/SmsChannel.php +++ b/src/Messaging/Channel/SmsChannel.php @@ -2,10 +2,12 @@ namespace Bow\Messaging\Channel; -use Twilio\Rest\Client; -use Bow\Messaging\Messaging; use Bow\Database\Barry\Model; use Bow\Messaging\Contracts\ChannelInterface; +use Bow\Messaging\Messaging; +use InvalidArgumentException; +use Twilio\Exceptions\ConfigurationException; +use Twilio\Rest\Client; class SmsChannel implements ChannelInterface { @@ -22,7 +24,7 @@ class SmsChannel implements ChannelInterface /** * Constructor * - * @throws \InvalidArgumentException When Twilio credentials are missing + * @throws InvalidArgumentException|ConfigurationException When Twilio credentials are missing */ public function __construct() { @@ -31,7 +33,7 @@ public function __construct() $this->from_number = config('messaging.twilio.from'); if (!$account_sid || !$auth_token || !$this->from_number) { - throw new \InvalidArgumentException('Twilio credentials are required'); + throw new InvalidArgumentException('Twilio credentials are required'); } $this->client = new Client($account_sid, $auth_token); @@ -69,13 +71,13 @@ private function sendWithTwilio(Model $context, Messaging $message): void $this->from_number = config('messaging.twilio.from'); if (!$account_sid || !$auth_token || !$this->from_number) { - throw new \InvalidArgumentException('Twilio credentials are required'); + throw new InvalidArgumentException('Twilio credentials are required'); } $this->client = new Client($account_sid, $auth_token); if (!isset($data['to']) || !isset($data['message'])) { - throw new \InvalidArgumentException('The phone number and message are required'); + throw new InvalidArgumentException('The phone number and message are required'); } try { diff --git a/src/Messaging/Channel/TelegramChannel.php b/src/Messaging/Channel/TelegramChannel.php index e3f60d35..8896da8a 100644 --- a/src/Messaging/Channel/TelegramChannel.php +++ b/src/Messaging/Channel/TelegramChannel.php @@ -2,10 +2,14 @@ namespace Bow\Messaging\Channel; -use GuzzleHttp\Client; -use Bow\Messaging\Messaging; use Bow\Database\Barry\Model; use Bow\Messaging\Contracts\ChannelInterface; +use Bow\Messaging\Messaging; +use Exception; +use GuzzleHttp\Client; +use GuzzleHttp\Exception\GuzzleException; +use InvalidArgumentException; +use RuntimeException; class TelegramChannel implements ChannelInterface { @@ -17,14 +21,14 @@ class TelegramChannel implements ChannelInterface /** * Constructor * - * @throws \InvalidArgumentException When Telegram bot token is missing + * @throws InvalidArgumentException When Telegram bot token is missing */ public function __construct() { $this->botToken = config('messaging.telegram.bot_token'); if (!$this->botToken) { - throw new \InvalidArgumentException('The Telegram bot token is required'); + throw new InvalidArgumentException('The Telegram bot token is required'); } } @@ -34,6 +38,7 @@ public function __construct() * @param Model $context * @param Messaging $message * @return void + * @throws GuzzleException */ public function send(Model $context, Messaging $message): void { @@ -44,7 +49,7 @@ public function send(Model $context, Messaging $message): void $data = $message->toTelegram($context); if (!isset($data['chat_id']) || !isset($data['message'])) { - throw new \InvalidArgumentException('The chat ID and message are required for Telegram'); + throw new InvalidArgumentException('The chat ID and message are required for Telegram'); } $client = new Client(); @@ -58,8 +63,8 @@ public function send(Model $context, Messaging $message): void 'parse_mode' => $data['parse_mode'] ?? 'HTML' ] ]); - } catch (\Exception $e) { - throw new \RuntimeException('Error while sending Telegram message: ' . $e->getMessage()); + } catch (Exception $e) { + throw new RuntimeException('Error while sending Telegram message: ' . $e->getMessage()); } } } diff --git a/src/Messaging/Contracts/ChannelInterface.php b/src/Messaging/Contracts/ChannelInterface.php index e41ab325..b8b253f2 100644 --- a/src/Messaging/Contracts/ChannelInterface.php +++ b/src/Messaging/Contracts/ChannelInterface.php @@ -2,8 +2,8 @@ namespace Bow\Messaging\Contracts; -use Bow\Messaging\Messaging; use Bow\Database\Barry\Model; +use Bow\Messaging\Messaging; interface ChannelInterface { diff --git a/src/Messaging/Messaging.php b/src/Messaging/Messaging.php index 7172028a..e1799b72 100644 --- a/src/Messaging/Messaging.php +++ b/src/Messaging/Messaging.php @@ -2,12 +2,12 @@ namespace Bow\Messaging; -use Bow\Mail\Envelop; use Bow\Database\Barry\Model; -use Bow\Messaging\Channel\SmsChannel; +use Bow\Mail\Envelop; +use Bow\Messaging\Channel\DatabaseChannel; use Bow\Messaging\Channel\MailChannel; use Bow\Messaging\Channel\SlackChannel; -use Bow\Messaging\Channel\DatabaseChannel; +use Bow\Messaging\Channel\SmsChannel; use Bow\Messaging\Channel\TelegramChannel; abstract class Messaging diff --git a/tests/Application/ApplicationTest.php b/tests/Application/ApplicationTest.php index 52e5451e..0f9602dc 100644 --- a/tests/Application/ApplicationTest.php +++ b/tests/Application/ApplicationTest.php @@ -2,14 +2,14 @@ namespace Bow\Tests\Application; -use Mockery; +use Bow\Application\Application; +use Bow\Container\Capsule; use Bow\Http\Request; use Bow\Http\Response; -use Bow\Container\Capsule; -use Bow\Application\Application; -use Bow\Testing\KernelTesting; use Bow\Router\Exception\RouterException; +use Bow\Testing\KernelTesting; use Bow\Tests\Config\TestingConfiguration; +use Mockery; class ApplicationTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Auth/AuthenticationTest.php b/tests/Auth/AuthenticationTest.php index da9b06ea..7cf7880f 100644 --- a/tests/Auth/AuthenticationTest.php +++ b/tests/Auth/AuthenticationTest.php @@ -3,16 +3,16 @@ namespace Bow\Tests\Auth; use Bow\Auth\Auth; -use Bow\Security\Hash; -use Policier\Policier; -use Bow\Database\Database; use Bow\Auth\Authentication; +use Bow\Auth\Exception\AuthenticationException; +use Bow\Auth\Guards\GuardContract; use Bow\Auth\Guards\JwtGuard; use Bow\Auth\Guards\SessionGuard; -use Bow\Auth\Guards\GuardContract; +use Bow\Database\Database; +use Bow\Security\Hash; use Bow\Tests\Auth\Stubs\UserModelStub; use Bow\Tests\Config\TestingConfiguration; -use Bow\Auth\Exception\AuthenticationException; +use Policier\Policier; class AuthenticationTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Console/CustomCommandTest.php b/tests/Console/CustomCommandTest.php index fa001c70..de15135e 100644 --- a/tests/Console/CustomCommandTest.php +++ b/tests/Console/CustomCommandTest.php @@ -4,7 +4,6 @@ use Bow\Console\Console; use Bow\Console\Setting; -use Bow\Tests\Console\Stubs\CustomCommand; class CustomCommandTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Container/CapsuleTest.php b/tests/Container/CapsuleTest.php index d9f0aa51..47519bb1 100644 --- a/tests/Container/CapsuleTest.php +++ b/tests/Container/CapsuleTest.php @@ -2,9 +2,9 @@ namespace Bow\Tests\Container; -use StdClass; use Bow\Container\Capsule; use Bow\Tests\Container\Stubs\MyClass; +use StdClass; class CapsuleTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Database/ConnectionTest.php b/tests/Database/ConnectionTest.php index 4319ae35..7c34454f 100644 --- a/tests/Database/ConnectionTest.php +++ b/tests/Database/ConnectionTest.php @@ -2,12 +2,12 @@ namespace Bow\Tests\Database; -use Bow\Tests\Config\TestingConfiguration; +use Bow\Configuration\Loader as ConfigurationLoader; use Bow\Database\Connection\AbstractConnection; use Bow\Database\Connection\Adapter\MysqlAdapter; -use Bow\Database\Connection\Adapter\SqliteAdapter; -use Bow\Configuration\Loader as ConfigurationLoader; use Bow\Database\Connection\Adapter\PostgreSQLAdapter; +use Bow\Database\Connection\Adapter\SqliteAdapter; +use Bow\Tests\Config\TestingConfiguration; class ConnectionTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Database/PaginationTest.php b/tests/Database/PaginationTest.php index 2b90cda2..9c23fe9a 100644 --- a/tests/Database/PaginationTest.php +++ b/tests/Database/PaginationTest.php @@ -4,8 +4,8 @@ namespace Tests\Bow\Database; -use PHPUnit\Framework\TestCase; use Bow\Database\Pagination; +use PHPUnit\Framework\TestCase; class PaginationTest extends TestCase { diff --git a/tests/Database/Relation/BelongsToRelationQueryTest.php b/tests/Database/Relation/BelongsToRelationQueryTest.php index d17be65a..67130ee0 100644 --- a/tests/Database/Relation/BelongsToRelationQueryTest.php +++ b/tests/Database/Relation/BelongsToRelationQueryTest.php @@ -6,9 +6,9 @@ use Bow\Database\Database; use Bow\Database\Migration\SQLGenerator; use Bow\Tests\Config\TestingConfiguration; -use Bow\Tests\Database\Stubs\PetModelStub; -use Bow\Tests\Database\Stubs\PetMasterModelStub; use Bow\Tests\Database\Stubs\MigrationExtendedStub; +use Bow\Tests\Database\Stubs\PetMasterModelStub; +use Bow\Tests\Database\Stubs\PetModelStub; class BelongsToRelationQueryTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Database/Stubs/PetMasterModelStub.php b/tests/Database/Stubs/PetMasterModelStub.php index 40601440..7ce52aec 100644 --- a/tests/Database/Stubs/PetMasterModelStub.php +++ b/tests/Database/Stubs/PetMasterModelStub.php @@ -3,7 +3,6 @@ namespace Bow\Tests\Database\Stubs; use Bow\Database\Barry\Relations\HasMany; -use Bow\Tests\Database\Stubs\PetModelStub; class PetMasterModelStub extends \Bow\Database\Barry\Model { diff --git a/tests/Database/Stubs/PetWithMasterModelStub.php b/tests/Database/Stubs/PetWithMasterModelStub.php index 9a436d58..346f03d5 100644 --- a/tests/Database/Stubs/PetWithMasterModelStub.php +++ b/tests/Database/Stubs/PetWithMasterModelStub.php @@ -3,7 +3,6 @@ namespace Bow\Tests\Database\Stubs; use Bow\Database\Barry\Relations\BelongsTo; -use Bow\Tests\Database\Stubs\PetMasterModelStub; class PetWithMasterModelStub extends \Bow\Database\Barry\Model { diff --git a/tests/Events/EventTest.php b/tests/Events/EventTest.php index 02197404..73d2c508 100644 --- a/tests/Events/EventTest.php +++ b/tests/Events/EventTest.php @@ -2,13 +2,13 @@ namespace Bow\Tests\Events; -use Bow\Event\Event; use Bow\Database\Database; +use Bow\Event\Event; use Bow\Tests\Config\TestingConfiguration; -use PHPUnit\Framework\Assert; use Bow\Tests\Events\Stubs\EventModelStub; -use Bow\Tests\Events\Stubs\UserEventStub; use Bow\Tests\Events\Stubs\UserEventListenerStub; +use Bow\Tests\Events\Stubs\UserEventStub; +use PHPUnit\Framework\Assert; class EventTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Events/Stubs/UserEventStub.php b/tests/Events/Stubs/UserEventStub.php index 695d0e46..84fd65c4 100644 --- a/tests/Events/Stubs/UserEventStub.php +++ b/tests/Events/Stubs/UserEventStub.php @@ -2,8 +2,8 @@ namespace Bow\Tests\Events\Stubs; -use Bow\Event\Dispatchable; use Bow\Event\Contracts\AppEvent; +use Bow\Event\Dispatchable; class UserEventStub implements AppEvent { diff --git a/tests/Hashing/SecurityTest.php b/tests/Hashing/SecurityTest.php index c3bd3261..e544bf0d 100644 --- a/tests/Hashing/SecurityTest.php +++ b/tests/Hashing/SecurityTest.php @@ -2,10 +2,8 @@ namespace Bow\Tests\Hashing; -use Bow\Auth\Auth; -use Bow\Database\Database; -use Bow\Security\Hash; use Bow\Security\Crypto; +use Bow\Security\Hash; use Bow\Tests\Config\TestingConfiguration; class SecurityTest extends \PHPUnit\Framework\TestCase diff --git a/tests/Messaging/MessagingTest.php b/tests/Messaging/MessagingTest.php index e283961c..a3d94069 100644 --- a/tests/Messaging/MessagingTest.php +++ b/tests/Messaging/MessagingTest.php @@ -8,8 +8,8 @@ use Bow\Queue\Connection as QueueConnection; use Bow\Tests\Messaging\Stubs\TestMessage; use Bow\Tests\Messaging\Stubs\TestNotifiableModel; -use PHPUnit\Framework\TestCase; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class MessagingTest extends TestCase { diff --git a/tests/Queue/QueueTest.php b/tests/Queue/QueueTest.php index 1a87786f..e76f562d 100644 --- a/tests/Queue/QueueTest.php +++ b/tests/Queue/QueueTest.php @@ -12,12 +12,11 @@ use Bow\Queue\Adapters\DatabaseAdapter; use Bow\Queue\Adapters\SQSAdapter; use Bow\Queue\Adapters\SyncAdapter; -use Bow\Tests\Config\TestingConfiguration; -use Bow\Tests\Queue\Stubs\PetModelStub; use Bow\Queue\Connection as QueueConnection; -use Bow\Testing\KernelTesting; -use Bow\Tests\Queue\Stubs\ModelProducerStub; +use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Queue\Stubs\BasicProducerStubs; +use Bow\Tests\Queue\Stubs\ModelProducerStub; +use Bow\Tests\Queue\Stubs\PetModelStub; class QueueTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Queue/Stubs/MixedProducerStub.php b/tests/Queue/Stubs/MixedProducerStub.php index ed17d1da..e81b5e58 100644 --- a/tests/Queue/Stubs/MixedProducerStub.php +++ b/tests/Queue/Stubs/MixedProducerStub.php @@ -3,7 +3,6 @@ namespace Bow\Tests\Queue\Stubs; use Bow\Queue\ProducerService; -use Bow\Tests\Queue\Stubs\ServiceStub; class MixedProducerStub extends ProducerService { diff --git a/tests/Queue/Stubs/ModelProducerStub.php b/tests/Queue/Stubs/ModelProducerStub.php index 50ebe323..c467f73b 100644 --- a/tests/Queue/Stubs/ModelProducerStub.php +++ b/tests/Queue/Stubs/ModelProducerStub.php @@ -3,7 +3,6 @@ namespace Bow\Tests\Queue\Stubs; use Bow\Queue\ProducerService; -use Bow\Tests\Queue\Stubs\PetModelStub; class ModelProducerStub extends ProducerService { diff --git a/tests/Support/EnvTest.php b/tests/Support/EnvTest.php index e387b993..f624b9cf 100644 --- a/tests/Support/EnvTest.php +++ b/tests/Support/EnvTest.php @@ -2,7 +2,6 @@ namespace Bow\Tests\Support; -use Bow\View\View; use Bow\Support\Env; class EnvTest extends \PHPUnit\Framework\TestCase diff --git a/tests/Translate/TranslationTest.php b/tests/Translate/TranslationTest.php index c92ccea0..a31fd938 100644 --- a/tests/Translate/TranslationTest.php +++ b/tests/Translate/TranslationTest.php @@ -2,8 +2,8 @@ namespace Bow\Tests\Translate; -use Bow\Translate\Translator; use Bow\Tests\Config\TestingConfiguration; +use Bow\Translate\Translator; class TranslationTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/Validation/ValidationTest.php b/tests/Validation/ValidationTest.php index 17105e4b..ec3a2582 100644 --- a/tests/Validation/ValidationTest.php +++ b/tests/Validation/ValidationTest.php @@ -3,9 +3,9 @@ namespace Bow\Tests\Validation; use Bow\Database\Database; +use Bow\Tests\Config\TestingConfiguration; use Bow\Translate\Translator; use Bow\Validation\Validator; -use Bow\Tests\Config\TestingConfiguration; class ValidationTest extends \PHPUnit\Framework\TestCase { From 48a7199df2a0ab53385858b8a2efa10a0049368a Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sun, 26 Jan 2025 01:20:35 +0000 Subject: [PATCH 05/10] refactor: normalize files wording --- .github/FUNDING.yml | 4 +- .github/ISSUE_TEMPLATE.md | 2 +- .github/workflows/coding-standards.yml | 56 ++++++------ .github/workflows/issues.yml | 10 +-- .github/workflows/pull-requests.yml | 10 +-- .github/workflows/tests.yml | 90 +++++++++---------- .github/workflows/update-changelog.yml | 8 +- CHANGELOG.md | 1 + CODE_OF_CONDUCT.md | 6 +- CONTRIBUTING.md | 21 +++-- composer.json | 5 +- docker-compose.yml | 54 +++++------ php.dist.ini | 2 +- readme.md | 3 +- src/Application/Application.php | 4 +- .../CacheAdapterInterface.php | 2 +- .../{Adapter => Adapters}/DatabaseAdapter.php | 2 +- .../FilesystemAdapter.php | 2 +- .../{Adapter => Adapters}/RedisAdapter.php | 2 +- src/Cache/Cache.php | 8 +- .../GenerateResourceControllerCommand.php | 9 +- src/Container/{Action.php => Compass.php} | 24 ++--- src/Container/ContainerConfiguration.php | 2 +- src/Database/Barry/Concerns/Relationship.php | 20 +++-- src/Database/Barry/Model.php | 10 ++- src/Database/Barry/Relations/BelongsTo.php | 7 +- .../{Adapter => Adapters}/MysqlAdapter.php | 2 +- .../PostgreSQLAdapter.php | 2 +- .../{Adapter => Adapters}/SqliteAdapter.php | 2 +- src/Database/Pagination.php | 13 +-- src/Database/QueryBuilder.php | 53 ++++++----- src/Event/EventProducer.php | 3 +- src/Http/Response.php | 7 +- .../LogDriver.php => Adapters/LogAdapter.php} | 14 +-- .../NativeAdapter.php} | 10 +-- .../SesDriver.php => Adapters/SesAdapter.php} | 8 +- .../SmtpAdapter.php} | 6 +- ...Interface.php => MailAdapterInterface.php} | 2 +- src/Mail/Envelop.php | 22 ++--- src/Mail/Mail.php | 30 +++---- src/Mail/MailQueueProducer.php | 7 +- src/Mail/README.md | 2 +- src/Mail/Security/DkimSigner.php | 4 +- src/Mail/Security/SpfChecker.php | 68 +++++++------- .../DatabaseChannelAdapter.php} | 6 +- .../MailChannelAdapter.php} | 6 +- .../SlackChannelAdapter.php} | 6 +- .../SmsChannelAdapter.php} | 8 +- .../TelegramChannelAdapter.php} | 8 +- ...erface.php => ChannelAdapterInterface.php} | 2 +- src/Messaging/Messaging.php | 22 ++--- src/Messaging/MessagingQueueProducer.php | 5 +- src/Messaging/README.md | 3 +- src/Queue/Adapters/QueueAdapter.php | 6 +- src/Queue/WorkerService.php | 11 +-- src/Router/Route.php | 4 +- src/Router/Router.php | 9 +- .../ArrayAdapter.php} | 4 +- .../DatabaseAdapter.php} | 4 +- .../{Driver => Adapters}/DurationTrait.php | 2 +- .../FilesystemAdapter.php} | 4 +- src/Session/Cookie.php | 7 +- src/Session/Session.php | 12 +-- src/Support/Serializes.php | 3 +- src/Support/helpers.php | 48 +++++----- .../Exception/ValidationException.php | 5 +- src/View/EngineAbstract.php | 22 ++--- tests/Auth/AuthenticationTest.php | 4 +- tests/Cache/CacheDatabaseTest.php | 4 +- tests/Cache/CacheFilesystemTest.php | 20 ++--- tests/Cache/CacheRedisTest.php | 20 ++--- tests/Config/stubs/database.php | 4 +- tests/Config/stubs/mail.php | 12 +-- tests/Config/stubs/storage.php | 4 +- tests/Console/CustomCommandTest.php | 20 ++--- ...Test__test_generate_messaging_stubs__1.txt | 7 +- tests/Container/CapsuleTest.php | 4 +- tests/Database/ConnectionTest.php | 6 +- tests/Database/Migration/MigrationTest.php | 22 ++--- .../Migration/Mysql/SQLGeneratorTest.php | 10 +-- .../Migration/Mysql/SQLGenetorHelpersTest.php | 11 +-- .../Migration/Pgsql/SQLGeneratorTest.php | 10 +-- .../Migration/Pgsql/SQLGenetorHelpersTest.php | 10 +-- .../Migration/SQLite/SQLGeneratorTest.php | 10 +-- .../SQLite/SQLGenetorHelpersTest.php | 10 +-- tests/Database/PaginationTest.php | 24 ++--- tests/Database/Query/DatabaseQueryTest.php | 22 ++--- tests/Database/Query/ModelQueryTest.php | 55 ++++++------ tests/Database/Query/PaginationTest.php | 22 ++--- tests/Database/Query/QueryBuilderTest.php | 46 +++++----- tests/Database/RedisTest.php | 12 +-- tests/Filesystem/DiskFilesystemTest.php | 22 ++--- tests/Filesystem/FTPServiceTest.php | 36 ++++---- tests/Mail/MailServiceTest.php | 49 +++++----- tests/Messaging/MessagingTest.php | 18 ++-- tests/Queue/MailQueueTest.php | 1 - tests/Queue/QueueTest.php | 2 +- tests/Queue/Stubs/BasicProducerStubs.php | 3 +- tests/Queue/Stubs/MixedProducerStub.php | 5 +- tests/Queue/Stubs/ModelProducerStub.php | 5 +- tests/Support/ArraydotifyTest.php | 10 +-- tests/Support/stubs/env.json | 2 +- 102 files changed, 698 insertions(+), 650 deletions(-) rename src/Cache/{Adapter => Adapters}/CacheAdapterInterface.php (98%) rename src/Cache/{Adapter => Adapters}/DatabaseAdapter.php (99%) rename src/Cache/{Adapter => Adapters}/FilesystemAdapter.php (99%) rename src/Cache/{Adapter => Adapters}/RedisAdapter.php (99%) rename src/Container/{Action.php => Compass.php} (96%) rename src/Database/Connection/{Adapter => Adapters}/MysqlAdapter.php (97%) rename src/Database/Connection/{Adapter => Adapters}/PostgreSQLAdapter.php (98%) rename src/Database/Connection/{Adapter => Adapters}/SqliteAdapter.php (96%) rename src/Mail/{Driver/LogDriver.php => Adapters/LogAdapter.php} (77%) rename src/Mail/{Driver/NativeDriver.php => Adapters/NativeAdapter.php} (92%) rename src/Mail/{Driver/SesDriver.php => Adapters/SesAdapter.php} (92%) rename src/Mail/{Driver/SmtpDriver.php => Adapters/SmtpAdapter.php} (98%) rename src/Mail/Contracts/{MailDriverInterface.php => MailAdapterInterface.php} (88%) rename src/Messaging/{Channel/DatabaseChannel.php => Adapters/DatabaseChannelAdapter.php} (82%) rename src/Messaging/{Channel/MailChannel.php => Adapters/MailChannelAdapter.php} (76%) rename src/Messaging/{Channel/SlackChannel.php => Adapters/SlackChannelAdapter.php} (89%) rename src/Messaging/{Channel/SmsChannel.php => Adapters/SmsChannelAdapter.php} (94%) rename src/Messaging/{Channel/TelegramChannel.php => Adapters/TelegramChannelAdapter.php} (91%) rename src/Messaging/Contracts/{ChannelInterface.php => ChannelAdapterInterface.php} (90%) rename src/Session/{Driver/ArrayDriver.php => Adapters/ArrayAdapter.php} (95%) rename src/Session/{Driver/DatabaseDriver.php => Adapters/DatabaseAdapter.php} (97%) rename src/Session/{Driver => Adapters}/DurationTrait.php (92%) rename src/Session/{Driver/FilesystemDriver.php => Adapters/FilesystemAdapter.php} (96%) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 8adb87ac..5c212c1f 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,5 +1,5 @@ # These are supported funding model platforms -github: [papac] +github: [ papac ] open_collective: bowphp -custom: ["https://www.buymeacoffee.com/iOLqZ3h"] +custom: [ "https://www.buymeacoffee.com/iOLqZ3h" ] diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 16a9d3e2..8bbd6336 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -5,7 +5,7 @@ If you would like to propose new Bow features, please make a pull request, or op - Version: #.#.# - Tintin Version: #.#.# - PHP Version: #.#.# -- Database Driver & Version: Mysql|Sqlite +- Database Adapters & Version: Mysql|Sqlite ### Description diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml index 7c014d20..2f104523 100644 --- a/.github/workflows/coding-standards.yml +++ b/.github/workflows/coding-standards.yml @@ -1,41 +1,41 @@ name: fix code styling on: - workflow_call: - inputs: - php: - default: "8.1" - type: string - message: - default: Fix code styling - type: string - fix: - default: true - type: boolean + workflow_call: + inputs: + php: + default: "8.1" + type: string + message: + default: Fix code styling + type: string + fix: + default: true + type: boolean jobs: - lint: - runs-on: ubuntu-latest + lint: + runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ inputs.php }} - extensions: json, dom, curl, libxml, mbstring - coverage: none + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ inputs.php }} + extensions: json, dom, curl, libxml, mbstring + coverage: none - - name: Install PHP CS - run: composer global require squizlabs/php_codesniffer + - name: Install PHP CS + run: composer global require squizlabs/php_codesniffer - - name: Run Phpcbf - run: phpcbf --standard=psr11 --tab-width=4 --severity=4 + - name: Run Phpcbf + run: phpcbf --standard=psr11 --tab-width=4 --severity=4 - - name: Commit linted files - if: ${{ inputs.fix }} - uses: stefanzweifel/git-auto-commit-action@v4 - with: - commit_message: ${{ inputs.message }} + - name: Commit linted files + if: ${{ inputs.fix }} + uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: ${{ inputs.message }} diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml index ab84f3a4..9332224d 100644 --- a/.github/workflows/issues.yml +++ b/.github/workflows/issues.yml @@ -1,12 +1,12 @@ name: issues on: - issues: - types: [labeled] + issues: + types: [ labeled ] permissions: - issues: write + issues: write jobs: - help-wanted: - uses: bowphp/.github/.github/workflows/issues.yml@main + help-wanted: + uses: bowphp/.github/.github/workflows/issues.yml@main diff --git a/.github/workflows/pull-requests.yml b/.github/workflows/pull-requests.yml index 1bc67d39..4437c822 100644 --- a/.github/workflows/pull-requests.yml +++ b/.github/workflows/pull-requests.yml @@ -1,12 +1,12 @@ name: pull requests on: - pull_request_target: - types: [opened] + pull_request_target: + types: [ opened ] permissions: - pull-requests: write + pull-requests: write jobs: - uneditable: - uses: bowphp/.github/.github/workflows/pull-requests.yml@main + uneditable: + uses: bowphp/.github/.github/workflows/pull-requests.yml@main diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 78443439..99d0165f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,50 +3,50 @@ name: bowphp on: [ push, pull_request ] env: - FTP_HOST: localhost - FTP_USER: username - FTP_PASSWORD: password - FTP_PORT: 21 - FTP_ROOT: /tmp + FTP_HOST: localhost + FTP_USER: username + FTP_PASSWORD: password + FTP_PORT: 21 + FTP_ROOT: /tmp jobs: - lunix-tests: - runs-on: ${{ matrix.os }} - strategy: - matrix: - php: [8.1, 8.2, 8.3] - os: [ubuntu-latest] - stability: [prefer-lowest, prefer-stable] + lunix-tests: + runs-on: ${{ matrix.os }} + strategy: + matrix: + php: [ 8.1, 8.2, 8.3 ] + os: [ ubuntu-latest ] + stability: [ prefer-lowest, prefer-stable ] - name: PHP ${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} + name: PHP ${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} - steps: - - name: Checkout code - uses: actions/checkout@v2 + steps: + - name: Checkout code + uses: actions/checkout@v2 - - name: Setup MySQL - uses: mirromutth/mysql-action@v1.1 - with: - host port: 3306 - container port: 3306 - character set server: 'utf8mb4' - collation server: 'utf8mb4_general_ci' - mysql version: '5.7' - mysql database: 'test_db' - mysql root password: 'password' + - name: Setup MySQL + uses: mirromutth/mysql-action@v1.1 + with: + host port: 3306 + container port: 3306 + character set server: 'utf8mb4' + collation server: 'utf8mb4_general_ci' + mysql version: '5.7' + mysql database: 'test_db' + mysql root password: 'password' - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php }} - extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, mysql, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, redis - coverage: none + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, mysql, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, redis + coverage: none - - run: docker run -p 21:21 -p 20:20 -p 12020:12020 -p 12021:12021 -p 12022:12022 -p 12023:12023 -p 12024:12024 -p 12025:12025 -e USER=$FTP_USER -e PASS=$FTP_PASSWORD -d --name ftp papacdev/vsftpd - - run: docker run -p 1080:1080 -p 1025:1025 -d --name maildev soulteary/maildev - - run: docker run -p 6379:6379 -d --name redis redis - - run: docker run -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -e POSTGRES_PASSWORD=postgres -d postgis/postgis - - run: docker run -d -p 11300:11300 schickling/beanstalkd + - run: docker run -p 21:21 -p 20:20 -p 12020:12020 -p 12021:12021 -p 12022:12022 -p 12023:12023 -p 12024:12024 -p 12025:12025 -e USER=$FTP_USER -e PASS=$FTP_PASSWORD -d --name ftp papacdev/vsftpd + - run: docker run -p 1080:1080 -p 1025:1025 -d --name maildev soulteary/maildev + - run: docker run -p 6379:6379 -d --name redis redis + - run: docker run -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -e POSTGRES_PASSWORD=postgres -d postgis/postgis + - run: docker run -d -p 11300:11300 schickling/beanstalkd - name: Cache Composer packages id: composer-cache @@ -57,14 +57,14 @@ jobs: restore-keys: | ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} - - name: Copy the php ini config - run: sudo cp php.dist.ini php.ini + - name: Copy the php ini config + run: sudo cp php.dist.ini php.ini - - name: Install dependencies - run: sudo composer update --prefer-dist --no-interaction + - name: Install dependencies + run: sudo composer update --prefer-dist --no-interaction - - name: Create test cache directory - run: if [ ! -d /tmp/bowphp_testing ]; then mkdir -p /tmp/bowphp_testing; fi; + - name: Create test cache directory + run: if [ ! -d /tmp/bowphp_testing ]; then mkdir -p /tmp/bowphp_testing; fi; - - name: Run test suite - run: sudo composer run-script test + - name: Run test suite + run: sudo composer run-script test diff --git a/.github/workflows/update-changelog.yml b/.github/workflows/update-changelog.yml index 1c8b5d5a..b90851fe 100644 --- a/.github/workflows/update-changelog.yml +++ b/.github/workflows/update-changelog.yml @@ -1,9 +1,9 @@ name: update changelog on: - release: - types: [released] + release: + types: [ released ] jobs: - update: - uses: bowphp/.github/.github/workflows/update-changelog.yml@main + update: + uses: bowphp/.github/.github/workflows/update-changelog.yml@main diff --git a/CHANGELOG.md b/CHANGELOG.md index 6229627b..45de58fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ This method aims to execute an SQL transaction around a passed arrow function. ```php Database::transaction(fn() => $user->update(['name' => ''])); ``` + Ref: #255 ## 5.1.0 - 2023-06-07 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 3a33ad4d..511a25cc 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,6 +1,8 @@ -Bow's code of conduct is derived from the Ruby Code of Conduct. Any breach of the code of conduct may be reported to Franck DAKIA (dakiafranck@gmail.com). +Bow's code of conduct is derived from the Ruby Code of Conduct. Any breach of the code of conduct may be reported to +Franck DAKIA (dakiafranck@gmail.com). - Participants will be tolerant of opposing points of view. -- Participants must ensure that their language and actions are free from personal attacks and derogatory personal remarks. +- Participants must ensure that their language and actions are free from personal attacks and derogatory personal + remarks. - By interpreting the words and actions of others, participants must always assume good intentions. - Behavior that can reasonably be considered harassment will not be tolerated. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3f0eb5d0..35e41f6b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,10 +1,10 @@ # Contribution - [Contribution](#contribution) - - [Introduction](#introduction) - - [Cutting the project](#cutting-the-project) - - [How to make the commits](#how-to-make-the-commits) - - [Contact](#contact) + - [Introduction](#introduction) + - [Cutting the project](#cutting-the-project) + - [How to make the commits](#how-to-make-the-commits) + - [Contact](#contact) ## Introduction @@ -14,14 +14,16 @@ To participate in the project you must: - Clone the project from your github `git clone account https://github.com/your-account/app` - Create a branch whose name will be the summary of your change `git branch branch-of-your-works` - Make a publication on your depot `git push origin branch-of-your-works` -- Finally make a [pull-request](https://www.thinkful.com/learn/github-pull-request-tutorial/Keep-Tabs-on-the-Project#Time-to-Submit-Your-First-PR) - +- Finally make + a [pull-request](https://www.thinkful.com/learn/github-pull-request-tutorial/Keep-Tabs-on-the-Project#Time-to-Submit-Your-First-PR) ## Cutting the project -The Bow framework project is split into a subproject. Then each participant will be able to participate on the section in which he feels the best. +The Bow framework project is split into a subproject. Then each participant will be able to participate on the section +in which he feels the best. -Imagine that you are more comfortable with the construction of Routing. Just focus on `src/Routing`. Note that the sections have to be independent and therefore have the own configuration. +Imagine that you are more comfortable with the construction of Routing. Just focus on `src/Routing`. Note that the +sections have to be independent and therefore have the own configuration. ## How to make the commits @@ -63,4 +65,5 @@ In case your modification affect more section? You give a message and a descript ## Contact -Please, if there is a bug on the project please contact me by email or leave me a message on the [slack](https://bowphp.slack.com). +Please, if there is a bug on the project please contact me by email or leave me a message on +the [slack](https://bowphp.slack.com). diff --git a/composer.json b/composer.json index 5335f4f9..d5d422dd 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,10 @@ { "name": "bowphp/framework", "description": "The bow PHP Framework", - "keywords": ["framework", "bow"], + "keywords": [ + "framework", + "bow" + ], "license": "MIT", "support": { "issues": "https://github.com/bowphp/framework/issues", diff --git a/docker-compose.yml b/docker-compose.yml index 6025bf6e..1c981c66 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,31 +1,31 @@ version: "3" services: - db: - container_name: mysql - command: --default-authentication-plugin=mysql_native_password --max_allowed_packet=1073741824 - image: mysql - ports: - - "3306:3306" - environment: - MYSQL_DATABASE: test - MYSQL_USERNAME: travis - MYSQL_ALLOW_EMPTY_PASSWORD: "yes" - ftp: - container_name: ftp-server - image: emilybache/vsftpd-server - ports: - - "21" - environment: - USER: bob - PASS: "12345" - volumes: - - "ftp_storage:/ftp/$USER" - mail: - container_name: mail - image: maildev/maildev - ports: - - "1025:25" - - "1080:80" + db: + container_name: mysql + command: --default-authentication-plugin=mysql_native_password --max_allowed_packet=1073741824 + image: mysql + ports: + - "3306:3306" + environment: + MYSQL_DATABASE: test + MYSQL_USERNAME: travis + MYSQL_ALLOW_EMPTY_PASSWORD: "yes" + ftp: + container_name: ftp-server + image: emilybache/vsftpd-server + ports: + - "21" + environment: + USER: bob + PASS: "12345" + volumes: + - "ftp_storage:/ftp/$USER" + mail: + container_name: mail + image: maildev/maildev + ports: + - "1025:25" + - "1080:80" volumes: - ftp_storage: \ No newline at end of file + ftp_storage: diff --git a/php.dist.ini b/php.dist.ini index 87fe7632..7ae9566e 100644 --- a/php.dist.ini +++ b/php.dist.ini @@ -1 +1 @@ -sendmail_path=/tmp/sendmail -t -i +sendmail_path = /tmp/sendmail -t -i diff --git a/readme.md b/readme.md index f60325f2..bf3b8fe3 100644 --- a/readme.md +++ b/readme.md @@ -47,5 +47,6 @@ Thank you for considering contributing to Bow Framework! The contribution guide [papac@bowphp.com](mailto:papac@bowphp.com) - [@papacdev](https://twitter.com/papacdev) -Please, if there is a bug on the project contact me by email or leave me a message on [Slack](https://bowphp.slack.com). or [join us on Slask](https://join.slack.com/t/bowphp/shared_invite/enQtNzMxOTQ0MTM2ODM5LTQ3MWQ3Mzc1NDFiNDYxMTAyNzBkNDJlMTgwNDJjM2QyMzA2YTk4NDYyN2NiMzM0YTZmNjU1YjBhNmJjZThiM2Q) +Please, if there is a bug on the project contact me by email or leave me a message on [Slack](https://bowphp.slack.com). +or [join us on Slask](https://join.slack.com/t/bowphp/shared_invite/enQtNzMxOTQ0MTM2ODM5LTQ3MWQ3Mzc1NDFiNDYxMTAyNzBkNDJlMTgwNDJjM2QyMzA2YTk4NDYyN2NiMzM0YTZmNjU1YjBhNmJjZThiM2Q) diff --git a/src/Application/Application.php b/src/Application/Application.php index 25493056..d77d4345 100644 --- a/src/Application/Application.php +++ b/src/Application/Application.php @@ -6,8 +6,8 @@ use Bow\Application\Exception\ApplicationException; use Bow\Configuration\Loader; -use Bow\Container\Action; use Bow\Container\Capsule; +use Bow\Container\Compass; use Bow\Contracts\ResponseInterface; use Bow\Http\Exception\BadRequestException; use Bow\Http\Exception\HttpException; @@ -182,7 +182,7 @@ public function send(): bool ); } - $response = Action::getInstance()->execute($this->error_code[404], []); + $response = Compass::getInstance()->execute($this->error_code[404], []); $this->sendResponse($response, 404); diff --git a/src/Cache/Adapter/CacheAdapterInterface.php b/src/Cache/Adapters/CacheAdapterInterface.php similarity index 98% rename from src/Cache/Adapter/CacheAdapterInterface.php rename to src/Cache/Adapters/CacheAdapterInterface.php index 08727a3f..89cf0dd3 100644 --- a/src/Cache/Adapter/CacheAdapterInterface.php +++ b/src/Cache/Adapters/CacheAdapterInterface.php @@ -1,6 +1,6 @@ write('controller/rest', [ 'modelNamespace' => $model_namespace, 'prefix' => $prefix, diff --git a/src/Container/Action.php b/src/Container/Compass.php similarity index 96% rename from src/Container/Action.php rename to src/Container/Compass.php index 90b565d8..f4ef5f57 100644 --- a/src/Container/Action.php +++ b/src/Container/Compass.php @@ -16,7 +16,7 @@ use ReflectionException; use ReflectionFunction; -class Action +class Compass { private const INJECTION_EXCEPTION_TYPE = [ 'string', 'array', 'bool', 'int', @@ -24,11 +24,11 @@ class Action 'object', 'stdclass', '\closure', 'closure' ]; /** - * The Action instance + * The Compass instance * - * @var ?Action + * @var ?Compass */ - private static ?Action $instance = null; + private static ?Compass $instance = null; /** * The list of namespaces defined in the application * @@ -49,7 +49,7 @@ class Action private MiddlewareDispatcher $dispatcher; /** - * Action constructor + * Compass constructor * * @param array $namespaces * @param array $middlewares @@ -64,17 +64,17 @@ public function __construct(array $namespaces, array $middlewares) } /** - * Action configuration + * Compass configuration * * @param array $namespaces * @param array $middlewares * * @return static */ - public static function configure(array $namespaces, array $middlewares): Action + public static function configure(array $namespaces, array $middlewares): Compass { if (is_null(static::$instance)) { - static::$instance = new Action($namespaces, $middlewares); + static::$instance = new Compass($namespaces, $middlewares); } return static::$instance; @@ -263,11 +263,11 @@ public function call(callable|string|array $actions, ?array $param = null): mixe } /** - * Retrieves Action instance + * Retrieves Compass instance * - * @return Action + * @return Compass */ - public static function getInstance(): Action + public static function getInstance(): Compass { return static::$instance; } @@ -372,7 +372,7 @@ private function getInjectParameter(mixed $class): ?object { $class_name = $class->getName(); - if (in_array(strtolower($class_name), Action::INJECTION_EXCEPTION_TYPE)) { + if (in_array(strtolower($class_name), Compass::INJECTION_EXCEPTION_TYPE)) { return null; } diff --git a/src/Container/ContainerConfiguration.php b/src/Container/ContainerConfiguration.php index d2dc1dbf..53b7f483 100644 --- a/src/Container/ContainerConfiguration.php +++ b/src/Container/ContainerConfiguration.php @@ -24,7 +24,7 @@ public function create(Loader $config): void $this->container->bind('action', function () use ($config) { $middlewares = array_merge($config->getMiddlewares(), $this->middlewares); - return Action::configure($config->namespaces(), $middlewares); + return Compass::configure($config->namespaces(), $middlewares); }); } diff --git a/src/Database/Barry/Concerns/Relationship.php b/src/Database/Barry/Concerns/Relationship.php index fa9b359d..4b828bf1 100644 --- a/src/Database/Barry/Concerns/Relationship.php +++ b/src/Database/Barry/Concerns/Relationship.php @@ -20,10 +20,11 @@ trait Relationship * @return BelongsTo */ public function belongsTo( - string $related, + string $related, ?string $foreign_key = null, ?string $local_key = null - ): BelongsTo { + ): BelongsTo + { // Create the new instance of model from container $related_model = app()->make($related); @@ -55,10 +56,11 @@ abstract public function getKey(): string; * @return BelongsToMany */ public function belongsToMany( - string $related, + string $related, ?string $primary_key = null, ?string $foreign_key = null - ): BelongsToMany { + ): BelongsToMany + { $related_model = app()->make($related); if (is_null($primary_key)) { @@ -82,10 +84,11 @@ public function belongsToMany( * @return HasMany */ public function hasMany( - string $related, + string $related, ?string $primary_key = null, ?string $foreign_key = null - ): HasMany { + ): HasMany + { $related_model = app()->make($related); if (is_null($primary_key)) { @@ -109,10 +112,11 @@ public function hasMany( * @return HasOne */ public function hasOne( - string $related, + string $related, ?string $foreign_key = null, ?string $primary_key = null - ): HasOne { + ): HasOne + { $related_model = app()->make($related); if (is_null($primary_key)) { diff --git a/src/Database/Barry/Model.php b/src/Database/Barry/Model.php index 4ac41aa0..ed885180 100644 --- a/src/Database/Barry/Model.php +++ b/src/Database/Barry/Model.php @@ -311,8 +311,9 @@ public static function findBy(string $column, mixed $value): Collection */ public static function findAndDelete( int|string|array $id, - array $select = ['*'] - ): Collection|Model|null { + array $select = ['*'] + ): Collection|Model|null + { $model = static::find($id, $select); if (is_null($model)) { @@ -338,8 +339,9 @@ public static function findAndDelete( */ public static function find( int|string|array $id, - array $select = ['*'] - ): Collection|Model|null { + array $select = ['*'] + ): Collection|Model|null + { $id = (array)$id; $model = new static(); diff --git a/src/Database/Barry/Relations/BelongsTo.php b/src/Database/Barry/Relations/BelongsTo.php index 335cdd6e..511a960b 100644 --- a/src/Database/Barry/Relations/BelongsTo.php +++ b/src/Database/Barry/Relations/BelongsTo.php @@ -20,11 +20,12 @@ class BelongsTo extends Relation * @param string $local_key */ public function __construct( - Model $related, - Model $parent, + Model $related, + Model $parent, string $foreign_key, string $local_key - ) { + ) + { $this->local_key = $local_key; $this->foreign_key = $foreign_key; diff --git a/src/Database/Connection/Adapter/MysqlAdapter.php b/src/Database/Connection/Adapters/MysqlAdapter.php similarity index 97% rename from src/Database/Connection/Adapter/MysqlAdapter.php rename to src/Database/Connection/Adapters/MysqlAdapter.php index 910dfb4f..2fb2cb10 100644 --- a/src/Database/Connection/Adapter/MysqlAdapter.php +++ b/src/Database/Connection/Adapters/MysqlAdapter.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Bow\Database\Connection\Adapter; +namespace Bow\Database\Connection\Adapters; use Bow\Database\Connection\AbstractConnection; use Bow\Support\Str; diff --git a/src/Database/Connection/Adapter/PostgreSQLAdapter.php b/src/Database/Connection/Adapters/PostgreSQLAdapter.php similarity index 98% rename from src/Database/Connection/Adapter/PostgreSQLAdapter.php rename to src/Database/Connection/Adapters/PostgreSQLAdapter.php index 265c3178..fe5ec75a 100644 --- a/src/Database/Connection/Adapter/PostgreSQLAdapter.php +++ b/src/Database/Connection/Adapters/PostgreSQLAdapter.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Bow\Database\Connection\Adapter; +namespace Bow\Database\Connection\Adapters; use Bow\Database\Connection\AbstractConnection; use InvalidArgumentException; diff --git a/src/Database/Connection/Adapter/SqliteAdapter.php b/src/Database/Connection/Adapters/SqliteAdapter.php similarity index 96% rename from src/Database/Connection/Adapter/SqliteAdapter.php rename to src/Database/Connection/Adapters/SqliteAdapter.php index 6fa20ee5..4e9f1680 100644 --- a/src/Database/Connection/Adapter/SqliteAdapter.php +++ b/src/Database/Connection/Adapters/SqliteAdapter.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Bow\Database\Connection\Adapter; +namespace Bow\Database\Connection\Adapters; use Bow\Database\Connection\AbstractConnection; use InvalidArgumentException; diff --git a/src/Database/Pagination.php b/src/Database/Pagination.php index b01c6341..7798301d 100644 --- a/src/Database/Pagination.php +++ b/src/Database/Pagination.php @@ -8,13 +8,14 @@ class Pagination { public function __construct( - private readonly int $next, - private readonly int $previous, - private readonly int $total, - private readonly int $perPage, - private readonly int $current, + 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 - ) { + ) + { } public function next(): int diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index c67c1b45..b7a34d12 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -240,10 +240,11 @@ public function orWhere(string $column, mixed $comparator = '=', mixed $value = */ public function where( string $column, - mixed $comparator = '=', - mixed $value = null, + mixed $comparator = '=', + mixed $value = null, string $boolean = 'and' - ): QueryBuilder { + ): QueryBuilder + { // We check here the applied comparator if (!static::isComparisonOperator($comparator) || is_null($value)) { @@ -542,11 +543,12 @@ public function whereIn(string $column, array $range, string $boolean = 'and'): * @return QueryBuilder */ public function join( - string $table, - string $first, - mixed $comparator = '=', + string $table, + string $first, + mixed $comparator = '=', ?string $second = null - ): QueryBuilder { + ): QueryBuilder + { $table = $this->getPrefix() . $table; if (is_null($this->join)) { @@ -601,11 +603,12 @@ public function setPrefix(string $prefix): QueryBuilder * @throws QueryBuilderException */ public function leftJoin( - string $table, - string $first, - mixed $comparator = '=', + string $table, + string $first, + mixed $comparator = '=', ?string $second = null - ): QueryBuilder { + ): QueryBuilder + { $table = $this->getPrefix() . $table; if (is_null($this->join)) { @@ -637,11 +640,12 @@ public function leftJoin( * @throws QueryBuilderException */ public function rightJoin( - string $table, - string $first, - mixed $comparator = '=', + string $table, + string $first, + mixed $comparator = '=', ?string $second = null - ): QueryBuilder { + ): QueryBuilder + { $table = $this->getPrefix() . $table; if (is_null($this->join)) { @@ -759,10 +763,11 @@ public function groupBy(string $column): QueryBuilder */ public function having( string $column, - mixed $comparator = '=', - $value = null, - $boolean = 'and' - ): QueryBuilder { + mixed $comparator = '=', + $value = null, + $boolean = 'and' + ): QueryBuilder + { // We check here the applied comparator if (!$this->isComparisonOperator($comparator)) { $value = $comparator; @@ -1170,7 +1175,7 @@ public function remove(string $column, mixed $comparator = '=', $value = null): } /** - * Delete Action + * Delete Compass * * @return int */ @@ -1198,7 +1203,7 @@ public function delete(): int } /** - * Action increment, add 1 by default to the specified field + * Compass increment, add 1 by default to the specified field * * @param string $column * @param int $step @@ -1267,7 +1272,7 @@ public function distinct(string $column) } /** - * Truncate Action, empty the table + * Truncate Compass, empty the table * * @return bool */ @@ -1301,7 +1306,7 @@ public function insertAndGetLastId(array $values): string|int|bool } /** - * Insert Action + * Insert Compass * * The data to be inserted into the database. * @@ -1357,7 +1362,7 @@ private function insertOne(array $value): int } /** - * Drop Action, remove the table + * Drop Compass, remove the table * * @return mixed */ diff --git a/src/Event/EventProducer.php b/src/Event/EventProducer.php index 44c534c8..c889b922 100644 --- a/src/Event/EventProducer.php +++ b/src/Event/EventProducer.php @@ -17,7 +17,8 @@ class EventProducer extends ProducerService public function __construct( private readonly mixed $event, private readonly mixed $payload = null, - ) { + ) + { parent::__construct(); } diff --git a/src/Http/Response.php b/src/Http/Response.php index 2adb8f1d..5ccc6362 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -120,10 +120,11 @@ public function addHeaders(array $headers): Response * @return string */ public function download( - string $file, + string $file, ?string $filename = null, - array $headers = [] - ): string { + array $headers = [] + ): string + { $type = mime_content_type($file); if (is_null($filename)) { diff --git a/src/Mail/Driver/LogDriver.php b/src/Mail/Adapters/LogAdapter.php similarity index 77% rename from src/Mail/Driver/LogDriver.php rename to src/Mail/Adapters/LogAdapter.php index 63a47149..8b3b0622 100644 --- a/src/Mail/Driver/LogDriver.php +++ b/src/Mail/Adapters/LogAdapter.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace Bow\Mail\Driver; +namespace Bow\Mail\Adapters; -use Bow\Mail\Contracts\MailDriverInterface; +use Bow\Mail\Contracts\MailAdapterInterface; use Bow\Mail\Envelop; use Bow\Support\Str; -class LogDriver implements MailDriverInterface +class LogAdapter implements MailAdapterInterface { /** * The configuration @@ -25,7 +25,7 @@ class LogDriver implements MailDriverInterface private string $path; /** - * LogDriver Constructor + * LogAdapter Constructor * * @param array $config */ @@ -54,12 +54,12 @@ public function send(Envelop $envelop): bool $content .= $envelop->compileHeaders(); $content .= "To: " . implode(', ', array_map(function ($to) { - return $to[0] ? "{$to[0]} <{$to[1]}>" : $to[1]; - }, $envelop->getTo())) . "\n"; + return $to[0] ? "{$to[0]} <{$to[1]}>" : $to[1]; + }, $envelop->getTo())) . "\n"; $content .= "Subject: " . $envelop->getSubject() . "\n"; $content .= $envelop->getMessage(); - return (bool) file_put_contents($filepath, $content); + return (bool)file_put_contents($filepath, $content); } } diff --git a/src/Mail/Driver/NativeDriver.php b/src/Mail/Adapters/NativeAdapter.php similarity index 92% rename from src/Mail/Driver/NativeDriver.php rename to src/Mail/Adapters/NativeAdapter.php index b640cfec..b99f4491 100644 --- a/src/Mail/Driver/NativeDriver.php +++ b/src/Mail/Adapters/NativeAdapter.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace Bow\Mail\Driver; +namespace Bow\Mail\Adapters; -use Bow\Mail\Contracts\MailDriverInterface; +use Bow\Mail\Contracts\MailAdapterInterface; use Bow\Mail\Envelop; use Bow\Mail\Exception\MailException; use InvalidArgumentException; -class NativeDriver implements MailDriverInterface +class NativeAdapter implements MailAdapterInterface { /** * The configuration @@ -43,10 +43,10 @@ public function __construct(array $config = []) * Switch on other define from * * @param string $from - * @return NativeDriver + * @return NativeAdapter * @throws MailException */ - public function on(string $from): NativeDriver + public function on(string $from): NativeAdapter { if (!isset($this->config["froms"][$from])) { throw new MailException( diff --git a/src/Mail/Driver/SesDriver.php b/src/Mail/Adapters/SesAdapter.php similarity index 92% rename from src/Mail/Driver/SesDriver.php rename to src/Mail/Adapters/SesAdapter.php index 53c6b184..6f1e7ac2 100644 --- a/src/Mail/Driver/SesDriver.php +++ b/src/Mail/Adapters/SesAdapter.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace Bow\Mail\Driver; +namespace Bow\Mail\Adapters; use Aws\Ses\SesClient; -use Bow\Mail\Contracts\MailDriverInterface; +use Bow\Mail\Contracts\MailAdapterInterface; use Bow\Mail\Envelop; -class SesDriver implements MailDriverInterface +class SesAdapter implements MailAdapterInterface { /** * The SES Instance @@ -25,7 +25,7 @@ class SesDriver implements MailDriverInterface private bool $config_set = false; /** - * SesDriver constructor + * SesAdapter constructor * * @param array $config * @return void diff --git a/src/Mail/Driver/SmtpDriver.php b/src/Mail/Adapters/SmtpAdapter.php similarity index 98% rename from src/Mail/Driver/SmtpDriver.php rename to src/Mail/Adapters/SmtpAdapter.php index 2d3971cf..ff61ccdb 100644 --- a/src/Mail/Driver/SmtpDriver.php +++ b/src/Mail/Adapters/SmtpAdapter.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace Bow\Mail\Driver; +namespace Bow\Mail\Adapters; -use Bow\Mail\Contracts\MailDriverInterface; +use Bow\Mail\Contracts\MailAdapterInterface; use Bow\Mail\Envelop; use Bow\Mail\Exception\MailException; use Bow\Mail\Exception\SmtpException; @@ -13,7 +13,7 @@ use Bow\Mail\Security\SpfChecker; use ErrorException; -class SmtpDriver implements MailDriverInterface +class SmtpAdapter implements MailAdapterInterface { /** * Socket connection diff --git a/src/Mail/Contracts/MailDriverInterface.php b/src/Mail/Contracts/MailAdapterInterface.php similarity index 88% rename from src/Mail/Contracts/MailDriverInterface.php rename to src/Mail/Contracts/MailAdapterInterface.php index 99eacde0..d53ed908 100644 --- a/src/Mail/Contracts/MailDriverInterface.php +++ b/src/Mail/Contracts/MailAdapterInterface.php @@ -6,7 +6,7 @@ use Bow\Mail\Envelop; -interface MailDriverInterface +interface MailAdapterInterface { /** * Send mail by any driver diff --git a/src/Mail/Envelop.php b/src/Mail/Envelop.php index 0f602f8c..1a4de18d 100644 --- a/src/Mail/Envelop.php +++ b/src/Mail/Envelop.php @@ -384,16 +384,6 @@ public function addPriority(int $priority): Envelop return $this; } - /** - * @param string $message - * @param string $type - * @see setEnvelop - */ - public function message(string $message, string $type = 'text/html'): void - { - $this->setMessage($message, $type); - } - /** * Get the headers * @@ -500,4 +490,16 @@ public function view(string $view, array $data = []): Envelop return $this; } + + /** + * Alias of setMessage + * + * @param string $message + * @param string $type + * @see setEnvelop + */ + public function message(string $message, string $type = 'text/html'): void + { + $this->setMessage($message, $type); + } } diff --git a/src/Mail/Mail.php b/src/Mail/Mail.php index 64197c8c..475c3996 100644 --- a/src/Mail/Mail.php +++ b/src/Mail/Mail.php @@ -4,10 +4,10 @@ namespace Bow\Mail; -use Bow\Mail\Contracts\MailDriverInterface; -use Bow\Mail\Driver\NativeDriver; -use Bow\Mail\Driver\SesDriver; -use Bow\Mail\Driver\SmtpDriver; +use Bow\Mail\Adapters\NativeAdapter; +use Bow\Mail\Adapters\SesAdapter; +use Bow\Mail\Adapters\SmtpAdapter; +use Bow\Mail\Contracts\MailAdapterInterface; use Bow\Mail\Exception\MailException; use Bow\View\View; use ErrorException; @@ -27,17 +27,17 @@ class Mail * @var array */ private static array $drivers = [ - 'smtp' => SmtpDriver::class, - 'mail' => NativeDriver::class, - 'ses' => SesDriver::class, + 'smtp' => SmtpAdapter::class, + 'mail' => NativeAdapter::class, + 'ses' => SesAdapter::class, ]; /** * The mail driver instance * - * @var ?MailDriverInterface + * @var ?MailAdapterInterface */ - private static ?MailDriverInterface $instance = null; + private static ?MailAdapterInterface $instance = null; /** * The mail configuration @@ -61,10 +61,10 @@ public function __construct(array $config = []) * Configure la classe Mail * * @param array $config - * @return MailDriverInterface + * @return MailAdapterInterface * @throws MailException */ - public static function configure(array $config = []): MailDriverInterface + public static function configure(array $config = []): MailAdapterInterface { if (empty(static::$config)) { static::$config = $config; @@ -97,9 +97,9 @@ public static function configure(array $config = []): MailDriverInterface /** * Get mail instance * - * @return MailDriverInterface + * @return MailAdapterInterface */ - public static function getInstance(): MailDriverInterface + public static function getInstance(): MailAdapterInterface { return static::$instance; } @@ -244,10 +244,10 @@ public static function laterOn(int $delay, string $queue, string $template, arra * Modify the smtp|mail|ses driver * * @param string $driver - * @return MailDriverInterface + * @return MailAdapterInterface * @throws MailException */ - public static function setDriver(string $driver): MailDriverInterface + public static function setDriver(string $driver): MailAdapterInterface { if (static::$config == null) { throw new MailException( diff --git a/src/Mail/MailQueueProducer.php b/src/Mail/MailQueueProducer.php index ba061b94..05979df1 100644 --- a/src/Mail/MailQueueProducer.php +++ b/src/Mail/MailQueueProducer.php @@ -23,10 +23,11 @@ class MailQueueProducer extends ProducerService * @param Envelop $message */ public function __construct( - string $view, - array $data, + string $view, + array $data, Envelop $envelop - ) { + ) + { parent::__construct(); $this->bags = [ diff --git a/src/Mail/README.md b/src/Mail/README.md index 8fac6e3e..e0b873a6 100644 --- a/src/Mail/README.md +++ b/src/Mail/README.md @@ -10,7 +10,7 @@ Bow Framework's mail system is very simple email delivery system with support: Let's show a little exemple: ```php -use Bow\Mail\Message; +use Bow\Mail\Envelop; email('view.template', function (Message $message) { $message->to("papac@bowphp.com"); diff --git a/src/Mail/Security/DkimSigner.php b/src/Mail/Security/DkimSigner.php index cac1b3cf..90f0b668 100644 --- a/src/Mail/Security/DkimSigner.php +++ b/src/Mail/Security/DkimSigner.php @@ -140,7 +140,7 @@ private function buildDkimHeader(array $headers, string $signature, string $body $signedHeaders = implode(':', array_map('strtolower', array_keys($headers))); return "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d={$domain}; s={$selector};\r\n" . - "\tt=" . time() . "; bh={$bodyHash};\r\n" . - "\th={$signedHeaders}; b={$signature};"; + "\tt=" . time() . "; bh={$bodyHash};\r\n" . + "\th={$signedHeaders}; b={$signature};"; } } diff --git a/src/Mail/Security/SpfChecker.php b/src/Mail/Security/SpfChecker.php index 32b2e602..0322f2cf 100644 --- a/src/Mail/Security/SpfChecker.php +++ b/src/Mail/Security/SpfChecker.php @@ -157,23 +157,6 @@ private function checkIp4(string $mechanism, string $ip, string $qualifier): ?st return null; } - /** - * Check IPv6 mechanism - * - * @param string $mechanism - * @param string $ip - * @param string $qualifier - * @return string|null - */ - private function checkIp6(string $mechanism, string $ip, string $qualifier): ?string - { - $range = substr($mechanism, 4); - if ($this->ipInRange($ip, $range)) { - return $this->getQualifierResult($qualifier); - } - return null; - } - /** * Check if IP is in range * @@ -193,6 +176,40 @@ private function ipInRange(string $ip, string $range): bool return $ip === $range; } + /** + * Get result based on qualifier + * + * @param string $qualifier + * @return string + */ + private function getQualifierResult(string $qualifier): string + { + return match ($qualifier) { + '+' => 'pass', + '-' => 'fail', + '~' => 'softfail', + '?' => 'neutral', + default => 'neutral' + }; + } + + /** + * Check IPv6 mechanism + * + * @param string $mechanism + * @param string $ip + * @param string $qualifier + * @return string|null + */ + private function checkIp6(string $mechanism, string $ip, string $qualifier): ?string + { + $range = substr($mechanism, 4); + if ($this->ipInRange($ip, $range)) { + return $this->getQualifierResult($qualifier); + } + return null; + } + /** * Check A record mechanism * @@ -235,21 +252,4 @@ private function checkMx(string $mechanism, string $ip, string $domain, string $ } return null; } - - /** - * Get result based on qualifier - * - * @param string $qualifier - * @return string - */ - private function getQualifierResult(string $qualifier): string - { - return match ($qualifier) { - '+' => 'pass', - '-' => 'fail', - '~' => 'softfail', - '?' => 'neutral', - default => 'neutral' - }; - } } diff --git a/src/Messaging/Channel/DatabaseChannel.php b/src/Messaging/Adapters/DatabaseChannelAdapter.php similarity index 82% rename from src/Messaging/Channel/DatabaseChannel.php rename to src/Messaging/Adapters/DatabaseChannelAdapter.php index c3fb04c9..ca3c799b 100644 --- a/src/Messaging/Channel/DatabaseChannel.php +++ b/src/Messaging/Adapters/DatabaseChannelAdapter.php @@ -1,13 +1,13 @@ MailChannel::class, - "database" => DatabaseChannel::class, - "telegram" => TelegramChannel::class, - "slack" => SlackChannel::class, - "sms" => SmsChannel::class, + "mail" => MailChannelAdapter::class, + "database" => DatabaseChannelAdapter::class, + "telegram" => TelegramChannelAdapter::class, + "slack" => SlackChannelAdapter::class, + "sms" => SmsChannelAdapter::class, ]; /** @@ -98,7 +98,7 @@ public function toTelegram(Model $context): array * @param Model $context * @return void */ - final function process(Model $context): void + final public function process(Model $context): void { $channels = $this->channels($context); diff --git a/src/Messaging/MessagingQueueProducer.php b/src/Messaging/MessagingQueueProducer.php index a4610d98..ad767098 100644 --- a/src/Messaging/MessagingQueueProducer.php +++ b/src/Messaging/MessagingQueueProducer.php @@ -22,9 +22,10 @@ class MessagingQueueProducer extends ProducerService * @param Messaging $message */ public function __construct( - Model $context, + Model $context, Messaging $message, - ) { + ) + { parent::__construct(); $this->bags = [ diff --git a/src/Messaging/README.md b/src/Messaging/README.md index 92943bfa..b94fd038 100644 --- a/src/Messaging/README.md +++ b/src/Messaging/README.md @@ -1,6 +1,7 @@ # Bow Framework - Messaging System -Le système de messaging de Bow Framework permet d'envoyer des notifications à travers différents canaux (email, base de données, etc.) de manière simple et flexible. +Le système de messaging de Bow Framework permet d'envoyer des notifications à travers différents canaux (email, base de +données, etc.) de manière simple et flexible. ## Utilisation basique diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index 0b379ced..2310b4ad 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -64,7 +64,8 @@ abstract public function push(ProducerService $producer): void; */ public function serializeProducer( ProducerService $producer - ): string { + ): string + { return serialize($producer); } @@ -76,7 +77,8 @@ public function serializeProducer( */ public function unserializeProducer( string $producer - ): ProducerService { + ): ProducerService + { return unserialize($producer); } diff --git a/src/Queue/WorkerService.php b/src/Queue/WorkerService.php index b9177c7b..dcdca31c 100644 --- a/src/Queue/WorkerService.php +++ b/src/Queue/WorkerService.php @@ -39,11 +39,12 @@ public function setConnection(QueueAdapter $connection): void */ #[NoReturn] public function run( string $queue = "default", - int $tries = 3, - int $sleep = 5, - int $timeout = 60, - int $memory = 128 - ): void { + int $tries = 3, + int $sleep = 5, + int $timeout = 60, + int $memory = 128 + ): void + { $this->connection->setQueue($queue); $this->connection->setTries($tries); $this->connection->setSleep($sleep); diff --git a/src/Router/Route.php b/src/Router/Route.php index 86e9679f..64e6e3f1 100644 --- a/src/Router/Route.php +++ b/src/Router/Route.php @@ -5,7 +5,7 @@ namespace Bow\Router; use Bow\Configuration\Loader; -use Bow\Container\Action; +use Bow\Container\Compass; class Route { @@ -158,7 +158,7 @@ public function call(): mixed $this->match[$key] = $tmp; } - return Action::getInstance()->call($this->cb, $this->match); + return Compass::getInstance()->call($this->cb, $this->match); } /** diff --git a/src/Router/Router.php b/src/Router/Router.php index 08bae6e1..1edd229b 100644 --- a/src/Router/Router.php +++ b/src/Router/Router.php @@ -80,11 +80,12 @@ class Router * @param array $middlewares */ protected function __construct( - string $method, + string $method, ?string $magic_method = null, - string $base_route = '', - array $middlewares = [] - ) { + string $base_route = '', + array $middlewares = [] + ) + { $this->method = $method; $this->magic_method = $magic_method; $this->middlewares = $middlewares; diff --git a/src/Session/Driver/ArrayDriver.php b/src/Session/Adapters/ArrayAdapter.php similarity index 95% rename from src/Session/Driver/ArrayDriver.php rename to src/Session/Adapters/ArrayAdapter.php index ce367265..2033cd30 100644 --- a/src/Session/Driver/ArrayDriver.php +++ b/src/Session/Adapters/ArrayAdapter.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace Bow\Session\Driver; +namespace Bow\Session\Adapters; use SessionHandlerInterface; -class ArrayDriver implements SessionHandlerInterface +class ArrayAdapter implements SessionHandlerInterface { use DurationTrait; diff --git a/src/Session/Driver/DatabaseDriver.php b/src/Session/Adapters/DatabaseAdapter.php similarity index 97% rename from src/Session/Driver/DatabaseDriver.php rename to src/Session/Adapters/DatabaseAdapter.php index 61bd8182..732515c5 100644 --- a/src/Session/Driver/DatabaseDriver.php +++ b/src/Session/Adapters/DatabaseAdapter.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace Bow\Session\Driver; +namespace Bow\Session\Adapters; use Bow\Database\Database; use Bow\Database\Exception\QueryBuilderException; use Bow\Database\QueryBuilder; use SessionHandlerInterface; -class DatabaseDriver implements SessionHandlerInterface +class DatabaseAdapter implements SessionHandlerInterface { use DurationTrait; diff --git a/src/Session/Driver/DurationTrait.php b/src/Session/Adapters/DurationTrait.php similarity index 92% rename from src/Session/Driver/DurationTrait.php rename to src/Session/Adapters/DurationTrait.php index 7038c22a..66928b0b 100644 --- a/src/Session/Driver/DurationTrait.php +++ b/src/Session/Adapters/DurationTrait.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Bow\Session\Driver; +namespace Bow\Session\Adapters; trait DurationTrait { diff --git a/src/Session/Driver/FilesystemDriver.php b/src/Session/Adapters/FilesystemAdapter.php similarity index 96% rename from src/Session/Driver/FilesystemDriver.php rename to src/Session/Adapters/FilesystemAdapter.php index d569abae..e020f1eb 100644 --- a/src/Session/Driver/FilesystemDriver.php +++ b/src/Session/Adapters/FilesystemAdapter.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace Bow\Session\Driver; +namespace Bow\Session\Adapters; use SessionHandlerInterface; -class FilesystemDriver implements SessionHandlerInterface +class FilesystemAdapter implements SessionHandlerInterface { use DurationTrait; diff --git a/src/Session/Cookie.php b/src/Session/Cookie.php index 58ca6d21..f0c68327 100644 --- a/src/Session/Cookie.php +++ b/src/Session/Cookie.php @@ -118,9 +118,10 @@ public static function remove(string $key): string|bool|null */ public static function set( int|string $key, - mixed $data, - int $expiration = 3600, - ): bool { + mixed $data, + int $expiration = 3600, + ): bool + { $data = Crypto::encrypt(json_encode($data)); return setcookie( diff --git a/src/Session/Session.php b/src/Session/Session.php index 4b7e9644..9aef80ee 100644 --- a/src/Session/Session.php +++ b/src/Session/Session.php @@ -7,9 +7,9 @@ use BadMethodCallException; use Bow\Contracts\CollectionInterface; use Bow\Security\Crypto; -use Bow\Session\Driver\ArrayDriver; -use Bow\Session\Driver\DatabaseDriver; -use Bow\Session\Driver\FilesystemDriver; +use Bow\Session\Adapters\ArrayAdapter; +use Bow\Session\Adapters\DatabaseAdapter; +use Bow\Session\Adapters\FilesystemAdapter; use Bow\Session\Exception\SessionException; use InvalidArgumentException; use stdClass; @@ -41,9 +41,9 @@ class Session implements CollectionInterface * @var array */ private array $driver = [ - 'database' => DatabaseDriver::class, - 'array' => ArrayDriver::class, - 'file' => FilesystemDriver::class, + 'database' => DatabaseAdapter::class, + 'array' => ArrayAdapter::class, + 'file' => FilesystemAdapter::class, ]; /** * The session configuration diff --git a/src/Support/Serializes.php b/src/Support/Serializes.php index 266a5da9..e295d5fa 100644 --- a/src/Support/Serializes.php +++ b/src/Support/Serializes.php @@ -57,7 +57,8 @@ public function __serialize() */ protected function getPropertyValue( ReflectionProperty $property - ): mixed { + ): mixed + { return $property->getValue($this); } diff --git a/src/Support/helpers.php b/src/Support/helpers.php index 0eacf2b3..ff92285d 100644 --- a/src/Support/helpers.php +++ b/src/Support/helpers.php @@ -16,7 +16,7 @@ use Bow\Http\Redirect; use Bow\Http\Request; use Bow\Http\Response; -use Bow\Mail\Contracts\MailDriverInterface; +use Bow\Mail\Contracts\MailAdapterInterface; use Bow\Mail\Mail; use Bow\Queue\ProducerService; use Bow\Security\Crypto; @@ -777,13 +777,14 @@ function flash(string $key, string $message): mixed * @param null|string $view * @param array $data * @param callable|null $cb - * @return MailDriverInterface|bool + * @return MailAdapterInterface|bool */ function email( - string $view = null, - array $data = [], + string $view = null, + array $data = [], callable $cb = null - ): MailDriverInterface|bool { + ): MailAdapterInterface|bool + { if ($view === null) { return Mail::getInstance(); } @@ -847,9 +848,10 @@ function session(array|string $value = null, mixed $default = null): mixed */ function cookie( string $key = null, - mixed $data = null, - int $expiration = 3600 - ): string|array|object|null { + mixed $data = null, + int $expiration = 3600 + ): string|array|object|null + { if ($key === null) { return Cookie::all(); } @@ -1072,9 +1074,10 @@ function bow_hash(string $data, string $hash_value = null): bool|string */ function app_trans( string $key = null, - array $data = [], - bool $choose = false - ): string|Translator { + array $data = [], + bool $choose = false + ): string|Translator + { if (is_null($key)) { return Translator::getInstance(); } @@ -1099,9 +1102,10 @@ function app_trans( */ function t( string $key, - array $data = [], - bool $choose = false - ): string|Translator { + array $data = [], + bool $choose = false + ): string|Translator + { return app_trans($key, $data, $choose); } } @@ -1117,9 +1121,10 @@ function t( */ function __( string $key, - array $data = [], - bool $choose = false - ): string|Translator { + array $data = [], + bool $choose = false + ): string|Translator + { return app_trans($key, $data, $choose); } } @@ -1185,10 +1190,11 @@ function app_abort(int $code = 500, string $message = ''): Response * @throws HttpException */ function app_abort_if( - bool $boolean, - int $code, + bool $boolean, + int $code, string $message = '' - ): Response|null { + ): Response|null + { if ($boolean) { return app_abort($code, $message); } @@ -1251,10 +1257,10 @@ function old(string $key, mixed $fullback = null): mixed /** * Recovery of the guard * - * @deprecated * @param string|null $guard * @return GuardContract * @throws AuthenticationException + * @deprecated */ function auth(string $guard = null): GuardContract { diff --git a/src/Validation/Exception/ValidationException.php b/src/Validation/Exception/ValidationException.php index af43179e..483a1199 100644 --- a/src/Validation/Exception/ValidationException.php +++ b/src/Validation/Exception/ValidationException.php @@ -24,9 +24,10 @@ class ValidationException extends HttpException */ public function __construct( string $message, - array $errors = [], + array $errors = [], string $status = 'VALIDATION_ERROR' - ) { + ) + { parent::__construct($message, 400); $this->errors = $errors; $this->status = $status; diff --git a/src/View/EngineAbstract.php b/src/View/EngineAbstract.php index 5b80e0dd..588053ae 100644 --- a/src/View/EngineAbstract.php +++ b/src/View/EngineAbstract.php @@ -103,6 +103,17 @@ public function fileExists(string $filename): bool return file_exists($this->config['path'] . '/' . $normalized_filename); } + /** + * Normalize the file + * + * @param string $filename + * @return string + */ + private function normalizeFilename(string $filename): string + { + return preg_replace('/@|\./', '/', $filename) . '.' . trim($this->config['extension'], '.'); + } + /** * Check the parsed file * @@ -129,15 +140,4 @@ protected function checkParseFile(string $filename, bool $extended = true): stri return $extended ? $normalized_filename : $filename; } - - /** - * Normalize the file - * - * @param string $filename - * @return string - */ - private function normalizeFilename(string $filename): string - { - return preg_replace('/@|\./', '/', $filename) . '.' . trim($this->config['extension'], '.'); - } } diff --git a/tests/Auth/AuthenticationTest.php b/tests/Auth/AuthenticationTest.php index 7cf7880f..d6156e3b 100644 --- a/tests/Auth/AuthenticationTest.php +++ b/tests/Auth/AuthenticationTest.php @@ -100,7 +100,7 @@ public function test_attempt_login_with_jwt_provider() $this->assertTrue($result); - $token = (string) $auth->getToken(); + $token = (string)$auth->getToken(); $user = $auth->user(); $this->assertInstanceOf(Authentication::class, $user); @@ -114,7 +114,7 @@ public function test_direct_login_with_jwt_provider() $auth = Auth::guard('api'); $auth->login(UserModelStub::first()); - $token = (string) $auth->getToken(); + $token = (string)$auth->getToken(); $user = $auth->user(); $this->assertTrue($auth->check()); diff --git a/tests/Cache/CacheDatabaseTest.php b/tests/Cache/CacheDatabaseTest.php index 179a1729..0e4747b6 100644 --- a/tests/Cache/CacheDatabaseTest.php +++ b/tests/Cache/CacheDatabaseTest.php @@ -40,8 +40,8 @@ public function test_get_cache() public function test_add_with_callback_cache() { - $result = Cache::add('lastname', fn () => 'Franck'); - $result = $result && Cache::add('age', fn () => 25, 20000); + $result = Cache::add('lastname', fn() => 'Franck'); + $result = $result && Cache::add('age', fn() => 25, 20000); $this->assertEquals($result, true); } diff --git a/tests/Cache/CacheFilesystemTest.php b/tests/Cache/CacheFilesystemTest.php index d957b2ee..91d15570 100644 --- a/tests/Cache/CacheFilesystemTest.php +++ b/tests/Cache/CacheFilesystemTest.php @@ -7,14 +7,6 @@ class CacheFilesystemTest extends \PHPUnit\Framework\TestCase { - protected function setUp(): void - { - parent::setUp(); - $config = TestingConfiguration::getConfig(); - Cache::configure($config["cache"]); - Cache::store("file"); - } - public function test_create_cache() { $result = Cache::add('name', 'Dakia'); @@ -29,8 +21,8 @@ public function test_get_cache() public function test_add_with_callback_cache() { - $result = Cache::add('lastname', fn () => 'Franck'); - $result = $result && Cache::add('age', fn () => 25, 20000); + $result = Cache::add('lastname', fn() => 'Franck'); + $result = $result && Cache::add('age', fn() => 25, 20000); $this->assertEquals($result, true); } @@ -138,4 +130,12 @@ public function test_clear_cache() $this->assertNull(Cache::get('name')); $this->assertNull(Cache::get('first_name')); } + + protected function setUp(): void + { + parent::setUp(); + $config = TestingConfiguration::getConfig(); + Cache::configure($config["cache"]); + Cache::store("file"); + } } diff --git a/tests/Cache/CacheRedisTest.php b/tests/Cache/CacheRedisTest.php index fb6c3126..bd816159 100644 --- a/tests/Cache/CacheRedisTest.php +++ b/tests/Cache/CacheRedisTest.php @@ -7,14 +7,6 @@ class CacheRedisTest extends \PHPUnit\Framework\TestCase { - protected function setUp(): void - { - parent::setUp(); - $config = TestingConfiguration::getConfig(); - Cache::configure($config["cache"]); - Cache::store("redis"); - } - public function test_create_cache() { $result = Cache::add('name', 'Dakia'); @@ -29,8 +21,8 @@ public function test_get_cache() public function test_add_with_callback_cache() { - $result = Cache::add('lastname', fn () => 'Franck'); - $result = $result && Cache::add('age', fn () => 25, 20000); + $result = Cache::add('lastname', fn() => 'Franck'); + $result = $result && Cache::add('age', fn() => 25, 20000); $this->assertEquals($result, true); } @@ -158,4 +150,12 @@ public function test_clear_cache() $this->assertNull(Cache::get('name')); $this->assertNull(Cache::get('first_name')); } + + protected function setUp(): void + { + parent::setUp(); + $config = TestingConfiguration::getConfig(); + Cache::configure($config["cache"]); + Cache::store("redis"); + } } diff --git a/tests/Config/stubs/database.php b/tests/Config/stubs/database.php index f6cb2527..cabfbbfe 100644 --- a/tests/Config/stubs/database.php +++ b/tests/Config/stubs/database.php @@ -10,7 +10,7 @@ 'username' => getenv('MYSQL_USER'), 'password' => getenv('MYSQL_PASSWORD'), 'database' => getenv('MYSQL_DATABASE'), - 'charset' => getenv('MYSQL_CHARSET'), + 'charset' => getenv('MYSQL_CHARSET'), 'collation' => getenv('MYSQL_COLLATE') ? getenv('MYSQL_COLLATE') : 'utf8_unicode_ci', 'port' => 3306, 'socket' => null @@ -21,7 +21,7 @@ 'username' => "postgres", 'password' => "postgres", 'database' => "postgres", - 'charset' => "utf8", + 'charset' => "utf8", 'prefix' => app_env('DB_PREFIX', ''), 'port' => 5432, 'socket' => null diff --git a/tests/Config/stubs/mail.php b/tests/Config/stubs/mail.php index 7fb3cf6b..26d5aa7f 100644 --- a/tests/Config/stubs/mail.php +++ b/tests/Config/stubs/mail.php @@ -2,21 +2,21 @@ return [ 'driver' => 'smtp', - 'charset' => 'utf8', + 'charset' => 'utf8', 'smtp' => [ 'hostname' => 'localhost', 'username' => 'test@test.dev', 'password' => null, - 'port' => 1025, - 'tls' => false, - 'ssl' => false, - 'timeout' => 150, + 'port' => 1025, + 'tls' => false, + 'ssl' => false, + 'timeout' => 150, ], 'mail' => [ 'default' => 'contact', - 'froms' => [ + 'from' => [ 'contact' => [ 'address' => app_env('MAIL_FROM_EMAIL'), 'name' => app_env('MAIL_FROM_NAME') diff --git a/tests/Config/stubs/storage.php b/tests/Config/stubs/storage.php index 81857865..fc981f5e 100644 --- a/tests/Config/stubs/storage.php +++ b/tests/Config/stubs/storage.php @@ -26,7 +26,7 @@ 'hostname' => app_env('FTP_HOST', 'localhost'), 'password' => app_env('FTP_PASSWORD', 'password'), 'username' => app_env('FTP_USERNAME', 'username'), - 'port' => app_env('FTP_PORT', 21), + 'port' => app_env('FTP_PORT', 21), 'root' => app_env('FTP_ROOT', '/tmp'), // Start directory 'tls' => app_env('FTP_SSL', false), // `true` enable the secure connexion. 'timeout' => app_env('FTP_TIMEOUT', 90) // Temps d'attente de connection @@ -38,7 +38,7 @@ 's3' => [ "driver" => "s3", 'credentials' => [ - 'key' => getenv('AWS_KEY'), + 'key' => getenv('AWS_KEY'), 'secret' => getenv('AWS_SECRET'), ], 'bucket' => getenv('AWS_S3_BUCKET'), diff --git a/tests/Console/CustomCommandTest.php b/tests/Console/CustomCommandTest.php index de15135e..fe3b0a79 100644 --- a/tests/Console/CustomCommandTest.php +++ b/tests/Console/CustomCommandTest.php @@ -29,15 +29,9 @@ public function test_create_the_custom_command_from_static_calling() $this->clearFile(); } - public function test_create_the_custom_command_from_instance_calling() + protected function getFileContent() { - static::$console->addCommand("command", CustomCommand::class); - static::$console->call("command"); - - $content = $this->getFileContent(); - $this->assertEquals($content, 'ok'); - - $this->clearFile(); + return file_get_contents(TESTING_RESOURCE_BASE_DIRECTORY . '/test_custom_command.txt'); } protected function clearFile() @@ -45,8 +39,14 @@ protected function clearFile() file_put_contents(TESTING_RESOURCE_BASE_DIRECTORY . '/test_custom_command.txt', ''); } - protected function getFileContent() + public function test_create_the_custom_command_from_instance_calling() { - return file_get_contents(TESTING_RESOURCE_BASE_DIRECTORY . '/test_custom_command.txt'); + static::$console->addCommand("command", CustomCommand::class); + static::$console->call("command"); + + $content = $this->getFileContent(); + $this->assertEquals($content, 'ok'); + + $this->clearFile(); } } diff --git a/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_messaging_stubs__1.txt b/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_messaging_stubs__1.txt index 4e9ffe23..1f8fdcb8 100644 --- a/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_messaging_stubs__1.txt +++ b/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_messaging_stubs__1.txt @@ -3,6 +3,7 @@ namespace App\Messages; use Bow\Database\Barry\Model; +use Bow\Mail\Envelop; use Bow\Messaging\Messaging; class WelcomeMessage extends Messaging @@ -22,11 +23,11 @@ class WelcomeMessage extends Messaging * Send notification to mail * * @param Model $notifiable - * @return Message|null + * @return Envelop|null */ - public function toMail(Model $notifiable): ?Message + public function toMail(Model $notifiable): ?Envelop { - return (new Message()); + return (new Envelop()); } /** diff --git a/tests/Container/CapsuleTest.php b/tests/Container/CapsuleTest.php index 47519bb1..d0c91124 100644 --- a/tests/Container/CapsuleTest.php +++ b/tests/Container/CapsuleTest.php @@ -17,8 +17,8 @@ public static function setUpBeforeClass(): void { static::$capsule = new Capsule(); static::$capsule->factory('\Bow\Support\Collection', fn() => new \Bow\Support\Collection()); - static::$capsule->bind('std-class', fn () => new StdClass()); - static::$capsule->bind('my-class', fn (Capsule $container) => new MyClass($container['\Bow\Support\Collection'])); + static::$capsule->bind('std-class', fn() => new StdClass()); + static::$capsule->bind('my-class', fn(Capsule $container) => new MyClass($container['\Bow\Support\Collection'])); static::$capsule->instance("my-class-instance", new MyClass(new \Bow\Support\Collection())); } diff --git a/tests/Database/ConnectionTest.php b/tests/Database/ConnectionTest.php index 7c34454f..8e214e3f 100644 --- a/tests/Database/ConnectionTest.php +++ b/tests/Database/ConnectionTest.php @@ -4,9 +4,9 @@ use Bow\Configuration\Loader as ConfigurationLoader; use Bow\Database\Connection\AbstractConnection; -use Bow\Database\Connection\Adapter\MysqlAdapter; -use Bow\Database\Connection\Adapter\PostgreSQLAdapter; -use Bow\Database\Connection\Adapter\SqliteAdapter; +use Bow\Database\Connection\Adapters\MysqlAdapter; +use Bow\Database\Connection\Adapters\PostgreSQLAdapter; +use Bow\Database\Connection\Adapters\SqliteAdapter; use Bow\Tests\Config\TestingConfiguration; class ConnectionTest extends \PHPUnit\Framework\TestCase diff --git a/tests/Database/Migration/MigrationTest.php b/tests/Database/Migration/MigrationTest.php index 623cf72b..193d1b06 100644 --- a/tests/Database/Migration/MigrationTest.php +++ b/tests/Database/Migration/MigrationTest.php @@ -25,17 +25,6 @@ public static function setUpBeforeClass(): void Database::configure($config["database"]); } - protected function setUp(): void - { - $this->migration = new MigrationExtendedStub(); - ob_start(); - } - - protected function tearDown(): void - { - ob_get_clean(); - } - /** * @dataProvider connectionNames */ @@ -131,4 +120,15 @@ public function connectionNames() ['mysql'], ['sqlite'], ['pgsql'] ]; } + + protected function setUp(): void + { + $this->migration = new MigrationExtendedStub(); + ob_start(); + } + + protected function tearDown(): void + { + ob_get_clean(); + } } diff --git a/tests/Database/Migration/Mysql/SQLGeneratorTest.php b/tests/Database/Migration/Mysql/SQLGeneratorTest.php index bf190b7c..0822b8bb 100644 --- a/tests/Database/Migration/Mysql/SQLGeneratorTest.php +++ b/tests/Database/Migration/Mysql/SQLGeneratorTest.php @@ -13,11 +13,6 @@ class SQLGeneratorTest extends \PHPUnit\Framework\TestCase */ private $generator; - protected function setUp(): void - { - $this->generator = new SQLGenerator('bow_tests', 'mysql', 'create'); - } - /** * Test Add column action */ @@ -139,4 +134,9 @@ public function test_should_create_correct_timestamps_sql_statement() $this->assertEquals($sql, '`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'); } + + protected function setUp(): void + { + $this->generator = new SQLGenerator('bow_tests', 'mysql', 'create'); + } } diff --git a/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php b/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php index 9d312573..61fe8bcb 100644 --- a/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php +++ b/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php @@ -14,11 +14,6 @@ class SQLGenetorHelpersTest extends \PHPUnit\Framework\TestCase */ private $generator; - protected function setUp(): void - { - $this->generator = new SQLGenerator('bow_tests', 'mysql', 'create'); - } - /** * @dataProvider getStringTypesWithSize */ @@ -170,6 +165,7 @@ public function test_change_string_without_size_sql_statement(string $type, stri $sql = $this->generator->{"change$method"}('name', ['unique' => true])->make(); $this->assertEquals($sql, "MODIFY COLUMN `name` {$type} UNIQUE NOT NULL"); } + /** * Test Add column action * @dataProvider getNumberTypes @@ -233,4 +229,9 @@ public function getStringTypesWithoutSize() ["json", "Json", "{}"], ]; } + + protected function setUp(): void + { + $this->generator = new SQLGenerator('bow_tests', 'mysql', 'create'); + } } diff --git a/tests/Database/Migration/Pgsql/SQLGeneratorTest.php b/tests/Database/Migration/Pgsql/SQLGeneratorTest.php index a24ad598..686419bd 100644 --- a/tests/Database/Migration/Pgsql/SQLGeneratorTest.php +++ b/tests/Database/Migration/Pgsql/SQLGeneratorTest.php @@ -14,11 +14,6 @@ class SQLGeneratorTest extends \PHPUnit\Framework\TestCase */ private $generator; - protected function setUp(): void - { - $this->generator = new SQLGenerator('bow_tests', 'pgsql', 'create'); - } - /** * Test Add column action */ @@ -146,4 +141,9 @@ public function test_should_create_correct_timestamps_sql_statement() $this->assertEquals($sql, '"created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'); } + + protected function setUp(): void + { + $this->generator = new SQLGenerator('bow_tests', 'pgsql', 'create'); + } } diff --git a/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php b/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php index ab046d86..50257820 100644 --- a/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php +++ b/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php @@ -14,11 +14,6 @@ class SQLGenetorHelpersTest extends \PHPUnit\Framework\TestCase */ private $generator; - protected function setUp(): void - { - $this->generator = new SQLGenerator('bow_tests', 'pgsql', 'create'); - } - /** * @dataProvider getStringTypesWithSize */ @@ -311,4 +306,9 @@ public function getStringTypesWithoutSize() ["json", "Json", "{}"], ]; } + + protected function setUp(): void + { + $this->generator = new SQLGenerator('bow_tests', 'pgsql', 'create'); + } } diff --git a/tests/Database/Migration/SQLite/SQLGeneratorTest.php b/tests/Database/Migration/SQLite/SQLGeneratorTest.php index 62f76002..57f7221d 100644 --- a/tests/Database/Migration/SQLite/SQLGeneratorTest.php +++ b/tests/Database/Migration/SQLite/SQLGeneratorTest.php @@ -15,11 +15,6 @@ class SQLGeneratorTest extends \PHPUnit\Framework\TestCase */ private $generator; - protected function setUp(): void - { - $this->generator = new SQLGenerator('bow_tests', 'sqlite', 'create'); - } - /** * Test Add column action */ @@ -157,4 +152,9 @@ public function test_should_create_correct_timestamps_sql_statement() $this->assertEquals($sql, '`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'); } + + protected function setUp(): void + { + $this->generator = new SQLGenerator('bow_tests', 'sqlite', 'create'); + } } diff --git a/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php b/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php index 9c3ee1b7..d6e1d186 100644 --- a/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php +++ b/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php @@ -13,11 +13,6 @@ class SQLGenetorHelpersTest extends \PHPUnit\Framework\TestCase */ private $generator; - protected function setUp(): void - { - $this->generator = new SQLGenerator('bow_tests', 'sqlite', 'create'); - } - /** * Test Add column action */ @@ -89,4 +84,9 @@ public function getNumberTypes() ["MediumInteger", 1], ]; } + + protected function setUp(): void + { + $this->generator = new SQLGenerator('bow_tests', 'sqlite', 'create'); + } } diff --git a/tests/Database/PaginationTest.php b/tests/Database/PaginationTest.php index 9c23fe9a..8a806798 100644 --- a/tests/Database/PaginationTest.php +++ b/tests/Database/PaginationTest.php @@ -11,18 +11,6 @@ class PaginationTest extends TestCase { private Pagination $pagination; - protected function setUp(): void - { - $this->pagination = new Pagination( - next: 2, - previous: 0, - total: 3, - perPage: 10, - current: 1, - data: collect(['item1', 'item2', 'item3']) - ); - } - public function test_next(): void { $this->assertSame(2, $this->pagination->next()); @@ -47,4 +35,16 @@ public function test_total(): void { $this->assertSame(3, $this->pagination->total()); } + + protected function setUp(): void + { + $this->pagination = new Pagination( + next: 2, + previous: 0, + total: 3, + perPage: 10, + current: 1, + data: collect(['item1', 'item2', 'item3']) + ); + } } diff --git a/tests/Database/Query/DatabaseQueryTest.php b/tests/Database/Query/DatabaseQueryTest.php index 1e42e41e..6b3443bf 100644 --- a/tests/Database/Query/DatabaseQueryTest.php +++ b/tests/Database/Query/DatabaseQueryTest.php @@ -60,6 +60,14 @@ public function test_simple_insert_table(string $name) $this->assertEquals($result, 2); } + public function createTestingTable() + { + Database::statement('drop table if exists pets'); + Database::statement( + 'create table pets (id int primary key, name varchar(255))' + ); + } + /** * @dataProvider connectionNameProvider */ @@ -85,9 +93,9 @@ public function test_array_multile_insert_table(string $name) $this->createTestingTable(); $result = $database->insert("insert into pets values(:id, :name);", [ - [ "id" => 1, 'name' => 'Ploy'], - [ "id" => 2, 'name' => 'Cesar'], - [ "id" => 3, 'name' => 'Louis'], + ["id" => 1, 'name' => 'Ploy'], + ["id" => 2, 'name' => 'Cesar'], + ["id" => 3, 'name' => 'Louis'], ]); $this->assertEquals($result, 3); @@ -277,12 +285,4 @@ public function test_stement_table_2(string $name) $this->assertEquals(is_bool($result), true); } - - public function createTestingTable() - { - Database::statement('drop table if exists pets'); - Database::statement( - 'create table pets (id int primary key, name varchar(255))' - ); - } } diff --git a/tests/Database/Query/ModelQueryTest.php b/tests/Database/Query/ModelQueryTest.php index f5776be2..72701783 100644 --- a/tests/Database/Query/ModelQueryTest.php +++ b/tests/Database/Query/ModelQueryTest.php @@ -27,12 +27,39 @@ public function test_the_first_result_should_be_the_instance_of_same_model(strin $this->assertInstanceOf(PetModelStub::class, $pet); } + /** + * @param string $name + */ + public function createTestingTable(string $name) + { + $connection = Database::connection($name); + + if ($name == 'pgsql') { + $sql = 'create table pets (id serial primary key, name varchar(255))'; + } + + if ($name == 'sqlite') { + $sql = 'create table pets (id integer not null primary key autoincrement, name varchar(255))'; + } + + if ($name == 'mysql') { + $sql = 'create table pets (id int not null primary key auto_increment, name varchar(255))'; + } + + $connection->statement('drop table if exists pets'); + $connection->statement($sql); + $connection->insert('insert into pets(name) values(:name)', [ + ['name' => 'Couli'], ['name' => 'Bobi'] + ]); + } + /** * @dataProvider connectionNameProvider */ public function test_take_method_and_the_result_should_be_the_instance_of_the_same_model( string $name - ) { + ) + { $this->createTestingTable($name); $pet_model = new PetModelStub(); @@ -199,30 +226,4 @@ public function connectionNameProvider() { return [['mysql'], ['sqlite'], ['pgsql']]; } - - /** - * @param string $name - */ - public function createTestingTable(string $name) - { - $connection = Database::connection($name); - - if ($name == 'pgsql') { - $sql = 'create table pets (id serial primary key, name varchar(255))'; - } - - if ($name == 'sqlite') { - $sql = 'create table pets (id integer not null primary key autoincrement, name varchar(255))'; - } - - if ($name == 'mysql') { - $sql = 'create table pets (id int not null primary key auto_increment, name varchar(255))'; - } - - $connection->statement('drop table if exists pets'); - $connection->statement($sql); - $connection->insert('insert into pets(name) values(:name)', [ - ['name' => 'Couli'], ['name' => 'Bobi'] - ]); - } } diff --git a/tests/Database/Query/PaginationTest.php b/tests/Database/Query/PaginationTest.php index d0487569..b6c4afc9 100644 --- a/tests/Database/Query/PaginationTest.php +++ b/tests/Database/Query/PaginationTest.php @@ -32,6 +32,17 @@ public function test_go_current_pagination(string $name) $this->assertEquals($result->next(), 2); } + public function createTestingTable(string $name) + { + $connection = Database::connection($name); + $connection->statement('drop table if exists pets'); + $connection->statement('create table pets (id int primary key, name varchar(255))'); + $connection->table("pets")->truncate(); + foreach (range(1, 30) as $key) { + $connection->insert('insert into pets values(:id, :name)', ['id' => $key, 'name' => 'Pet ' . $key]); + } + } + /** * @dataProvider connectionNameProvider * @param Database $database @@ -75,15 +86,4 @@ public function connectionNameProvider() { return [['mysql'], ['sqlite'], ['pgsql']]; } - - public function createTestingTable(string $name) - { - $connection = Database::connection($name); - $connection->statement('drop table if exists pets'); - $connection->statement('create table pets (id int primary key, name varchar(255))'); - $connection->table("pets")->truncate(); - foreach (range(1, 30) as $key) { - $connection->insert('insert into pets values(:id, :name)', ['id' => $key, 'name' => 'Pet ' . $key]); - } - } } diff --git a/tests/Database/Query/QueryBuilderTest.php b/tests/Database/Query/QueryBuilderTest.php index 03718acf..c602d147 100644 --- a/tests/Database/Query/QueryBuilderTest.php +++ b/tests/Database/Query/QueryBuilderTest.php @@ -36,7 +36,7 @@ public function test_get_database_connection() } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -46,8 +46,16 @@ public function test_get_instance(string $name, Database $database) $this->assertInstanceOf(QueryBuilder::class, $database->connection($name)->table('pets')); } + public function createTestingTable(string $name) + { + Database::connection($name)->statement('drop table if exists pets'); + Database::connection($name)->statement( + 'create table pets (id int primary key, name varchar(255))' + ); + } + /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -66,7 +74,7 @@ public function test_insert_by_passing_a_array(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -78,16 +86,16 @@ public function test_insert_by_passing_a_mutilple_array(string $name, Database $ $table->truncate(); $r = $table->insert([ - [ 'id' => 1, 'name' => 'Milou'], - [ 'id' => 2, 'name' => 'Foli'], - [ 'id' => 3, 'name' => 'Bob'], + ['id' => 1, 'name' => 'Milou'], + ['id' => 2, 'name' => 'Foli'], + ['id' => 3, 'name' => 'Bob'], ]); $this->assertEquals($r, 3); } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -104,7 +112,7 @@ public function test_select_rows(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -118,7 +126,7 @@ public function test_select_chain_rows(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -139,7 +147,7 @@ public function test_select_first_chain_rows(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -153,7 +161,7 @@ public function test_where_in_chain_rows(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -167,7 +175,7 @@ public function test_where_null_chain_rows(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -181,7 +189,7 @@ public function test_where_between_chain_rows(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -195,7 +203,7 @@ public function test_where_not_between_chain_rows(string $name, Database $databa } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -209,7 +217,7 @@ public function test_where_not_null_chain_rows(string $name, Database $database) } /** - * @depends test_get_database_connection + * @depends test_get_database_connection * @dataProvider connectionNameProvider * @param Database $database */ @@ -233,12 +241,4 @@ public function connectionNameProvider() { return [['mysql'], ['sqlite'], ['pgsql']]; } - - public function createTestingTable(string $name) - { - Database::connection($name)->statement('drop table if exists pets'); - Database::connection($name)->statement( - 'create table pets (id int primary key, name varchar(255))' - ); - } } diff --git a/tests/Database/RedisTest.php b/tests/Database/RedisTest.php index 45f4fa2d..6a25c225 100644 --- a/tests/Database/RedisTest.php +++ b/tests/Database/RedisTest.php @@ -7,12 +7,6 @@ class RedisTest extends \PHPUnit\Framework\TestCase { - protected function setUp(): void - { - parent::setUp(); - $config = TestingConfiguration::getConfig(); - } - public function test_create_cache() { $result = Redis::get('name', 'Dakia'); @@ -27,4 +21,10 @@ public function test_get_cache() $this->assertNull(Redis::get('name')); $this->assertEquals(Redis::get('lastname'), "papac"); } + + protected function setUp(): void + { + parent::setUp(); + $config = TestingConfiguration::getConfig(); + } } diff --git a/tests/Filesystem/DiskFilesystemTest.php b/tests/Filesystem/DiskFilesystemTest.php index 0659af03..a973cc0c 100644 --- a/tests/Filesystem/DiskFilesystemTest.php +++ b/tests/Filesystem/DiskFilesystemTest.php @@ -29,17 +29,6 @@ public function setUp(): void $this->storage = Storage::disk(); } - public function getUploadedFileMock(): \PHPUnit\Framework\MockObject\MockObject - { - $uploadedFile = $this->getMockBuilder(UploadedFile::class) - ->disableOriginalConstructor() - ->getMock(); - - $uploadedFile->method("getContent")->willReturn("some content"); - - return $uploadedFile; - } - public function test_configuration() { $this->assertInstanceOf(DiskFilesystemService::class, $this->storage); @@ -136,6 +125,17 @@ public function test_store() $this->assertTrue($result); } + public function getUploadedFileMock(): \PHPUnit\Framework\MockObject\MockObject + { + $uploadedFile = $this->getMockBuilder(UploadedFile::class) + ->disableOriginalConstructor() + ->getMock(); + + $uploadedFile->method("getContent")->willReturn("some content"); + + return $uploadedFile; + } + public function test_store_on_custom_store() { $uploadedFile = $this->getUploadedFileMock(); diff --git a/tests/Filesystem/FTPServiceTest.php b/tests/Filesystem/FTPServiceTest.php index d0510a08..5e8d26de 100644 --- a/tests/Filesystem/FTPServiceTest.php +++ b/tests/Filesystem/FTPServiceTest.php @@ -20,16 +20,6 @@ public static function setUpBeforeClass(): void Storage::configure($config["storage"]); } - protected function setUp(): void - { - $this->ftp_service = Storage::service('ftp'); - } - - protected function tearDown(): void - { - $this->ftp_service->changePath(); - } - public function test_the_connection() { $this->assertInstanceOf(FTPService::class, $this->ftp_service); @@ -55,6 +45,18 @@ public function test_create_new_file_into_ftp_server() $this->assertTrue($result); } + private function createFile(FTPService $ftp_service, $filename, $content = '') + { + $uploaded_file = $this->getMockBuilder(\Bow\Http\UploadedFile::class) + ->disableOriginalConstructor() + ->getMock(); + + $uploaded_file->method('getContent')->willReturn($content); + $uploaded_file->method('getFilename')->willReturn($filename); + + return $ftp_service->store($uploaded_file, $filename); + } + public function test_file_should_not_be_existe() { $this->expectException(\Bow\Storage\Exception\ResourceException::class); @@ -179,15 +181,13 @@ public function test_put_content_into_file() $this->assertTrue(true); } - private function createFile(FTPService $ftp_service, $filename, $content = '') + protected function setUp(): void { - $uploaded_file = $this->getMockBuilder(\Bow\Http\UploadedFile::class) - ->disableOriginalConstructor() - ->getMock(); - - $uploaded_file->method('getContent')->willReturn($content); - $uploaded_file->method('getFilename')->willReturn($filename); + $this->ftp_service = Storage::service('ftp'); + } - return $ftp_service->store($uploaded_file, $filename); + protected function tearDown(): void + { + $this->ftp_service->changePath(); } } diff --git a/tests/Mail/MailServiceTest.php b/tests/Mail/MailServiceTest.php index 2fe9daf3..c2551bc1 100644 --- a/tests/Mail/MailServiceTest.php +++ b/tests/Mail/MailServiceTest.php @@ -3,23 +3,17 @@ namespace Bow\Tests\Mail; use Bow\Configuration\Loader as ConfigurationLoader; -use Bow\Mail\Contracts\MailDriverInterface; +use Bow\Mail\Contracts\MailAdapterInterface; +use Bow\Mail\Envelop; use Bow\Mail\Mail; -use Bow\Mail\Message; use Bow\Tests\Config\TestingConfiguration; use Bow\View\Exception\ViewException; use Bow\View\View; class MailServiceTest extends \PHPUnit\Framework\TestCase { - private ConfigurationLoader $config; - private static string $sendmail_command; - - protected function setUp(): void - { - $this->config = TestingConfiguration::getConfig(); - } + private ConfigurationLoader $config; public static function setUpBeforeClass(): void { @@ -33,13 +27,13 @@ public static function setUpBeforeClass(): void public function test_configuration_instance() { $mail = Mail::configure($this->config["mail"]); - $this->assertInstanceOf(MailDriverInterface::class, $mail); + $this->assertInstanceOf(MailAdapterInterface::class, $mail); } public function test_default_configuration_must_be_smtp_driver() { $mail = Mail::configure($this->config["mail"]); - $this->assertInstanceOf(\Bow\Mail\Driver\SmtpDriver::class, $mail); + $this->assertInstanceOf(\Bow\Mail\Adapters\SmtpAdapter::class, $mail); } public function test_send_mail_with_raw_content_for_stmp_driver() @@ -55,8 +49,8 @@ public function test_send_mail_with_view_for_stmp_driver() View::configure($this->config["view"]); Mail::configure($this->config["mail"]); - $response = Mail::send('mail', ['name' => "papac"], function (Message $message) { - $message->to('bow@bowphp.com'); + $response = Mail::send('mail', ['name' => "papac"], function (Envelop $envelop) { + $envelop->to('bow@bowphp.com'); }); $this->assertTrue($response); @@ -70,9 +64,9 @@ public function test_send_mail_with_view_not_found_for_smtp_driver() $this->expectException(ViewException::class); $this->expectExceptionMessage('The view [mail_view_not_found.twig] does not exists.'); - Mail::send('mail_view_not_found', ['name' => "papac"], function (Message $message) { - $message->to('bow@bowphp.com'); - $message->subject('test email'); + Mail::send('mail_view_not_found', ['name' => "papac"], function (Envelop $envelop) { + $envelop->to('bow@bowphp.com'); + $envelop->subject('test email'); }); } @@ -82,7 +76,7 @@ public function test_configuration_must_be_native_driver() $config['driver'] = 'mail'; $mail_instance = Mail::configure($config); - $this->assertInstanceOf(\Bow\Mail\Driver\NativeDriver::class, $mail_instance); + $this->assertInstanceOf(\Bow\Mail\Adapters\NativeAdapter::class, $mail_instance); } public function test_send_mail_with_raw_content_for_notive_driver() @@ -110,13 +104,13 @@ public function test_send_mail_with_view_for_notive_driver() return $this->markTestSkipped('Test have been skip because /usr/sbin/sendmail not found'); } - $config = (array) $this->config["mail"]; + $config = (array)$this->config["mail"]; View::configure($this->config["view"]); Mail::configure([...$config, "driver" => "mail"]); - $response = Mail::send('mail', ['name' => "papac"], function (Message $message) { - $message->to('bow@bowphp.com'); - $message->subject('test email'); + $response = Mail::send('mail', ['name' => "papac"], function (Envelop $envelop) { + $envelop->to('bow@bowphp.com'); + $envelop->subject('test email'); }); $this->assertTrue($response); @@ -124,7 +118,7 @@ public function test_send_mail_with_view_for_notive_driver() public function test_send_mail_with_view_not_found_for_notive_driver() { - $config = (array) $this->config["mail"]; + $config = (array)$this->config["mail"]; View::configure($this->config["view"]); Mail::configure([...$config, "driver" => "mail"]); @@ -132,9 +126,14 @@ public function test_send_mail_with_view_not_found_for_notive_driver() $this->expectException(ViewException::class); $this->expectExceptionMessage('The view [mail_view_not_found.twig] does not exists.'); - Mail::send('mail_view_not_found', ['name' => "papac"], function (Message $message) { - $message->to('bow@bowphp.com'); - $message->subject('test email'); + Mail::send('mail_view_not_found', ['name' => "papac"], function (Envelop $envelop) { + $envelop->to('bow@bowphp.com'); + $envelop->subject('test email'); }); } + + protected function setUp(): void + { + $this->config = TestingConfiguration::getConfig(); + } } diff --git a/tests/Messaging/MessagingTest.php b/tests/Messaging/MessagingTest.php index a3d94069..b9daad7e 100644 --- a/tests/Messaging/MessagingTest.php +++ b/tests/Messaging/MessagingTest.php @@ -13,9 +13,9 @@ class MessagingTest extends TestCase { + private static QueueConnection $queueConnection; private MockObject|Model $context; private MockObject|TestMessage $message; - private static QueueConnection $queueConnection; public static function setUpBeforeClass(): void { @@ -32,14 +32,6 @@ public static function setUpBeforeClass(): void ]); } - protected function setUp(): void - { - parent::setUp(); - - $this->context = $this->createMock(TestNotifiableModel::class); - $this->message = $this->createMock(TestMessage::class); - } - public function test_can_send_message_synchronously(): void { $this->message->expects($this->once()) @@ -191,4 +183,12 @@ public function test_message_can_send_to_telegram(): void $this->assertEquals('Test Telegram message', $data['message']); $this->assertEquals('HTML', $data['parse_mode']); } + + protected function setUp(): void + { + parent::setUp(); + + $this->context = $this->createMock(TestNotifiableModel::class); + $this->message = $this->createMock(TestMessage::class); + } } diff --git a/tests/Queue/MailQueueTest.php b/tests/Queue/MailQueueTest.php index 5de77c54..3a8872e7 100644 --- a/tests/Queue/MailQueueTest.php +++ b/tests/Queue/MailQueueTest.php @@ -5,7 +5,6 @@ use Bow\Configuration\LoggerConfiguration; use Bow\Mail\MailConfiguration; use Bow\Mail\MailQueueProducer; -use Bow\Mail\Message; use Bow\Queue\Connection as QueueConnection; use Bow\Queue\QueueConfiguration; use Bow\Tests\Config\TestingConfiguration; diff --git a/tests/Queue/QueueTest.php b/tests/Queue/QueueTest.php index e76f562d..d1f28868 100644 --- a/tests/Queue/QueueTest.php +++ b/tests/Queue/QueueTest.php @@ -2,7 +2,7 @@ namespace Bow\Tests\Queue; -use Bow\Cache\Adapter\RedisAdapter; +use Bow\Cache\Adapters\RedisAdapter; use Bow\Cache\CacheConfiguration; use Bow\Configuration\EnvConfiguration; use Bow\Configuration\LoggerConfiguration; diff --git a/tests/Queue/Stubs/BasicProducerStubs.php b/tests/Queue/Stubs/BasicProducerStubs.php index 1f720027..ae427c2e 100644 --- a/tests/Queue/Stubs/BasicProducerStubs.php +++ b/tests/Queue/Stubs/BasicProducerStubs.php @@ -8,7 +8,8 @@ class BasicProducerStubs extends ProducerService { public function __construct( private string $connection - ) { + ) + { } public function process(): void diff --git a/tests/Queue/Stubs/MixedProducerStub.php b/tests/Queue/Stubs/MixedProducerStub.php index e81b5e58..cae1a005 100644 --- a/tests/Queue/Stubs/MixedProducerStub.php +++ b/tests/Queue/Stubs/MixedProducerStub.php @@ -8,8 +8,9 @@ class MixedProducerStub extends ProducerService { public function __construct( private ServiceStub $service, - private string $connection - ) { + private string $connection + ) + { } public function process(): void diff --git a/tests/Queue/Stubs/ModelProducerStub.php b/tests/Queue/Stubs/ModelProducerStub.php index c467f73b..81213e9f 100644 --- a/tests/Queue/Stubs/ModelProducerStub.php +++ b/tests/Queue/Stubs/ModelProducerStub.php @@ -8,8 +8,9 @@ class ModelProducerStub extends ProducerService { public function __construct( private PetModelStub $pet, - private string $connection - ) { + private string $connection + ) + { $this->pet = $pet; $this->connection = $connection; } diff --git a/tests/Support/ArraydotifyTest.php b/tests/Support/ArraydotifyTest.php index 07c170c2..6bc0a451 100644 --- a/tests/Support/ArraydotifyTest.php +++ b/tests/Support/ArraydotifyTest.php @@ -33,11 +33,6 @@ class ArraydotifyTest extends \PHPUnit\Framework\TestCase ] ]; - protected function setUp(): void - { - $this->dot = new \Bow\Support\Arraydotify(['code' => $this->collection]); - } - public function test_get_normal() { $this->assertTrue(is_array($this->dot['code'])); @@ -78,4 +73,9 @@ public function test_get_unset_location() $this->assertTrue(isset($this->dot['code.location'])); } + + protected function setUp(): void + { + $this->dot = new \Bow\Support\Arraydotify(['code' => $this->collection]); + } } diff --git a/tests/Support/stubs/env.json b/tests/Support/stubs/env.json index 07b2781d..14108d3d 100644 --- a/tests/Support/stubs/env.json +++ b/tests/Support/stubs/env.json @@ -1,3 +1,3 @@ { - "APP_NAME": "papac" + "APP_NAME": "papac" } From 7c696c735dbc6299001978029ce0339c7ffa09fb Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sun, 26 Jan 2025 13:03:22 +0000 Subject: [PATCH 06/10] test(messaging): separate queue testing --- .../GenerateResourceControllerCommand.php | 9 +- src/Database/Barry/Concerns/Relationship.php | 20 ++- src/Database/Barry/Model.php | 10 +- src/Database/Barry/Relations/BelongsTo.php | 7 +- src/Database/Pagination.php | 13 +- src/Database/QueryBuilder.php | 43 +++--- src/Event/EventProducer.php | 3 +- src/Http/Response.php | 7 +- src/Mail/Adapters/LogAdapter.php | 2 +- src/Mail/Envelop.php | 5 +- src/Mail/MailQueueProducer.php | 7 +- src/Messaging/Messaging.php | 2 +- src/Messaging/MessagingQueueProducer.php | 5 +- src/Queue/Adapters/QueueAdapter.php | 6 +- src/Queue/WorkerService.php | 11 +- src/Router/Router.php | 9 +- src/Session/Cookie.php | 7 +- src/Support/Serializes.php | 3 +- src/Support/helpers.php | 42 +++--- .../Exception/ValidationException.php | 5 +- tests/Database/Query/ModelQueryTest.php | 3 +- tests/Messaging/MessagingTest.php | 101 +++------------ tests/Messaging/Stubs/TestMessage.php | 2 +- tests/Queue/EventQueueTest.php | 17 ++- tests/Queue/MailQueueTest.php | 24 ++-- tests/Queue/MessagingQueueTest.php | 122 ++++++++++++++++++ tests/Queue/QueueTest.php | 21 +-- tests/Queue/Stubs/BasicProducerStubs.php | 3 +- tests/Queue/Stubs/MixedProducerStub.php | 5 +- tests/Queue/Stubs/ModelProducerStub.php | 5 +- 30 files changed, 274 insertions(+), 245 deletions(-) create mode 100644 tests/Queue/MessagingQueueTest.php diff --git a/src/Console/Command/GenerateResourceControllerCommand.php b/src/Console/Command/GenerateResourceControllerCommand.php index cd08aa0f..eb3911bf 100644 --- a/src/Console/Command/GenerateResourceControllerCommand.php +++ b/src/Console/Command/GenerateResourceControllerCommand.php @@ -96,11 +96,10 @@ private function createDefaultView(string $base_directory): void */ private function createResourceController( Generator $generator, - string $prefix, - string $controller, - string $model_namespace = '' - ): void - { + string $prefix, + string $controller, + string $model_namespace = '' + ): void { $generator->write('controller/rest', [ 'modelNamespace' => $model_namespace, 'prefix' => $prefix, diff --git a/src/Database/Barry/Concerns/Relationship.php b/src/Database/Barry/Concerns/Relationship.php index 4b828bf1..fa9b359d 100644 --- a/src/Database/Barry/Concerns/Relationship.php +++ b/src/Database/Barry/Concerns/Relationship.php @@ -20,11 +20,10 @@ trait Relationship * @return BelongsTo */ public function belongsTo( - string $related, + string $related, ?string $foreign_key = null, ?string $local_key = null - ): BelongsTo - { + ): BelongsTo { // Create the new instance of model from container $related_model = app()->make($related); @@ -56,11 +55,10 @@ abstract public function getKey(): string; * @return BelongsToMany */ public function belongsToMany( - string $related, + string $related, ?string $primary_key = null, ?string $foreign_key = null - ): BelongsToMany - { + ): BelongsToMany { $related_model = app()->make($related); if (is_null($primary_key)) { @@ -84,11 +82,10 @@ public function belongsToMany( * @return HasMany */ public function hasMany( - string $related, + string $related, ?string $primary_key = null, ?string $foreign_key = null - ): HasMany - { + ): HasMany { $related_model = app()->make($related); if (is_null($primary_key)) { @@ -112,11 +109,10 @@ public function hasMany( * @return HasOne */ public function hasOne( - string $related, + string $related, ?string $foreign_key = null, ?string $primary_key = null - ): HasOne - { + ): HasOne { $related_model = app()->make($related); if (is_null($primary_key)) { diff --git a/src/Database/Barry/Model.php b/src/Database/Barry/Model.php index ed885180..4ac41aa0 100644 --- a/src/Database/Barry/Model.php +++ b/src/Database/Barry/Model.php @@ -311,9 +311,8 @@ public static function findBy(string $column, mixed $value): Collection */ public static function findAndDelete( int|string|array $id, - array $select = ['*'] - ): Collection|Model|null - { + array $select = ['*'] + ): Collection|Model|null { $model = static::find($id, $select); if (is_null($model)) { @@ -339,9 +338,8 @@ public static function findAndDelete( */ public static function find( int|string|array $id, - array $select = ['*'] - ): Collection|Model|null - { + array $select = ['*'] + ): Collection|Model|null { $id = (array)$id; $model = new static(); diff --git a/src/Database/Barry/Relations/BelongsTo.php b/src/Database/Barry/Relations/BelongsTo.php index 511a960b..335cdd6e 100644 --- a/src/Database/Barry/Relations/BelongsTo.php +++ b/src/Database/Barry/Relations/BelongsTo.php @@ -20,12 +20,11 @@ class BelongsTo extends Relation * @param string $local_key */ public function __construct( - Model $related, - Model $parent, + Model $related, + Model $parent, string $foreign_key, string $local_key - ) - { + ) { $this->local_key = $local_key; $this->foreign_key = $foreign_key; diff --git a/src/Database/Pagination.php b/src/Database/Pagination.php index 7798301d..b01c6341 100644 --- a/src/Database/Pagination.php +++ b/src/Database/Pagination.php @@ -8,14 +8,13 @@ class Pagination { public function __construct( - private readonly int $next, - private readonly int $previous, - private readonly int $total, - private readonly int $perPage, - private readonly int $current, + 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 - ) - { + ) { } public function next(): int diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index b7a34d12..d26b9fd3 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -240,11 +240,10 @@ public function orWhere(string $column, mixed $comparator = '=', mixed $value = */ public function where( string $column, - mixed $comparator = '=', - mixed $value = null, + mixed $comparator = '=', + mixed $value = null, string $boolean = 'and' - ): QueryBuilder - { + ): QueryBuilder { // We check here the applied comparator if (!static::isComparisonOperator($comparator) || is_null($value)) { @@ -543,12 +542,11 @@ public function whereIn(string $column, array $range, string $boolean = 'and'): * @return QueryBuilder */ public function join( - string $table, - string $first, - mixed $comparator = '=', + string $table, + string $first, + mixed $comparator = '=', ?string $second = null - ): QueryBuilder - { + ): QueryBuilder { $table = $this->getPrefix() . $table; if (is_null($this->join)) { @@ -603,12 +601,11 @@ public function setPrefix(string $prefix): QueryBuilder * @throws QueryBuilderException */ public function leftJoin( - string $table, - string $first, - mixed $comparator = '=', + string $table, + string $first, + mixed $comparator = '=', ?string $second = null - ): QueryBuilder - { + ): QueryBuilder { $table = $this->getPrefix() . $table; if (is_null($this->join)) { @@ -640,12 +637,11 @@ public function leftJoin( * @throws QueryBuilderException */ public function rightJoin( - string $table, - string $first, - mixed $comparator = '=', + string $table, + string $first, + mixed $comparator = '=', ?string $second = null - ): QueryBuilder - { + ): QueryBuilder { $table = $this->getPrefix() . $table; if (is_null($this->join)) { @@ -763,11 +759,10 @@ public function groupBy(string $column): QueryBuilder */ public function having( string $column, - mixed $comparator = '=', - $value = null, - $boolean = 'and' - ): QueryBuilder - { + mixed $comparator = '=', + $value = null, + $boolean = 'and' + ): QueryBuilder { // We check here the applied comparator if (!$this->isComparisonOperator($comparator)) { $value = $comparator; diff --git a/src/Event/EventProducer.php b/src/Event/EventProducer.php index c889b922..44c534c8 100644 --- a/src/Event/EventProducer.php +++ b/src/Event/EventProducer.php @@ -17,8 +17,7 @@ class EventProducer extends ProducerService public function __construct( private readonly mixed $event, private readonly mixed $payload = null, - ) - { + ) { parent::__construct(); } diff --git a/src/Http/Response.php b/src/Http/Response.php index 5ccc6362..2adb8f1d 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -120,11 +120,10 @@ public function addHeaders(array $headers): Response * @return string */ public function download( - string $file, + string $file, ?string $filename = null, - array $headers = [] - ): string - { + array $headers = [] + ): string { $type = mime_content_type($file); if (is_null($filename)) { diff --git a/src/Mail/Adapters/LogAdapter.php b/src/Mail/Adapters/LogAdapter.php index 8b3b0622..92744d4f 100644 --- a/src/Mail/Adapters/LogAdapter.php +++ b/src/Mail/Adapters/LogAdapter.php @@ -55,7 +55,7 @@ public function send(Envelop $envelop): bool $content .= "To: " . implode(', ', array_map(function ($to) { return $to[0] ? "{$to[0]} <{$to[1]}>" : $to[1]; - }, $envelop->getTo())) . "\n"; + }, $envelop->getTo())) . "\n"; $content .= "Subject: " . $envelop->getSubject() . "\n"; $content .= $envelop->getMessage(); diff --git a/src/Mail/Envelop.php b/src/Mail/Envelop.php index 1a4de18d..c86f28e5 100644 --- a/src/Mail/Envelop.php +++ b/src/Mail/Envelop.php @@ -4,9 +4,10 @@ namespace Bow\Mail; -use Bow\Mail\Exception\MailException; +use Bow\View\View; use Bow\Support\Str; use InvalidArgumentException; +use Bow\Mail\Exception\MailException; class Envelop { @@ -486,7 +487,7 @@ public function fromIsDefined(): bool */ public function view(string $view, array $data = []): Envelop { - $this->message(view($view, $data)->getContent()); + $this->message(View::parse($view, $data)->getContent()); return $this; } diff --git a/src/Mail/MailQueueProducer.php b/src/Mail/MailQueueProducer.php index 05979df1..ba061b94 100644 --- a/src/Mail/MailQueueProducer.php +++ b/src/Mail/MailQueueProducer.php @@ -23,11 +23,10 @@ class MailQueueProducer extends ProducerService * @param Envelop $message */ public function __construct( - string $view, - array $data, + string $view, + array $data, Envelop $envelop - ) - { + ) { parent::__construct(); $this->bags = [ diff --git a/src/Messaging/Messaging.php b/src/Messaging/Messaging.php index ecc2c3ec..38fd7c07 100644 --- a/src/Messaging/Messaging.php +++ b/src/Messaging/Messaging.php @@ -98,7 +98,7 @@ public function toTelegram(Model $context): array * @param Model $context * @return void */ - final public function process(Model $context): void + public function process(Model $context): void { $channels = $this->channels($context); diff --git a/src/Messaging/MessagingQueueProducer.php b/src/Messaging/MessagingQueueProducer.php index ad767098..a4610d98 100644 --- a/src/Messaging/MessagingQueueProducer.php +++ b/src/Messaging/MessagingQueueProducer.php @@ -22,10 +22,9 @@ class MessagingQueueProducer extends ProducerService * @param Messaging $message */ public function __construct( - Model $context, + Model $context, Messaging $message, - ) - { + ) { parent::__construct(); $this->bags = [ diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index 2310b4ad..0b379ced 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -64,8 +64,7 @@ abstract public function push(ProducerService $producer): void; */ public function serializeProducer( ProducerService $producer - ): string - { + ): string { return serialize($producer); } @@ -77,8 +76,7 @@ public function serializeProducer( */ public function unserializeProducer( string $producer - ): ProducerService - { + ): ProducerService { return unserialize($producer); } diff --git a/src/Queue/WorkerService.php b/src/Queue/WorkerService.php index dcdca31c..b9177c7b 100644 --- a/src/Queue/WorkerService.php +++ b/src/Queue/WorkerService.php @@ -39,12 +39,11 @@ public function setConnection(QueueAdapter $connection): void */ #[NoReturn] public function run( string $queue = "default", - int $tries = 3, - int $sleep = 5, - int $timeout = 60, - int $memory = 128 - ): void - { + int $tries = 3, + int $sleep = 5, + int $timeout = 60, + int $memory = 128 + ): void { $this->connection->setQueue($queue); $this->connection->setTries($tries); $this->connection->setSleep($sleep); diff --git a/src/Router/Router.php b/src/Router/Router.php index 1edd229b..08bae6e1 100644 --- a/src/Router/Router.php +++ b/src/Router/Router.php @@ -80,12 +80,11 @@ class Router * @param array $middlewares */ protected function __construct( - string $method, + string $method, ?string $magic_method = null, - string $base_route = '', - array $middlewares = [] - ) - { + string $base_route = '', + array $middlewares = [] + ) { $this->method = $method; $this->magic_method = $magic_method; $this->middlewares = $middlewares; diff --git a/src/Session/Cookie.php b/src/Session/Cookie.php index f0c68327..58ca6d21 100644 --- a/src/Session/Cookie.php +++ b/src/Session/Cookie.php @@ -118,10 +118,9 @@ public static function remove(string $key): string|bool|null */ public static function set( int|string $key, - mixed $data, - int $expiration = 3600, - ): bool - { + mixed $data, + int $expiration = 3600, + ): bool { $data = Crypto::encrypt(json_encode($data)); return setcookie( diff --git a/src/Support/Serializes.php b/src/Support/Serializes.php index e295d5fa..266a5da9 100644 --- a/src/Support/Serializes.php +++ b/src/Support/Serializes.php @@ -57,8 +57,7 @@ public function __serialize() */ protected function getPropertyValue( ReflectionProperty $property - ): mixed - { + ): mixed { return $property->getValue($this); } diff --git a/src/Support/helpers.php b/src/Support/helpers.php index ff92285d..7bb49e19 100644 --- a/src/Support/helpers.php +++ b/src/Support/helpers.php @@ -780,11 +780,10 @@ function flash(string $key, string $message): mixed * @return MailAdapterInterface|bool */ function email( - string $view = null, - array $data = [], + string $view = null, + array $data = [], callable $cb = null - ): MailAdapterInterface|bool - { + ): MailAdapterInterface|bool { if ($view === null) { return Mail::getInstance(); } @@ -848,10 +847,9 @@ function session(array|string $value = null, mixed $default = null): mixed */ function cookie( string $key = null, - mixed $data = null, - int $expiration = 3600 - ): string|array|object|null - { + mixed $data = null, + int $expiration = 3600 + ): string|array|object|null { if ($key === null) { return Cookie::all(); } @@ -1074,10 +1072,9 @@ function bow_hash(string $data, string $hash_value = null): bool|string */ function app_trans( string $key = null, - array $data = [], - bool $choose = false - ): string|Translator - { + array $data = [], + bool $choose = false + ): string|Translator { if (is_null($key)) { return Translator::getInstance(); } @@ -1102,10 +1099,9 @@ function app_trans( */ function t( string $key, - array $data = [], - bool $choose = false - ): string|Translator - { + array $data = [], + bool $choose = false + ): string|Translator { return app_trans($key, $data, $choose); } } @@ -1121,10 +1117,9 @@ function t( */ function __( string $key, - array $data = [], - bool $choose = false - ): string|Translator - { + array $data = [], + bool $choose = false + ): string|Translator { return app_trans($key, $data, $choose); } } @@ -1190,11 +1185,10 @@ function app_abort(int $code = 500, string $message = ''): Response * @throws HttpException */ function app_abort_if( - bool $boolean, - int $code, + bool $boolean, + int $code, string $message = '' - ): Response|null - { + ): Response|null { if ($boolean) { return app_abort($code, $message); } diff --git a/src/Validation/Exception/ValidationException.php b/src/Validation/Exception/ValidationException.php index 483a1199..af43179e 100644 --- a/src/Validation/Exception/ValidationException.php +++ b/src/Validation/Exception/ValidationException.php @@ -24,10 +24,9 @@ class ValidationException extends HttpException */ public function __construct( string $message, - array $errors = [], + array $errors = [], string $status = 'VALIDATION_ERROR' - ) - { + ) { parent::__construct($message, 400); $this->errors = $errors; $this->status = $status; diff --git a/tests/Database/Query/ModelQueryTest.php b/tests/Database/Query/ModelQueryTest.php index 72701783..bdaa9c0d 100644 --- a/tests/Database/Query/ModelQueryTest.php +++ b/tests/Database/Query/ModelQueryTest.php @@ -58,8 +58,7 @@ public function createTestingTable(string $name) */ public function test_take_method_and_the_result_should_be_the_instance_of_the_same_model( string $name - ) - { + ) { $this->createTestingTable($name); $pet_model = new PetModelStub(); diff --git a/tests/Messaging/MessagingTest.php b/tests/Messaging/MessagingTest.php index b9daad7e..3dd6264e 100644 --- a/tests/Messaging/MessagingTest.php +++ b/tests/Messaging/MessagingTest.php @@ -2,14 +2,15 @@ namespace Bow\Tests\Messaging; -use Bow\Database\Barry\Model; +use Bow\View\View; use Bow\Mail\Envelop; -use Bow\Messaging\MessagingQueueProducer; -use Bow\Queue\Connection as QueueConnection; +use Bow\Database\Barry\Model; +use PHPUnit\Framework\TestCase; +use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Messaging\Stubs\TestMessage; -use Bow\Tests\Messaging\Stubs\TestNotifiableModel; +use Bow\Queue\Connection as QueueConnection; use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; +use Bow\Tests\Messaging\Stubs\TestNotifiableModel; class MessagingTest extends TestCase { @@ -22,86 +23,26 @@ public static function setUpBeforeClass(): void parent::setUpBeforeClass(); // Initialize queue connection - static::$queueConnection = new QueueConnection([ - 'default' => 'sync', - 'connections' => [ - 'sync' => [ - 'driver' => 'sync' - ] - ] - ]); - } - - public function test_can_send_message_synchronously(): void - { - $this->message->expects($this->once()) - ->method('process') - ->with($this->context); - - $this->context->sendMessage($this->message); - } + $config = TestingConfiguration::getConfig(); - public function test_can_send_message_to_queue(): void - { - $producer = new MessagingQueueProducer($this->context, $this->message); - - // Verify that the producer is created with correct parameters - $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - - // Push to queue and verify - static::$queueConnection->getAdapter()->push($producer); - - $this->context->setMessageQueue($this->message); + View::configure($config["view"]); } - public function test_can_send_message_to_specific_queue(): void - { - $queue = 'high-priority'; - $producer = new MessagingQueueProducer($this->context, $this->message); - - // Verify that the producer is created with correct parameters - $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - - // Push to specific queue and verify - $adapter = static::$queueConnection->getAdapter(); - $adapter->setQueue($queue); - $adapter->push($producer); - - $this->context->sendMessageQueueOn($queue, $this->message); - } - - public function test_can_send_message_with_delay(): void + protected function setUp(): void { - $delay = 3600; - $producer = new MessagingQueueProducer($this->context, $this->message); - - // Verify that the producer is created with correct parameters - $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - - // Push to queue and verify - $adapter = static::$queueConnection->getAdapter(); - $adapter->setSleep($delay); - $adapter->push($producer); + parent::setUp(); - $this->context->sendMessageLater($delay, $this->message); + $this->context = new TestNotifiableModel(); + $this->message = $this->createMock(TestMessage::class); } - public function test_can_send_message_with_delay_on_specific_queue(): void + public function test_can_send_message_synchronously(): void { - $delay = 3600; - $queue = 'delayed-notifications'; - $producer = new MessagingQueueProducer($this->context, $this->message); - - // Verify that the producer is created with correct parameters - $this->assertInstanceOf(MessagingQueueProducer::class, $producer); - - // Push to specific queue with delay and verify - $adapter = static::$queueConnection->getAdapter(); - $adapter->setQueue($queue); - $adapter->setSleep($delay); - $adapter->push($producer); + $this->message->expects($this->once()) + ->method('process') + ->with($this->context); - $this->context->sendMessageLaterOn($delay, $queue, $this->message); + $this->context->sendMessage($this->message); } public function test_message_sends_to_correct_channels(): void @@ -183,12 +124,4 @@ public function test_message_can_send_to_telegram(): void $this->assertEquals('Test Telegram message', $data['message']); $this->assertEquals('HTML', $data['parse_mode']); } - - protected function setUp(): void - { - parent::setUp(); - - $this->context = $this->createMock(TestNotifiableModel::class); - $this->message = $this->createMock(TestMessage::class); - } } diff --git a/tests/Messaging/Stubs/TestMessage.php b/tests/Messaging/Stubs/TestMessage.php index e3cef600..6ce69499 100644 --- a/tests/Messaging/Stubs/TestMessage.php +++ b/tests/Messaging/Stubs/TestMessage.php @@ -18,7 +18,7 @@ public function toMail(Model $context): Envelop return (new Envelop()) ->to('test@example.com') ->subject('Test Message') - ->view('test-view'); + ->view('email'); } public function toDatabase(Model $context): array diff --git a/tests/Queue/EventQueueTest.php b/tests/Queue/EventQueueTest.php index 31c52429..26ca7bee 100644 --- a/tests/Queue/EventQueueTest.php +++ b/tests/Queue/EventQueueTest.php @@ -1,18 +1,21 @@ to("bow@bow.org"); - $message->subject("hello from bow"); - $producer = new MailQueueProducer("email", [], $message); + $envelop = new Envelop(); + $envelop->to("bow@bow.org"); + $envelop->subject("hello from bow"); + $producer = new MailQueueProducer("email", [], $envelop); $adapter = static::$connection->setConnection("beanstalkd")->getAdapter(); diff --git a/tests/Queue/MessagingQueueTest.php b/tests/Queue/MessagingQueueTest.php new file mode 100644 index 00000000..1d67504a --- /dev/null +++ b/tests/Queue/MessagingQueueTest.php @@ -0,0 +1,122 @@ +boot(); + + static::$connection = new QueueConnection($config["queue"]); + } + + protected function setUp(): void + { + parent::setUp(); + + $this->context = new TestNotifiableModel(); + $this->message = $this->createMock(TestMessage::class); + } + + public function test_can_send_message_synchronously(): void + { + $this->message->expects($this->once()) + ->method('process') + ->with($this->context); + + $this->context->sendMessage($this->message); + } + + public function test_can_send_message_to_queue(): void + { + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to queue and verify + static::$connection->setConnection("beanstalkd")->getAdapter()->push($producer); + + $this->context->setMessageQueue($this->message); + } + + public function test_can_send_message_to_specific_queue(): void + { + $queue = 'high-priority'; + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to specific queue and verify + $adapter = static::$connection->setConnection("beanstalkd")->getAdapter(); + $adapter->setQueue($queue); + $adapter->push($producer); + + $this->context->sendMessageQueueOn($queue, $this->message); + } + + public function test_can_send_message_with_delay(): void + { + $delay = 3600; + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to queue and verify + $adapter = static::$connection->setConnection("beanstalkd")->getAdapter(); + $adapter->setSleep($delay); + $adapter->push($producer); + + $this->context->sendMessageLater($delay, $this->message); + } + + public function test_can_send_message_with_delay_on_specific_queue(): void + { + $delay = 3600; + $queue = 'delayed-notifications'; + $producer = new MessagingQueueProducer($this->context, $this->message); + + // Verify that the producer is created with correct parameters + $this->assertInstanceOf(MessagingQueueProducer::class, $producer); + + // Push to specific queue with delay and verify + $adapter = static::$connection->setConnection("beanstalkd")->getAdapter(); + $adapter->setQueue($queue); + $adapter->setSleep($delay); + $adapter->push($producer); + + $this->context->sendMessageLaterOn($delay, $queue, $this->message); + } +} diff --git a/tests/Queue/QueueTest.php b/tests/Queue/QueueTest.php index d1f28868..8a9ec4e9 100644 --- a/tests/Queue/QueueTest.php +++ b/tests/Queue/QueueTest.php @@ -2,23 +2,24 @@ namespace Bow\Tests\Queue; -use Bow\Cache\Adapters\RedisAdapter; +use Bow\Database\Database; +use PHPUnit\Framework\TestCase; use Bow\Cache\CacheConfiguration; +use Bow\Queue\Adapters\SQSAdapter; +use Bow\Queue\Adapters\SyncAdapter; +use Bow\Cache\Adapters\RedisAdapter; use Bow\Configuration\EnvConfiguration; -use Bow\Configuration\LoggerConfiguration; -use Bow\Database\Database; use Bow\Database\DatabaseConfiguration; -use Bow\Queue\Adapters\BeanstalkdAdapter; use Bow\Queue\Adapters\DatabaseAdapter; -use Bow\Queue\Adapters\SQSAdapter; -use Bow\Queue\Adapters\SyncAdapter; -use Bow\Queue\Connection as QueueConnection; +use Bow\Tests\Queue\Stubs\PetModelStub; +use Bow\Queue\Adapters\BeanstalkdAdapter; +use Bow\Configuration\LoggerConfiguration; use Bow\Tests\Config\TestingConfiguration; -use Bow\Tests\Queue\Stubs\BasicProducerStubs; +use Bow\Queue\Connection as QueueConnection; use Bow\Tests\Queue\Stubs\ModelProducerStub; -use Bow\Tests\Queue\Stubs\PetModelStub; +use Bow\Tests\Queue\Stubs\BasicProducerStubs; -class QueueTest extends \PHPUnit\Framework\TestCase +class QueueTest extends TestCase { private static $connection; diff --git a/tests/Queue/Stubs/BasicProducerStubs.php b/tests/Queue/Stubs/BasicProducerStubs.php index ae427c2e..1f720027 100644 --- a/tests/Queue/Stubs/BasicProducerStubs.php +++ b/tests/Queue/Stubs/BasicProducerStubs.php @@ -8,8 +8,7 @@ class BasicProducerStubs extends ProducerService { public function __construct( private string $connection - ) - { + ) { } public function process(): void diff --git a/tests/Queue/Stubs/MixedProducerStub.php b/tests/Queue/Stubs/MixedProducerStub.php index cae1a005..e81b5e58 100644 --- a/tests/Queue/Stubs/MixedProducerStub.php +++ b/tests/Queue/Stubs/MixedProducerStub.php @@ -8,9 +8,8 @@ class MixedProducerStub extends ProducerService { public function __construct( private ServiceStub $service, - private string $connection - ) - { + private string $connection + ) { } public function process(): void diff --git a/tests/Queue/Stubs/ModelProducerStub.php b/tests/Queue/Stubs/ModelProducerStub.php index 81213e9f..c467f73b 100644 --- a/tests/Queue/Stubs/ModelProducerStub.php +++ b/tests/Queue/Stubs/ModelProducerStub.php @@ -8,9 +8,8 @@ class ModelProducerStub extends ProducerService { public function __construct( private PetModelStub $pet, - private string $connection - ) - { + private string $connection + ) { $this->pet = $pet; $this->connection = $connection; } From 6624634a52ef3cd9e71eca1dccea2040d05606f8 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sun, 26 Jan 2025 13:43:53 +0000 Subject: [PATCH 07/10] refactor: update envelop api --- src/Mail/Adapters/NativeAdapter.php | 9 ++- src/Mail/Envelop.php | 104 ++++++++++++---------------- src/Mail/Mail.php | 2 +- tests/Queue/MessagingQueueTest.php | 8 ++- 4 files changed, 58 insertions(+), 65 deletions(-) diff --git a/src/Mail/Adapters/NativeAdapter.php b/src/Mail/Adapters/NativeAdapter.php index b99f4491..74a21ac7 100644 --- a/src/Mail/Adapters/NativeAdapter.php +++ b/src/Mail/Adapters/NativeAdapter.php @@ -48,14 +48,14 @@ public function __construct(array $config = []) */ public function on(string $from): NativeAdapter { - if (!isset($this->config["froms"][$from])) { + if (!isset($this->config["from"][$from])) { throw new MailException( "There are not entry for [$from]", E_USER_ERROR ); } - $this->from = $this->config["froms"][$from]; + $this->from = $this->config["from"][$from]; return $this; } @@ -86,7 +86,10 @@ public function send(Envelop $envelop): bool $envelop->setDefaultHeader(); - foreach ($envelop->getTo() as $value) { + foreach ($envelop->getTo() as $key => $value) { + if ($key > 0) { + $to .= ', '; + } if ($value[0] !== null) { $to .= $value[0] . ' <' . $value[1] . '>'; } else { diff --git a/src/Mail/Envelop.php b/src/Mail/Envelop.php index c86f28e5..34e18004 100644 --- a/src/Mail/Envelop.php +++ b/src/Mail/Envelop.php @@ -142,53 +142,16 @@ public function addHeader(string $key, string $value): void /** * Define the receiver * - * @param string $to - * @param ?string $name + * @param string|array $to * * @return Envelop */ - public function to(string $to, ?string $name = null): Envelop - { - $this->to[] = $this->formatEmail($to, $name); - - return $this; - } - - /** - * Format the email receiver - * - * @param string $email - * @param ?string $name - * @return array - */ - private function formatEmail(string $email, ?string $name = null): array + public function to(string|array $to): Envelop { - /** - * Organization of the list of senders - */ - if (!is_string($name) && preg_match('/^(.+)\s+<(.*)>\z$/', $email, $matches)) { - array_shift($matches); - $name = $matches[0]; - $email = $matches[1]; - } + $recipients = (array) $to; - if (!Str::isMail($email)) { - throw new InvalidArgumentException("$email is not valid email.", E_USER_ERROR); - } - - return [$name, $email]; - } - - /** - * Define the receiver in list - * - * @param array $recipients - * @return $this - */ - public function toList(array $recipients): Envelop - { - foreach ($recipients as $name => $to) { - $this->to[] = $this->formatEmail($to, !is_int($name) ? $name : null); + foreach ($recipients as $to) { + $this->to[] = $this->formatEmail($to); } return $this; @@ -275,22 +238,6 @@ public function html(string $html): Envelop return $this->type($html, "text/html"); } - /** - * Add message body and set message type - * - * @param string $message - * @param string $type - * @return Envelop - */ - private function type(string $message, string $type): Envelop - { - $this->type = $type; - - $this->message = $message; - - return $this; - } - /** * Add message body * @@ -503,4 +450,45 @@ public function message(string $message, string $type = 'text/html'): void { $this->setMessage($message, $type); } + + /** + * Format the email receiver + * + * @param string $email + * @return array + */ + private function formatEmail(string $email): array + { + /** + * Organization of the list of senders + */ + $name = null; + if (preg_match('/^(.+)\s+<(.*)>\z$/', $email, $matches)) { + array_shift($matches); + $name = $matches[0]; + $email = $matches[1]; + } + + if (!Str::isMail($email)) { + throw new InvalidArgumentException("$email is not valid email.", E_USER_ERROR); + } + + return [$name, $email]; + } + + /** + * Add message body and set message type + * + * @param string $message + * @param string $type + * @return Envelop + */ + private function type(string $message, string $type): Envelop + { + $this->type = $type; + + $this->message = $message; + + return $this; + } } diff --git a/src/Mail/Mail.php b/src/Mail/Mail.php index 475c3996..2edeff59 100644 --- a/src/Mail/Mail.php +++ b/src/Mail/Mail.php @@ -119,7 +119,7 @@ public static function raw(string|array $to, string $subject, string $data, arra $envelop = new Envelop(); - $envelop->toList($to)->subject($subject)->setMessage($data); + $envelop->to($to)->subject($subject)->setMessage($data); foreach ($headers as $key => $value) { $envelop->addHeader($key, $value); diff --git a/tests/Queue/MessagingQueueTest.php b/tests/Queue/MessagingQueueTest.php index 1d67504a..e354685f 100644 --- a/tests/Queue/MessagingQueueTest.php +++ b/tests/Queue/MessagingQueueTest.php @@ -44,17 +44,19 @@ protected function setUp(): void { parent::setUp(); - $this->context = new TestNotifiableModel(); + $this->context = $this->createMock(TestNotifiableModel::class); $this->message = $this->createMock(TestMessage::class); } public function test_can_send_message_synchronously(): void { + $context = new TestNotifiableModel(); + $this->message->expects($this->once()) ->method('process') - ->with($this->context); + ->with($context); - $this->context->sendMessage($this->message); + $context->sendMessage($this->message); } public function test_can_send_message_to_queue(): void From 348da204283f869189e40178060272bcdc29696f Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sun, 26 Jan 2025 14:08:19 +0000 Subject: [PATCH 08/10] refactor: update mail api --- .github/workflows/tests.yml | 2 +- docker-compose.yml | 131 +++++++++++++++++++++++--- src/Database/README.md | 58 +++++++++++- src/Mail/Adapters/SesAdapter.php | 2 +- src/Mail/Adapters/SmtpAdapter.php | 4 +- src/Mail/Envelop.php | 100 +++++++++++--------- src/Messaging/README.md | 36 +++++++ src/Router/README.md | 41 ++++++++ tests/Config/TestingConfiguration.php | 4 +- tests/Messaging/MessagingTest.php | 29 +++--- tests/Queue/EventQueueTest.php | 17 ++-- tests/Queue/MailQueueTest.php | 16 ++-- tests/Queue/MessagingQueueTest.php | 34 +++---- tests/Queue/QueueTest.php | 24 ++--- 14 files changed, 376 insertions(+), 122 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 99d0165f..c9ccf779 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -45,7 +45,7 @@ jobs: - run: docker run -p 21:21 -p 20:20 -p 12020:12020 -p 12021:12021 -p 12022:12022 -p 12023:12023 -p 12024:12024 -p 12025:12025 -e USER=$FTP_USER -e PASS=$FTP_PASSWORD -d --name ftp papacdev/vsftpd - run: docker run -p 1080:1080 -p 1025:1025 -d --name maildev soulteary/maildev - run: docker run -p 6379:6379 -d --name redis redis - - run: docker run -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -e POSTGRES_PASSWORD=postgres -d postgis/postgis + - run: docker run -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -d postgis/postgis - run: docker run -d -p 11300:11300 schickling/beanstalkd - name: Cache Composer packages diff --git a/docker-compose.yml b/docker-compose.yml index 1c981c66..521377e2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,31 +1,132 @@ -version: "3" +version: '3.8' + +volumes: + mysql_data: + driver: local + postgres_data: + driver: local + redis_data: + driver: local + ftp_storage: + driver: local + +networks: + bowphp_network: + driver: bridge + services: - db: - container_name: mysql - command: --default-authentication-plugin=mysql_native_password --max_allowed_packet=1073741824 - image: mysql + mysql: + container_name: bowphp_mysql + image: mysql/mysql-server:8.0 + restart: unless-stopped ports: - "3306:3306" environment: - MYSQL_DATABASE: test - MYSQL_USERNAME: travis - MYSQL_ALLOW_EMPTY_PASSWORD: "yes" + MYSQL_DATABASE: test_db + MYSQL_ROOT_PASSWORD: password + MYSQL_ROOT_HOST: "%" + MYSQL_ALLOW_EMPTY_PASSWORD: "no" + command: --default-authentication-plugin=mysql_native_password + volumes: + - mysql_data:/var/lib/mysql + networks: + - bowphp_network + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-ppassword"] + interval: 10s + timeout: 5s + retries: 5 + postgres: + container_name: bowphp_postgres + image: postgis/postgis:15-3.3 + restart: unless-stopped + ports: + - "5432:5432" + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: postgres + volumes: + - postgres_data:/var/lib/postgresql/data + networks: + - bowphp_network + healthcheck: + test: ["CMD-SHELL", "pg_isready -U bowphp"] + interval: 10s + timeout: 5s + retries: 5 ftp: - container_name: ftp-server - image: emilybache/vsftpd-server + container_name: bowphp_ftp + image: papacdev/vsftpd + restart: unless-stopped ports: - - "21" + - "21:21" + - "20:20" + - "12020-12025:12020-12025" environment: USER: bob PASS: "12345" volumes: - "ftp_storage:/ftp/$USER" + networks: + - bowphp_network mail: - container_name: mail + container_name: bowphp_mail image: maildev/maildev + restart: unless-stopped ports: - "1025:25" - "1080:80" - -volumes: - ftp_storage: + networks: + - bowphp_network + healthcheck: + test: ["CMD", "nc", "-z", "localhost", "25"] + interval: 10s + timeout: 5s + retries: 5 + beanstalkd: + container_name: bowphp_beanstalkd + image: schickling/beanstalkd + restart: unless-stopped + ports: + - "11300:11300" + networks: + - bowphp_network + healthcheck: + test: ["CMD", "nc", "-z", "localhost", "11300"] + interval: 10s + timeout: 5s + retries: 5 + redis: + container_name: bowphp_redis + image: redis:7-alpine + restart: unless-stopped + ports: + - "6379:6379" + volumes: + - redis_data:/data + networks: + - bowphp_network + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 5 + command: redis-server --appendonly yes + memcached: + container_name: bowphp_memcached + image: memcached:1.6-alpine + restart: unless-stopped + ports: + - "11211:11211" + command: + - --conn-limit=1024 + - --memory-limit=64 + - --threads=4 + networks: + - bowphp_network + healthcheck: + test: ["CMD", "nc", "-z", "localhost", "11211"] + interval: 10s + timeout: 5s + retries: 5 diff --git a/src/Database/README.md b/src/Database/README.md index 45b39e37..deca0e68 100644 --- a/src/Database/README.md +++ b/src/Database/README.md @@ -32,7 +32,16 @@ Database::configure([ "database" => ":memory:", "prefix" => "table_prefix" ], - // TODO: Build the pgsql support for v5.0 + 'pgsql' => [ + 'driver' => 'pgsql', + 'hostname' => app_env('DB_HOSTNAME', 'localhost'), + 'username' => app_env('DB_USERNAME', 'test'), + 'password' => app_env('DB_PASSWORD', 'test'), + 'database' => app_env('DB_DBNAME', 'test'), + 'charset' => app_env('DB_CHARSET', 'utf8'), + 'prefix' => app_env('DB_PREFIX', ''), + 'port' => app_env('DB_PORT', 3306) + ], ] ]); ``` @@ -53,4 +62,51 @@ use App\Models\User as UserModel; $users = UserModel::all(); ``` +## Diagramme de séquence + +```mermaid +sequenceDiagram + participant App as Application + participant DB as Database + participant Adapter as DatabaseAdapter + participant Query as QueryBuilder + participant PDO as PDO Connection + participant DB_Server as Database Server + + Note over App,DB_Server: Configuration and Connection + + App->>DB: Database::configure(config) + DB->>DB: getInstance() + + alt MySQL Connection + DB->>Adapter: new MysqlAdapter(config) + else PostgreSQL Connection + DB->>Adapter: new PostgreSQLAdapter(config) + else SQLite Connection + DB->>Adapter: new SqliteAdapter(config) + end + + Adapter->>PDO: new PDO(dsn, username, password) + PDO-->>DB_Server: Establishes connection + + Note over App,DB_Server: Queries with Query Builder + + App->>DB: table('users') + DB->>Query: new QueryBuilder('users', connection) + Query->>Adapter: getInstance() + + alt Select Query + App->>Query: where('id', 1)->get() + Query->>Query: toSql() + Query->>PDO: prepare(sql) + PDO->>DB_Server: Execute Query + DB_Server-->>App: Results + else Insert Query + App->>Query: insert(['name' => 'John']) + Query->>PDO: prepare(sql) + PDO->>DB_Server: Execute Query + DB_Server-->>App: Affected Rows + end +``` + Is very enjoyful api diff --git a/src/Mail/Adapters/SesAdapter.php b/src/Mail/Adapters/SesAdapter.php index 6f1e7ac2..13d7c54c 100644 --- a/src/Mail/Adapters/SesAdapter.php +++ b/src/Mail/Adapters/SesAdapter.php @@ -79,7 +79,7 @@ public function send(Envelop $envelop): bool $email = [ 'Destination' => [ - 'ToAddresses' => $envelop->getTo(), + 'ToAddresses' => array_map(fn($value) => $value[0] !== null ? $value[0] . ' <' . $value[1] . '>' : '<' . $value[1] . '>', $envelop->getTo()), ], 'Source' => $envelop->getFrom(), 'Envelop' => [ diff --git a/src/Mail/Adapters/SmtpAdapter.php b/src/Mail/Adapters/SmtpAdapter.php index ff61ccdb..ec562bab 100644 --- a/src/Mail/Adapters/SmtpAdapter.php +++ b/src/Mail/Adapters/SmtpAdapter.php @@ -130,7 +130,7 @@ public function send(Envelop $envelop): bool // Validate SPF if enabled if ($this->spfChecker !== null) { $senderIp = $_SERVER['REMOTE_ADDR'] ?? ''; - $senderEmail = $envelop->getFrom()[0][1] ?? ''; + $senderEmail = $envelop->getFrom(); $senderHelo = gethostname(); $spfResult = $this->spfChecker->verify($senderIp, $senderEmail, $senderHelo); @@ -158,7 +158,7 @@ public function send(Envelop $envelop): bool foreach ($envelop->getTo() as $value) { if ($value[0] !== null) { - $to = $value[0] . '<' . $value[1] . '>'; + $to = $value[0] . ' <' . $value[1] . '>'; } else { $to = '<' . $value[1] . '>'; } diff --git a/src/Mail/Envelop.php b/src/Mail/Envelop.php index 34e18004..65ad85c2 100644 --- a/src/Mail/Envelop.php +++ b/src/Mail/Envelop.php @@ -4,10 +4,10 @@ namespace Bow\Mail; -use Bow\View\View; +use Bow\Mail\Exception\MailException; use Bow\Support\Str; +use Bow\View\View; use InvalidArgumentException; -use Bow\Mail\Exception\MailException; class Envelop { @@ -148,7 +148,7 @@ public function addHeader(string $key, string $value): void */ public function to(string|array $to): Envelop { - $recipients = (array) $to; + $recipients = (array)$to; foreach ($recipients as $to) { $this->to[] = $this->formatEmail($to); @@ -157,6 +157,31 @@ public function to(string|array $to): Envelop return $this; } + /** + * Format the email receiver + * + * @param string $email + * @return array + */ + private function formatEmail(string $email): array + { + /** + * Organization of the list of senders + */ + $name = null; + if (preg_match('/^(.+)\s+<(.*)>\z$/', $email, $matches)) { + array_shift($matches); + $name = $matches[0]; + $email = $matches[1]; + } + + if (!Str::isMail($email)) { + throw new InvalidArgumentException("$email is not valid email.", E_USER_ERROR); + } + + return [$name, $email]; + } + /** * Add an attachment file * @@ -238,6 +263,22 @@ public function html(string $html): Envelop return $this->type($html, "text/html"); } + /** + * Add message body and set message type + * + * @param string $message + * @param string $type + * @return Envelop + */ + private function type(string $message, string $type): Envelop + { + $this->type = $type; + + $this->message = $message; + + return $this; + } + /** * Add message body * @@ -342,16 +383,6 @@ public function getHeaders(): array return $this->headers; } - /** - * Get the list of receivers - * - * @return array - */ - public function getTo(): array - { - return $this->to; - } - /** * Get the subject of the email * @@ -451,44 +482,27 @@ public function message(string $message, string $type = 'text/html'): void $this->setMessage($message, $type); } - /** - * Format the email receiver - * - * @param string $email - * @return array - */ - private function formatEmail(string $email): array + public function composeTo() { - /** - * Organization of the list of senders - */ - $name = null; - if (preg_match('/^(.+)\s+<(.*)>\z$/', $email, $matches)) { - array_shift($matches); - $name = $matches[0]; - $email = $matches[1]; - } + $to = ''; + foreach ($this->getTo() as $value) { + if ($value[0] !== null) { + $to .= $value[0] . ' <' . $value[1] . '>'; + } else { + $to .= '<' . $value[1] . '>'; + } - if (!Str::isMail($email)) { - throw new InvalidArgumentException("$email is not valid email.", E_USER_ERROR); + $this->write('RCPT TO: ' . $to, 250); } - - return [$name, $email]; } /** - * Add message body and set message type + * Get the list of receivers * - * @param string $message - * @param string $type - * @return Envelop + * @return array */ - private function type(string $message, string $type): Envelop + public function getTo(): array { - $this->type = $type; - - $this->message = $message; - - return $this; + return $this->to; } } diff --git a/src/Messaging/README.md b/src/Messaging/README.md index b94fd038..97a70fec 100644 --- a/src/Messaging/README.md +++ b/src/Messaging/README.md @@ -91,6 +91,9 @@ class User extends Model - `mail` : Envoi par email - `database` : Stockage en base de données +- `sms` : Envoi par SMS avec Twilio +- `slack` : Envoi par Slack +- `telegram` : Envoi par Telegram - Possibilité d'ajouter des canaux personnalisés ## Bonnes pratiques @@ -99,3 +102,36 @@ class User extends Model 2. Utilisez les files d'attente pour les notifications non urgentes 3. Personnalisez les canaux en fonction du contexte 4. Utilisez les vues pour les templates d'emails + +## Exemple de configuration + +```mermaid +sequenceDiagram + participant User as Utilisateur + participant Model as Modèle (User) + participant Message as WelcomeMessage + participant Mail as Canal Email + participant DB as Canal Database + participant Services as Services (SMTP/BDD) + + Note over User,Services: Envoi d'une notification de bienvenue + + User->>Model: sendMessage(new WelcomeMessage("Bienvenue!")) + Model->>Message: process(context) + Message->>Message: channels(context) + + par Canal Email + Message->>Mail: toMail(context) + Mail->>Services: Envoie via SMTP + Services-->>User: Email reçu + and Canal Database + Message->>DB: toDatabase(context) + DB->>Services: Sauvegarde notification + Services-->>User: Notification in-app + end + + Note over User,Services: Envoi asynchrone + User->>Model: setMessageQueue(new WelcomeMessage()) + Model->>Services: Ajout à la file d'attente + Services-->>Model: Confirmation +``` diff --git a/src/Router/README.md b/src/Router/README.md index 4ae89357..b6aa8524 100644 --- a/src/Router/README.md +++ b/src/Router/README.md @@ -14,4 +14,45 @@ $app->get('/', function () { }); ``` +## Diagramme de flux du routage + +```mermaid +sequenceDiagram + participant Client as Client HTTP + participant Router as Router + participant Route as Route + participant Middleware as Middleware + participant Controller as Controller/Callback + participant Response as Response + + Note over Client,Response: Traitement d'une requête HTTP + + Client->>Router: Requête HTTP (GET /users) + + Router->>Router: match(uri) + + alt Route trouvée + Router->>Route: match(uri) + Route->>Route: checkRequestUri() + + alt Avec Middleware + Route->>Middleware: process(request) + Middleware-->>Route: next(request) + end + + Route->>Route: getParameters() + Route->>Controller: call(parameters) + Controller-->>Response: return response + Response-->>Client: Envoie réponse HTTP + else Route non trouvée + Router-->>Response: 404 Not Found + Response-->>Client: Erreur 404 + end + + Note over Client,Response: Exemple de définition de route + + Note right of Router: $app->get('/users/:id', function($id) { ... }) + Note right of Router: $app->post('/users', [UserController::class, 'store']) +``` + Is very enjoyful api diff --git a/tests/Config/TestingConfiguration.php b/tests/Config/TestingConfiguration.php index 16c40d59..9d62df56 100644 --- a/tests/Config/TestingConfiguration.php +++ b/tests/Config/TestingConfiguration.php @@ -21,7 +21,7 @@ public function __construct() * @param array $configurations * @return void */ - public static function withConfigurations(array $configurations) + public static function withConfigurations(array $configurations): void { KernelTesting::withConfigurations($configurations); } @@ -32,7 +32,7 @@ public static function withConfigurations(array $configurations) * @param array $middlewares * @return void */ - public static function withMiddlewares(array $middlewares) + public static function withMiddlewares(array $middlewares): void { KernelTesting::withMiddlewares($middlewares); } diff --git a/tests/Messaging/MessagingTest.php b/tests/Messaging/MessagingTest.php index 3dd6264e..90f6fa89 100644 --- a/tests/Messaging/MessagingTest.php +++ b/tests/Messaging/MessagingTest.php @@ -2,19 +2,17 @@ namespace Bow\Tests\Messaging; -use Bow\View\View; -use Bow\Mail\Envelop; use Bow\Database\Barry\Model; -use PHPUnit\Framework\TestCase; +use Bow\Mail\Envelop; use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Messaging\Stubs\TestMessage; -use Bow\Queue\Connection as QueueConnection; -use PHPUnit\Framework\MockObject\MockObject; use Bow\Tests\Messaging\Stubs\TestNotifiableModel; +use Bow\View\View; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class MessagingTest extends TestCase { - private static QueueConnection $queueConnection; private MockObject|Model $context; private MockObject|TestMessage $message; @@ -28,14 +26,6 @@ public static function setUpBeforeClass(): void View::configure($config["view"]); } - protected function setUp(): void - { - parent::setUp(); - - $this->context = new TestNotifiableModel(); - $this->message = $this->createMock(TestMessage::class); - } - public function test_can_send_message_synchronously(): void { $this->message->expects($this->once()) @@ -61,9 +51,10 @@ public function test_message_can_send_to_mail(): void $message = new TestMessage(); $mailMessage = $message->toMail($context); + [$email] = $mailMessage->getTo(); $this->assertInstanceOf(Envelop::class, $mailMessage); - $this->assertEquals('test@example.com', $mailMessage->getTo()); + $this->assertEquals('test@example.com', $email[1]); $this->assertEquals('Test Message', $mailMessage->getSubject()); } @@ -124,4 +115,12 @@ public function test_message_can_send_to_telegram(): void $this->assertEquals('Test Telegram message', $data['message']); $this->assertEquals('HTML', $data['parse_mode']); } + + protected function setUp(): void + { + parent::setUp(); + + $this->context = new TestNotifiableModel(); + $this->message = $this->createMock(TestMessage::class); + } } diff --git a/tests/Queue/EventQueueTest.php b/tests/Queue/EventQueueTest.php index 26ca7bee..481b85b1 100644 --- a/tests/Queue/EventQueueTest.php +++ b/tests/Queue/EventQueueTest.php @@ -2,18 +2,19 @@ namespace Bow\Tests\Queue; -use Bow\Queue\Connection; -use Bow\Event\EventProducer; -use Bow\Mail\MailConfiguration; -use Bow\View\ViewConfiguration; -use PHPUnit\Framework\TestCase; use Bow\Cache\CacheConfiguration; -use Bow\Queue\QueueConfiguration; use Bow\Configuration\EnvConfiguration; -use Bow\Tests\Events\Stubs\UserEventStub; use Bow\Configuration\LoggerConfiguration; +use Bow\Database\DatabaseConfiguration; +use Bow\Event\EventProducer; +use Bow\Mail\MailConfiguration; +use Bow\Queue\Connection; +use Bow\Queue\QueueConfiguration; use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Events\Stubs\UserEventListenerStub; +use Bow\Tests\Events\Stubs\UserEventStub; +use Bow\View\ViewConfiguration; +use PHPUnit\Framework\TestCase; class EventQueueTest extends TestCase { @@ -24,11 +25,13 @@ public static function setUpBeforeClass(): void TestingConfiguration::withConfigurations([ CacheConfiguration::class, QueueConfiguration::class, + DatabaseConfiguration::class, EnvConfiguration::class, LoggerConfiguration::class, MailConfiguration::class, ViewConfiguration::class, ]); + $config = TestingConfiguration::getConfig(); $config->boot(); diff --git a/tests/Queue/MailQueueTest.php b/tests/Queue/MailQueueTest.php index d8726a3c..27eca6a3 100644 --- a/tests/Queue/MailQueueTest.php +++ b/tests/Queue/MailQueueTest.php @@ -2,27 +2,29 @@ namespace Bow\Tests\Queue; +use Bow\Cache\CacheConfiguration; +use Bow\Configuration\EnvConfiguration; +use Bow\Configuration\LoggerConfiguration; +use Bow\Database\DatabaseConfiguration; use Bow\Mail\Envelop; use Bow\Mail\MailConfiguration; use Bow\Mail\MailQueueProducer; -use Bow\View\ViewConfiguration; -use PHPUnit\Framework\TestCase; -use Bow\Cache\CacheConfiguration; +use Bow\Queue\Connection as QueueConnection; use Bow\Queue\QueueConfiguration; -use Bow\Configuration\EnvConfiguration; -use Bow\Configuration\LoggerConfiguration; use Bow\Tests\Config\TestingConfiguration; -use Bow\Queue\Connection as QueueConnection; +use Bow\View\ViewConfiguration; +use PHPUnit\Framework\TestCase; class MailQueueTest extends TestCase { - private static $connection; + private static QueueConnection $connection; public static function setUpBeforeClass(): void { TestingConfiguration::withConfigurations([ CacheConfiguration::class, QueueConfiguration::class, + DatabaseConfiguration::class, EnvConfiguration::class, LoggerConfiguration::class, MailConfiguration::class, diff --git a/tests/Queue/MessagingQueueTest.php b/tests/Queue/MessagingQueueTest.php index e354685f..8047cca7 100644 --- a/tests/Queue/MessagingQueueTest.php +++ b/tests/Queue/MessagingQueueTest.php @@ -2,20 +2,21 @@ namespace Bow\Tests\Queue; -use Bow\Database\Barry\Model; -use Bow\Mail\MailConfiguration; -use Bow\View\ViewConfiguration; -use PHPUnit\Framework\TestCase; use Bow\Cache\CacheConfiguration; -use Bow\Queue\QueueConfiguration; use Bow\Configuration\EnvConfiguration; -use Bow\Messaging\MessagingQueueProducer; use Bow\Configuration\LoggerConfiguration; +use Bow\Database\Barry\Model; +use Bow\Database\DatabaseConfiguration; +use Bow\Mail\MailConfiguration; +use Bow\Messaging\MessagingQueueProducer; +use Bow\Queue\Connection as QueueConnection; +use Bow\Queue\QueueConfiguration; use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Messaging\Stubs\TestMessage; -use Bow\Queue\Connection as QueueConnection; -use PHPUnit\Framework\MockObject\MockObject; use Bow\Tests\Messaging\Stubs\TestNotifiableModel; +use Bow\View\ViewConfiguration; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; class MessagingQueueTest extends TestCase { @@ -27,6 +28,7 @@ public static function setUpBeforeClass(): void { TestingConfiguration::withConfigurations([ CacheConfiguration::class, + DatabaseConfiguration::class, QueueConfiguration::class, EnvConfiguration::class, LoggerConfiguration::class, @@ -40,14 +42,6 @@ public static function setUpBeforeClass(): void static::$connection = new QueueConnection($config["queue"]); } - protected function setUp(): void - { - parent::setUp(); - - $this->context = $this->createMock(TestNotifiableModel::class); - $this->message = $this->createMock(TestMessage::class); - } - public function test_can_send_message_synchronously(): void { $context = new TestNotifiableModel(); @@ -121,4 +115,12 @@ public function test_can_send_message_with_delay_on_specific_queue(): void $this->context->sendMessageLaterOn($delay, $queue, $this->message); } + + protected function setUp(): void + { + parent::setUp(); + + $this->context = $this->createMock(TestNotifiableModel::class); + $this->message = $this->createMock(TestMessage::class); + } } diff --git a/tests/Queue/QueueTest.php b/tests/Queue/QueueTest.php index 8a9ec4e9..dbbec331 100644 --- a/tests/Queue/QueueTest.php +++ b/tests/Queue/QueueTest.php @@ -2,22 +2,22 @@ namespace Bow\Tests\Queue; -use Bow\Database\Database; -use PHPUnit\Framework\TestCase; -use Bow\Cache\CacheConfiguration; -use Bow\Queue\Adapters\SQSAdapter; -use Bow\Queue\Adapters\SyncAdapter; use Bow\Cache\Adapters\RedisAdapter; +use Bow\Cache\CacheConfiguration; use Bow\Configuration\EnvConfiguration; +use Bow\Configuration\LoggerConfiguration; +use Bow\Database\Database; use Bow\Database\DatabaseConfiguration; -use Bow\Queue\Adapters\DatabaseAdapter; -use Bow\Tests\Queue\Stubs\PetModelStub; use Bow\Queue\Adapters\BeanstalkdAdapter; -use Bow\Configuration\LoggerConfiguration; -use Bow\Tests\Config\TestingConfiguration; +use Bow\Queue\Adapters\DatabaseAdapter; +use Bow\Queue\Adapters\SQSAdapter; +use Bow\Queue\Adapters\SyncAdapter; use Bow\Queue\Connection as QueueConnection; -use Bow\Tests\Queue\Stubs\ModelProducerStub; +use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Queue\Stubs\BasicProducerStubs; +use Bow\Tests\Queue\Stubs\ModelProducerStub; +use Bow\Tests\Queue\Stubs\PetModelStub; +use PHPUnit\Framework\TestCase; class QueueTest extends TestCase { @@ -103,7 +103,7 @@ public function test_push_service_adapter($connection) * @param string $connection * @return void */ - public function test_push_service_adapter_with_model($connection) + public function test_push_service_adapter_with_model(string $connection) { $adapter = static::$connection->setConnection($connection)->getAdapter(); $pet = new PetModelStub(["name" => "Filou"]); @@ -134,7 +134,7 @@ public function getConnection(): array ["beanstalkd"], ["database"], ["sync"], - // ["sqs"], + ["sqs"], // ["redis"], // ["rabbitmq"] ]; From 453af82158217046bd6bfcd855ed261d0bbfd033 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Thu, 30 Jan 2025 06:56:27 +0000 Subject: [PATCH 09/10] change: find to retrieve and save to persiste --- composer.json | 3 +- docker-compose.yml | 2 - phpunit.dist.xml | 28 ++++- src/Console/Command/MigrationCommand.php | 4 +- src/Console/stubs/model/cache.stub | 2 +- src/Console/stubs/model/create.stub | 2 +- src/Console/stubs/model/notification.stub | 2 +- src/Console/stubs/model/queue.stub | 2 +- src/Console/stubs/model/session.stub | 2 +- src/Console/stubs/model/standard.stub | 2 +- src/Console/stubs/model/table.stub | 2 +- src/Container/Compass.php | 4 + src/Database/Barry/Concerns/Relationship.php | 2 + src/Database/Barry/Model.php | 40 +++--- src/Database/Migration/Migration.php | 4 +- .../Migration/Shortcut/ConstraintColumn.php | 30 ++--- .../Migration/Shortcut/DateColumn.php | 50 ++++---- .../Migration/Shortcut/MixedColumn.php | 86 ++++++------- .../Migration/Shortcut/NumberColumn.php | 114 +++++++++--------- .../Migration/Shortcut/TextColumn.php | 50 ++++---- .../Migration/{SQLGenerator.php => Table.php} | 32 ++--- src/Database/QueryBuilder.php | 20 +-- src/Router/README.md | 2 +- ...test_generate_cache_migration_stubs__1.txt | 2 +- ...est_generate_create_migration_stubs__1.txt | 2 +- ...test_generate_queue_migration_stubs__1.txt | 2 +- ...st_generate_session_migration_stubs__1.txt | 2 +- ...t_generate_standard_migration_stubs__1.txt | 2 +- ...test_generate_table_migration_stubs__1.txt | 2 +- tests/Database/Migration/MigrationTest.php | 12 +- .../Migration/Mysql/SQLGeneratorTest.php | 10 +- .../Migration/Mysql/SQLGenetorHelpersTest.php | 8 +- .../Migration/Pgsql/SQLGeneratorTest.php | 8 +- .../Migration/Pgsql/SQLGenetorHelpersTest.php | 8 +- .../Migration/SQLite/SQLGeneratorTest.php | 8 +- .../SQLite/SQLGenetorHelpersTest.php | 8 +- tests/Database/PaginationTest.php | 2 +- tests/Database/Query/DatabaseQueryTest.php | 27 ++++- tests/Database/Query/ModelQueryTest.php | 36 ++++-- tests/Database/Query/PaginationTest.php | 10 +- tests/Database/Query/QueryBuilderTest.php | 34 +++++- .../Relation/BelongsToRelationQueryTest.php | 12 +- tests/Events/EventTest.php | 4 +- tests/Filesystem/FTPServiceTest.php | 4 +- tests/Queue/Stubs/ModelProducerStub.php | 2 +- tests/Support/CollectionTest.php | 22 ++-- 46 files changed, 401 insertions(+), 311 deletions(-) rename src/Database/Migration/{SQLGenerator.php => Table.php} (91%) diff --git a/composer.json b/composer.json index d5d422dd..f21303e6 100644 --- a/composer.json +++ b/composer.json @@ -38,7 +38,8 @@ "mockery/mockery": "^1.5", "spatie/phpunit-snapshot-assertions": "^4.2", "predis/predis": "^2.1", - "twilio/sdk": "^8.3" + "twilio/sdk": "^8.3", + "bowphp/slack-webhook": "^1.0" }, "authors": [ { diff --git a/docker-compose.yml b/docker-compose.yml index 521377e2..dc8671ce 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,3 @@ -version: '3.8' - volumes: mysql_data: driver: local diff --git a/phpunit.dist.xml b/phpunit.dist.xml index c0b66c64..8fa8f071 100644 --- a/phpunit.dist.xml +++ b/phpunit.dist.xml @@ -1,4 +1,18 @@ - + + tests/ ./tests/SessionTest.php @@ -15,5 +29,17 @@ + + + + + + src + + + vendor + tests + + diff --git a/src/Console/Command/MigrationCommand.php b/src/Console/Command/MigrationCommand.php index bc540dfd..f9437943 100644 --- a/src/Console/Command/MigrationCommand.php +++ b/src/Console/Command/MigrationCommand.php @@ -10,7 +10,7 @@ use Bow\Database\Database; use Bow\Database\Exception\ConnectionException; use Bow\Database\Exception\QueryBuilderException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; use Bow\Database\QueryBuilder; use Bow\Support\Str; use ErrorException; @@ -80,7 +80,7 @@ private function createMigrationTable(): void $adapter = Database::getConnectionAdapter(); $table = $adapter->getTablePrefix() . config('database.migration', 'migrations'); - $generator = new SQLGenerator( + $generator = new Table( $table, $adapter->getName(), 'create' diff --git a/src/Console/stubs/model/cache.stub b/src/Console/stubs/model/cache.stub index a3ccd881..a62facfe 100644 --- a/src/Console/stubs/model/cache.stub +++ b/src/Console/stubs/model/cache.stub @@ -1,7 +1,7 @@ first(); } /** - * Find by column name + * retrieve by column name * * @param string $column * @param mixed $value * @return Collection */ - public static function findBy(string $column, mixed $value): Collection + public static function retrieveBy(string $column, mixed $value): Collection { $model = new static(); $model->where($column, $value); @@ -302,18 +302,18 @@ public static function findBy(string $column, mixed $value): Collection } /** - * Find information and delete it + * retrieve information and delete it * * @param mixed $id * @param array $select * * @return Collection|Model|null */ - public static function findAndDelete( + public static function retrieveAndDelete( int|string|array $id, array $select = ['*'] ): Collection|Model|null { - $model = static::find($id, $select); + $model = static::retrieve($id, $select); if (is_null($model)) { return null; @@ -330,17 +330,17 @@ public static function findAndDelete( } /** - * find + * retrieve * * @param mixed $id * @param array $select - * @return Collection|static|null + * @return array|object|null */ - public static function find( + public static function retrieve( int|string|array $id, array $select = ['*'] - ): Collection|Model|null { - $id = (array)$id; + ): array|object|null { + $id = (array) $id; $model = new static(); $model->select($select); @@ -398,17 +398,17 @@ public function getKeyValue(): mixed } /** - * Find information by id or throws an + * retrieve information by id or throws an * exception in data box not found * * @param mixed $id * @param array $select - * @return Model + * @return array|object * @throws NotFoundException */ - public static function findOrFail(int|string $id, array $select = ['*']): Model + public static function retrieveOrFail(int|string $id, array $select = ['*']): array|object { - $result = static::find($id, $select); + $result = static::retrieve($id, $select); if (is_null($result)) { throw new NotFoundException('No recordings found at ' . $id . '.'); @@ -451,18 +451,18 @@ public static function create(array $data): Model // Override the olds model attributes $model->setAttributes($data); - $model->save(); + $model->persist(); return $model; } /** - * Save aliases on insert action + * persist aliases on insert action * * @return int * @throws */ - public function save(): int + public function persist(): int { $builder = static::query(); @@ -777,7 +777,7 @@ public function touch(): bool $this->setAttribute($this->updated_at, date('Y-m-d H:i:s')); } - return (bool)$this->save(); + return (bool) $this->persist(); } /** diff --git a/src/Database/Migration/Migration.php b/src/Database/Migration/Migration.php index ee9a6987..dfb77777 100644 --- a/src/Database/Migration/Migration.php +++ b/src/Database/Migration/Migration.php @@ -151,7 +151,7 @@ final public function create(string $table, callable $cb): Migration $table = $this->getTablePrefixed($table); call_user_func_array($cb, [ - $generator = new SQLGenerator($table, $this->adapter->getName(), 'create') + $generator = new Table($table, $this->adapter->getName(), 'create') ]); if ($this->adapter->getName() == 'mysql') { @@ -191,7 +191,7 @@ final public function alter(string $table, callable $cb): Migration $table = $this->getTablePrefixed($table); call_user_func_array($cb, [ - $generator = new SQLGenerator($table, $this->adapter->getName(), 'alter') + $generator = new Table($table, $this->adapter->getName(), 'alter') ]); if ($this->adapter->getName() === 'pgsql') { diff --git a/src/Database/Migration/Shortcut/ConstraintColumn.php b/src/Database/Migration/Shortcut/ConstraintColumn.php index 2413e7ff..80d5058a 100644 --- a/src/Database/Migration/Shortcut/ConstraintColumn.php +++ b/src/Database/Migration/Shortcut/ConstraintColumn.php @@ -4,7 +4,7 @@ namespace Bow\Database\Migration\Shortcut; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; trait ConstraintColumn { @@ -13,9 +13,9 @@ trait ConstraintColumn * * @param string $name * @param array $attributes - * @return SQLGenerator + * @return Table */ - public function addForeign(string $name, array $attributes = []): SQLGenerator + public function addForeign(string $name, array $attributes = []): Table { if ($this->scope == 'alter') { $command = 'ADD CONSTRAINT'; @@ -77,9 +77,9 @@ public function addForeign(string $name, array $attributes = []): SQLGenerator * * @param string|array $name * @param bool $as_raw - * @return SQLGenerator + * @return Table */ - public function dropForeign(string|array $name, bool $as_raw = false): SQLGenerator + public function dropForeign(string|array $name, bool $as_raw = false): Table { $names = (array)$name; @@ -101,9 +101,9 @@ public function dropForeign(string|array $name, bool $as_raw = false): SQLGenera * Add table index; * * @param string $name - * @return SQLGenerator + * @return Table */ - public function addIndex(string $name): SQLGenerator + public function addIndex(string $name): Table { if ($this->scope == 'alter') { $command = 'ADD INDEX'; @@ -124,9 +124,9 @@ public function addIndex(string $name): SQLGenerator * Drop table index; * * @param string $name - * @return SQLGenerator + * @return Table */ - public function dropIndex(string $name): SQLGenerator + public function dropIndex(string $name): Table { $names = (array)$name; @@ -144,9 +144,9 @@ public function dropIndex(string $name): SQLGenerator /** * Drop primary column; * - * @return SQLGenerator + * @return Table */ - public function dropPrimary(): SQLGenerator + public function dropPrimary(): Table { $this->sqls[] = 'DROP PRIMARY KEY'; @@ -157,9 +157,9 @@ public function dropPrimary(): SQLGenerator * Add table unique; * * @param string $name - * @return SQLGenerator + * @return Table */ - public function addUnique(string $name): SQLGenerator + public function addUnique(string $name): Table { if ($this->scope == 'alter') { $command = 'ADD UNIQUE'; @@ -180,9 +180,9 @@ public function addUnique(string $name): SQLGenerator * Drop table unique; * * @param string $name - * @return SQLGenerator + * @return Table */ - public function dropUnique(string $name): SQLGenerator + public function dropUnique(string $name): Table { $names = (array)$name; diff --git a/src/Database/Migration/Shortcut/DateColumn.php b/src/Database/Migration/Shortcut/DateColumn.php index 6d890914..07fc97b1 100644 --- a/src/Database/Migration/Shortcut/DateColumn.php +++ b/src/Database/Migration/Shortcut/DateColumn.php @@ -5,7 +5,7 @@ namespace Bow\Database\Migration\Shortcut; use Bow\Database\Exception\SQLGeneratorException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; trait DateColumn { @@ -14,10 +14,10 @@ trait DateColumn * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addDatetime(string $column, array $attribute = []): SQLGenerator + public function addDatetime(string $column, array $attribute = []): Table { if ($this->adapter == 'pgsql') { return $this->addTimestamp($column, $attribute); @@ -31,10 +31,10 @@ public function addDatetime(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addTimestamp(string $column, array $attribute = []): SQLGenerator + public function addTimestamp(string $column, array $attribute = []): Table { return $this->addColumn($column, 'timestamp', $attribute); } @@ -44,10 +44,10 @@ public function addTimestamp(string $column, array $attribute = []): SQLGenerato * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addDate(string $column, array $attribute = []): SQLGenerator + public function addDate(string $column, array $attribute = []): Table { return $this->addColumn($column, 'date', $attribute); } @@ -57,10 +57,10 @@ public function addDate(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addTime(string $column, array $attribute = []): SQLGenerator + public function addTime(string $column, array $attribute = []): Table { return $this->addColumn($column, 'time', $attribute); } @@ -70,10 +70,10 @@ public function addTime(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addYear(string $column, array $attribute = []): SQLGenerator + public function addYear(string $column, array $attribute = []): Table { return $this->addColumn($column, 'year', $attribute); } @@ -81,10 +81,10 @@ public function addYear(string $column, array $attribute = []): SQLGenerator /** * Add default timestamps * - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addTimestamps(): SQLGenerator + public function addTimestamps(): Table { if ($this->adapter == 'pgsql') { $this->addTimestamp('created_at', ['default' => 'CURRENT_TIMESTAMP']); @@ -104,10 +104,10 @@ public function addTimestamps(): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeDatetime(string $column, array $attribute = []): SQLGenerator + public function changeDatetime(string $column, array $attribute = []): Table { if ($this->adapter == 'pgsql') { return $this->addTimestamp($column, $attribute); @@ -121,10 +121,10 @@ public function changeDatetime(string $column, array $attribute = []): SQLGenera * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeDate(string $column, array $attribute = []): SQLGenerator + public function changeDate(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'date', $attribute); } @@ -134,10 +134,10 @@ public function changeDate(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeTime(string $column, array $attribute = []): SQLGenerator + public function changeTime(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'time', $attribute); } @@ -147,10 +147,10 @@ public function changeTime(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeYear(string $column, array $attribute = []): SQLGenerator + public function changeYear(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'year', $attribute); } @@ -160,10 +160,10 @@ public function changeYear(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeTimestamp(string $column, array $attribute = []): SQLGenerator + public function changeTimestamp(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'timestamp', $attribute); } @@ -171,10 +171,10 @@ public function changeTimestamp(string $column, array $attribute = []): SQLGener /** * Change default timestamps * - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeTimestamps(): SQLGenerator + public function changeTimestamps(): Table { 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 18ed20ba..b9046c6b 100644 --- a/src/Database/Migration/Shortcut/MixedColumn.php +++ b/src/Database/Migration/Shortcut/MixedColumn.php @@ -5,7 +5,7 @@ namespace Bow\Database\Migration\Shortcut; use Bow\Database\Exception\SQLGeneratorException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; trait MixedColumn { @@ -14,10 +14,10 @@ trait MixedColumn * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addBoolean(string $column, array $attribute = []): SQLGenerator + public function addBoolean(string $column, array $attribute = []): Table { return $this->addColumn($column, 'boolean', $attribute); } @@ -27,10 +27,10 @@ public function addBoolean(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addUuidPrimary(string $column, array $attribute = []): SQLGenerator + public function addUuidPrimary(string $column, array $attribute = []): Table { $attribute['primary'] = true; @@ -50,10 +50,10 @@ public function addUuidPrimary(string $column, array $attribute = []): SQLGenera * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addUuid(string $column, array $attribute = []): SQLGenerator + public function addUuid(string $column, array $attribute = []): Table { if (isset($attribute['increment'])) { throw new SQLGeneratorException( @@ -82,10 +82,10 @@ public function addUuid(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addBinary(string $column, array $attribute = []): SQLGenerator + public function addBinary(string $column, array $attribute = []): Table { return $this->addColumn($column, 'binary', $attribute); } @@ -95,10 +95,10 @@ public function addBinary(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addTinyBlob(string $column, array $attribute = []): SQLGenerator + public function addTinyBlob(string $column, array $attribute = []): Table { return $this->addColumn($column, 'tinyblob', $attribute); } @@ -108,10 +108,10 @@ public function addTinyBlob(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addLongBlob(string $column, array $attribute = []): SQLGenerator + public function addLongBlob(string $column, array $attribute = []): Table { return $this->addColumn($column, 'longblob', $attribute); } @@ -121,10 +121,10 @@ public function addLongBlob(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addMediumBlob(string $column, array $attribute = []): SQLGenerator + public function addMediumBlob(string $column, array $attribute = []): Table { return $this->addColumn($column, 'mediumblob', $attribute); } @@ -134,10 +134,10 @@ public function addMediumBlob(string $column, array $attribute = []): SQLGenerat * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addIpAddress(string $column, array $attribute = []): SQLGenerator + public function addIpAddress(string $column, array $attribute = []): Table { return $this->addColumn($column, 'ip', $attribute); } @@ -147,10 +147,10 @@ public function addIpAddress(string $column, array $attribute = []): SQLGenerato * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addMacAddress(string $column, array $attribute = []): SQLGenerator + public function addMacAddress(string $column, array $attribute = []): Table { return $this->addColumn($column, 'mac', $attribute); } @@ -160,10 +160,10 @@ public function addMacAddress(string $column, array $attribute = []): SQLGenerat * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addEnum(string $column, array $attribute = []): SQLGenerator + public function addEnum(string $column, array $attribute = []): Table { if (!isset($attribute['size'])) { throw new SQLGeneratorException("The enum values should be define!"); @@ -185,10 +185,10 @@ public function addEnum(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addCheck(string $column, array $attribute = []): SQLGenerator + public function addCheck(string $column, array $attribute = []): Table { $this->verifyCheckAttribute($attribute); @@ -222,10 +222,10 @@ private function verifyCheckAttribute($attribute): void * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeBoolean(string $column, array $attribute = []): SQLGenerator + public function changeBoolean(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'boolean', $attribute); } @@ -235,10 +235,10 @@ public function changeBoolean(string $column, array $attribute = []): SQLGenerat * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeUuid(string $column, array $attribute = []): SQLGenerator + public function changeUuid(string $column, array $attribute = []): Table { if (isset($attribute['size'])) { throw new SQLGeneratorException("Cannot define size to uuid type"); @@ -261,10 +261,10 @@ public function changeUuid(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeBinary(string $column, array $attribute = []): SQLGenerator + public function changeBinary(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'binary', $attribute); } @@ -274,10 +274,10 @@ public function changeBinary(string $column, array $attribute = []): SQLGenerato * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeLongBlob(string $column, array $attribute = []): SQLGenerator + public function changeLongBlob(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'longblob', $attribute); } @@ -287,10 +287,10 @@ public function changeLongBlob(string $column, array $attribute = []): SQLGenera * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeMediumBlob(string $column, array $attribute = []): SQLGenerator + public function changeMediumBlob(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'mediumblob', $attribute); } @@ -300,10 +300,10 @@ public function changeMediumBlob(string $column, array $attribute = []): SQLGene * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeTinyBlob(string $column, array $attribute = []): SQLGenerator + public function changeTinyBlob(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'tinyblob', $attribute); } @@ -313,10 +313,10 @@ public function changeTinyBlob(string $column, array $attribute = []): SQLGenera * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeIpAddress(string $column, array $attribute = []): SQLGenerator + public function changeIpAddress(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'ip', $attribute); } @@ -326,10 +326,10 @@ public function changeIpAddress(string $column, array $attribute = []): SQLGener * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeMacAddress(string $column, array $attribute = []): SQLGenerator + public function changeMacAddress(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'mac', $attribute); } @@ -339,10 +339,10 @@ public function changeMacAddress(string $column, array $attribute = []): SQLGene * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeEnum(string $column, array $attribute = []): SQLGenerator + public function changeEnum(string $column, array $attribute = []): Table { if (!isset($attribute['size'])) { throw new SQLGeneratorException("The enum values should be define!"); @@ -364,10 +364,10 @@ public function changeEnum(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeCheck(string $column, array $attribute = []): SQLGenerator + public function changeCheck(string $column, array $attribute = []): Table { $this->verifyCheckAttribute($attribute); diff --git a/src/Database/Migration/Shortcut/NumberColumn.php b/src/Database/Migration/Shortcut/NumberColumn.php index c032f634..f96aeabe 100644 --- a/src/Database/Migration/Shortcut/NumberColumn.php +++ b/src/Database/Migration/Shortcut/NumberColumn.php @@ -5,7 +5,7 @@ namespace Bow\Database\Migration\Shortcut; use Bow\Database\Exception\SQLGeneratorException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; trait NumberColumn { @@ -14,10 +14,10 @@ trait NumberColumn * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addFloat(string $column, array $attribute = []): SQLGenerator + public function addFloat(string $column, array $attribute = []): Table { return $this->addColumn($column, 'float', $attribute); } @@ -27,10 +27,10 @@ public function addFloat(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addDouble(string $column, array $attribute = []): SQLGenerator + public function addDouble(string $column, array $attribute = []): Table { return $this->addColumn($column, 'double', $attribute); } @@ -39,10 +39,10 @@ public function addDouble(string $column, array $attribute = []): SQLGenerator * Add double primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addDoublePrimary(string $column): SQLGenerator + public function addDoublePrimary(string $column): Table { return $this->addColumn($column, 'double', ['primary' => true]); } @@ -51,10 +51,10 @@ public function addDoublePrimary(string $column): SQLGenerator * Add float primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addFloatPrimary(string $column): SQLGenerator + public function addFloatPrimary(string $column): Table { return $this->addColumn($column, 'float', ['primary' => true]); } @@ -63,10 +63,10 @@ public function addFloatPrimary(string $column): SQLGenerator * Add increment primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addIncrement(string $column): SQLGenerator + public function addIncrement(string $column): Table { return $this->addColumn($column, 'int', ['primary' => true, 'increment' => true]); } @@ -76,10 +76,10 @@ public function addIncrement(string $column): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addInteger(string $column, array $attribute = []): SQLGenerator + public function addInteger(string $column, array $attribute = []): Table { return $this->addColumn($column, 'int', $attribute); } @@ -88,10 +88,10 @@ public function addInteger(string $column, array $attribute = []): SQLGenerator * Add integer primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addIntegerPrimary(string $column): SQLGenerator + public function addIntegerPrimary(string $column): Table { return $this->addColumn($column, 'int', ['primary' => true]); } @@ -100,10 +100,10 @@ public function addIntegerPrimary(string $column): SQLGenerator * Add big increment primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addBigIncrement(string $column): SQLGenerator + public function addBigIncrement(string $column): Table { return $this->addColumn($column, 'bigint', ['primary' => true, 'increment' => true]); } @@ -113,10 +113,10 @@ public function addBigIncrement(string $column): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addTinyInteger(string $column, array $attribute = []): SQLGenerator + public function addTinyInteger(string $column, array $attribute = []): Table { return $this->addColumn($column, 'tinyint', $attribute); } @@ -126,10 +126,10 @@ public function addTinyInteger(string $column, array $attribute = []): SQLGenera * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addBigInteger(string $column, array $attribute = []): SQLGenerator + public function addBigInteger(string $column, array $attribute = []): Table { return $this->addColumn($column, 'bigint', $attribute); } @@ -139,10 +139,10 @@ public function addBigInteger(string $column, array $attribute = []): SQLGenerat * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addMediumInteger(string $column, array $attribute = []): SQLGenerator + public function addMediumInteger(string $column, array $attribute = []): Table { return $this->addColumn($column, 'mediumint', $attribute); } @@ -151,10 +151,10 @@ public function addMediumInteger(string $column, array $attribute = []): SQLGene * Add Medium integer column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addMediumIncrement(string $column): SQLGenerator + public function addMediumIncrement(string $column): Table { return $this->addColumn($column, 'mediumint', ['primary' => true, 'increment' => true]); } @@ -164,10 +164,10 @@ public function addMediumIncrement(string $column): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addSmallInteger(string $column, array $attribute = []): SQLGenerator + public function addSmallInteger(string $column, array $attribute = []): Table { return $this->addColumn($column, 'smallint', $attribute); } @@ -176,10 +176,10 @@ public function addSmallInteger(string $column, array $attribute = []): SQLGener * Add Smallint integer column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addSmallIntegerIncrement(string $column): SQLGenerator + public function addSmallIntegerIncrement(string $column): Table { return $this->addColumn($column, 'smallint', ['primary' => true, 'increment' => true]); } @@ -189,10 +189,10 @@ public function addSmallIntegerIncrement(string $column): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeFloat(string $column, array $attribute = []): SQLGenerator + public function changeFloat(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'float', $attribute); } @@ -202,10 +202,10 @@ public function changeFloat(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeDouble(string $column, array $attribute = []): SQLGenerator + public function changeDouble(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'double', $attribute); } @@ -214,10 +214,10 @@ public function changeDouble(string $column, array $attribute = []): SQLGenerato * Change double primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeDoublePrimary(string $column): SQLGenerator + public function changeDoublePrimary(string $column): Table { return $this->changeColumn($column, 'double', ['primary' => true]); } @@ -226,10 +226,10 @@ public function changeDoublePrimary(string $column): SQLGenerator * Change float primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeFloatPrimary(string $column): SQLGenerator + public function changeFloatPrimary(string $column): Table { return $this->changeColumn($column, 'float', ['primary' => true]); } @@ -238,10 +238,10 @@ public function changeFloatPrimary(string $column): SQLGenerator * Change increment primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeIncrement(string $column): SQLGenerator + public function changeIncrement(string $column): Table { return $this->changeColumn($column, 'int', ['primary' => true, 'increment' => true]); } @@ -251,10 +251,10 @@ public function changeIncrement(string $column): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeInteger(string $column, array $attribute = []): SQLGenerator + public function changeInteger(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'int', $attribute); } @@ -263,10 +263,10 @@ public function changeInteger(string $column, array $attribute = []): SQLGenerat * Change integer primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeIntegerPrimary(string $column): SQLGenerator + public function changeIntegerPrimary(string $column): Table { return $this->changeColumn($column, 'int', ['primary' => true]); } @@ -275,10 +275,10 @@ public function changeIntegerPrimary(string $column): SQLGenerator * Change big increment primary column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeBigIncrement(string $column): SQLGenerator + public function changeBigIncrement(string $column): Table { return $this->changeColumn($column, 'bigint', ['primary' => true, 'increment' => true]); } @@ -288,10 +288,10 @@ public function changeBigIncrement(string $column): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeTinyInteger(string $column, array $attribute = []): SQLGenerator + public function changeTinyInteger(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'tinyint', $attribute); } @@ -301,10 +301,10 @@ public function changeTinyInteger(string $column, array $attribute = []): SQLGen * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeBigInteger(string $column, array $attribute = []): SQLGenerator + public function changeBigInteger(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'bigint', $attribute); } @@ -314,10 +314,10 @@ public function changeBigInteger(string $column, array $attribute = []): SQLGene * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeMediumInteger(string $column, array $attribute = []): SQLGenerator + public function changeMediumInteger(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'mediumint', $attribute); } @@ -326,10 +326,10 @@ public function changeMediumInteger(string $column, array $attribute = []): SQLG * Change Medium integer column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeMediumIncrement(string $column): SQLGenerator + public function changeMediumIncrement(string $column): Table { return $this->changeColumn($column, 'mediumint', ['primary' => true, 'increment' => true]); } @@ -339,10 +339,10 @@ public function changeMediumIncrement(string $column): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeSmallInteger(string $column, array $attribute = []): SQLGenerator + public function changeSmallInteger(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'smallint', $attribute); } @@ -351,10 +351,10 @@ public function changeSmallInteger(string $column, array $attribute = []): SQLGe * Change Small integer column * * @param string $column - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeSmallIntegerPrimary(string $column): SQLGenerator + public function changeSmallIntegerPrimary(string $column): Table { 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 4eeeecae..64c74c4f 100644 --- a/src/Database/Migration/Shortcut/TextColumn.php +++ b/src/Database/Migration/Shortcut/TextColumn.php @@ -5,7 +5,7 @@ namespace Bow\Database\Migration\Shortcut; use Bow\Database\Exception\SQLGeneratorException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; trait TextColumn { @@ -14,10 +14,10 @@ trait TextColumn * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addString(string $column, array $attribute = []): SQLGenerator + public function addString(string $column, array $attribute = []): Table { return $this->addColumn($column, 'string', $attribute); } @@ -27,10 +27,10 @@ public function addString(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addJson(string $column, array $attribute = []): SQLGenerator + public function addJson(string $column, array $attribute = []): Table { return $this->addColumn($column, 'json', $attribute); } @@ -40,10 +40,10 @@ public function addJson(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addChar(string $column, array $attribute = []): SQLGenerator + public function addChar(string $column, array $attribute = []): Table { return $this->addColumn($column, 'char', $attribute); } @@ -53,10 +53,10 @@ public function addChar(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addLongtext(string $column, array $attribute = []): SQLGenerator + public function addLongtext(string $column, array $attribute = []): Table { return $this->addColumn($column, 'longtext', $attribute); } @@ -66,10 +66,10 @@ public function addLongtext(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addText(string $column, array $attribute = []): SQLGenerator + public function addText(string $column, array $attribute = []): Table { return $this->addColumn($column, 'text', $attribute); } @@ -79,10 +79,10 @@ public function addText(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addBlob(string $column, array $attribute = []): SQLGenerator + public function addBlob(string $column, array $attribute = []): Table { return $this->addColumn($column, 'blob', $attribute); } @@ -92,10 +92,10 @@ public function addBlob(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeString(string $column, array $attribute = []): SQLGenerator + public function changeString(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'string', $attribute); } @@ -105,10 +105,10 @@ public function changeString(string $column, array $attribute = []): SQLGenerato * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeJson(string $column, array $attribute = []): SQLGenerator + public function changeJson(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'json', $attribute); } @@ -118,10 +118,10 @@ public function changeJson(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeChar(string $column, array $attribute = []): SQLGenerator + public function changeChar(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'char', $attribute); } @@ -131,10 +131,10 @@ public function changeChar(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeLongtext(string $column, array $attribute = []): SQLGenerator + public function changeLongtext(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'longtext', $attribute); } @@ -144,10 +144,10 @@ public function changeLongtext(string $column, array $attribute = []): SQLGenera * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeText(string $column, array $attribute = []): SQLGenerator + public function changeText(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'text', $attribute); } @@ -157,10 +157,10 @@ public function changeText(string $column, array $attribute = []): SQLGenerator * * @param string $column * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeBlob(string $column, array $attribute = []): SQLGenerator + public function changeBlob(string $column, array $attribute = []): Table { return $this->changeColumn($column, 'blob', $attribute); } diff --git a/src/Database/Migration/SQLGenerator.php b/src/Database/Migration/Table.php similarity index 91% rename from src/Database/Migration/SQLGenerator.php rename to src/Database/Migration/Table.php index 91b3e54c..905af102 100644 --- a/src/Database/Migration/SQLGenerator.php +++ b/src/Database/Migration/Table.php @@ -6,7 +6,7 @@ use Bow\Database\Exception\SQLGeneratorException; -class SQLGenerator +class Table { use Shortcut\NumberColumn; use Shortcut\MixedColumn; @@ -69,7 +69,7 @@ class SQLGenerator private string $charset; /** - * SQLGenerator constructor + * Table constructor * * @param string $table * @param string $adapter @@ -102,9 +102,9 @@ public function make(): string * Add a raw column definition * * @param string $definition - * @return SQLGenerator + * @return Table */ - public function addRaw(string $definition): SQLGenerator + public function addRaw(string $definition): Table { $this->sqls[] = $definition; @@ -117,10 +117,10 @@ public function addRaw(string $definition): SQLGenerator * @param string $name * @param string $type * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function addColumn(string $name, string $type, array $attribute = []): SQLGenerator + public function addColumn(string $name, string $type, array $attribute = []): Table { if ($this->scope == 'alter') { $command = 'ADD COLUMN'; @@ -165,10 +165,10 @@ private function composeAddColumn(string $name, array $description): string * @param string $name * @param string $type * @param array $attribute - * @return SQLGenerator + * @return Table * @throws SQLGeneratorException */ - public function changeColumn(string $name, string $type, array $attribute = []): SQLGenerator + public function changeColumn(string $name, string $type, array $attribute = []): Table { $command = 'MODIFY COLUMN'; @@ -185,9 +185,9 @@ public function changeColumn(string $name, string $type, array $attribute = []): * * @param string $name * @param string $new - * @return SQLGenerator + * @return Table */ - public function renameColumn(string $name, string $new): SQLGenerator + public function renameColumn(string $name, string $new): Table { if (!in_array($this->adapter, ['mysql', 'pgsql'])) { $this->renameColumnOnSqlite($name, $new); @@ -208,9 +208,9 @@ public function renameColumn(string $name, string $new): SQLGenerator * Drop table column * * @param string $name - * @return SQLGenerator + * @return Table */ - public function dropColumn(string $name): SQLGenerator + public function dropColumn(string $name): Table { if ($this->adapter === 'mysql') { $this->dropColumnForMysql($name); @@ -313,9 +313,9 @@ public function setTable(string $table): string * Set the scope * * @param string $scope - * @return SQLGenerator + * @return Table */ - public function setScope(string $scope): SQLGenerator + public function setScope(string $scope): Table { $this->scope = $scope; @@ -326,9 +326,9 @@ public function setScope(string $scope): SQLGenerator * Set the adapter * * @param string $adapter - * @return SQLGenerator + * @return Table */ - public function setAdapter(string $adapter): SQLGenerator + public function setAdapter(string $adapter): Table { $this->adapter = $adapter; diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index d26b9fd3..dca8b703 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -18,21 +18,21 @@ class QueryBuilder implements JsonSerializable /** * The table name * - * @var string + * @var ?string */ protected ?string $table = null; /** * Select statement collector * - * @var string + * @var ?string */ protected ?string $select = null; /** * Where statement collector * - * @var string + * @var ?string */ protected ?string $where = null; @@ -46,49 +46,49 @@ class QueryBuilder implements JsonSerializable /** * Join statement collector * - * @var string + * @var ?string */ protected ?string $join = null; /** * Limit statement collector * - * @var string + * @var ?string */ protected ?string $limit = null; /** * Group statement collector * - * @var string + * @var ?string */ protected ?string $group = null; /** * Having statement collector * - * @var string + * @var ?string */ protected ?string $having = null; /** * Order By statement collector * - * @var string + * @var ?string */ protected ?string $order = null; /** * Define the table as * - * @var string + * @var ?string */ protected ?string $as = null; /** * The PDO instance * - * @var PDO + * @var ?PDO */ protected ?PDO $connection = null; diff --git a/src/Router/README.md b/src/Router/README.md index b6aa8524..545655e8 100644 --- a/src/Router/README.md +++ b/src/Router/README.md @@ -55,4 +55,4 @@ sequenceDiagram Note right of Router: $app->post('/users', [UserController::class, 'store']) ``` -Is very enjoyful api +Is very joyful api diff --git a/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_cache_migration_stubs__1.txt b/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_cache_migration_stubs__1.txt index fd8289ff..daa208f5 100644 --- a/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_cache_migration_stubs__1.txt +++ b/tests/Console/__snapshots__/GeneratorDeepTest__test_generate_cache_migration_stubs__1.txt @@ -1,7 +1,7 @@ expectException(MigrationException::class); } - $status = $this->migration->connection($name)->create('bow_testing', function (SQLGenerator $generator) { + $status = $this->migration->connection($name)->create('bow_testing', function (Table $generator) { $generator->addColumn('id', 'string', ['size' => 225, 'primary' => true]); $generator->addColumn('name', 'typenotfound', ['size' => 225]); // Sqlite tranform the unknown type to NULL type $generator->addColumn('lastname', 'string', ['size' => 225]); @@ -74,7 +74,7 @@ public function test_create_fail(string $name) public function test_create_success(string $name) { Database::connection($name)->statement("drop table if exists bow_testing;"); - $status = $this->migration->connection($name)->create('bow_testing', function (SQLGenerator $generator) use ($name) { + $status = $this->migration->connection($name)->create('bow_testing', function (Table $generator) use ($name) { $generator->addColumn('id', 'string', ['size' => 225, 'primary' => true]); $generator->addColumn('name', 'string', ['size' => 225]); $generator->addColumn('lastname', 'string', ['size' => 225]); @@ -93,7 +93,7 @@ public function test_create_success(string $name) public function test_alter_success(string $name) { $this->migration->connection($name)->addSql('create table if not exists bow_testing (name varchar(255));'); - $status = $this->migration->connection($name)->alter('bow_testing', function (SQLGenerator $generator) { + $status = $this->migration->connection($name)->alter('bow_testing', function (Table $generator) { $generator->dropColumn('name'); $generator->addColumn('age', 'int', ['size' => 11, 'default' => 12]); }); @@ -107,7 +107,7 @@ public function test_alter_success(string $name) public function test_alter_fail(string $name) { $this->expectException(MigrationException::class); - $this->migration->connection($name)->alter('bow_testing', function (SQLGenerator $generator) { + $this->migration->connection($name)->alter('bow_testing', function (Table $generator) { $generator->dropColumn('name'); $generator->dropColumn('lastname'); $generator->addColumn('age', 'int', ['size' => 11, 'default' => 12]); diff --git a/tests/Database/Migration/Mysql/SQLGeneratorTest.php b/tests/Database/Migration/Mysql/SQLGeneratorTest.php index 0822b8bb..5ec7f6b0 100644 --- a/tests/Database/Migration/Mysql/SQLGeneratorTest.php +++ b/tests/Database/Migration/Mysql/SQLGeneratorTest.php @@ -2,19 +2,21 @@ namespace Bow\Tests\Database\Migration\Mysql; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Exception\SQLGeneratorException; +use Bow\Database\Migration\Table; class SQLGeneratorTest extends \PHPUnit\Framework\TestCase { /** * The sql generator * - * @var SQLGenerator + * @var Table */ - private $generator; + private Table $generator; /** * Test Add column action + * @throws SQLGeneratorException */ public function test_add_column_sql_statement() { @@ -137,6 +139,6 @@ public function test_should_create_correct_timestamps_sql_statement() protected function setUp(): void { - $this->generator = new SQLGenerator('bow_tests', 'mysql', 'create'); + $this->generator = new Table('bow_tests', 'mysql', 'create'); } } diff --git a/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php b/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php index 61fe8bcb..a41632e5 100644 --- a/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php +++ b/tests/Database/Migration/Mysql/SQLGenetorHelpersTest.php @@ -3,16 +3,16 @@ namespace Bow\Tests\Database\Migration\Mysql; use Bow\Database\Exception\SQLGeneratorException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; class SQLGenetorHelpersTest extends \PHPUnit\Framework\TestCase { /** * The sql generator * - * @var SQLGenerator + * @var Table */ - private $generator; + private Table $generator; /** * @dataProvider getStringTypesWithSize @@ -232,6 +232,6 @@ public function getStringTypesWithoutSize() protected function setUp(): void { - $this->generator = new SQLGenerator('bow_tests', 'mysql', 'create'); + $this->generator = new Table('bow_tests', 'mysql', 'create'); } } diff --git a/tests/Database/Migration/Pgsql/SQLGeneratorTest.php b/tests/Database/Migration/Pgsql/SQLGeneratorTest.php index 686419bd..79affc41 100644 --- a/tests/Database/Migration/Pgsql/SQLGeneratorTest.php +++ b/tests/Database/Migration/Pgsql/SQLGeneratorTest.php @@ -3,16 +3,16 @@ namespace Bow\Tests\Database\Migration\Pgsql; use Bow\Database\Exception\SQLGeneratorException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; class SQLGeneratorTest extends \PHPUnit\Framework\TestCase { /** * The sql generator * - * @var SQLGenerator + * @var Table */ - private $generator; + private Table $generator; /** * Test Add column action @@ -144,6 +144,6 @@ public function test_should_create_correct_timestamps_sql_statement() protected function setUp(): void { - $this->generator = new SQLGenerator('bow_tests', 'pgsql', 'create'); + $this->generator = new Table('bow_tests', 'pgsql', 'create'); } } diff --git a/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php b/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php index 50257820..ff3e6feb 100644 --- a/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php +++ b/tests/Database/Migration/Pgsql/SQLGenetorHelpersTest.php @@ -3,16 +3,16 @@ namespace Bow\Tests\Database\Migration\Pgsql; use Bow\Database\Exception\SQLGeneratorException; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; class SQLGenetorHelpersTest extends \PHPUnit\Framework\TestCase { /** * The sql generator * - * @var SQLGenerator + * @var Table */ - private $generator; + private Table $generator; /** * @dataProvider getStringTypesWithSize @@ -309,6 +309,6 @@ public function getStringTypesWithoutSize() protected function setUp(): void { - $this->generator = new SQLGenerator('bow_tests', 'pgsql', 'create'); + $this->generator = new Table('bow_tests', 'pgsql', 'create'); } } diff --git a/tests/Database/Migration/SQLite/SQLGeneratorTest.php b/tests/Database/Migration/SQLite/SQLGeneratorTest.php index 57f7221d..35537d33 100644 --- a/tests/Database/Migration/SQLite/SQLGeneratorTest.php +++ b/tests/Database/Migration/SQLite/SQLGeneratorTest.php @@ -3,7 +3,7 @@ namespace Bow\Tests\Database\Migration\SQLite; use Bow\Database\Database; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; use Bow\Tests\Config\TestingConfiguration; class SQLGeneratorTest extends \PHPUnit\Framework\TestCase @@ -11,9 +11,9 @@ class SQLGeneratorTest extends \PHPUnit\Framework\TestCase /** * The sql generator * - * @var SQLGenerator + * @var Table */ - private $generator; + private Table $generator; /** * Test Add column action @@ -155,6 +155,6 @@ public function test_should_create_correct_timestamps_sql_statement() protected function setUp(): void { - $this->generator = new SQLGenerator('bow_tests', 'sqlite', 'create'); + $this->generator = new Table('bow_tests', 'sqlite', 'create'); } } diff --git a/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php b/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php index d6e1d186..9e4858a8 100644 --- a/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php +++ b/tests/Database/Migration/SQLite/SQLGenetorHelpersTest.php @@ -2,16 +2,16 @@ namespace Bow\Tests\Database\Migration\SQLite; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; class SQLGenetorHelpersTest extends \PHPUnit\Framework\TestCase { /** * The sql generator * - * @var SQLGenerator + * @var Table */ - private $generator; + private Table $generator; /** * Test Add column action @@ -87,6 +87,6 @@ public function getNumberTypes() protected function setUp(): void { - $this->generator = new SQLGenerator('bow_tests', 'sqlite', 'create'); + $this->generator = new Table('bow_tests', 'sqlite', 'create'); } } diff --git a/tests/Database/PaginationTest.php b/tests/Database/PaginationTest.php index 8a806798..401448d2 100644 --- a/tests/Database/PaginationTest.php +++ b/tests/Database/PaginationTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Tests\Bow\Database; +namespace Bow\Tests\Database; use Bow\Database\Pagination; use PHPUnit\Framework\TestCase; diff --git a/tests/Database/Query/DatabaseQueryTest.php b/tests/Database/Query/DatabaseQueryTest.php index 6b3443bf..2b964d5e 100644 --- a/tests/Database/Query/DatabaseQueryTest.php +++ b/tests/Database/Query/DatabaseQueryTest.php @@ -3,6 +3,7 @@ namespace Bow\Tests\Database\Query; use Bow\Database\Database; +use Bow\Database\Exception\ConnectionException; use Bow\Tests\Config\TestingConfiguration; class DatabaseQueryTest extends \PHPUnit\Framework\TestCase @@ -21,7 +22,7 @@ public function setUp(): void /** * @return array */ - public function connectionNameProvider() + public function connectionNameProvider(): array { return [['mysql'], ['sqlite'], ['pgsql']]; } @@ -29,6 +30,7 @@ public function connectionNameProvider() /** * @dataProvider connectionNameProvider * @param string $name + * @throws ConnectionException */ public function test_instance_of_database(string $name) { @@ -37,6 +39,7 @@ public function test_instance_of_database(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_get_database_connection(string $name) { @@ -49,6 +52,7 @@ public function test_get_database_connection(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_simple_insert_table(string $name) { @@ -60,7 +64,7 @@ public function test_simple_insert_table(string $name) $this->assertEquals($result, 2); } - public function createTestingTable() + public function createTestingTable(): void { Database::statement('drop table if exists pets'); Database::statement( @@ -70,6 +74,7 @@ public function createTestingTable() /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_array_insert_table(string $name) { @@ -86,8 +91,9 @@ public function test_array_insert_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ - public function test_array_multile_insert_table(string $name) + public function test_array_multiple_insert_table(string $name) { $database = Database::connection($name); $this->createTestingTable(); @@ -103,6 +109,7 @@ public function test_array_multile_insert_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_select_table(string $name) { @@ -116,6 +123,7 @@ public function test_select_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_select_table_and_check_item_length(string $name) { @@ -135,6 +143,7 @@ public function test_select_table_and_check_item_length(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_select_with_get_one_element_table(string $name) { @@ -150,6 +159,7 @@ public function test_select_with_get_one_element_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_select_with_not_get_element_table(string $name) { @@ -164,6 +174,7 @@ public function test_select_with_not_get_element_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_select_one_table(string $name) { @@ -180,6 +191,7 @@ public function test_select_one_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_update_table(string $name) { @@ -197,6 +209,7 @@ public function test_update_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_delete_table(string $name) { @@ -214,6 +227,7 @@ public function test_delete_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_transaction_table(string $name) { @@ -232,6 +246,7 @@ public function test_transaction_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_rollback_table(string $name) { @@ -262,8 +277,9 @@ public function test_rollback_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ - public function test_stement_table(string $name) + public function test_statement_table(string $name) { $database = Database::connection($name); $this->createTestingTable(); @@ -275,8 +291,9 @@ public function test_stement_table(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ - public function test_stement_table_2(string $name) + public function test_statement_table_2(string $name) { $database = Database::connection($name); $this->createTestingTable(); diff --git a/tests/Database/Query/ModelQueryTest.php b/tests/Database/Query/ModelQueryTest.php index bdaa9c0d..af26f2cd 100644 --- a/tests/Database/Query/ModelQueryTest.php +++ b/tests/Database/Query/ModelQueryTest.php @@ -3,6 +3,7 @@ namespace Bow\Tests\Database\Query; use Bow\Database\Database; +use Bow\Database\Exception\ConnectionException; use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Database\Stubs\PetModelStub; @@ -29,8 +30,9 @@ public function test_the_first_result_should_be_the_instance_of_same_model(strin /** * @param string $name + * @throws ConnectionException */ - public function createTestingTable(string $name) + public function createTestingTable(string $name): void { $connection = Database::connection($name); @@ -55,6 +57,7 @@ public function createTestingTable(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_take_method_and_the_result_should_be_the_instance_of_the_same_model( string $name @@ -69,6 +72,7 @@ public function test_take_method_and_the_result_should_be_the_instance_of_the_sa /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_instance_off_collection(string $name) { @@ -93,6 +97,7 @@ public function test_chain_select(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_count_simple(string $name) { @@ -105,6 +110,7 @@ public function test_count_simple(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_count_selected(string $name) { @@ -118,6 +124,7 @@ public function test_count_selected(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_count_selected_with_collection_count(string $name) { @@ -131,6 +138,7 @@ public function test_count_selected_with_collection_count(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_insert_by_create_method(string $name) { @@ -139,7 +147,7 @@ public function test_insert_by_create_method(string $name) $next_id = PetModelStub::all()->count() + 1; $insert_result = PetModelStub::create(['name' => 'Tor']); - $select_result = PetModelStub::findBy('id', $next_id)->first(); + $select_result = PetModelStub::retrieveBy('id', $next_id)->first(); $this->assertInstanceOf(PetModelStub::class, $insert_result); $this->assertInstanceOf(PetModelStub::class, $select_result); @@ -153,6 +161,7 @@ public function test_insert_by_create_method(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ public function test_save(string $name) { @@ -160,7 +169,7 @@ public function test_save(string $name) $pet = PetModelStub::first(); $pet->name = "Lofi"; - $pet->save(); + $pet->persist(); $this->assertNotEquals($pet->name, 'Couli'); $this->assertInstanceOf(PetModelStub::class, $pet); @@ -168,36 +177,39 @@ public function test_save(string $name) /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ - public function test_find_should_not_be_empty(string $name) + public function test_retrieve_should_not_be_empty(string $name) { $this->createTestingTable($name); - $pet = PetModelStub::find(1); + $pet = PetModelStub::retrieve(1); $this->assertEquals($pet->name, 'Couli'); } /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ - public function test_find_result_should_be_empty(string $name) + public function test_retrieve_result_should_be_empty(string $name) { $this->createTestingTable($name); - $pet = PetModelStub::find(100); + $pet = PetModelStub::retrieve(100); $this->assertNull($pet); } /** * @dataProvider connectionNameProvider + * @throws ConnectionException */ - public function test_findby_result_should_not_be_empty(string $name) + public function test_retrieve_by_result_should_not_be_empty(string $name) { $this->createTestingTable($name); - $result = PetModelStub::findBy('id', 1); + $result = PetModelStub::retrieveBy('id', 1); $pet = $result->first(); $this->assertNotEquals($result->count(), 0); @@ -208,11 +220,11 @@ public function test_findby_result_should_not_be_empty(string $name) /** * @dataProvider connectionNameProvider */ - public function test_find_by_method_should_be_empty(string $name) + public function test_retrieve_by_method_should_be_empty(string $name) { $this->createTestingTable($name); - $result = PetModelStub::findBy('id', 100); + $result = PetModelStub::retrieveBy('id', 100); $pet = $result->first(); $this->assertNull($pet); @@ -221,7 +233,7 @@ public function test_find_by_method_should_be_empty(string $name) /** * @return array */ - public function connectionNameProvider() + public function connectionNameProvider(): array { return [['mysql'], ['sqlite'], ['pgsql']]; } diff --git a/tests/Database/Query/PaginationTest.php b/tests/Database/Query/PaginationTest.php index b6c4afc9..b901b34b 100644 --- a/tests/Database/Query/PaginationTest.php +++ b/tests/Database/Query/PaginationTest.php @@ -16,7 +16,7 @@ public static function setUpBeforeClass(): void /** * @dataProvider connectionNameProvider - * @param Database $database + * @param string $name */ public function test_go_current_pagination(string $name) { @@ -32,7 +32,7 @@ public function test_go_current_pagination(string $name) $this->assertEquals($result->next(), 2); } - public function createTestingTable(string $name) + public function createTestingTable(string $name): void { $connection = Database::connection($name); $connection->statement('drop table if exists pets'); @@ -45,7 +45,7 @@ public function createTestingTable(string $name) /** * @dataProvider connectionNameProvider - * @param Database $database + * @param string $name */ public function test_go_next_2_pagination(string $name) { @@ -63,7 +63,7 @@ public function test_go_next_2_pagination(string $name) /** * @dataProvider connectionNameProvider - * @param Database $database + * @param string $name */ public function test_go_next_3_pagination(string $name) { @@ -82,7 +82,7 @@ public function test_go_next_3_pagination(string $name) /** * @return array */ - public function connectionNameProvider() + public function connectionNameProvider(): array { return [['mysql'], ['sqlite'], ['pgsql']]; } diff --git a/tests/Database/Query/QueryBuilderTest.php b/tests/Database/Query/QueryBuilderTest.php index c602d147..24b5b1bb 100644 --- a/tests/Database/Query/QueryBuilderTest.php +++ b/tests/Database/Query/QueryBuilderTest.php @@ -3,6 +3,8 @@ namespace Bow\Tests\Database\Query; use Bow\Database\Database; +use Bow\Database\Exception\ConnectionException; +use Bow\Database\Exception\QueryBuilderException; use Bow\Database\QueryBuilder; use Bow\Tests\Config\TestingConfiguration; @@ -46,7 +48,7 @@ public function test_get_instance(string $name, Database $database) $this->assertInstanceOf(QueryBuilder::class, $database->connection($name)->table('pets')); } - public function createTestingTable(string $name) + public function createTestingTable(string $name): void { Database::connection($name)->statement('drop table if exists pets'); Database::connection($name)->statement( @@ -57,7 +59,9 @@ public function createTestingTable(string $name) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException */ public function test_insert_by_passing_a_array(string $name, Database $database) { @@ -76,9 +80,11 @@ public function test_insert_by_passing_a_array(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException */ - public function test_insert_by_passing_a_mutilple_array(string $name, Database $database) + public function test_insert_by_passing_a_multiple_array(string $name, Database $database) { $this->createTestingTable($name); $table = $database->connection($name)->table('pets'); @@ -97,7 +103,9 @@ public function test_insert_by_passing_a_mutilple_array(string $name, Database $ /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException */ public function test_select_rows(string $name, Database $database) { @@ -114,7 +122,9 @@ public function test_select_rows(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException */ public function test_select_chain_rows(string $name, Database $database) { @@ -128,7 +138,9 @@ public function test_select_chain_rows(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException */ public function test_select_first_chain_rows(string $name, Database $database) { @@ -149,7 +161,10 @@ public function test_select_first_chain_rows(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException + * @throws QueryBuilderException */ public function test_where_in_chain_rows(string $name, Database $database) { @@ -163,7 +178,9 @@ public function test_where_in_chain_rows(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException */ public function test_where_null_chain_rows(string $name, Database $database) { @@ -177,7 +194,10 @@ public function test_where_null_chain_rows(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException + * @throws QueryBuilderException */ public function test_where_between_chain_rows(string $name, Database $database) { @@ -191,7 +211,9 @@ public function test_where_between_chain_rows(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException */ public function test_where_not_between_chain_rows(string $name, Database $database) { @@ -205,7 +227,10 @@ public function test_where_not_between_chain_rows(string $name, Database $databa /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException + * @throws QueryBuilderException */ public function test_where_not_null_chain_rows(string $name, Database $database) { @@ -219,7 +244,10 @@ public function test_where_not_null_chain_rows(string $name, Database $database) /** * @depends test_get_database_connection * @dataProvider connectionNameProvider + * @param string $name * @param Database $database + * @throws ConnectionException + * @throws QueryBuilderException */ public function test_where_chain_rows(string $name, Database $database) { @@ -237,7 +265,7 @@ public function test_where_chain_rows(string $name, Database $database) /** * @return array */ - public function connectionNameProvider() + public function connectionNameProvider(): array { return [['mysql'], ['sqlite'], ['pgsql']]; } diff --git a/tests/Database/Relation/BelongsToRelationQueryTest.php b/tests/Database/Relation/BelongsToRelationQueryTest.php index 67130ee0..08e51981 100644 --- a/tests/Database/Relation/BelongsToRelationQueryTest.php +++ b/tests/Database/Relation/BelongsToRelationQueryTest.php @@ -4,7 +4,7 @@ use Bow\Cache\Cache; use Bow\Database\Database; -use Bow\Database\Migration\SQLGenerator; +use Bow\Database\Migration\Table; use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Database\Stubs\MigrationExtendedStub; use Bow\Tests\Database\Stubs\PetMasterModelStub; @@ -19,7 +19,7 @@ public static function setUpBeforeClass(): void Cache::configure($config["cache"]); } - public function connectionNames() + public function connectionNames(): array { return [ ['mysql'], ['sqlite'], ['pgsql'] @@ -43,23 +43,23 @@ public function test_get_the_relationship(string $name) { $this->executeMigration($name); - $pet = PetModelStub::connection($name)->find(1); + $pet = PetModelStub::connection($name)->retrieve(1); $master = $pet->master; $this->assertInstanceOf(PetMasterModelStub::class, $master); $this->assertEquals('didi', $master->name); } - public function executeMigration(string $name) + public function executeMigration(string $name): void { $migration = new MigrationExtendedStub(); $migration->connection($name)->dropIfExists("pets"); $migration->connection($name)->dropIfExists("pet_masters"); - $migration->connection($name)->create("pet_masters", function (SQLGenerator $table) { + $migration->connection($name)->create("pet_masters", function (Table $table) { $table->addIncrement("id"); $table->addString("name"); }); - $migration->connection($name)->create("pets", function (SQLGenerator $table) { + $migration->connection($name)->create("pets", function (Table $table) { $table->addIncrement("id"); $table->addString("name"); $table->addInteger("master_id"); diff --git a/tests/Events/EventTest.php b/tests/Events/EventTest.php index 73d2c508..0c834ec2 100644 --- a/tests/Events/EventTest.php +++ b/tests/Events/EventTest.php @@ -50,7 +50,7 @@ public function test_model_created_event_emited() 'id' => 3, 'name' => 'Filou' ]); - $this->assertEquals($event->save(), 1); + $this->assertEquals($event->persist(), 1); $this->assertEquals('created', file_get_contents(static::$cache_filename)); } @@ -58,7 +58,7 @@ public function test_model_updated_event_emited() { $pet = EventModelStub::connection("mysql")->first(); $pet->name = 'Loulou'; - $this->assertEquals($pet->save(), 1); + $this->assertEquals($pet->persist(), 1); $this->assertEquals('updated', file_get_contents(static::$cache_filename)); } diff --git a/tests/Filesystem/FTPServiceTest.php b/tests/Filesystem/FTPServiceTest.php index 5e8d26de..dc464325 100644 --- a/tests/Filesystem/FTPServiceTest.php +++ b/tests/Filesystem/FTPServiceTest.php @@ -11,7 +11,7 @@ class FTPServiceTest extends \PHPUnit\Framework\TestCase /** * @var FTPService */ - private $ftp_service; + private FTPService $ftp_service; public static function setUpBeforeClass(): void { @@ -45,7 +45,7 @@ public function test_create_new_file_into_ftp_server() $this->assertTrue($result); } - private function createFile(FTPService $ftp_service, $filename, $content = '') + private function createFile(FTPService $ftp_service, $filename, $content = ''): bool { $uploaded_file = $this->getMockBuilder(\Bow\Http\UploadedFile::class) ->disableOriginalConstructor() diff --git a/tests/Queue/Stubs/ModelProducerStub.php b/tests/Queue/Stubs/ModelProducerStub.php index c467f73b..c6cb0301 100644 --- a/tests/Queue/Stubs/ModelProducerStub.php +++ b/tests/Queue/Stubs/ModelProducerStub.php @@ -16,7 +16,7 @@ public function __construct( public function process(): void { - $this->pet->save(); + $this->pet->persist(); file_put_contents(TESTING_RESOURCE_BASE_DIRECTORY . "/{$this->connection}_queue_pet_model_stub.txt", $this->pet->toJson()); diff --git a/tests/Support/CollectionTest.php b/tests/Support/CollectionTest.php index 2dfb427f..cd376639 100644 --- a/tests/Support/CollectionTest.php +++ b/tests/Support/CollectionTest.php @@ -17,7 +17,7 @@ public function test_get_instance() } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_sum(Collection $collection) @@ -26,7 +26,7 @@ public function test_sum(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_max(Collection $collection) @@ -35,7 +35,7 @@ public function test_max(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_min(Collection $collection) @@ -44,7 +44,7 @@ public function test_min(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_count(Collection $collection) @@ -53,7 +53,7 @@ public function test_count(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_pop(Collection $collection) @@ -62,7 +62,7 @@ public function test_pop(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_shift(Collection $collection) @@ -71,7 +71,7 @@ public function test_shift(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_reserve(Collection $collection) @@ -80,7 +80,7 @@ public function test_reserve(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_generator(Collection $collection) @@ -91,7 +91,7 @@ public function test_generator(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_json(Collection $collection) @@ -100,7 +100,7 @@ public function test_json(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_excepts(Collection $collection) @@ -109,7 +109,7 @@ public function test_excepts(Collection $collection) } /** - * @param $collection + * @param Collection $collection * @depends test_get_instance */ public function test_push(Collection $collection) From 8fc6ae3b86c8e6765f07b9204e25f029e98c6d2c Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Thu, 30 Jan 2025 08:47:50 +0000 Subject: [PATCH 10/10] feat: add the database notification accessor --- .github/workflows/coding-standards.yml | 56 ++-- .github/workflows/issues.yml | 10 +- .github/workflows/pull-requests.yml | 10 +- .github/workflows/tests.yml | 90 +++--- .github/workflows/update-changelog.yml | 8 +- docker-compose.yml | 7 +- src/Application/Application.php | 32 +-- .../Exception/BaseErrorHandler.php | 10 +- src/Auth/Auth.php | 8 +- src/Auth/AuthenticationConfiguration.php | 9 +- src/Auth/Guards/GuardContract.php | 8 +- src/Auth/Guards/JwtGuard.php | 15 +- src/Auth/Guards/SessionGuard.php | 6 +- src/Auth/Traits/LoginUserTrait.php | 6 +- src/Cache/Adapters/CacheAdapterInterface.php | 38 +-- src/Cache/Adapters/DatabaseAdapter.php | 31 ++- src/Cache/Adapters/RedisAdapter.php | 4 +- src/Cache/Cache.php | 10 +- src/Cache/CacheConfiguration.php | 9 +- src/Configuration/Configuration.php | 2 +- src/Configuration/EnvConfiguration.php | 23 +- src/Configuration/Loader.php | 8 +- src/Configuration/LoggerConfiguration.php | 33 ++- src/Console/AbstractCommand.php | 4 +- src/Console/Argument.php | 8 +- src/Console/Color.php | 16 +- src/Console/Command.php | 6 +- src/Console/Command/AppEventCommand.php | 4 +- src/Console/Command/ClearCommand.php | 4 +- 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 | 4 +- .../GenerateResourceControllerCommand.php | 19 +- src/Console/Command/MessagingCommand.php | 4 +- src/Console/Command/MiddlewareCommand.php | 4 +- src/Console/Command/MigrationCommand.php | 60 ++-- src/Console/Command/ModelCommand.php | 2 +- src/Console/Command/ProducerCommand.php | 4 +- src/Console/Command/ReplCommand.php | 2 +- src/Console/Command/SeederCommand.php | 8 +- src/Console/Command/ServiceCommand.php | 4 +- src/Console/Command/ValidationCommand.php | 4 +- src/Console/Command/WorkerCommand.php | 4 +- src/Console/Console.php | 20 +- src/Console/Generator.php | 22 +- src/Console/Setting.php | 46 +-- src/Console/Traits/ConsoleTrait.php | 6 +- src/Container/Capsule.php | 20 +- src/Container/Compass.php | 32 +-- src/Container/ContainerConfiguration.php | 11 +- src/Container/MiddlewareDispatcher.php | 8 +- src/Contracts/CollectionInterface.php | 18 +- src/Database/Barry/Builder.php | 8 +- src/Database/Barry/Concerns/Relationship.php | 24 +- src/Database/Barry/Model.php | 136 +++++---- src/Database/Barry/Relation.php | 6 +- src/Database/Barry/Relations/BelongsTo.php | 4 +- .../Barry/Relations/BelongsToMany.php | 4 +- src/Database/Barry/Relations/HasMany.php | 8 +- src/Database/Barry/Relations/HasOne.php | 4 +- .../Barry/Traits/ArrayAccessTrait.php | 7 +- src/Database/Barry/Traits/EventTrait.php | 2 +- src/Database/Collection.php | 8 +- .../Connection/AbstractConnection.php | 4 +- src/Database/Database.php | 46 +-- src/Database/DatabaseConfiguration.php | 9 +- .../Migration/Compose/MysqlCompose.php | 6 +- .../Migration/Compose/PgsqlCompose.php | 12 +- .../Migration/Compose/SqliteCompose.php | 50 ++-- src/Database/Migration/Migration.php | 42 +-- .../Migration/Shortcut/ConstraintColumn.php | 16 +- .../Migration/Shortcut/DateColumn.php | 40 +-- .../Migration/Shortcut/MixedColumn.php | 84 +++--- .../Migration/Shortcut/NumberColumn.php | 84 +++--- .../Migration/Shortcut/TextColumn.php | 48 ++-- src/Database/Migration/Table.php | 38 +-- .../Notification/DatabaseNotification.php | 35 +++ .../Notification/WithNotification.php | 35 +++ src/Database/Pagination.php | 50 ++++ src/Database/QueryBuilder.php | 211 +++++++------- src/Database/Redis.php | 14 +- src/Event/Contracts/EventListener.php | 2 +- src/Event/Dispatchable.php | 8 +- src/Event/Event.php | 25 +- src/Event/EventProducer.php | 2 +- src/Event/Listener.php | 4 +- src/Http/Client/HttpClient.php | 28 +- src/Http/Client/Response.php | 4 +- src/Http/Exception/HttpException.php | 2 +- src/Http/Exception/RequestException.php | 2 +- src/Http/Exception/ResponseException.php | 2 +- src/Http/HttpStatus.php | 2 +- src/Http/Redirect.php | 18 +- src/Http/Request.php | 56 ++-- src/Http/Response.php | 42 +-- src/Http/ServerAccessControl.php | 14 +- src/Http/UploadedFile.php | 2 +- src/Mail/Adapters/LogAdapter.php | 14 +- src/Mail/Adapters/NativeAdapter.php | 4 +- src/Mail/Adapters/SesAdapter.php | 4 +- src/Mail/Adapters/SmtpAdapter.php | 10 +- src/Mail/Contracts/MailAdapterInterface.php | 2 +- src/Mail/Envelop.php | 34 +-- src/Mail/Mail.php | 60 ++-- src/Mail/MailConfiguration.php | 9 +- src/Mail/MailQueueProducer.php | 6 +- src/Mail/Security/DkimSigner.php | 30 +- src/Mail/Security/SpfChecker.php | 60 ++-- .../Adapters/DatabaseChannelAdapter.php | 10 +- src/Messaging/Adapters/MailChannelAdapter.php | 4 +- .../Adapters/SlackChannelAdapter.php | 11 +- src/Messaging/Adapters/SmsChannelAdapter.php | 15 +- .../Adapters/TelegramChannelAdapter.php | 11 +- src/Messaging/CanSendMessage.php | 18 +- .../Contracts/ChannelAdapterInterface.php | 4 +- src/Messaging/Messaging.php | 17 +- src/Messaging/MessagingQueueProducer.php | 4 +- src/Middleware/AuthMiddleware.php | 6 +- src/Middleware/BaseMiddleware.php | 6 +- src/Middleware/CsrfMiddleware.php | 6 +- src/Queue/Adapters/BeanstalkdAdapter.php | 16 +- src/Queue/Adapters/DatabaseAdapter.php | 46 +-- src/Queue/Adapters/QueueAdapter.php | 30 +- src/Queue/Adapters/SQSAdapter.php | 38 ++- src/Queue/Adapters/SyncAdapter.php | 4 +- src/Queue/Connection.php | 10 +- src/Queue/ProducerService.php | 8 +- src/Queue/QueueConfiguration.php | 9 +- src/Queue/WorkerService.php | 14 +- src/Router/Resource.php | 14 +- src/Router/Route.php | 20 +- src/Router/Router.php | 66 ++--- src/Security/Crypto.php | 4 +- src/Security/CryptoConfiguration.php | 11 +- src/Security/Hash.php | 10 +- src/Security/Sanitize.php | 8 +- src/Security/Tokenize.php | 17 +- src/Session/Adapters/ArrayAdapter.php | 14 +- src/Session/Adapters/DatabaseAdapter.php | 26 +- src/Session/Adapters/DurationTrait.php | 2 +- src/Session/Adapters/FilesystemAdapter.php | 16 +- src/Session/Cookie.php | 16 +- src/Session/Session.php | 46 +-- src/Session/SessionConfiguration.php | 17 +- src/Storage/Contracts/FilesystemInterface.php | 46 +-- .../Exception/ServiceNotFoundException.php | 2 +- src/Storage/Service/DiskFilesystemService.php | 32 +-- src/Storage/Service/FTPService.php | 109 +++++--- src/Storage/Service/S3Service.php | 82 +++--- src/Storage/Storage.php | 42 +-- src/Storage/StorageConfiguration.php | 9 +- src/Storage/Temporary.php | 2 +- src/Support/Arraydotify.php | 29 +- src/Support/Collection.php | 91 +++--- src/Support/Env.php | 12 +- src/Support/Log.php | 4 +- src/Support/LoggerService.php | 24 +- src/Support/Serializes.php | 4 +- src/Support/Str.php | 110 ++++---- src/Support/Util.php | 14 +- src/Support/helpers.php | 263 +++++++++--------- src/Testing/Features/FeatureHelper.php | 2 +- src/Testing/Features/SeedingHelper.php | 4 +- src/Testing/KernelTesting.php | 6 +- src/Testing/Response.php | 24 +- src/Testing/TestCase.php | 48 ++-- src/Translate/Translator.php | 22 +- src/Translate/TranslatorConfiguration.php | 29 +- .../Exception/ValidationException.php | 2 +- src/Validation/FieldLexical.php | 12 +- src/Validation/RequestValidation.php | 6 +- src/Validation/Rules/DatabaseRule.php | 20 +- src/Validation/Rules/DatetimeRule.php | 8 +- src/Validation/Rules/EmailRule.php | 4 +- src/Validation/Rules/NumericRule.php | 12 +- src/Validation/Rules/RegexRule.php | 4 +- src/Validation/Rules/StringRule.php | 83 +++--- src/Validation/Validate.php | 4 +- src/Validation/Validator.php | 2 +- src/View/Engine/PHPEngine.php | 6 +- src/View/Engine/TwigEngine.php | 2 +- src/View/EngineAbstract.php | 10 +- src/View/View.php | 24 +- src/View/ViewConfiguration.php | 11 +- tests/Application/ApplicationTest.php | 6 + tests/Database/Query/ModelQueryTest.php | 1 + tests/Messaging/MessagingTest.php | 10 +- tests/Queue/EventQueueTest.php | 2 +- tests/Queue/QueueTest.php | 2 +- tests/Support/stubs/env.json | 6 +- tests/Translate/TranslationTest.php | 4 +- tests/Translate/stubs/en/welcome.php | 2 +- tests/Translate/stubs/fr/welcome.php | 2 +- 195 files changed, 2242 insertions(+), 1861 deletions(-) create mode 100644 src/Database/Notification/DatabaseNotification.php create mode 100644 src/Database/Notification/WithNotification.php diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml index 2f104523..7c014d20 100644 --- a/.github/workflows/coding-standards.yml +++ b/.github/workflows/coding-standards.yml @@ -1,41 +1,41 @@ name: fix code styling on: - workflow_call: - inputs: - php: - default: "8.1" - type: string - message: - default: Fix code styling - type: string - fix: - default: true - type: boolean + workflow_call: + inputs: + php: + default: "8.1" + type: string + message: + default: Fix code styling + type: string + fix: + default: true + type: boolean jobs: - lint: - runs-on: ubuntu-latest + lint: + runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ inputs.php }} - extensions: json, dom, curl, libxml, mbstring - coverage: none + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ inputs.php }} + extensions: json, dom, curl, libxml, mbstring + coverage: none - - name: Install PHP CS - run: composer global require squizlabs/php_codesniffer + - name: Install PHP CS + run: composer global require squizlabs/php_codesniffer - - name: Run Phpcbf - run: phpcbf --standard=psr11 --tab-width=4 --severity=4 + - name: Run Phpcbf + run: phpcbf --standard=psr11 --tab-width=4 --severity=4 - - name: Commit linted files - if: ${{ inputs.fix }} - uses: stefanzweifel/git-auto-commit-action@v4 - with: - commit_message: ${{ inputs.message }} + - name: Commit linted files + if: ${{ inputs.fix }} + uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: ${{ inputs.message }} diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml index 9332224d..ab84f3a4 100644 --- a/.github/workflows/issues.yml +++ b/.github/workflows/issues.yml @@ -1,12 +1,12 @@ name: issues on: - issues: - types: [ labeled ] + issues: + types: [labeled] permissions: - issues: write + issues: write jobs: - help-wanted: - uses: bowphp/.github/.github/workflows/issues.yml@main + help-wanted: + uses: bowphp/.github/.github/workflows/issues.yml@main diff --git a/.github/workflows/pull-requests.yml b/.github/workflows/pull-requests.yml index 4437c822..1bc67d39 100644 --- a/.github/workflows/pull-requests.yml +++ b/.github/workflows/pull-requests.yml @@ -1,12 +1,12 @@ name: pull requests on: - pull_request_target: - types: [ opened ] + pull_request_target: + types: [opened] permissions: - pull-requests: write + pull-requests: write jobs: - uneditable: - uses: bowphp/.github/.github/workflows/pull-requests.yml@main + uneditable: + uses: bowphp/.github/.github/workflows/pull-requests.yml@main diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c9ccf779..5f9f5919 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,50 +3,50 @@ name: bowphp on: [ push, pull_request ] env: - FTP_HOST: localhost - FTP_USER: username - FTP_PASSWORD: password - FTP_PORT: 21 - FTP_ROOT: /tmp + FTP_HOST: localhost + FTP_USER: username + FTP_PASSWORD: password + FTP_PORT: 21 + FTP_ROOT: /tmp jobs: - lunix-tests: - runs-on: ${{ matrix.os }} - strategy: - matrix: - php: [ 8.1, 8.2, 8.3 ] - os: [ ubuntu-latest ] - stability: [ prefer-lowest, prefer-stable ] + lunix-tests: + runs-on: ${{ matrix.os }} + strategy: + matrix: + php: [8.1, 8.2, 8.3] + os: [ubuntu-latest] + stability: [prefer-lowest, prefer-stable] - name: PHP ${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} + name: PHP ${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} - steps: - - name: Checkout code - uses: actions/checkout@v2 + steps: + - name: Checkout code + uses: actions/checkout@v4 - - name: Setup MySQL - uses: mirromutth/mysql-action@v1.1 - with: - host port: 3306 - container port: 3306 - character set server: 'utf8mb4' - collation server: 'utf8mb4_general_ci' - mysql version: '5.7' - mysql database: 'test_db' - mysql root password: 'password' + - name: Setup MySQL + uses: mirromutth/mysql-action@v1.1 + with: + host port: 3306 + container port: 3306 + character set server: 'utf8mb4' + collation server: 'utf8mb4_general_ci' + mysql version: '5.7' + mysql database: 'test_db' + mysql root password: 'password' - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php }} - extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, mysql, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, redis - coverage: none + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, mysql, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, redis + coverage: none - - run: docker run -p 21:21 -p 20:20 -p 12020:12020 -p 12021:12021 -p 12022:12022 -p 12023:12023 -p 12024:12024 -p 12025:12025 -e USER=$FTP_USER -e PASS=$FTP_PASSWORD -d --name ftp papacdev/vsftpd - - run: docker run -p 1080:1080 -p 1025:1025 -d --name maildev soulteary/maildev - - run: docker run -p 6379:6379 -d --name redis redis - - run: docker run -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -d postgis/postgis - - run: docker run -d -p 11300:11300 schickling/beanstalkd + - run: docker run -p 21:21 -p 20:20 -p 12020:12020 -p 12021:12021 -p 12022:12022 -p 12023:12023 -p 12024:12024 -p 12025:12025 -e USER=$FTP_USER -e PASS=$FTP_PASSWORD -d --name ftp papacdev/vsftpd + - run: docker run -p 1080:1080 -p 1025:1025 -d --name maildev soulteary/maildev + - run: docker run -p 6379:6379 -d --name redis redis + - run: docker run -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -e POSTGRES_PASSWORD=postgres -d postgis/postgis + - run: docker run -d -p 11300:11300 schickling/beanstalkd - name: Cache Composer packages id: composer-cache @@ -57,14 +57,14 @@ jobs: restore-keys: | ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} - - name: Copy the php ini config - run: sudo cp php.dist.ini php.ini + - name: Copy the php ini config + run: sudo cp php.dist.ini php.ini - - name: Install dependencies - run: sudo composer update --prefer-dist --no-interaction + - name: Install dependencies + run: sudo composer update --prefer-dist --no-interaction - - name: Create test cache directory - run: if [ ! -d /tmp/bowphp_testing ]; then mkdir -p /tmp/bowphp_testing; fi; + - name: Create test cache directory + run: if [ ! -d /tmp/bowphp_testing ]; then mkdir -p /tmp/bowphp_testing; fi; - - name: Run test suite - run: sudo composer run-script test + - name: Run test suite + run: sudo composer run-script test diff --git a/.github/workflows/update-changelog.yml b/.github/workflows/update-changelog.yml index b90851fe..1c8b5d5a 100644 --- a/.github/workflows/update-changelog.yml +++ b/.github/workflows/update-changelog.yml @@ -1,9 +1,9 @@ name: update changelog on: - release: - types: [ released ] + release: + types: [released] jobs: - update: - uses: bowphp/.github/.github/workflows/update-changelog.yml@main + update: + uses: bowphp/.github/.github/workflows/update-changelog.yml@main diff --git a/docker-compose.yml b/docker-compose.yml index dc8671ce..f9d91443 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -15,15 +15,14 @@ networks: services: mysql: container_name: bowphp_mysql - image: mysql/mysql-server:8.0 + image: mysql:8.3.0 restart: unless-stopped ports: - "3306:3306" environment: MYSQL_DATABASE: test_db MYSQL_ROOT_PASSWORD: password - MYSQL_ROOT_HOST: "%" - MYSQL_ALLOW_EMPTY_PASSWORD: "no" + MYSQL_ALLOW_EMPTY_PASSWORD: "yes" command: --default-authentication-plugin=mysql_native_password volumes: - mysql_data:/var/lib/mysql @@ -42,7 +41,7 @@ services: - "5432:5432" environment: POSTGRES_USER: postgres - POSTGRES_PASSWORD: postgres + POSTGRES_PASSWORD: password POSTGRES_DB: postgres volumes: - postgres_data:/var/lib/postgresql/data diff --git a/src/Application/Application.php b/src/Application/Application.php index d77d4345..45a6c3d1 100644 --- a/src/Application/Application.php +++ b/src/Application/Application.php @@ -70,8 +70,8 @@ class Application extends Router /** * Application constructor * - * @param Request $request - * @param Response $response + * @param Request $request + * @param Response $response * @throws BadRequestException */ public function __construct(Request $request, Response $response) @@ -192,8 +192,8 @@ public function send(): bool /** * Send the answer to the customer * - * @param mixed $response - * @param int $code + * @param mixed $response + * @param int $code * @return void */ private function sendResponse(mixed $response, int $code = 200): void @@ -219,9 +219,9 @@ public function disablePoweredByMention(): void /** * Make the REST API base on route and resource controller. * - * @param string $url - * @param string|array $controller_name - * @param array $where + * @param string $url + * @param string|array $controller_name + * @param array $where * @return Application * * @throws ApplicationException @@ -273,8 +273,8 @@ public function rest(string $url, string|array $controller_name, array $where = /** * Build the application * - * @param Request $request - * @param Response $response + * @param Request $request + * @param Response $response * @return Application * @throws BadRequestException */ @@ -290,9 +290,9 @@ public static function make(Request $request, Response $response): Application /** * Abort application * - * @param int $code - * @param string $message - * @param array $headers + * @param int $code + * @param string $message + * @param array $headers * @return void * * @throws HttpException @@ -315,8 +315,8 @@ public function abort(int $code = 500, string $message = '', array $headers = [] /** * Build dependence * - * @param ?string $name - * @param ?callable $callable + * @param ?string $name + * @param ?callable $callable * @return mixed * @throws ApplicationException */ @@ -344,7 +344,7 @@ public function container(?string $name = null, ?callable $callable = null): mix /** * Configuration Association * - * @param Loader $config + * @param Loader $config * @return void */ public function bind(Loader $config): void @@ -384,7 +384,7 @@ private function boot(): void * * This point method on the container system * - * @param array $params + * @param array $params * @return mixed * @throws ApplicationException */ diff --git a/src/Application/Exception/BaseErrorHandler.php b/src/Application/Exception/BaseErrorHandler.php index d382b89e..90ee2f96 100644 --- a/src/Application/Exception/BaseErrorHandler.php +++ b/src/Application/Exception/BaseErrorHandler.php @@ -17,8 +17,8 @@ class BaseErrorHandler /** * Render view as response * - * @param string $view - * @param array $data + * @param string $view + * @param array $data * @return string */ protected function render(string $view, array $data = []): string @@ -29,11 +29,11 @@ protected function render(string $view, array $data = []): string /** * Send the json as response * - * @param $exception - * @param mixed|null $code + * @param $exception + * @param mixed|null $code * @return void */ - #[NoReturn] protected function json($exception, mixed $code = null): void + protected function json($exception, mixed $code = null): void { if ($exception instanceof TokenInvalidException) { $code = 'TOKEN_INVALID'; diff --git a/src/Auth/Auth.php b/src/Auth/Auth.php index c6bd05d3..cbc11ee5 100644 --- a/src/Auth/Auth.php +++ b/src/Auth/Auth.php @@ -36,7 +36,7 @@ class Auth /** * Configure Auth system * - * @param array $config + * @param array $config * @return ?GuardContract * @throws AuthenticationException */ @@ -54,7 +54,7 @@ public static function configure(array $config): ?GuardContract /** * Check if user is authenticated * - * @param null|string $guard + * @param null|string $guard * @return GuardContract * @throws AuthenticationException */ @@ -100,8 +100,8 @@ public static function getInstance(): ?GuardContract /** * __callStatic * - * @param string $method - * @param array $params + * @param string $method + * @param array $params * @return ?GuardContract * @throws ErrorException */ diff --git a/src/Auth/AuthenticationConfiguration.php b/src/Auth/AuthenticationConfiguration.php index f0ddf35d..27e4f494 100644 --- a/src/Auth/AuthenticationConfiguration.php +++ b/src/Auth/AuthenticationConfiguration.php @@ -14,9 +14,12 @@ class AuthenticationConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('auth', function () use ($config) { - return Auth::configure($config['auth']); - }); + $this->container->bind( + 'auth', + function () use ($config) { + return Auth::configure($config['auth']); + } + ); } /** diff --git a/src/Auth/Guards/GuardContract.php b/src/Auth/Guards/GuardContract.php index d967260f..b2fb846c 100644 --- a/src/Auth/Guards/GuardContract.php +++ b/src/Auth/Guards/GuardContract.php @@ -51,7 +51,7 @@ abstract public function logout(): bool; /** * Logout * - * @param Authentication $user + * @param Authentication $user * @return bool */ abstract public function login(Authentication $user): bool; @@ -66,7 +66,7 @@ abstract public function user(): ?Authentication; /** * Check if user is authenticated * - * @param array $credentials + * @param array $credentials * @return bool */ abstract public function attempts(array $credentials): bool; @@ -84,11 +84,11 @@ public function getName(): string /** * Load the guard * - * @param string|null $guard + * @param string|null $guard * @return GuardContract * @throws AuthenticationException */ - public function guard(string $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 e098bbb1..ce48bff8 100644 --- a/src/Auth/Guards/JwtGuard.php +++ b/src/Auth/Guards/JwtGuard.php @@ -33,8 +33,8 @@ class JwtGuard extends GuardContract /** * JwtGuard constructor. * - * @param array $provider - * @param string $guard + * @param array $provider + * @param string $guard * @throws AuthenticationException */ public function __construct(array $provider, string $guard) @@ -50,7 +50,7 @@ public function __construct(array $provider, string $guard) /** * Check if user is authenticated * - * @param array $credentials + * @param array $credentials * @return bool * @throws AuthenticationException * @throws Exception @@ -142,16 +142,19 @@ private function getPolicier(): Policier /** * Make direct login * - * @param Authentication $user + * @param Authentication $user * @return bool * @throws Exception */ public function login(Authentication $user): bool { - $attributes = array_merge($user->customJwtAttributes(), [ + $attributes = array_merge( + $user->customJwtAttributes(), + [ "id" => $user->getAuthenticateUserId(), "logged" => true - ]); + ] + ); $this->token = $this->getPolicier()->encode($user->getAuthenticateUserId(), $attributes); diff --git a/src/Auth/Guards/SessionGuard.php b/src/Auth/Guards/SessionGuard.php index 3f339afd..0096072d 100644 --- a/src/Auth/Guards/SessionGuard.php +++ b/src/Auth/Guards/SessionGuard.php @@ -32,7 +32,7 @@ class SessionGuard extends GuardContract /** * SessionGuard constructor. * - * @param array $provider + * @param array $provider * @param string $guard */ public function __construct(array $provider, string $guard) @@ -45,7 +45,7 @@ public function __construct(array $provider, string $guard) /** * Check if user is authenticated * - * @param array $credentials + * @param array $credentials * @return bool * @throws AuthenticationException|SessionException */ @@ -112,7 +112,7 @@ public function guest(): bool /** * Make direct login * - * @param mixed $user + * @param mixed $user * @return bool * @throws AuthenticationException|SessionException */ diff --git a/src/Auth/Traits/LoginUserTrait.php b/src/Auth/Traits/LoginUserTrait.php index 0c01e2d3..ba86b883 100644 --- a/src/Auth/Traits/LoginUserTrait.php +++ b/src/Auth/Traits/LoginUserTrait.php @@ -13,7 +13,7 @@ trait LoginUserTrait /** * Make login * - * @param array $credentials + * @param array $credentials * @return ?Authentication * @throws AuthenticationException */ @@ -45,8 +45,8 @@ private function makeLogin(array $credentials): ?Authentication /** * Get user by key * - * @param string $key - * @param float|int|string $value + * @param string $key + * @param float|int|string $value * @return Model|null */ private function getUserBy(string $key, float|int|string $value): ?Authentication diff --git a/src/Cache/Adapters/CacheAdapterInterface.php b/src/Cache/Adapters/CacheAdapterInterface.php index 89cf0dd3..18161084 100644 --- a/src/Cache/Adapters/CacheAdapterInterface.php +++ b/src/Cache/Adapters/CacheAdapterInterface.php @@ -7,9 +7,9 @@ interface CacheAdapterInterface /** * Add new enter in the cache system * - * @param string $key - * @param mixed $data - * @param ?int $time + * @param string $key + * @param mixed $data + * @param ?int $time * @return bool */ public function add(string $key, mixed $data, ?int $time = null): bool; @@ -17,9 +17,9 @@ public function add(string $key, mixed $data, ?int $time = null): bool; /** * Set a new enter * - * @param string $key - * @param mixed $data - * @param ?int $time + * @param string $key + * @param mixed $data + * @param ?int $time * @return bool */ public function set(string $key, mixed $data, ?int $time = null): bool; @@ -27,7 +27,7 @@ public function set(string $key, mixed $data, ?int $time = null): bool; /** * Add many item * - * @param array $data + * @param array $data * @return bool */ public function addMany(array $data): bool; @@ -35,8 +35,8 @@ public function addMany(array $data): bool; /** * Adds a cache that will persist * - * @param string $key The cache key - * @param mixed $data + * @param string $key The cache key + * @param mixed $data * @return bool */ public function forever(string $key, mixed $data): bool; @@ -44,8 +44,8 @@ public function forever(string $key, mixed $data): bool; /** * Add new enter in the cache system * - * @param string $key The cache key - * @param mixed $data + * @param string $key The cache key + * @param mixed $data * @return bool */ public function push(string $key, array $data): bool; @@ -53,8 +53,8 @@ public function push(string $key, array $data): bool; /** * Retrieve an entry in the cache * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed */ public function get(string $key, mixed $default = null): mixed; @@ -62,8 +62,8 @@ public function get(string $key, mixed $default = null): mixed; /** * Increase the cache expiration time * - * @param string $key - * @param int $time + * @param string $key + * @param int $time * @return bool */ public function addTime(string $key, int $time): bool; @@ -71,7 +71,7 @@ public function addTime(string $key, int $time): bool; /** * Retrieves the cache expiration time * - * @param string $key + * @param string $key * @return int|bool|string */ public function timeOf(string $key): int|bool|string; @@ -79,7 +79,7 @@ public function timeOf(string $key): int|bool|string; /** * Delete an entry in the cache * - * @param string $key + * @param string $key * @return bool */ public function forget(string $key): bool; @@ -87,7 +87,7 @@ public function forget(string $key): bool; /** * Check for an entry in the cache. * - * @param string $key + * @param string $key * @return bool */ public function has(string $key): bool; @@ -95,7 +95,7 @@ public function has(string $key): bool; /** * Check if the cache has expired * - * @param string $key + * @param string $key * @return bool */ public function expired(string $key): bool; diff --git a/src/Cache/Adapters/DatabaseAdapter.php b/src/Cache/Adapters/DatabaseAdapter.php index 3fa30e36..65da4d04 100644 --- a/src/Cache/Adapters/DatabaseAdapter.php +++ b/src/Cache/Adapters/DatabaseAdapter.php @@ -20,7 +20,7 @@ class DatabaseAdapter implements CacheAdapterInterface /** * RedisAdapter constructor. * - * @param array $config + * @param array $config * @return void * @throws ConnectionException */ @@ -31,7 +31,7 @@ public function __construct(array $config) /** * @inheritDoc - * @throws Exception + * @throws Exception */ public function set(string $key, mixed $data, ?int $time = null): bool { @@ -40,7 +40,7 @@ public function set(string $key, mixed $data, ?int $time = null): bool /** * @inheritDoc - * @throws Exception + * @throws Exception */ public function add(string $key, mixed $data, ?int $time = null): bool { @@ -67,7 +67,7 @@ public function add(string $key, mixed $data, ?int $time = null): bool /** * @inheritDoc - * @throws QueryBuilderException + * @throws QueryBuilderException */ public function has(string $key): bool { @@ -76,6 +76,7 @@ public function has(string $key): bool /** * Update value from key + * * @throws Exception */ public function update(string $key, mixed $data, ?int $time = null): mixed @@ -102,7 +103,7 @@ public function update(string $key, mixed $data, ?int $time = null): mixed /** * @inheritDoc - * @throws Exception + * @throws Exception */ public function addMany(array $data): bool { @@ -117,7 +118,7 @@ public function addMany(array $data): bool /** * @inheritDoc - * @throws Exception + * @throws Exception */ public function forever(string $key, mixed $data): bool { @@ -126,7 +127,7 @@ public function forever(string $key, mixed $data): bool /** * @inheritDoc - * @throws Exception + * @throws Exception */ public function push(string $key, array $data): bool { @@ -144,8 +145,8 @@ public function push(string $key, array $data): bool /** * @inheritDoc - * @throws QueryBuilderException - * @throws Exception + * @throws QueryBuilderException + * @throws Exception */ public function addTime(string $key, int $time): bool { @@ -162,8 +163,8 @@ public function addTime(string $key, int $time): bool /** * @inheritDoc - * @throws QueryBuilderException - * @throws Exception + * @throws QueryBuilderException + * @throws Exception */ public function timeOf(string $key): int|bool|string { @@ -178,8 +179,8 @@ public function timeOf(string $key): int|bool|string /** * @inheritDoc - * @throws QueryBuilderException - * @throws Exception + * @throws QueryBuilderException + * @throws Exception */ public function forget(string $key): bool { @@ -192,7 +193,7 @@ public function forget(string $key): bool /** * @inheritDoc - * @throws QueryBuilderException + * @throws QueryBuilderException */ public function expired(string $key): bool { @@ -201,7 +202,7 @@ public function expired(string $key): bool /** * @inheritDoc - * @throws QueryBuilderException + * @throws QueryBuilderException */ public function get(string $key, mixed $default = null): mixed { diff --git a/src/Cache/Adapters/RedisAdapter.php b/src/Cache/Adapters/RedisAdapter.php index 1bbbb793..3efe787f 100644 --- a/src/Cache/Adapters/RedisAdapter.php +++ b/src/Cache/Adapters/RedisAdapter.php @@ -17,7 +17,7 @@ class RedisAdapter implements CacheAdapterInterface /** * RedisAdapter constructor. * - * @param array $config + * @param array $config * @return void */ public function __construct(array $config) @@ -34,7 +34,7 @@ public function __construct(array $config) /** * Ping the redis service * - * @param ?string $message + * @param ?string $message * @return RedisAdapter */ public function ping(?string $message = null): RedisAdapter diff --git a/src/Cache/Cache.php b/src/Cache/Cache.php index 7bb07474..c33f734f 100644 --- a/src/Cache/Cache.php +++ b/src/Cache/Cache.php @@ -42,7 +42,7 @@ class Cache /** * Cache configuration method * - * @param array $config + * @param array $config * @return CacheAdapterInterface|null */ public static function configure(array $config): ?CacheAdapterInterface @@ -64,7 +64,7 @@ public static function configure(array $config): ?CacheAdapterInterface /** * Get the cache instance * - * @param string $store + * @param string $store * @return CacheAdapterInterface */ public static function store(string $store): CacheAdapterInterface @@ -100,7 +100,7 @@ public static function getInstance(): CacheAdapterInterface /** * Add the custom adapters * - * @param array $adapters + * @param array $adapters * @return void */ public static function addAdapters(array $adapters): void @@ -113,8 +113,8 @@ public static function addAdapters(array $adapters): void /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed * @throws BadMethodCallException * @throws ErrorException diff --git a/src/Cache/CacheConfiguration.php b/src/Cache/CacheConfiguration.php index 0349bf86..5e3ce162 100644 --- a/src/Cache/CacheConfiguration.php +++ b/src/Cache/CacheConfiguration.php @@ -14,9 +14,12 @@ class CacheConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('cache', function () use ($config) { - return Cache::configure($config['cache']); - }); + $this->container->bind( + 'cache', + function () use ($config) { + return Cache::configure($config['cache']); + } + ); } /** diff --git a/src/Configuration/Configuration.php b/src/Configuration/Configuration.php index b3319dd1..f37bb4d3 100644 --- a/src/Configuration/Configuration.php +++ b/src/Configuration/Configuration.php @@ -46,7 +46,7 @@ public function getName(): string /** * Create and configure the server or package * - * @param Loader $config + * @param Loader $config * @return void */ abstract public function create(Loader $config): void; diff --git a/src/Configuration/EnvConfiguration.php b/src/Configuration/EnvConfiguration.php index eecd9548..b81fdf0b 100644 --- a/src/Configuration/EnvConfiguration.php +++ b/src/Configuration/EnvConfiguration.php @@ -14,17 +14,20 @@ class EnvConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('env', function () use ($config) { - $path = $config['app.env_file']; - if ($path === false) { - throw new InvalidArgumentException( - "The application environment file [.env.json] is not exists. " - . "Copy the .env.example.json file to .env.json" - ); - } + $this->container->bind( + 'env', + function () use ($config) { + $path = $config['app.env_file']; + if ($path === false) { + throw new InvalidArgumentException( + "The application environment file [.env.json] is not exists. " + . "Copy the .env.example.json file to .env.json" + ); + } - Env::load($config['app.env_file']); - }); + Env::load($config['app.env_file']); + } + ); } /** diff --git a/src/Configuration/Loader.php b/src/Configuration/Loader.php index fe6fbc1c..73131e1a 100644 --- a/src/Configuration/Loader.php +++ b/src/Configuration/Loader.php @@ -51,7 +51,7 @@ class Loader implements ArrayAccess private bool $without_session = false; /** - * @param string $base_path + * @param string $base_path * @throws */ private function __construct(string $base_path) @@ -89,7 +89,7 @@ private function __construct(string $base_path) /** * Configuration Loader * - * @param string $base_path + * @param string $base_path * @return Loader * @throws */ @@ -286,8 +286,8 @@ public function events(): array /** * __invoke * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * @return mixed */ public function __invoke(string $key, mixed $value = null): mixed diff --git a/src/Configuration/LoggerConfiguration.php b/src/Configuration/LoggerConfiguration.php index b2f97dac..3f7fd3ba 100644 --- a/src/Configuration/LoggerConfiguration.php +++ b/src/Configuration/LoggerConfiguration.php @@ -25,25 +25,28 @@ class LoggerConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('logger', function () use ($config) { - $monolog = $this->loadFileLogger( - realpath($config['storage.log']), - $config['app.name'] ?? 'Bow' - ); - - if (php_sapi_name() != "cli") { - $this->loadFrontLogger($monolog, $config['app.error_handle']); - } + $this->container->bind( + 'logger', + function () use ($config) { + $monolog = $this->loadFileLogger( + realpath($config['storage.log']), + $config['app.name'] ?? 'Bow' + ); + + if (php_sapi_name() != "cli") { + $this->loadFrontLogger($monolog, $config['app.error_handle']); + } - return $monolog; - }); + return $monolog; + } + ); } /** * Loader file logger via Monolog * - * @param string $log_dir - * @param string $name + * @param string $log_dir + * @param string $name * @return Logger * @throws Exception */ @@ -65,8 +68,8 @@ private function loadFileLogger(string $log_dir, string $name): Logger /** * Loader view logger * - * @param Logger $monolog - * @param $error_handler + * @param Logger $monolog + * @param $error_handler * @return void */ private function loadFrontLogger(Logger $monolog, $error_handler): void diff --git a/src/Console/AbstractCommand.php b/src/Console/AbstractCommand.php index c2d9f04c..cc0a43c7 100644 --- a/src/Console/AbstractCommand.php +++ b/src/Console/AbstractCommand.php @@ -34,8 +34,8 @@ abstract class AbstractCommand /** * AbstractCommand constructor * - * @param Setting $setting - * @param Argument $arg + * @param Setting $setting + * @param Argument $arg * @return void */ public function __construct(Setting $setting, Argument $arg) diff --git a/src/Console/Argument.php b/src/Console/Argument.php index 0cbbbd72..ce4bfc26 100644 --- a/src/Console/Argument.php +++ b/src/Console/Argument.php @@ -99,7 +99,7 @@ private function formatParameters(): void /** * Initialize main command * - * @param string $param + * @param string $param * @return void */ private function initCommand(string $param): void @@ -115,8 +115,8 @@ private function initCommand(string $param): void /** * Retrieves a parameter * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return bool|string|null */ public function getParameter(string $key, mixed $default = null): mixed @@ -187,7 +187,7 @@ public function hasTrash(): bool /** * Read line * - * @param string $message + * @param string $message * @return bool */ public function readline(string $message): bool diff --git a/src/Console/Color.php b/src/Console/Color.php index ddf51d55..ba2a1827 100644 --- a/src/Console/Color.php +++ b/src/Console/Color.php @@ -9,7 +9,7 @@ class Color /** * Red message with '[danger]' prefix * - * @param string $message + * @param string $message * @return string */ public static function danger(string $message): string @@ -20,7 +20,7 @@ public static function danger(string $message): string /** * Red message * - * @param string $message + * @param string $message * @return string */ public static function red(string $message): string @@ -31,7 +31,7 @@ public static function red(string $message): string /** * Blue message with '[info]' prefix * - * @param string $message + * @param string $message * @return string */ public static function info(string $message): string @@ -42,7 +42,7 @@ public static function info(string $message): string /** * Blue message * - * @param string $message + * @param string $message * @return string */ public static function blue(string $message): string @@ -53,7 +53,7 @@ public static function blue(string $message): string /** * Yellow message with '[warning]' prefix * - * @param string $message + * @param string $message * @return string */ public static function warning(string $message): string @@ -64,7 +64,7 @@ public static function warning(string $message): string /** * Yellow message * - * @param string $message + * @param string $message * @return string */ public static function yellow(string $message): string @@ -75,7 +75,7 @@ public static function yellow(string $message): string /** * Green message with '[success]' prefix * - * @param string $message + * @param string $message * @return string */ public static function success(string $message): string @@ -86,7 +86,7 @@ public static function success(string $message): string /** * Green message * - * @param string $message + * @param string $message * @return string */ public static function green(string $message): string diff --git a/src/Console/Command.php b/src/Console/Command.php index 4683cac4..45cbad47 100644 --- a/src/Console/Command.php +++ b/src/Console/Command.php @@ -78,9 +78,9 @@ class Command extends AbstractCommand /** * The call command * - * @param string $action - * @param string $command - * @param array $rest + * @param string $action + * @param string $command + * @param array $rest * @return mixed * @throws ErrorException */ diff --git a/src/Console/Command/AppEventCommand.php b/src/Console/Command/AppEventCommand.php index 29c29b78..7ea9fcc4 100644 --- a/src/Console/Command/AppEventCommand.php +++ b/src/Console/Command/AppEventCommand.php @@ -13,10 +13,10 @@ class AppEventCommand extends AbstractCommand /** * Add event * - * @param string $event + * @param string $event * @return void */ - #[NoReturn] public function generate(string $event): void + 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 8804f24b..784f5b03 100644 --- a/src/Console/Command/ClearCommand.php +++ b/src/Console/Command/ClearCommand.php @@ -12,7 +12,7 @@ class ClearCommand extends AbstractCommand /** * Clear cache * - * @param string $action + * @param string $action * @return void */ public function make(string $action): void @@ -80,7 +80,7 @@ private function clear(string $action): void /** * Delete file * - * @param string $dirname + * @param string $dirname * @return void */ private function unlinks(string $dirname): void diff --git a/src/Console/Command/ConfigurationCommand.php b/src/Console/Command/ConfigurationCommand.php index 5a5d6593..7533535f 100644 --- a/src/Console/Command/ConfigurationCommand.php +++ b/src/Console/Command/ConfigurationCommand.php @@ -14,10 +14,10 @@ class ConfigurationCommand extends AbstractCommand /** * Add configuration * - * @param string $configuration + * @param string $configuration * @return void */ - #[NoReturn] public function generate(string $configuration): void + 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 bf7c4d30..40969a9f 100644 --- a/src/Console/Command/ConsoleCommand.php +++ b/src/Console/Command/ConsoleCommand.php @@ -13,10 +13,10 @@ class ConsoleCommand extends AbstractCommand /** * Add service * - * @param string $service + * @param string $service * @return void */ - #[NoReturn] public function generate(string $service): void + 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 264f5e3a..506bf35d 100644 --- a/src/Console/Command/ControllerCommand.php +++ b/src/Console/Command/ControllerCommand.php @@ -13,10 +13,10 @@ class ControllerCommand extends AbstractCommand /** * The add controller command * - * @param string $controller + * @param string $controller * @return void */ - #[NoReturn] public function generate(string $controller): void + 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 d110c2fa..1c3dbbb2 100644 --- a/src/Console/Command/EventListenerCommand.php +++ b/src/Console/Command/EventListenerCommand.php @@ -13,10 +13,10 @@ class EventListenerCommand extends AbstractCommand /** * Add event * - * @param string $event + * @param string $event * @return void */ - #[NoReturn] public function generate(string $event): void + 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 0c413b87..c32d1336 100644 --- a/src/Console/Command/ExceptionCommand.php +++ b/src/Console/Command/ExceptionCommand.php @@ -13,10 +13,10 @@ class ExceptionCommand extends AbstractCommand /** * Add middleware * - * @param string $exception + * @param string $exception * @return void */ - #[NoReturn] public function generate(string $exception): void + public function generate(string $exception): void { $generator = new Generator( $this->setting->getExceptionDirectory(), diff --git a/src/Console/Command/GenerateResourceControllerCommand.php b/src/Console/Command/GenerateResourceControllerCommand.php index eb3911bf..67e3cc98 100644 --- a/src/Console/Command/GenerateResourceControllerCommand.php +++ b/src/Console/Command/GenerateResourceControllerCommand.php @@ -15,11 +15,11 @@ class GenerateResourceControllerCommand extends AbstractCommand /** * Command used to set up the resource system. * - * @param string $controller + * @param string $controller * @return void * @throws */ - #[NoReturn] public function generate(string $controller): void + public function generate(string $controller): void { // We create command generator instance $generator = new Generator( @@ -67,7 +67,7 @@ class GenerateResourceControllerCommand extends AbstractCommand /** * Create the default view for rest Generation * - * @param string $base_directory + * @param string $base_directory * @return void */ private function createDefaultView(string $base_directory): void @@ -88,9 +88,9 @@ private function createDefaultView(string $base_directory): void * Create rest controller * * @param Generator $generator - * @param string $prefix - * @param string $controller - * @param string $model_namespace + * @param string $prefix + * @param string $controller + * @param string $model_namespace * * @return void */ @@ -100,12 +100,15 @@ private function createResourceController( string $controller, string $model_namespace = '' ): void { - $generator->write('controller/rest', [ + $generator->write( + 'controller/rest', + [ 'modelNamespace' => $model_namespace, 'prefix' => $prefix, 'className' => $controller, 'baseNamespace' => $this->namespaces['controller'] ?? 'App\\Controllers' - ]); + ] + ); echo Color::green('The controller Rest was well created.'); } diff --git a/src/Console/Command/MessagingCommand.php b/src/Console/Command/MessagingCommand.php index 69fdf33a..4c63202d 100644 --- a/src/Console/Command/MessagingCommand.php +++ b/src/Console/Command/MessagingCommand.php @@ -14,10 +14,10 @@ class MessagingCommand extends AbstractCommand /** * Generate session * - * @param string $messaging + * @param string $messaging * @return void */ - #[NoReturn] public function generate(string $messaging): void + public function generate(string $messaging): void { $generator = new Generator( $this->setting->getMessagingDirectory(), diff --git a/src/Console/Command/MiddlewareCommand.php b/src/Console/Command/MiddlewareCommand.php index fc116a05..bdf0a5a3 100644 --- a/src/Console/Command/MiddlewareCommand.php +++ b/src/Console/Command/MiddlewareCommand.php @@ -14,10 +14,10 @@ class MiddlewareCommand extends AbstractCommand /** * Add middleware * - * @param string $middleware + * @param string $middleware * @return void */ - #[NoReturn] public function generate(string $middleware): void + 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 f9437943..e4e8407e 100644 --- a/src/Console/Command/MigrationCommand.php +++ b/src/Console/Command/MigrationCommand.php @@ -33,7 +33,7 @@ public function migrate(): void /** * Create a migration in both directions * - * @param string $type + * @param string $type * @return void * @throws Exception */ @@ -88,10 +88,13 @@ private function createMigrationTable(): void $generator->addString('migration', ['unique' => true]); $generator->addInteger('batch'); - $generator->addDatetime('created_at', [ + $generator->addDatetime( + 'created_at', + [ 'default' => 'CURRENT_TIMESTAMP', 'nullable' => true - ]); + ] + ); $sql = sprintf( 'CREATE TABLE IF NOT EXISTS %s (%s);', @@ -157,10 +160,13 @@ public function generate(string $model): void $type = 'model/create'; } - $generator->write($type, [ + $generator->write( + $type, + [ 'table' => $table ?? 'table_name', 'className' => $filename - ]); + ] + ); // Print console information echo Color::green('The migration file has been successfully created') . "\n"; @@ -169,7 +175,7 @@ public function generate(string $model): void /** * Up migration * - * @param array $migrations + * @param array $migrations * @return void * @throws ConnectionException * @throws QueryBuilderException @@ -192,7 +198,7 @@ protected function makeUp(array $migrations): void } // Include the migration file - require $file; + include $file; try { // Up migration @@ -229,7 +235,7 @@ private function getMigrationTable(): QueryBuilder /** * Check the migration existence * - * @param string $migration + * @param string $migration * @return bool * @throws ConnectionException|QueryBuilderException */ @@ -246,9 +252,9 @@ private function checkIfMigrationExist(string $migration): bool * Throw migration exception * * @param Exception $exception - * @param string $migration + * @param string $migration */ - #[NoReturn] private function throwMigrationException(Exception $exception, string $migration): void + private function throwMigrationException(Exception $exception, string $migration): void { $this->printExceptionMessage( $exception->getMessage(), @@ -259,11 +265,11 @@ private function checkIfMigrationExist(string $migration): bool /** * Print the error message * - * @param string $message - * @param string $migration + * @param string $message + * @param string $migration * @return void */ - #[NoReturn] private function printExceptionMessage(string $message, string $migration): void + private function printExceptionMessage(string $message, string $migration): void { $message = Color::red($message); $migration = Color::yellow($migration); @@ -274,7 +280,7 @@ private function checkIfMigrationExist(string $migration): bool /** * Create migration status * - * @param string $migration + * @param string $migration * @return void * @throws ConnectionException */ @@ -282,18 +288,20 @@ private function createMigrationStatus(string $migration): void { $table = $this->getMigrationTable(); - $table->insert([ + $table->insert( + [ 'migration' => $migration, 'batch' => 1, 'created_at' => date('Y-m-d H:i:s') - ]); + ] + ); } /** * Update migration status * - * @param string $migration - * @param int $batch + * @param string $migration + * @param int $batch * @return void * @throws ConnectionException|QueryBuilderException */ @@ -301,16 +309,18 @@ private function updateMigrationStatus(string $migration, int $batch): void { $table = $this->getMigrationTable(); - $table->where('migration', $migration)->update([ + $table->where('migration', $migration)->update( + [ 'migration' => $migration, 'batch' => $batch - ]); + ] + ); } /** * Rollback migration * - * @param array $migrations + * @param array $migrations * @return void * @throws ConnectionException * @throws QueryBuilderException @@ -334,13 +344,13 @@ protected function makeRollback(array $migrations): void foreach ($migrations as $file => $migration) { if ( !($value->batch == 1 - && $migration == $value->migration) + && $migration == $value->migration) ) { continue; } // Include the migration file - require $file; + include $file; // Rollback migration try { @@ -383,7 +393,7 @@ public function rollback(): void /** * Reset migration * - * @param array $migrations + * @param array $migrations * @return void * @throws ConnectionException * @throws QueryBuilderException @@ -410,7 +420,7 @@ protected function makeReset(array $migrations): void } // Include the migration file - require $file; + include $file; // Rollback migration try { diff --git a/src/Console/Command/ModelCommand.php b/src/Console/Command/ModelCommand.php index 9a2b305c..12df7a86 100644 --- a/src/Console/Command/ModelCommand.php +++ b/src/Console/Command/ModelCommand.php @@ -13,7 +13,7 @@ class ModelCommand extends AbstractCommand /** * Add Model * - * @param string $model + * @param string $model * @return void */ public function generate(string $model): void diff --git a/src/Console/Command/ProducerCommand.php b/src/Console/Command/ProducerCommand.php index ae015f20..bccab487 100644 --- a/src/Console/Command/ProducerCommand.php +++ b/src/Console/Command/ProducerCommand.php @@ -14,10 +14,10 @@ class ProducerCommand extends AbstractCommand /** * Add producer * - * @param string $producer + * @param string $producer * @return void */ - #[NoReturn] public function generate(string $producer): void + 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 7d662e63..a5d9a8d7 100644 --- a/src/Console/Command/ReplCommand.php +++ b/src/Console/Command/ReplCommand.php @@ -24,7 +24,7 @@ public function run(): void if (is_string($include)) { $bootstraps = array_merge( $this->setting->getBootstrap(), - (array)$include + (array) $include ); $this->setting->setBootstrap($bootstraps); diff --git a/src/Console/Command/SeederCommand.php b/src/Console/Command/SeederCommand.php index 0a3c24f4..64e5a281 100644 --- a/src/Console/Command/SeederCommand.php +++ b/src/Console/Command/SeederCommand.php @@ -23,7 +23,7 @@ class SeederCommand extends AbstractCommand * * @param string $seeder */ - #[NoReturn] public function generate(string $seeder): void + public function generate(string $seeder): void { $seeder = Str::plural($seeder); @@ -60,12 +60,12 @@ public function all(): void /** * Make Seeder * - * @param string $seed_filename + * @param string $seed_filename * @return void */ private function make(string $seed_filename): void { - $seeds = require $seed_filename; + $seeds = include $seed_filename; $seed_collection = array_merge($seeds); @@ -97,7 +97,7 @@ private function make(string $seed_filename): void /** * Launch targeted seeding * - * @param string|null $seeder_name + * @param string|null $seeder_name * @return void */ public function table(?string $seeder_name = null): void diff --git a/src/Console/Command/ServiceCommand.php b/src/Console/Command/ServiceCommand.php index f1c64da6..eba84fb3 100644 --- a/src/Console/Command/ServiceCommand.php +++ b/src/Console/Command/ServiceCommand.php @@ -13,10 +13,10 @@ class ServiceCommand extends AbstractCommand /** * Add service * - * @param string $service + * @param string $service * @return void */ - #[NoReturn] public function generate(string $service): void + public function generate(string $service): void { $generator = new Generator( $this->setting->getServiceDirectory(), diff --git a/src/Console/Command/ValidationCommand.php b/src/Console/Command/ValidationCommand.php index 6c6d22cc..58887e70 100644 --- a/src/Console/Command/ValidationCommand.php +++ b/src/Console/Command/ValidationCommand.php @@ -14,10 +14,10 @@ class ValidationCommand extends AbstractCommand /** * Add validation * - * @param string $validation + * @param string $validation * @return void */ - #[NoReturn] public function generate(string $validation): void + public function generate(string $validation): void { $generator = new Generator( $this->setting->getValidationDirectory(), diff --git a/src/Console/Command/WorkerCommand.php b/src/Console/Command/WorkerCommand.php index d97b444d..5d6c574a 100644 --- a/src/Console/Command/WorkerCommand.php +++ b/src/Console/Command/WorkerCommand.php @@ -12,7 +12,7 @@ class WorkerCommand extends AbstractCommand /** * The run server command * - * @param string|null $connection + * @param string|null $connection * @return void */ public function run(?string $connection = null): void @@ -47,7 +47,7 @@ private function getWorderService() /** * Flush the queue * - * @param ?string $connection + * @param ?string $connection * @return void */ public function flush(?string $connection = null) diff --git a/src/Console/Console.php b/src/Console/Console.php index ed3255e7..326327ce 100644 --- a/src/Console/Console.php +++ b/src/Console/Console.php @@ -125,8 +125,8 @@ public static function getInstance(): ?Console * Add a custom order to the store from the web env * This method work on web and cli env * - * @param string $command - * @param callable|string $cb + * @param string $command + * @param callable|string $cb * @return void */ public static function register(string $command, callable|string $cb): void @@ -137,7 +137,7 @@ public static function register(string $command, callable|string $cb): void /** * Bind kernel * - * @param Loader $kernel + * @param Loader $kernel * @return void */ public function bind(Loader $kernel): void @@ -173,7 +173,7 @@ public function run(): mixed // Run all bootstraps files foreach ($this->setting->getBootstrap() as $item) { - require $item; + include $item; } // Get the argument command @@ -201,7 +201,7 @@ public function run(): mixed /** * Calls a command * - * @param string|null $command + * @param string|null $command * @return mixed * @throws ErrorException * @throws Exception @@ -243,7 +243,7 @@ public function call(?string $command): mixed /** * Display global help or helper command. * - * @param string|null $command + * @param string|null $command * @return int */ private function help(?string $command = null): int @@ -377,7 +377,7 @@ private function help(?string $command = null): int break; case 'run': // phpcs:disable - echo <<makeStubContent($type, array_merge([ - 'namespace' => $namespace, - 'className' => $classname - ], $data)); + $template = $this->makeStubContent( + $type, + array_merge( + [ + 'namespace' => $namespace, + 'className' => $classname + ], + $data + ) + ); return (bool)file_put_contents($this->getPath(), $template); } @@ -125,8 +131,8 @@ public function write(string $type, array $data = []): bool /** * Stub render * - * @param string $type - * @param array $data + * @param string $type + * @param array $data * @return string */ public function makeStubContent(string $type, array $data = []): string diff --git a/src/Console/Setting.php b/src/Console/Setting.php index a9b6d189..ce2edc03 100644 --- a/src/Console/Setting.php +++ b/src/Console/Setting.php @@ -181,7 +181,7 @@ class Setting /** * Command constructor. * - * @param string $dirname + * @param string $dirname * @return void */ public function __construct(string $dirname) @@ -192,7 +192,7 @@ public function __construct(string $dirname) /** * Set the server file * - * @param string $serve_filename + * @param string $serve_filename * @return void */ public function setServerFilename(string $serve_filename): void @@ -203,7 +203,7 @@ public function setServerFilename(string $serve_filename): void /** * Set the package configuration directory * - * @param string $configuration_directory + * @param string $configuration_directory * @return void */ public function setPackageDirectory(string $configuration_directory): void @@ -214,7 +214,7 @@ public function setPackageDirectory(string $configuration_directory): void /** * Set the application directory * - * @param string $app_directory + * @param string $app_directory * @return void */ public function setApplicationDirectory(string $app_directory): void @@ -235,7 +235,7 @@ public function getNamespaces(): array /** * Set the namespaces * - * @param array $namespaces + * @param array $namespaces * @return void */ public function setNamespaces(array $namespaces): void @@ -258,7 +258,7 @@ public function getVarDirectory(): string /** * Set the var directory * - * @param string $var_directory + * @param string $var_directory * @return void */ public function setVarDirectory(string $var_directory): void @@ -279,7 +279,7 @@ public function getComponentDirectory(): string /** * Set the component directory * - * @param string $component_directory + * @param string $component_directory * @return void */ public function setComponentDirectory(string $component_directory): void @@ -300,7 +300,7 @@ public function getConfigDirectory(): string /** * Set the config directory * - * @param string $config_directory + * @param string $config_directory * @return void */ public function setConfigDirectory(string $config_directory): void @@ -331,7 +331,7 @@ public function getMigrationDirectory(): string /** * Set the migration directory * - * @param string $migration_directory + * @param string $migration_directory * @return void */ public function setMigrationDirectory(string $migration_directory): void @@ -352,7 +352,7 @@ public function getSeederDirectory(): string /** * Set the seeder directory * - * @param string $seeder_directory + * @param string $seeder_directory * @return void */ public function setSeederDirectory(string $seeder_directory): void @@ -373,7 +373,7 @@ public function getValidationDirectory(): string /** * Set the validation directory * - * @param string $validation_directory + * @param string $validation_directory * @return void */ public function setValidationDirectory(string $validation_directory): void @@ -394,7 +394,7 @@ public function getServiceDirectory(): string /** * Set the service directory * - * @param string $service_directory + * @param string $service_directory * @return void */ public function setServiceDirectory(string $service_directory): void @@ -415,7 +415,7 @@ public function getProducerDirectory(): string /** * Set the producer directory * - * @param string $producer_directory + * @param string $producer_directory * @return void */ public function setProducerDirectory(string $producer_directory): void @@ -436,7 +436,7 @@ public function getCommandDirectory(): string /** * Set the command directory * - * @param string $command_directory + * @param string $command_directory * @return void */ public function setCommandDirectory(string $command_directory): void @@ -457,7 +457,7 @@ public function getEventDirectory(): string /** * Set the event directory * - * @param string $event_directory + * @param string $event_directory * @return void */ public function setEventDirectory(string $event_directory): void @@ -478,7 +478,7 @@ public function getEventListenerDirectory(): string /** * Set the event listener directory * - * @param string $event_listener_directory + * @param string $event_listener_directory * @return void */ public function setEventListenerDirectory(string $event_listener_directory): void @@ -499,7 +499,7 @@ public function getMiddlewareDirectory(): string /** * Set the middleware directory * - * @param string $middleware_directory + * @param string $middleware_directory * @return void */ public function setMiddlewareDirectory(string $middleware_directory): void @@ -520,7 +520,7 @@ public function getMessagingDirectory(): string /** * Set the messaging directory * - * @param string $messaging_directory + * @param string $messaging_directory * @return void */ public function setMessagingDirectory(string $messaging_directory): void @@ -541,7 +541,7 @@ public function getModelDirectory(): string /** * Set the model directory * - * @param string $model_directory + * @param string $model_directory * @return void */ public function setModelDirectory(string $model_directory): void @@ -562,7 +562,7 @@ public function getControllerDirectory(): string /** * Set the controller directory * - * @param string $controller_directory + * @param string $controller_directory * @return void */ public function setControllerDirectory(string $controller_directory): void @@ -603,7 +603,7 @@ public function getBootstrap(): array /** * Set the bootstrap files * - * @param array $bootstrap + * @param array $bootstrap * @return void */ public function setBootstrap(array $bootstrap): void @@ -634,7 +634,7 @@ public function getPublicDirectory(): string /** * Set the public directory * - * @param string $public_directory + * @param string $public_directory * @return void */ public function setPublicDirectory(string $public_directory): void @@ -655,7 +655,7 @@ public function getExceptionDirectory(): string /** * Set the exception directory * - * @param string $exception_directory + * @param string $exception_directory * @return void */ public function setExceptionDirectory(string $exception_directory): void diff --git a/src/Console/Traits/ConsoleTrait.php b/src/Console/Traits/ConsoleTrait.php index 7ba931aa..b2055444 100644 --- a/src/Console/Traits/ConsoleTrait.php +++ b/src/Console/Traits/ConsoleTrait.php @@ -12,11 +12,11 @@ trait ConsoleTrait /** * Throw fails command * - * @param string $message - * @param string|null $command + * @param string $message + * @param string|null $command * @return void */ - #[NoReturn] protected function throwFailsCommand(string $message, ?string $command = null): void + protected function throwFailsCommand(string $message, ?string $command = null): void { echo Color::red($message) . "\n"; diff --git a/src/Container/Capsule.php b/src/Container/Capsule.php index 19057499..75c13d19 100644 --- a/src/Container/Capsule.php +++ b/src/Container/Capsule.php @@ -65,8 +65,8 @@ public static function getInstance(): Capsule /** * Compilation with parameter * - * @param string $key - * @param array $parameters + * @param string $key + * @param array $parameters * @return mixed * @throws */ @@ -84,7 +84,7 @@ public function makeWith(string $key, array $parameters = []): mixed /** * Instantiate a class by its key * - * @param string $key + * @param string $key * @return mixed * @throws */ @@ -128,7 +128,7 @@ private function resolve(string $key): mixed /** * Make the * - * @param string $key + * @param string $key * @return mixed * @throws */ @@ -170,8 +170,8 @@ public function make(string $key): mixed /** * Add to register * - * @param string $key - * @param callable $value + * @param string $key + * @param callable $value * @return Capsule */ public function bind(string $key, callable $value): Capsule @@ -186,8 +186,8 @@ public function bind(string $key, callable $value): Capsule /** * Register the instance of a class * - * @param string $key - * @param Closure|callable $value + * @param string $key + * @param Closure|callable $value * @return Capsule */ public function factory(string $key, Closure|callable $value): Capsule @@ -200,8 +200,8 @@ public function factory(string $key, Closure|callable $value): Capsule /** * Saves the instance of a class * - * @param string $key - * @param mixed $instance + * @param string $key + * @param mixed $instance * @return Capsule */ public function instance(string $key, mixed $instance): Capsule diff --git a/src/Container/Compass.php b/src/Container/Compass.php index 25636e10..5c4b5ca2 100644 --- a/src/Container/Compass.php +++ b/src/Container/Compass.php @@ -87,8 +87,8 @@ public static function configure(array $namespaces, array $middlewares): Compass /** * Add a middleware to the list * - * @param array $middlewares - * @param bool $end + * @param array $middlewares + * @param bool $end * @return void */ public function pushMiddleware(array $middlewares, bool $end = false): void @@ -105,7 +105,7 @@ public function pushMiddleware(array $middlewares, bool $end = false): void /** * Adding a namespace to the list * - * @param array|string $namespace + * @param array|string $namespace * @return void */ public function pushNamespace(array|string $namespace): void @@ -118,8 +118,8 @@ public function pushNamespace(array|string $namespace): void /** * Callback launcher * - * @param callable|string|array $actions - * @param ?array $param + * @param callable|string|array $actions + * @param ?array $param * @return mixed * @throws RouterException * @throws ReflectionException @@ -279,7 +279,7 @@ public static function getInstance(): Compass /** * Load the controllers defined as string * - * @param string $controller_name + * @param string $controller_name * @return array|null * @throws ReflectionException */ @@ -317,8 +317,8 @@ public function controller(string $controller_name): ?array /** * Make any class injection * - * @param string $classname - * @param ?string $method + * @param string $classname + * @param ?string $method * @return array * @throws ReflectionException */ @@ -338,7 +338,7 @@ public function injector(string $classname, ?string $method = null): array /** * Get all parameters define by user in method injectable * - * @param array $parameters + * @param array $parameters * @return array * @throws ReflectionException */ @@ -368,7 +368,7 @@ private function getInjectParameters(array $parameters): array /** * Get injectable parameter * - * @param mixed $class + * @param mixed $class * @return ?object * @throws ReflectionException */ @@ -403,7 +403,7 @@ private function getInjectParameter(mixed $class): ?object /** * Injection for closure * - * @param Closure|callable $closure + * @param Closure|callable $closure * @return array * @throws */ @@ -419,8 +419,8 @@ public function injectorForClosure(Closure|callable $closure): array /** * Execution of define controller * - * @param array $functions - * @param array $params + * @param array $functions + * @param array $params * @return mixed */ private function dispatchControllers(array $functions, array $params): mixed @@ -455,8 +455,8 @@ private function dispatchControllers(array $functions, array $params): mixed /** * Successively launches a function list. * - * @param array|callable|string $function - * @param array $arguments + * @param array|callable|string $function + * @param array $arguments * @return mixed * @throws ReflectionException */ @@ -490,7 +490,7 @@ public function execute(array|callable|string $function, array $arguments): mixe /** * Load the closure define as action * - * @param Closure $closure + * @param Closure $closure * @return array|null */ public function closure(Closure $closure): ?array diff --git a/src/Container/ContainerConfiguration.php b/src/Container/ContainerConfiguration.php index 53b7f483..938efe0c 100644 --- a/src/Container/ContainerConfiguration.php +++ b/src/Container/ContainerConfiguration.php @@ -21,11 +21,14 @@ class ContainerConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('action', function () use ($config) { - $middlewares = array_merge($config->getMiddlewares(), $this->middlewares); + $this->container->bind( + 'action', + function () use ($config) { + $middlewares = array_merge($config->getMiddlewares(), $this->middlewares); - return Compass::configure($config->namespaces(), $middlewares); - }); + return Compass::configure($config->namespaces(), $middlewares); + } + ); } /** diff --git a/src/Container/MiddlewareDispatcher.php b/src/Container/MiddlewareDispatcher.php index cc2f36ed..cde182a3 100644 --- a/src/Container/MiddlewareDispatcher.php +++ b/src/Container/MiddlewareDispatcher.php @@ -24,8 +24,8 @@ class MiddlewareDispatcher /** * Add a middleware to the runtime collection * - * @param string|callable $middleware - * @param array $params + * @param string|callable $middleware + * @param array $params * @return MiddlewareDispatcher */ public function pipe(string|callable $middleware, array $params = []): MiddlewareDispatcher @@ -42,8 +42,8 @@ public function pipe(string|callable $middleware, array $params = []): Middlewar /** * Start the middleware running process * - * @param Request $request - * @param array $args + * @param Request $request + * @param array $args * @return mixed */ public function process(Request $request, array ...$args): mixed diff --git a/src/Contracts/CollectionInterface.php b/src/Contracts/CollectionInterface.php index 2513fed6..afc4383f 100644 --- a/src/Contracts/CollectionInterface.php +++ b/src/Contracts/CollectionInterface.php @@ -9,7 +9,7 @@ interface CollectionInterface /** * Check for existence of a key in the session collection * - * @param string|int $key + * @param string|int $key * @return bool */ public function has(string|int $key): bool; @@ -24,8 +24,8 @@ public function isEmpty(): bool; /** * Allows to recover a value or value collection. * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed */ public function get(mixed $key, mixed $default = null): mixed; @@ -33,9 +33,9 @@ public function get(mixed $key, mixed $default = null): mixed; /** * Add an entry to the collection * - * @param string|int $key - * @param mixed $data - * @param bool $next + * @param string|int $key + * @param mixed $data + * @param bool $next * @return CollectionInterface */ public function add(string|int $key, mixed $data, bool $next = false): mixed; @@ -44,7 +44,7 @@ public function add(string|int $key, mixed $data, bool $next = false): mixed; /** * Delete an entry in the collection * - * @param string|int $key + * @param string|int $key * @return CollectionInterface */ public function remove(string|int $key): mixed; @@ -52,8 +52,8 @@ public function remove(string|int $key): mixed; /** * Modify an entry in the collection * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * @return CollectionInterface */ public function set(string $key, mixed $value): mixed; diff --git a/src/Database/Barry/Builder.php b/src/Database/Barry/Builder.php index befa85f6..1c75b2b7 100644 --- a/src/Database/Barry/Builder.php +++ b/src/Database/Barry/Builder.php @@ -21,7 +21,7 @@ class Builder extends QueryBuilder /** * Get information * - * @param array $columns + * @param array $columns * @return Model|Collection|null */ public function get(array $columns = []): Model|Collection|null @@ -47,8 +47,8 @@ public function get(array $columns = []): Model|Collection|null /** * Check if rows exists * - * @param string|null $column - * @param mixed $value + * @param string|null $column + * @param mixed $value * @return bool * @throws QueryBuilderException */ @@ -87,7 +87,7 @@ public function getModel(): string /** * Set model * - * @param string $model + * @param string $model * @return Builder */ public function setModel(string $model): Builder diff --git a/src/Database/Barry/Concerns/Relationship.php b/src/Database/Barry/Concerns/Relationship.php index d73c9868..5a3c3fa2 100644 --- a/src/Database/Barry/Concerns/Relationship.php +++ b/src/Database/Barry/Concerns/Relationship.php @@ -15,9 +15,9 @@ trait Relationship /** * The has one relative * - * @param string $related - * @param string|null $foreign_key - * @param string|null $local_key + * @param string $related + * @param string|null $foreign_key + * @param string|null $local_key * @return BelongsTo */ public function belongsTo( @@ -50,9 +50,9 @@ abstract public function getKey(): string; /** * The belongs to many relative * - * @param string $related - * @param string|null $primary_key - * @param string|null $foreign_key + * @param string $related + * @param string|null $primary_key + * @param string|null $foreign_key * @return BelongsToMany */ public function belongsToMany( @@ -77,9 +77,9 @@ public function belongsToMany( /** * The has many relative * - * @param string $related - * @param string|null $primary_key - * @param string|null $foreign_key + * @param string $related + * @param string|null $primary_key + * @param string|null $foreign_key * @return HasMany * @throws QueryBuilderException */ @@ -105,9 +105,9 @@ public function hasMany( /** * The has one relative * - * @param string $related - * @param string|null $foreign_key - * @param string|null $primary_key + * @param string $related + * @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 a6d456d4..ad2c8d3a 100644 --- a/src/Database/Barry/Model.php +++ b/src/Database/Barry/Model.php @@ -217,7 +217,7 @@ public static function query(): Builder /** * Set the connection * - * @param string $name + * @param string $name * @return Model * @throws ConnectionException */ @@ -233,7 +233,7 @@ public static function connection(string $name): Model /** * Set connection point * - * @param string $name + * @param string $name * @return Builder * @throws ConnectionException */ @@ -279,9 +279,9 @@ public static function latest(): ?Model /** * Get first rows * - * @return array|object + * @return array|object|null */ - public static function first(): array|object + public static function first(): array|object|null { return static::query()->first(); } @@ -289,8 +289,8 @@ public static function first(): array|object /** * retrieve by column name * - * @param string $column - * @param mixed $value + * @param string $column + * @param mixed $value * @return Collection */ public static function retrieveBy(string $column, mixed $value): Collection @@ -332,8 +332,8 @@ public static function retrieveAndDelete( /** * retrieve * - * @param mixed $id - * @param array $select + * @param mixed $id + * @param array $select * @return array|object|null */ public static function retrieve( @@ -401,8 +401,8 @@ public function getKeyValue(): mixed * retrieve information by id or throws an * exception in data box not found * - * @param mixed $id - * @param array $select + * @param mixed $id + * @param array $select * @return array|object * @throws NotFoundException */ @@ -420,7 +420,7 @@ public static function retrieveOrFail(int|string $id, array $select = ['*']): ar /** * Create a persist information * - * @param array $data + * @param array $data * @return Model */ public static function create(array $data): Model @@ -428,10 +428,13 @@ public static function create(array $data): Model $model = new static(); if ($model->timestamps) { - $data = array_merge($data, [ + $data = array_merge( + $data, + [ $model->created_at => date('Y-m-d H:i:s'), $model->updated_at => date('Y-m-d H:i:s') - ]); + ] + ); } // Check if the primary key exist on updating data @@ -443,15 +446,17 @@ public static function create(array $data): Model $id_value = [$model->primary_key => null]; $data = array_merge($id_value, $data); } elseif ($model->primary_key_type == 'string') { - $data = array_merge([ + $data = array_merge( + [ $model->primary_key => '' - ], $data); + ], + $data + ); } } // Override the olds model attributes $model->setAttributes($data); - $model->persist(); return $model; } @@ -484,9 +489,13 @@ public function persist(): int // We set the primary key value $this->original[$this->primary_key] = $primary_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); + $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) { @@ -510,7 +519,7 @@ public function persist(): int /** * Create the new row * - * @param Builder $builder + * @param Builder $builder * @return int */ private function writeRows(Builder $builder): int @@ -553,7 +562,7 @@ private function writeRows(Builder $builder): int /** * Trans-type the primary key value * - * @param mixed $primary_key_value + * @param mixed $primary_key_value * @return string|int|float */ private function transtypeKeyValue(mixed $primary_key_value): string|int|float @@ -573,7 +582,7 @@ private function transtypeKeyValue(mixed $primary_key_value): string|int|float /** * Delete a record * - * @param array $attributes + * @param array $attributes * @return int|bool * @throws */ @@ -594,9 +603,13 @@ public function update(array $attributes): int|bool $data_for_updating = $attributes; if (count($this->original) > 0) { - $data_for_updating = array_filter($attributes, function ($value, $key) { - return array_key_exists($key, $this->original) || $this->original[$key] !== $value; - }, ARRAY_FILTER_USE_BOTH); + $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 @@ -622,9 +635,9 @@ public function update(array $attributes): int|bool /** * Pagination configuration * - * @param int $page_number - * @param int $current - * @param int|null $chunk + * @param int $page_number + * @param int $current + * @param int|null $chunk * @return Pagination */ public static function paginate(int $page_number, int $current = 0, ?int $chunk = null): Pagination @@ -635,7 +648,7 @@ public static function paginate(int $page_number, int $current = 0, ?int $chunk /** * Allows to associate listener * - * @param callable $cb + * @param callable $cb * @throws */ public static function deleted(callable $cb): void @@ -648,7 +661,7 @@ public static function deleted(callable $cb): void /** * Allows to associate listener * - * @param callable $cb + * @param callable $cb * @throws */ public static function deleting(callable $cb): void @@ -661,7 +674,7 @@ public static function deleting(callable $cb): void /** * Allows to associate a listener * - * @param callable $cb + * @param callable $cb * @throws */ public static function creating(callable $cb): void @@ -674,7 +687,7 @@ public static function creating(callable $cb): void /** * Allows to associate a listener * - * @param callable $cb + * @param callable $cb * @throws */ public static function created(callable $cb): void @@ -687,7 +700,7 @@ public static function created(callable $cb): void /** * Allows to associate a listener * - * @param callable $cb + * @param callable $cb * @throws */ public static function updating(callable $cb): void @@ -700,7 +713,7 @@ public static function updating(callable $cb): void /** * Allows to associate a listener * - * @param callable $cb + * @param callable $cb * @throws */ public static function updated(callable $cb): void @@ -713,8 +726,8 @@ public static function updated(callable $cb): void /** * Delete Active Record by column name * - * @param string $column - * @param mixed $value + * @param string $column + * @param mixed $value * @return int * @throws QueryBuilderException */ @@ -728,8 +741,8 @@ public static function deleteBy(string $column, mixed $value): int /** * __callStatic * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed */ public static function __callStatic(string $name, array $arguments) @@ -814,7 +827,7 @@ public function setAttributes(array $attributes): void /** * Allows you to recover an attribute * - * @param string $key + * @param string $key * @return mixed|null */ public function getAttribute(string $key): mixed @@ -829,9 +842,13 @@ public function getAttribute(string $key): mixed */ public function toArray(): array { - return array_filter($this->attributes, function ($key) { - return !in_array($key, $this->hidden); - }, ARRAY_FILTER_USE_KEY); + return array_filter( + $this->attributes, + function ($key) { + return !in_array($key, $this->hidden); + }, + ARRAY_FILTER_USE_KEY + ); } /** @@ -839,15 +856,19 @@ public function toArray(): array */ public function jsonSerialize(): array { - return array_filter($this->attributes, function ($key) { - return !in_array($key, $this->hidden); - }, ARRAY_FILTER_USE_KEY); + return array_filter( + $this->attributes, + function ($key) { + return !in_array($key, $this->hidden); + }, + ARRAY_FILTER_USE_KEY + ); } /** * __get * - * @param string $name + * @param string $name * @return mixed */ public function __get(string $name): mixed @@ -922,7 +943,7 @@ public function __get(string $name): mixed * __set * * @param string $name - * @param mixed $value + * @param mixed $value */ public function __set(string $name, mixed $value) { @@ -936,9 +957,12 @@ public function __set(string $name, mixed $value) */ private function mutableDateAttributes(): array { - return array_merge($this->dates, [ + return array_merge( + $this->dates, + [ $this->created_at, $this->updated_at, 'expired_at', 'logged_at', 'signed_at' - ]); + ] + ); } /** @@ -958,9 +982,13 @@ public function __toString(): string */ public function toJson(): string { - $data = array_filter($this->attributes, function ($key) { - return !in_array($key, $this->hidden); - }, ARRAY_FILTER_USE_KEY); + $data = array_filter( + $this->attributes, + function ($key) { + return !in_array($key, $this->hidden); + }, + ARRAY_FILTER_USE_KEY + ); return json_encode($data); } @@ -968,8 +996,8 @@ public function toJson(): string /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed */ public function __call(string $name, array $arguments = []) diff --git a/src/Database/Barry/Relation.php b/src/Database/Barry/Relation.php index 31d72ed4..2b1bfa92 100644 --- a/src/Database/Barry/Relation.php +++ b/src/Database/Barry/Relation.php @@ -100,8 +100,8 @@ public function getRelated(): Model /** * _Call * - * @param string $method - * @param array $args + * @param string $method + * @param array $args * @return mixed */ public function __call(string $method, array $args = []) @@ -118,7 +118,7 @@ public function __call(string $method, array $args = []) /** * Create a new row of the related * - * @param array $attributes + * @param array $attributes * @return Model */ public function create(array $attributes): Model diff --git a/src/Database/Barry/Relations/BelongsTo.php b/src/Database/Barry/Relations/BelongsTo.php index 335cdd6e..66d6cf44 100644 --- a/src/Database/Barry/Relations/BelongsTo.php +++ b/src/Database/Barry/Relations/BelongsTo.php @@ -14,8 +14,8 @@ class BelongsTo extends Relation /** * Create a new belongs to relationship instance. * - * @param Model $related - * @param Model $parent + * @param Model $related + * @param Model $parent * @param string $foreign_key * @param string $local_key */ diff --git a/src/Database/Barry/Relations/BelongsToMany.php b/src/Database/Barry/Relations/BelongsToMany.php index 5b965bdd..7e4bf0b8 100644 --- a/src/Database/Barry/Relations/BelongsToMany.php +++ b/src/Database/Barry/Relations/BelongsToMany.php @@ -14,8 +14,8 @@ class BelongsToMany extends Relation /** * Create a new belongs to relationship instance. * - * @param Model $related - * @param Model $parent + * @param Model $related + * @param Model $parent * @param string $foreign_key * @param string $local_key */ diff --git a/src/Database/Barry/Relations/HasMany.php b/src/Database/Barry/Relations/HasMany.php index 5dc92669..b24f2286 100644 --- a/src/Database/Barry/Relations/HasMany.php +++ b/src/Database/Barry/Relations/HasMany.php @@ -14,10 +14,10 @@ class HasMany extends Relation /** * Create a new belongs to relationship instance. * - * @param Model $related - * @param Model $parent - * @param string $foreign_key - * @param string $local_key + * @param Model $related + * @param Model $parent + * @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 295f5943..7a4241f6 100644 --- a/src/Database/Barry/Relations/HasOne.php +++ b/src/Database/Barry/Relations/HasOne.php @@ -14,8 +14,8 @@ class HasOne extends Relation /** * Create a new belongs to relationship instance. * - * @param Model $related - * @param Model $parent + * @param Model $related + * @param Model $parent * @param string $foreign_key * @param string $local_key */ diff --git a/src/Database/Barry/Traits/ArrayAccessTrait.php b/src/Database/Barry/Traits/ArrayAccessTrait.php index da59e603..f71c878a 100644 --- a/src/Database/Barry/Traits/ArrayAccessTrait.php +++ b/src/Database/Barry/Traits/ArrayAccessTrait.php @@ -26,10 +26,9 @@ public function offsetSet(mixed $offset, mixed $value): void /** * _offsetExists * - * @param mixed $offset + * @param mixed $offset * @return bool - * @see http://php.net/manual/fr/class.arrayaccess.php - * + * @see http://php.net/manual/fr/class.arrayaccess.php */ public function offsetExists(mixed $offset): bool { @@ -51,7 +50,7 @@ public function offsetUnset(mixed $offset): void /** * _offsetGet * - * @param mixed $offset + * @param mixed $offset * @return mixed|null * * @see http://php.net/manual/fr/class.arrayaccess.php diff --git a/src/Database/Barry/Traits/EventTrait.php b/src/Database/Barry/Traits/EventTrait.php index 36fdb977..cc932519 100644 --- a/src/Database/Barry/Traits/EventTrait.php +++ b/src/Database/Barry/Traits/EventTrait.php @@ -25,7 +25,7 @@ private function fireEvent(string $event): void /** * Get event name * - * @param string $event + * @param string $event * @return string */ private static function formatEventName(string $event): string diff --git a/src/Database/Collection.php b/src/Database/Collection.php index 087d6691..814033a4 100644 --- a/src/Database/Collection.php +++ b/src/Database/Collection.php @@ -64,9 +64,11 @@ public function toArray(): array */ public function dropAll(): void { - $this->each(function (Model $model) { - $model->delete(); - }); + $this->each( + function (Model $model) { + $model->delete(); + } + ); } /** diff --git a/src/Database/Connection/AbstractConnection.php b/src/Database/Connection/AbstractConnection.php index 71a53527..38dcbfed 100644 --- a/src/Database/Connection/AbstractConnection.php +++ b/src/Database/Connection/AbstractConnection.php @@ -77,7 +77,7 @@ public function getName(): string /** * Sets the data recovery mode. * - * @param int $fetch + * @param int $fetch * @return void */ public function setFetchMode(int $fetch): void @@ -144,7 +144,7 @@ public function getPdoDriver(): string * Executes PDOStatement::bindValue on an instance of * * @param PDOStatement $pdo_statement - * @param array $bindings + * @param array $bindings * * @return PDOStatement */ diff --git a/src/Database/Database.php b/src/Database/Database.php index 56c0e3cd..3a4e5c7d 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -10,9 +10,9 @@ use Bow\Database\Exception\DatabaseException; use Bow\Database\Connection\AbstractConnection; use Bow\Database\Exception\ConnectionException; -use Bow\Database\Connection\Adapter\MysqlAdapter; -use Bow\Database\Connection\Adapter\SqliteAdapter; -use Bow\Database\Connection\Adapter\PostgreSQLAdapter; +use Bow\Database\Connection\Adapters\MysqlAdapter; +use Bow\Database\Connection\Adapters\SqliteAdapter; +use Bow\Database\Connection\Adapters\PostgreSQLAdapter; class Database { @@ -65,7 +65,7 @@ public static function configure(array $config): Database /** * Connection, starts the connection on the DB * - * @param ?string $name + * @param ?string $name * @return ?Database * @throws ConnectionException */ @@ -157,8 +157,8 @@ public static function getConnectionAdapter(): ?AbstractConnection /** * Execute an UPDATE request * - * @param string $sql_statement - * @param array $data + * @param string $sql_statement + * @param array $data * @return int */ public static function update(string $sql_statement, array $data = []): int @@ -175,8 +175,8 @@ public static function update(string $sql_statement, array $data = []): int /** * Execute the request of type delete insert update * - * @param string $sql_statement - * @param array $data + * @param string $sql_statement + * @param array $data * @return int */ private static function executePrepareQuery(string $sql_statement, array $data = []): int @@ -198,8 +198,8 @@ private static function executePrepareQuery(string $sql_statement, array $data = /** * Execute a SELECT request * - * @param string $sql_statement - * @param array $data + * @param string $sql_statement + * @param array $data * @return mixed|null */ public static function select(string $sql_statement, array $data = []): mixed @@ -235,8 +235,8 @@ public static function select(string $sql_statement, array $data = []): mixed /** * Executes a select query and returns a single record * - * @param string $sql_statement - * @param array $data + * @param string $sql_statement + * @param array $data * @return mixed|null */ public static function selectOne(string $sql_statement, array $data = []): mixed @@ -267,8 +267,8 @@ public static function selectOne(string $sql_statement, array $data = []): mixed /** * Execute an insert query * - * @param string $sql_statement - * @param array $data + * @param string $sql_statement + * @param array $data * @return int */ public static function insert(string $sql_statement, array $data = []): int @@ -316,7 +316,7 @@ public static function insert(string $sql_statement, array $data = []): int /** * Executes a request of type DROP | CREATE TABLE | TRUNCATE | ALTER Builder * - * @param string $sql_statement + * @param string $sql_statement * @return bool */ public static function statement(string $sql_statement): bool @@ -324,15 +324,15 @@ public static function statement(string $sql_statement): bool static::verifyConnection(); return static::$adapter - ->getConnection() - ->exec($sql_statement) === 0; + ->getConnection() + ->exec($sql_statement) === 0; } /** * Execute a delete request * - * @param string $sql_statement - * @param array $data + * @param string $sql_statement + * @param array $data * @return int */ public static function delete(string $sql_statement, array $data = []): int @@ -352,7 +352,7 @@ public static function delete(string $sql_statement, array $data = []): int /** * Load the query builder factory on the table name * - * @param string $table + * @param string $table * @return QueryBuilder */ public static function table(string $table): QueryBuilder @@ -370,7 +370,7 @@ public static function table(string $table): QueryBuilder /** * Starting the start of a transaction wrapper on top of the callback * - * @param callable $callback + * @param callable $callback * @return mixed */ public static function transaction(callable $callback): mixed @@ -478,8 +478,8 @@ public static function setPdo(PDO $pdo): void /** * __call * - * @param string $method - * @param array $arguments + * @param string $method + * @param array $arguments * @return mixed * @throws DatabaseException|ErrorException */ diff --git a/src/Database/DatabaseConfiguration.php b/src/Database/DatabaseConfiguration.php index cbb9b6aa..5f64a8e0 100644 --- a/src/Database/DatabaseConfiguration.php +++ b/src/Database/DatabaseConfiguration.php @@ -14,9 +14,12 @@ class DatabaseConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('db', function () use ($config) { - return Database::configure($config['database'] ?? $config['db']); - }); + $this->container->bind( + 'db', + function () use ($config) { + return Database::configure($config['database'] ?? $config['db']); + } + ); } /** diff --git a/src/Database/Migration/Compose/MysqlCompose.php b/src/Database/Migration/Compose/MysqlCompose.php index 452b4ef3..8332a3ae 100644 --- a/src/Database/Migration/Compose/MysqlCompose.php +++ b/src/Database/Migration/Compose/MysqlCompose.php @@ -9,8 +9,8 @@ trait MysqlCompose /** * Compose sql statement for mysql * - * @param string $name - * @param array $description + * @param string $name + * @param array $description * @return string * @throws SQLGeneratorException */ @@ -119,7 +119,7 @@ private function composeAddMysqlColumn(string $name, array $description): string /** * Drop Column action with mysql * - * @param string $name + * @param string $name * @return void */ private function dropColumnForMysql(string $name): void diff --git a/src/Database/Migration/Compose/PgsqlCompose.php b/src/Database/Migration/Compose/PgsqlCompose.php index 7333c148..c0cc5b30 100644 --- a/src/Database/Migration/Compose/PgsqlCompose.php +++ b/src/Database/Migration/Compose/PgsqlCompose.php @@ -26,8 +26,8 @@ public function getCustomTypeQueries(): array /** * Compose sql statement for pgsql * - * @param string $name - * @param array $description + * @param string $name + * @param array $description * @return string * @throws SQLGeneratorException */ @@ -134,9 +134,9 @@ private function composeAddPgsqlColumn(string $name, array $description): string /** * Format the CHECK in ENUM * - * @param string $name - * @param string $type - * @param array $attribute + * @param string $name + * @param string $type + * @param array $attribute * @return string */ private function formatCheckOrEnum(string $name, string $type, array $attribute): string @@ -196,7 +196,7 @@ private function formatCheckOrEnum(string $name, string $type, array $attribute) /** * Drop Column action with pgsql * - * @param string $name + * @param string $name * @return void */ private function dropColumnForPgsql(string $name): void diff --git a/src/Database/Migration/Compose/SqliteCompose.php b/src/Database/Migration/Compose/SqliteCompose.php index 9e756c21..a2335331 100644 --- a/src/Database/Migration/Compose/SqliteCompose.php +++ b/src/Database/Migration/Compose/SqliteCompose.php @@ -10,8 +10,8 @@ trait SqliteCompose /** * Compose sql statement for sqlite * - * @param string $name - * @param array $description + * @param string $name + * @param array $description * @return string * @throws SQLGeneratorException */ @@ -91,8 +91,8 @@ private function composeAddSqliteColumn(string $name, array $description): strin /** * Rename column with sqlite * - * @param string $old_name - * @param string $new_name + * @param string $old_name + * @param string $new_name * @return void */ private function renameColumnOnSqlite(string $old_name, string $new_name): void @@ -119,19 +119,23 @@ private function renameColumnOnSqlite(string $old_name, string $new_name): void $pdo->exec("ALTER TABLE " . $this->table . " RENAME TO __temp_rename_sqlite_table;"); $pdo->exec('PRAGMA foreign_keys=off'); - $pdo->exec(sprintf( - 'CREATE TABLE %s AS SELECT * FROM %s;', - $this->table, - '__temp_rename_sqlite_table' - )); + $pdo->exec( + sprintf( + 'CREATE TABLE %s AS SELECT * FROM %s;', + $this->table, + '__temp_rename_sqlite_table' + ) + ); - $pdo->exec(sprintf( - "INSERT INTO %s(%s) SELECT %s FROM %s", - $this->table, - implode(', ', $selects), - implode(', ', $old_selects), - '__temp_rename_sqlite_table' - )); + $pdo->exec( + sprintf( + "INSERT INTO %s(%s) SELECT %s FROM %s", + $this->table, + implode(', ', $selects), + implode(', ', $old_selects), + '__temp_rename_sqlite_table' + ) + ); $pdo->exec("DROP TABLE __temp_rename_sqlite_table;"); $pdo->exec('COMMIT;'); @@ -165,12 +169,14 @@ private function dropColumnForSqlite(string|array $name): void $pdo->exec("PRAGMA foreign_keys=off;"); $pdo->exec('BEGIN TRANSACTION;'); - $pdo->exec(sprintf( - 'CREATE TABLE __temp_sqlite_%s_table AS SELECT %s FROM %s;', - $this->table, - implode(', ', $columns), - $this->table, - )); + $pdo->exec( + sprintf( + 'CREATE TABLE __temp_sqlite_%s_table AS SELECT %s FROM %s;', + $this->table, + implode(', ', $columns), + $this->table, + ) + ); $pdo->exec(sprintf('DROP TABLE %s;', $this->table)); $pdo->exec(sprintf('ALTER TABLE __temp_sqlite_%s_table RENAME TO %s;', $this->table, $this->table)); $pdo->exec('COMMIT;'); diff --git a/src/Database/Migration/Migration.php b/src/Database/Migration/Migration.php index dfb77777..e519f800 100644 --- a/src/Database/Migration/Migration.php +++ b/src/Database/Migration/Migration.php @@ -47,7 +47,7 @@ abstract public function rollback(): void; /** * Switch connection * - * @param string $name + * @param string $name * @return Migration * @throws ConnectionException */ @@ -73,7 +73,7 @@ public function getAdapterName(): string /** * Drop table action * - * @param string $table + * @param string $table * @return Migration * @throws MigrationException */ @@ -89,7 +89,7 @@ final public function drop(string $table): Migration /** * Get prefixed table name * - * @param string $table + * @param string $table * @return string */ final public function getTablePrefixed(string $table): string @@ -100,7 +100,7 @@ final public function getTablePrefixed(string $table): string /** * Execute direct sql query * - * @param string $sql + * @param string $sql * @return Migration * @throws MigrationException */ @@ -121,7 +121,7 @@ private function executeSqlQuery(string $sql): Migration /** * Drop table if he exists action * - * @param string $table + * @param string $table * @return Migration * @throws MigrationException */ @@ -141,8 +141,8 @@ final public function dropIfExists(string $table): Migration /** * Function of creation of a new table in the database. * - * @param string $table - * @param callable $cb + * @param string $table + * @param callable $cb * @return Migration * @throws MigrationException */ @@ -150,9 +150,12 @@ final public function create(string $table, callable $cb): Migration { $table = $this->getTablePrefixed($table); - call_user_func_array($cb, [ + call_user_func_array( + $cb, + [ $generator = new Table($table, $this->adapter->getName(), 'create') - ]); + ] + ); if ($this->adapter->getName() == 'mysql') { $engine = sprintf(' ENGINE=%s', strtoupper($generator->getEngine())); @@ -181,8 +184,8 @@ final public function create(string $table, callable $cb): Migration /** * Alter table action. * - * @param string $table - * @param callable $cb + * @param string $table + * @param callable $cb * @return Migration * @throws MigrationException */ @@ -190,9 +193,12 @@ final public function alter(string $table, callable $cb): Migration { $table = $this->getTablePrefixed($table); - call_user_func_array($cb, [ + call_user_func_array( + $cb, + [ $generator = new Table($table, $this->adapter->getName(), 'alter') - ]); + ] + ); if ($this->adapter->getName() === 'pgsql') { $sql = sprintf('ALTER TABLE %s %s;', $table, $generator->make()); @@ -206,7 +212,7 @@ final public function alter(string $table, callable $cb): Migration /** * Add SQL query * - * @param string $sql + * @param string $sql * @return Migration * @throws MigrationException */ @@ -218,8 +224,8 @@ final public function addSql(string $sql): Migration /** * Rename table * - * @param string $table - * @param string $to + * @param string $table + * @param string $to * @return Migration * @throws MigrationException */ @@ -233,8 +239,8 @@ final public function renameTable(string $table, string $to): Migration /** * Rename table if exists * - * @param string $table - * @param string $to + * @param string $table + * @param string $to * @return Migration * @throws MigrationException */ diff --git a/src/Database/Migration/Shortcut/ConstraintColumn.php b/src/Database/Migration/Shortcut/ConstraintColumn.php index 80d5058a..49901924 100644 --- a/src/Database/Migration/Shortcut/ConstraintColumn.php +++ b/src/Database/Migration/Shortcut/ConstraintColumn.php @@ -11,8 +11,8 @@ trait ConstraintColumn /** * Add Foreign KEY constraints * - * @param string $name - * @param array $attributes + * @param string $name + * @param array $attributes * @return Table */ public function addForeign(string $name, array $attributes = []): Table @@ -75,8 +75,8 @@ public function addForeign(string $name, array $attributes = []): Table /** * Drop constraints column; * - * @param string|array $name - * @param bool $as_raw + * @param string|array $name + * @param bool $as_raw * @return Table */ public function dropForeign(string|array $name, bool $as_raw = false): Table @@ -100,7 +100,7 @@ public function dropForeign(string|array $name, bool $as_raw = false): Table /** * Add table index; * - * @param string $name + * @param string $name * @return Table */ public function addIndex(string $name): Table @@ -123,7 +123,7 @@ public function addIndex(string $name): Table /** * Drop table index; * - * @param string $name + * @param string $name * @return Table */ public function dropIndex(string $name): Table @@ -156,7 +156,7 @@ public function dropPrimary(): Table /** * Add table unique; * - * @param string $name + * @param string $name * @return Table */ public function addUnique(string $name): Table @@ -179,7 +179,7 @@ public function addUnique(string $name): Table /** * Drop table unique; * - * @param string $name + * @param string $name * @return Table */ public function dropUnique(string $name): Table diff --git a/src/Database/Migration/Shortcut/DateColumn.php b/src/Database/Migration/Shortcut/DateColumn.php index 07fc97b1..e92689c4 100644 --- a/src/Database/Migration/Shortcut/DateColumn.php +++ b/src/Database/Migration/Shortcut/DateColumn.php @@ -12,8 +12,8 @@ trait DateColumn /** * Add datetime column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -29,8 +29,8 @@ public function addDatetime(string $column, array $attribute = []): Table /** * Add timestamp column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -42,8 +42,8 @@ public function addTimestamp(string $column, array $attribute = []): Table /** * Add date column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -55,8 +55,8 @@ public function addDate(string $column, array $attribute = []): Table /** * Add time column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -68,8 +68,8 @@ public function addTime(string $column, array $attribute = []): Table /** * Add year column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -102,8 +102,8 @@ public function addTimestamps(): Table /** * Change datetime column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -119,8 +119,8 @@ public function changeDatetime(string $column, array $attribute = []): Table /** * Change date column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -132,8 +132,8 @@ public function changeDate(string $column, array $attribute = []): Table /** * Change time column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -145,8 +145,8 @@ public function changeTime(string $column, array $attribute = []): Table /** * Change year column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -158,8 +158,8 @@ public function changeYear(string $column, array $attribute = []): Table /** * Change timestamp column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ diff --git a/src/Database/Migration/Shortcut/MixedColumn.php b/src/Database/Migration/Shortcut/MixedColumn.php index b9046c6b..c1b9df03 100644 --- a/src/Database/Migration/Shortcut/MixedColumn.php +++ b/src/Database/Migration/Shortcut/MixedColumn.php @@ -12,8 +12,8 @@ trait MixedColumn /** * Add BOOLEAN column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -25,8 +25,8 @@ public function addBoolean(string $column, array $attribute = []): Table /** * Add UUID column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -48,8 +48,8 @@ public function addUuidPrimary(string $column, array $attribute = []): Table /** * Add UUID column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -80,8 +80,8 @@ public function addUuid(string $column, array $attribute = []): Table /** * Add BINARY column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -93,8 +93,8 @@ public function addBinary(string $column, array $attribute = []): Table /** * Add TINYBLOB column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -106,8 +106,8 @@ public function addTinyBlob(string $column, array $attribute = []): Table /** * Add LONGBLOB column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -119,8 +119,8 @@ public function addLongBlob(string $column, array $attribute = []): Table /** * Add MEDIUMBLOB column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -132,8 +132,8 @@ public function addMediumBlob(string $column, array $attribute = []): Table /** * Add ip column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -145,8 +145,8 @@ public function addIpAddress(string $column, array $attribute = []): Table /** * Add mac column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -158,8 +158,8 @@ public function addMacAddress(string $column, array $attribute = []): Table /** * Add enum column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -183,8 +183,8 @@ public function addEnum(string $column, array $attribute = []): Table /** * Add check column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -220,8 +220,8 @@ private function verifyCheckAttribute($attribute): void /** * Change boolean column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -233,8 +233,8 @@ public function changeBoolean(string $column, array $attribute = []): Table /** * Change UUID column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -259,8 +259,8 @@ public function changeUuid(string $column, array $attribute = []): Table /** * Change BLOB column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -272,8 +272,8 @@ public function changeBinary(string $column, array $attribute = []): Table /** * Change TINYBLOB column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -285,8 +285,8 @@ public function changeLongBlob(string $column, array $attribute = []): Table /** * Change MEDIUMBLOB column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -298,8 +298,8 @@ public function changeMediumBlob(string $column, array $attribute = []): Table /** * Change TINYBLOB column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -311,8 +311,8 @@ public function changeTinyBlob(string $column, array $attribute = []): Table /** * Change ip column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -324,8 +324,8 @@ public function changeIpAddress(string $column, array $attribute = []): Table /** * Change mac column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -337,8 +337,8 @@ public function changeMacAddress(string $column, array $attribute = []): Table /** * Change enum column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -362,8 +362,8 @@ public function changeEnum(string $column, array $attribute = []): Table /** * Change check column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ diff --git a/src/Database/Migration/Shortcut/NumberColumn.php b/src/Database/Migration/Shortcut/NumberColumn.php index f96aeabe..20a01db6 100644 --- a/src/Database/Migration/Shortcut/NumberColumn.php +++ b/src/Database/Migration/Shortcut/NumberColumn.php @@ -12,8 +12,8 @@ trait NumberColumn /** * Add float column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -25,8 +25,8 @@ public function addFloat(string $column, array $attribute = []): Table /** * Add double column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -38,7 +38,7 @@ public function addDouble(string $column, array $attribute = []): Table /** * Add double primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -50,7 +50,7 @@ public function addDoublePrimary(string $column): Table /** * Add float primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -62,7 +62,7 @@ public function addFloatPrimary(string $column): Table /** * Add increment primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -74,8 +74,8 @@ public function addIncrement(string $column): Table /** * Add integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -87,7 +87,7 @@ public function addInteger(string $column, array $attribute = []): Table /** * Add integer primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -99,7 +99,7 @@ public function addIntegerPrimary(string $column): Table /** * Add big increment primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -111,8 +111,8 @@ public function addBigIncrement(string $column): Table /** * Add tiny integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -124,8 +124,8 @@ public function addTinyInteger(string $column, array $attribute = []): Table /** * Add Big integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -137,8 +137,8 @@ public function addBigInteger(string $column, array $attribute = []): Table /** * Add Medium integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -150,7 +150,7 @@ public function addMediumInteger(string $column, array $attribute = []): Table /** * Add Medium integer column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -162,8 +162,8 @@ public function addMediumIncrement(string $column): Table /** * Add small integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -175,7 +175,7 @@ public function addSmallInteger(string $column, array $attribute = []): Table /** * Add Smallint integer column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -187,8 +187,8 @@ public function addSmallIntegerIncrement(string $column): Table /** * Change float column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -200,8 +200,8 @@ public function changeFloat(string $column, array $attribute = []): Table /** * Change double column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -213,7 +213,7 @@ public function changeDouble(string $column, array $attribute = []): Table /** * Change double primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -225,7 +225,7 @@ public function changeDoublePrimary(string $column): Table /** * Change float primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -237,7 +237,7 @@ public function changeFloatPrimary(string $column): Table /** * Change increment primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -249,8 +249,8 @@ public function changeIncrement(string $column): Table /** * Change integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -262,7 +262,7 @@ public function changeInteger(string $column, array $attribute = []): Table /** * Change integer primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -274,7 +274,7 @@ public function changeIntegerPrimary(string $column): Table /** * Change big increment primary column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -286,8 +286,8 @@ public function changeBigIncrement(string $column): Table /** * Change tiny integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -299,8 +299,8 @@ public function changeTinyInteger(string $column, array $attribute = []): Table /** * Change Big integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -312,8 +312,8 @@ public function changeBigInteger(string $column, array $attribute = []): Table /** * Change Medium integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -325,7 +325,7 @@ public function changeMediumInteger(string $column, array $attribute = []): Tabl /** * Change Medium integer column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ @@ -337,8 +337,8 @@ public function changeMediumIncrement(string $column): Table /** * Change Small integer column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -350,7 +350,7 @@ public function changeSmallInteger(string $column, array $attribute = []): Table /** * Change Small integer column * - * @param string $column + * @param string $column * @return Table * @throws SQLGeneratorException */ diff --git a/src/Database/Migration/Shortcut/TextColumn.php b/src/Database/Migration/Shortcut/TextColumn.php index 64c74c4f..eb4c12e1 100644 --- a/src/Database/Migration/Shortcut/TextColumn.php +++ b/src/Database/Migration/Shortcut/TextColumn.php @@ -12,8 +12,8 @@ trait TextColumn /** * Add string column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -25,8 +25,8 @@ public function addString(string $column, array $attribute = []): Table /** * Add json column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -38,8 +38,8 @@ public function addJson(string $column, array $attribute = []): Table /** * Add character column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -51,8 +51,8 @@ public function addChar(string $column, array $attribute = []): Table /** * Add longtext column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -64,8 +64,8 @@ public function addLongtext(string $column, array $attribute = []): Table /** * Add text column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -77,8 +77,8 @@ public function addText(string $column, array $attribute = []): Table /** * Add blob column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -90,8 +90,8 @@ public function addBlob(string $column, array $attribute = []): Table /** * Change string column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -103,8 +103,8 @@ public function changeString(string $column, array $attribute = []): Table /** * Change json column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -116,8 +116,8 @@ public function changeJson(string $column, array $attribute = []): Table /** * Change character column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -129,8 +129,8 @@ public function changeChar(string $column, array $attribute = []): Table /** * Change longtext column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -142,8 +142,8 @@ public function changeLongtext(string $column, array $attribute = []): Table /** * Change text column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -155,8 +155,8 @@ public function changeText(string $column, array $attribute = []): Table /** * Change blob column * - * @param string $column - * @param array $attribute + * @param string $column + * @param array $attribute * @return Table * @throws SQLGeneratorException */ diff --git a/src/Database/Migration/Table.php b/src/Database/Migration/Table.php index 905af102..d952dd77 100644 --- a/src/Database/Migration/Table.php +++ b/src/Database/Migration/Table.php @@ -101,7 +101,7 @@ public function make(): string /** * Add a raw column definition * - * @param string $definition + * @param string $definition * @return Table */ public function addRaw(string $definition): Table @@ -114,9 +114,9 @@ public function addRaw(string $definition): Table /** * Add new column in the table * - * @param string $name - * @param string $type - * @param array $attribute + * @param string $name + * @param string $type + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -139,8 +139,8 @@ public function addColumn(string $name, string $type, array $attribute = []): Ta /** * Compose sql instruction * - * @param string $name - * @param array $description + * @param string $name + * @param array $description * @return string * @throws SQLGeneratorException */ @@ -162,9 +162,9 @@ private function composeAddColumn(string $name, array $description): string /** * Change a column in the table * - * @param string $name - * @param string $type - * @param array $attribute + * @param string $name + * @param string $type + * @param array $attribute * @return Table * @throws SQLGeneratorException */ @@ -183,8 +183,8 @@ public function changeColumn(string $name, string $type, array $attribute = []): /** * Rename a column in the table * - * @param string $name - * @param string $new + * @param string $name + * @param string $new * @return Table */ public function renameColumn(string $name, string $new): Table @@ -207,7 +207,7 @@ public function renameColumn(string $name, string $new): Table /** * Drop table column * - * @param string $name + * @param string $name * @return Table */ public function dropColumn(string $name): Table @@ -226,7 +226,7 @@ public function dropColumn(string $name): Table /** * Set the engine * - * @param string $engine + * @param string $engine * @return void */ public function withEngine(string $engine): void @@ -247,7 +247,7 @@ public function getEngine(): string /** * Set the collation * - * @param string $collation + * @param string $collation * @return void */ public function withCollation(string $collation): void @@ -268,7 +268,7 @@ public function getCollation(): string /** * Set the charset * - * @param string $charset + * @param string $charset * @return void */ public function withCharset(string $charset): void @@ -299,7 +299,7 @@ public function getTable(): string /** * Set the define table name * - * @param string $table + * @param string $table * @return string */ public function setTable(string $table): string @@ -312,7 +312,7 @@ public function setTable(string $table): string /** * Set the scope * - * @param string $scope + * @param string $scope * @return Table */ public function setScope(string $scope): Table @@ -325,7 +325,7 @@ public function setScope(string $scope): Table /** * Set the adapter * - * @param string $adapter + * @param string $adapter * @return Table */ public function setAdapter(string $adapter): Table @@ -338,7 +338,7 @@ public function setAdapter(string $adapter): Table /** * Normalize the data type * - * @param string $type + * @param string $type * @return string */ public function normalizeOfType(string $type): string diff --git a/src/Database/Notification/DatabaseNotification.php b/src/Database/Notification/DatabaseNotification.php new file mode 100644 index 00000000..5c88e204 --- /dev/null +++ b/src/Database/Notification/DatabaseNotification.php @@ -0,0 +1,35 @@ + 'array', + ]; + + public function __construct(array $attributes = []) + { + parent::__construct($attributes); + + $this->table = config('notification.table') ?: 'notifications'; + } + + /** + * Mark notification as read + * + * @return bool|int + */ + public function markAsRead(): bool|int + { + return $this->update(['read_at' => app_now()]); + } +} diff --git a/src/Database/Notification/WithNotification.php b/src/Database/Notification/WithNotification.php new file mode 100644 index 00000000..c583c98a --- /dev/null +++ b/src/Database/Notification/WithNotification.php @@ -0,0 +1,35 @@ +where('concern_id', $this->getKeyValue()) + ->where('concern_type', get_class($this)); + } + + /** + * @throws ConnectionException|Exception\QueryBuilderException + */ + public function markAsRead(string $notification_id) + { + return $this->notifications()->where('id', $notification_id)->update(['read_at' => app_now()]); + } + + /** + * @throws ConnectionException|Exception\QueryBuilderException + */ + public function markAllAsRead() + { + return $this->notifications()->update(['read_at' => app_now()]); + } +} diff --git a/src/Database/Pagination.php b/src/Database/Pagination.php index b01c6341..99f2c8f5 100644 --- a/src/Database/Pagination.php +++ b/src/Database/Pagination.php @@ -7,6 +7,16 @@ class Pagination { + /** + * Pagination constructor. + * + * @param int $next The next page number. + * @param int $previous The previous page number. + * @param int $total The total number of items. + * @param int $perPage The number of items per page. + * @param int $current The current page number. + * @param SupportCollection|DatabaseCollection $data The collection of items for the current page. + */ public function __construct( private readonly int $next, private readonly int $previous, @@ -17,41 +27,81 @@ public function __construct( ) { } + /** + * Get the next page number. + * + * @return int + */ public function next(): int { return $this->next; } + /** + * Check if there is a next page. + * + * @return bool + */ public function hasNext(): bool { return $this->next != 0; } + /** + * Get the number of items per page. + * + * @return int + */ public function perPage(): int { return $this->perPage; } + /** + * Get the previous page number. + * + * @return int + */ public function previous(): int { return $this->previous; } + /** + * Check if there is a previous page. + * + * @return bool + */ public function hasPrevious(): bool { return $this->previous != 0; } + /** + * Get the current page number. + * + * @return int + */ public function current(): int { return $this->current; } + /** + * Get the collection of items for the current page. + * + * @return SupportCollection|DatabaseCollection + */ public function items(): SupportCollection|DatabaseCollection { return $this->data; } + /** + * Get the total number of items. + * + * @return int + */ public function total(): int { return $this->total; diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index dca8b703..25b701d1 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -116,7 +116,7 @@ class QueryBuilder implements JsonSerializable /** * QueryBuilder Constructor * - * @param string $table + * @param string $table * @param AbstractConnection|PDO $connection */ public function __construct(string $table, AbstractConnection|PDO $connection) @@ -155,7 +155,7 @@ public function getPdo(): PDO /** * Create the table as * - * @param string $as + * @param string $as * @return QueryBuilder */ public function as(string $as): QueryBuilder @@ -170,7 +170,7 @@ public function as(string $as): QueryBuilder * * WHERE column1 $comparator $value|column * - * @param string $where + * @param string $where * @return QueryBuilder */ public function whereRaw(string $where): QueryBuilder @@ -189,7 +189,7 @@ public function whereRaw(string $where): QueryBuilder * * WHERE column1 $comparator $value|column * - * @param string $where + * @param string $where * @return QueryBuilder */ public function orWhereRaw(string $where): QueryBuilder @@ -208,9 +208,9 @@ public function orWhereRaw(string $where): QueryBuilder * * [where column = value or column = value] * - * @param string $column - * @param mixed $comparator - * @param mixed $value + * @param string $column + * @param mixed $comparator + * @param mixed $value * @return QueryBuilder * @throws QueryBuilderException */ @@ -231,10 +231,10 @@ public function orWhere(string $column, mixed $comparator = '=', mixed $value = * * WHERE column1 $comparator $value|column * - * @param string $column - * @param mixed $comparator - * @param mixed $value - * @param string $boolean + * @param string $column + * @param mixed $comparator + * @param mixed $value + * @param string $boolean * @return QueryBuilder * @throws QueryBuilderException */ @@ -282,7 +282,7 @@ public function where( /** * Utility, allows to validate an operator * - * @param mixed $comparator + * @param mixed $comparator * @return bool */ private static function isComparisonOperator(mixed $comparator): bool @@ -291,12 +291,16 @@ private static function isComparisonOperator(mixed $comparator): bool return false; } - return in_array(Str::upper($comparator), [ + return in_array( + Str::upper($comparator), + [ '=', '>', '<', '>=', '=<', '<>', '!=', 'LIKE', 'NOT', 'IS NOT', "IN", "NOT IN", 'ILIKE', '&', '|', '<<', '>>', 'NOT LIKE', '&&', '@>', '<@', '?', '?|', '?&', '||', '-', '@?', '@@', '#-', 'IS DISTINCT FROM', 'IS NOT DISTINCT FROM', - ], true); + ], + true + ); } /** @@ -378,7 +382,7 @@ public function getTable(): string /** * Change the table's name * - * @param string $table + * @param string $table * @return QueryBuilder */ public function setTable(string $table): QueryBuilder @@ -393,8 +397,8 @@ public function setTable(string $table): QueryBuilder * * WHERE column IS NULL * - * @param string $column - * @param string $boolean + * @param string $column + * @param string $boolean * @return QueryBuilder */ public function whereNull(string $column, string $boolean = 'and'): QueryBuilder @@ -413,8 +417,8 @@ public function whereNull(string $column, string $boolean = 'and'): QueryBuilder * * WHERE column NOT NULL * - * @param $column - * @param string $boolean + * @param $column + * @param string $boolean * @return QueryBuilder */ public function whereNotNull($column, $boolean = 'and'): QueryBuilder @@ -431,8 +435,8 @@ public function whereNotNull($column, $boolean = 'and'): QueryBuilder /** * WHERE column NOT BETWEEN '' AND '' * - * @param string $column - * @param array $range + * @param string $column + * @param array $range * @return QueryBuilder */ public function whereNotBetween(string $column, array $range): QueryBuilder @@ -447,9 +451,9 @@ public function whereNotBetween(string $column, array $range): QueryBuilder * * WHERE column BETWEEN '' AND '' * - * @param string $column - * @param array $range - * @param string $boolean + * @param string $column + * @param array $range + * @param string $boolean * @return QueryBuilder * @throws QueryBuilderException */ @@ -478,8 +482,8 @@ public function whereBetween(string $column, array $range, string $boolean = 'an /** * Where clause with <> comparison * - * @param string $column - * @param array $range + * @param string $column + * @param array $range * @return QueryBuilder * @throws QueryBuilderException */ @@ -493,9 +497,9 @@ public function whereNotIn(string $column, array $range) /** * Where clause with <> comparison * - * @param string $column - * @param array $range - * @param string $boolean + * @param string $column + * @param array $range + * @param string $boolean * @return QueryBuilder * @throws QueryBuilderException */ @@ -535,10 +539,10 @@ public function whereIn(string $column, array $range, string $boolean = 'and'): /** * Join clause * - * @param string $table - * @param string $first - * @param mixed $comparator - * @param string $second + * @param string $table + * @param string $first + * @param mixed $comparator + * @param string $second * @return QueryBuilder */ public function join( @@ -580,7 +584,7 @@ public function getPrefix(): string /** * Modify the prefix * - * @param string $prefix + * @param string $prefix * @return QueryBuilder */ public function setPrefix(string $prefix): QueryBuilder @@ -593,10 +597,10 @@ public function setPrefix(string $prefix): QueryBuilder /** * Left Join clause * - * @param string $table - * @param string $first - * @param mixed $comparator - * @param string $second + * @param string $table + * @param string $first + * @param mixed $comparator + * @param string $second * @return QueryBuilder * @throws QueryBuilderException */ @@ -629,10 +633,10 @@ public function leftJoin( /** * Right Join clause * - * @param string $table - * @param string $first - * @param mixed $comparator - * @param string $second + * @param string $table + * @param string $first + * @param mixed $comparator + * @param string $second * @return QueryBuilder * @throws QueryBuilderException */ @@ -665,9 +669,9 @@ public function rightJoin( * On, if chained with itself must add an << and >> before, otherwise * if chained with "orOn" who add a "before" * - * @param string $first - * @param mixed $comparator - * @param string $second + * @param string $first + * @param mixed $comparator + * @param string $second * @return QueryBuilder * @throws QueryBuilderException */ @@ -695,9 +699,9 @@ public function andOn(string $first, $comparator = '=', $second = null): QueryBu * Clause On, followed by a combination by a comparator <> * The user has to do an "on()" before using the "orOn" * - * @param string $first - * @param mixed $comparator - * @param string $second + * @param string $first + * @param mixed $comparator + * @param string $second * @return QueryBuilder * @throws QueryBuilderException */ @@ -724,8 +728,8 @@ public function orOn(string $first, $comparator = '=', $second = null): QueryBui /** * Clause Group By * - * @param string $column - * @return QueryBuilder + * @param string $column + * @return QueryBuilder * @deprecated */ public function group($column) @@ -736,7 +740,7 @@ public function group($column) /** * Clause Group By * - * @param string $column + * @param string $column * @return QueryBuilder */ public function groupBy(string $column): QueryBuilder @@ -751,10 +755,10 @@ public function groupBy(string $column): QueryBuilder /** * clause having, is used with a groupBy * - * @param string $column - * @param mixed $comparator - * @param mixed $value - * @param string $boolean + * @param string $column + * @param mixed $comparator + * @param mixed $value + * @param string $boolean * @return QueryBuilder */ public function having( @@ -781,8 +785,8 @@ public function having( /** * Clause Order By * - * @param string $column - * @param string $type + * @param string $column + * @param string $type * @return QueryBuilder */ public function orderBy(string $column, string $type = 'asc'): QueryBuilder @@ -803,7 +807,7 @@ public function orderBy(string $column, string $type = 'asc'): QueryBuilder /** * Max * - * @param string $column + * @param string $column * @return int|float */ public function max(string $column): int|float @@ -814,8 +818,8 @@ public function max(string $column): int|float /** * Internally launches queries that use aggregates. * - * @param $aggregate - * @param string $column + * @param $aggregate + * @param string $column * @return mixed */ private function aggregate($aggregate, $column): mixed @@ -864,7 +868,7 @@ private function aggregate($aggregate, $column): mixed * Executes PDOStatement::bindValue on an instance of * * @param PDOStatement $pdo_statement - * @param array $bindings + * @param array $bindings * * @return void */ @@ -915,7 +919,7 @@ private function bind(PDOStatement $pdo_statement, array $bindings = []): void /** * Min * - * @param string $column + * @param string $column * @return int|float */ public function min($column): int|float @@ -926,7 +930,7 @@ public function min($column): int|float /** * Avg * - * @param string $column + * @param string $column * @return int|float */ public function avg($column): int|float @@ -937,7 +941,7 @@ public function avg($column): int|float /** * Sum * - * @param string $column + * @param string $column * @return int|float */ public function sum($column): int|float @@ -969,7 +973,7 @@ public function last(): ?object /** * Count * - * @param string $column + * @param string $column * @return int */ public function count($column = '*') @@ -994,7 +998,7 @@ public function first(): ?object /** * Take = Limit * - * @param int $limit + * @param int $limit * @return QueryBuilder */ public function take(int $limit): QueryBuilder @@ -1018,7 +1022,7 @@ public function take(int $limit): QueryBuilder * Get make, only on the select request * If the first selection mode is not active * - * @param array $columns + * @param array $columns * @return array|object|null * @throws */ @@ -1063,7 +1067,7 @@ public function get(array $columns = []): array|object|null * * SELECT $column | SELECT column1, column2, ... * - * @param array $select + * @param array $select * @return QueryBuilder */ public function select(array $select = ['*']) @@ -1103,7 +1107,7 @@ public function select(array $select = ['*']) /** * Jump = Offset * - * @param int $offset + * @param int $offset * @return QueryBuilder */ public function jump(int $offset = 0): QueryBuilder @@ -1123,7 +1127,7 @@ public function jump(int $offset = 0): QueryBuilder /** * Update action * - * @param array $data + * @param array $data * @return int */ public function update(array $data = []): int @@ -1156,9 +1160,9 @@ public function update(array $data = []): int /** * Remove simplified stream from delete. * - * @param string $column - * @param mixed $comparator - * @param string $value + * @param string $column + * @param mixed $comparator + * @param string $value * @return int * @throws QueryBuilderException */ @@ -1170,7 +1174,7 @@ public function remove(string $column, mixed $comparator = '=', $value = null): } /** - * Delete Compass + * Delete row on table * * @return int */ @@ -1198,10 +1202,10 @@ public function delete(): int } /** - * Compass increment, add 1 by default to the specified field + * Increment column * * @param string $column - * @param int $step + * @param int $step * * @return int */ @@ -1213,9 +1217,9 @@ public function increment(string $column, int $step = 1): int /** * Method to customize the increment and decrement methods * - * @param string $column - * @param int $step - * @param string $direction + * @param string $column + * @param int $step + * @param string $direction * @return int */ private function incrementAction(string $column, int $step = 1, string $direction = '+') @@ -1238,10 +1242,10 @@ private function incrementAction(string $column, int $step = 1, string $directio } /** - * Decrement action, subtracts 1 by default from the specified field + * Decrement column * - * @param string $column - * @param int $step + * @param string $column + * @param int $step * @return int */ public function decrement(string $column, int $step = 1): int @@ -1252,8 +1256,11 @@ public function decrement(string $column, int $step = 1): int /** * Allows a query with the DISTINCT clause * - * @param string $column - * @return QueryBuilder + * This method modifies the SELECT statement to include the DISTINCT keyword, + * ensuring that the results returned are unique for the specified column. + * + * @param string $column The column to apply the DISTINCT clause on. + * @return QueryBuilder Returns the current QueryBuilder instance. */ public function distinct(string $column) { @@ -1267,7 +1274,11 @@ public function distinct(string $column) } /** - * Truncate Compass, empty the table + * Truncate table + * + * This method will remove all rows from the table without logging the individual row deletions. + * It is faster than the DELETE statement because it does not generate individual row delete actions. + * However, it cannot be rolled back if the database is not in a transaction. * * @return bool */ @@ -1288,7 +1299,7 @@ public function truncate(): bool /** * InsertAndGetLastId action launches the insert and lastInsertId actions * - * @param array $values + * @param array $values * @return string|int|bool */ public function insertAndGetLastId(array $values): string|int|bool @@ -1301,11 +1312,11 @@ public function insertAndGetLastId(array $values): string|int|bool } /** - * Insert Compass + * Insert * * The data to be inserted into the database. * - * @param array $values + * @param array $values * @return int */ public function insert(array $values): int @@ -1334,9 +1345,9 @@ public function insert(array $values): int /** * Insert On, insert one row in the table * - * @param array $value + * @param array $value * @return int - * @see insert + * @see insert */ private function insertOne(array $value): int { @@ -1357,7 +1368,7 @@ private function insertOne(array $value): int } /** - * Drop Compass, remove the table + * Drop, remove the table * * @return mixed */ @@ -1369,9 +1380,9 @@ public function drop(): bool /** * Paginate, make pagination system * - * @param int $number_of_page - * @param int $current - * @param int $chunk + * @param int $number_of_page + * @param int $current + * @param int $chunk * @return Pagination */ public function paginate(int $number_of_page, int $current = 0, ?int $chunk = null): Pagination @@ -1426,8 +1437,8 @@ public function paginate(int $number_of_page, int $current = 0, ?int $chunk = nu /** * Check if a value already exists in the DB * - * @param string $column - * @param mixed $value + * @param string $column + * @param mixed $value * @return bool * @throws QueryBuilderException */ @@ -1443,7 +1454,7 @@ public function exists(?string $column = null, mixed $value = null): bool /** * Turn back the id of the last insertion * - * @param string $name [optional] + * @param string $name [optional] * @return string */ public function getLastInsertId(?string $name = null) @@ -1454,7 +1465,7 @@ public function getLastInsertId(?string $name = null) /** * JsonSerialize implementation * - * @see httsp://php.net/manual/en/jsonserializable.jsonserialize.php + * @see httsp://php.net/manual/en/jsonserializable.jsonserialize.php * @return string */ public function jsonSerialize(): mixed @@ -1465,7 +1476,7 @@ public function jsonSerialize(): mixed /** * Define the data to associate * - * @param array $data_binding + * @param array $data_binding * @return void */ public function setWhereDataBinding(array $data_binding): void @@ -1486,7 +1497,7 @@ public function __toString(): string /** * Transformation automatically the result to JSON * - * @param int $option + * @param int $option * @return string */ public function toJson(int $option = 0): string diff --git a/src/Database/Redis.php b/src/Database/Redis.php index ea51a5ab..0b312768 100644 --- a/src/Database/Redis.php +++ b/src/Database/Redis.php @@ -28,7 +28,7 @@ class Redis /** * RedisAdapter constructor. * - * @param array $config + * @param array $config * @return mixed */ public function __construct(array $config) @@ -88,9 +88,9 @@ public static function ping(?string $message = null): void /** * Set value on Redis * - * @param string $key - * @param mixed $data - * @param integer|null $time + * @param string $key + * @param mixed $data + * @param integer|null $time * @return boolean */ public static function set(string $key, mixed $data, ?int $time = null): bool @@ -133,8 +133,8 @@ public static function getInstance(): Redis /** * Get the value from Redis * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed */ public static function get(string $key, mixed $default = null): mixed @@ -155,7 +155,7 @@ public static function get(string $key, mixed $default = null): mixed /** * Get the php-redis client * - * @see https://github.com/phpredis/phpredis + * @see https://github.com/phpredis/phpredis * @return RedisClient */ public static function getClient(): RedisClient diff --git a/src/Event/Contracts/EventListener.php b/src/Event/Contracts/EventListener.php index d46cff90..b65605b9 100644 --- a/src/Event/Contracts/EventListener.php +++ b/src/Event/Contracts/EventListener.php @@ -9,7 +9,7 @@ interface EventListener /** * Process the event * - * @param AppEvent $event + * @param AppEvent $event * @return mixed */ public function process(AppEvent $event): void; diff --git a/src/Event/Dispatchable.php b/src/Event/Dispatchable.php index f0041708..d78166c5 100644 --- a/src/Event/Dispatchable.php +++ b/src/Event/Dispatchable.php @@ -17,8 +17,8 @@ public static function dispatch(): mixed /** * Dispatch the event with the given arguments if the given truth test passes. * - * @param bool $boolean - * @param mixed ...$arguments + * @param bool $boolean + * @param mixed ...$arguments * @return void */ public static function dispatchIf(bool $boolean, ...$arguments): void @@ -31,8 +31,8 @@ public static function dispatchIf(bool $boolean, ...$arguments): void /** * Dispatch the event with the given arguments unless the given truth test passes. * - * @param bool $boolean - * @param mixed ...$arguments + * @param bool $boolean + * @param mixed ...$arguments * @return void */ public static function dispatchUnless(bool $boolean, ...$arguments): void diff --git a/src/Event/Event.php b/src/Event/Event.php index bb724b3b..50f672ef 100644 --- a/src/Event/Event.php +++ b/src/Event/Event.php @@ -41,9 +41,9 @@ public static function getInstance(): Event /** * addEventListener * - * @param string $event + * @param string $event * @param callable|string $fn - * @param int $priority + * @param int $priority */ public static function on(string $event, callable|string $fn, int $priority = 0): void { @@ -53,15 +53,18 @@ public static function on(string $event, callable|string $fn, int $priority = 0) static::$events[$event][] = new Listener($fn, $priority); - uasort(static::$events[$event], function (Listener $first_listener, Listener $second_listener) { - return $first_listener->getPriority() < $second_listener->getPriority(); - }); + uasort( + static::$events[$event], + function (Listener $first_listener, Listener $second_listener) { + return $first_listener->getPriority() < $second_listener->getPriority(); + } + ); } /** * Check whether an event is already recorded at least once. * - * @param string $event + * @param string $event * @return bool */ public static function bound(string $event): bool @@ -74,9 +77,9 @@ public static function bound(string $event): bool /** * Associate a single listener to an event * - * @param string $event + * @param string $event * @param callable|array|string $fn - * @param int $priority + * @param int $priority */ public static function once(string $event, callable|array|string $fn, int $priority = 0): void { @@ -86,7 +89,7 @@ public static function once(string $event, callable|array|string $fn, int $prior /** * Dispatch event * - * @param string|AppEvent $event + * @param string|AppEvent $event * @return bool|null * @throws EventException */ @@ -137,8 +140,8 @@ public static function off(string $event): void /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed * @throws ErrorException */ diff --git a/src/Event/EventProducer.php b/src/Event/EventProducer.php index 44c534c8..583ce6f8 100644 --- a/src/Event/EventProducer.php +++ b/src/Event/EventProducer.php @@ -12,7 +12,7 @@ class EventProducer extends ProducerService * EventProducer constructor * * @param EventListener|EventShouldQueue $event - * @param mixed $payload + * @param mixed $payload */ public function __construct( private readonly mixed $event, diff --git a/src/Event/Listener.php b/src/Event/Listener.php index ecb3a5eb..f6eff84d 100644 --- a/src/Event/Listener.php +++ b/src/Event/Listener.php @@ -27,7 +27,7 @@ class Listener * Listener constructor. * * @param callable|string $callable - * @param int $priority + * @param int $priority */ public function __construct(callable|string $callable, int $priority) { @@ -39,7 +39,7 @@ public function __construct(callable|string $callable, int $priority) /** * Launch the listener function * - * @param array $data + * @param array $data * @return mixed */ public function call(array $data = []): mixed diff --git a/src/Http/Client/HttpClient.php b/src/Http/Client/HttpClient.php index d4d17380..dd9bc839 100644 --- a/src/Http/Client/HttpClient.php +++ b/src/Http/Client/HttpClient.php @@ -64,7 +64,7 @@ public function __construct(?string $base_url = null) /** * Set the base url * - * @param string $url + * @param string $url * @return void */ public function setBaseUrl(string $url): void @@ -75,8 +75,8 @@ public function setBaseUrl(string $url): void /** * Make get requester * - * @param string $url - * @param array $data + * @param string $url + * @param array $data * @return Response * @throws Exception */ @@ -99,7 +99,7 @@ public function get(string $url, array $data = []): Response /** * Reset always connection * - * @param string $url + * @param string $url * @return void */ private function init(string $url): void @@ -163,8 +163,8 @@ private function close(): void /** * Make post requester * - * @param string $url - * @param array $data + * @param string $url + * @param array $data * @return Response * @throws Exception */ @@ -195,7 +195,7 @@ public function post(string $url, array $data = []): Response /** * Add fields * - * @param array $data + * @param array $data * @return void */ private function addFields(array $data): void @@ -216,8 +216,8 @@ private function addFields(array $data): void /** * Make put requester * - * @param string $url - * @param array $data + * @param string $url + * @param array $data * @return Response * @throws Exception */ @@ -237,8 +237,8 @@ public function put(string $url, array $data = []): Response /** * Make put requester * - * @param string $url - * @param array $data + * @param string $url + * @param array $data * @return Response * @throws Exception */ @@ -258,7 +258,7 @@ public function delete(string $url, array $data = []): Response /** * Attach new file * - * @param string|array $attach + * @param string|array $attach * @return HttpClient */ public function addAttach(string|array $attach): HttpClient @@ -271,7 +271,7 @@ public function addAttach(string|array $attach): HttpClient /** * Set the user agent * - * @param string $user_agent + * @param string $user_agent * @return HttpClient */ public function setUserAgent(string $user_agent): HttpClient @@ -298,7 +298,7 @@ public function acceptJson(): HttpClient /** * Add additional header * - * @param array $headers + * @param array $headers * @return HttpClient */ public function addHeaders(array $headers): HttpClient diff --git a/src/Http/Client/Response.php b/src/Http/Client/Response.php index 1beeb641..48430686 100644 --- a/src/Http/Client/Response.php +++ b/src/Http/Client/Response.php @@ -37,7 +37,7 @@ class Response * Parser constructor. * * @param CurlHandle $ch - * @param ?string $content + * @param ?string $content */ public function __construct(CurlHandle &$ch, ?string $content = null) { @@ -60,7 +60,7 @@ public function toArray(): array /** * Get response content as json * - * @param bool|null $associative + * @param bool|null $associative * @return object|array */ public function toJson(?bool $associative = null): object|array diff --git a/src/Http/Exception/HttpException.php b/src/Http/Exception/HttpException.php index 4e1e265e..c78a40f0 100644 --- a/src/Http/Exception/HttpException.php +++ b/src/Http/Exception/HttpException.php @@ -26,7 +26,7 @@ class HttpException extends Exception * HttpException constructor * * @param string $message - * @param int $code + * @param int $code */ public function __construct(string $message, int $code = 200) { diff --git a/src/Http/Exception/RequestException.php b/src/Http/Exception/RequestException.php index 14227228..c53210a8 100644 --- a/src/Http/Exception/RequestException.php +++ b/src/Http/Exception/RequestException.php @@ -16,7 +16,7 @@ class RequestException extends HttpException /** * Set the http code * - * @param int $code + * @param int $code * @return void */ public function setCode(int $code) diff --git a/src/Http/Exception/ResponseException.php b/src/Http/Exception/ResponseException.php index d85ee80f..db3a2da7 100644 --- a/src/Http/Exception/ResponseException.php +++ b/src/Http/Exception/ResponseException.php @@ -16,7 +16,7 @@ class ResponseException extends HttpException /** * Set the http code * - * @param int $code + * @param int $code * @return void */ public function setCode(int $code) diff --git a/src/Http/HttpStatus.php b/src/Http/HttpStatus.php index 02331afe..5d1553fd 100644 --- a/src/Http/HttpStatus.php +++ b/src/Http/HttpStatus.php @@ -125,7 +125,7 @@ final class HttpStatus /** * Get the message * - * @param int $code + * @param int $code * @return string */ public static function getMessage(int $code): string diff --git a/src/Http/Redirect.php b/src/Http/Redirect.php index a481825e..5c3f5a15 100644 --- a/src/Http/Redirect.php +++ b/src/Http/Redirect.php @@ -62,7 +62,7 @@ public static function getInstance(): Redirect /** * Redirection with the query information * - * @param array $data + * @param array $data * @return Redirect */ public function withInput(array $data = []): Redirect @@ -79,8 +79,8 @@ public function withInput(array $data = []): Redirect /** * Redirection with define flash information * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * @return Redirect */ public function withFlash(string $key, mixed $value): Redirect @@ -93,9 +93,9 @@ public function withFlash(string $key, mixed $value): Redirect /** * Redirect with route definition * - * @param string $name - * @param array $data - * @param bool $absolute + * @param string $name + * @param array $data + * @param bool $absolute * @return Redirect */ public function route(string $name, array $data = [], bool $absolute = false): Redirect @@ -108,7 +108,7 @@ public function route(string $name, array $data = [], bool $absolute = false): R /** * Redirect on the previous URL * - * @param int $status + * @param int $status * @return Redirect */ public function back(int $status = 302): Redirect @@ -121,8 +121,8 @@ public function back(int $status = 302): Redirect /** * Redirect to another URL * - * @param string $path - * @param int $status + * @param string $path + * @param int $status * @return Redirect */ public function to(string $path, int $status = 302): Redirect diff --git a/src/Http/Request.php b/src/Http/Request.php index a21d0775..b4b66e0d 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -53,7 +53,7 @@ class Request /** * Check if file exists * - * @param mixed $file + * @param mixed $file * @return bool */ public static function hasFile(mixed $file): bool @@ -107,7 +107,7 @@ public function capture() /** * Get Request header * - * @param string $key + * @param string $key * @return ?string */ public function getHeader(string $key): ?string @@ -128,7 +128,7 @@ public function getHeader(string $key): ?string /** * Check if a header exists. * - * @param string $key + * @param string $key * @return bool */ public function hasHeader(string $key): bool @@ -171,8 +171,8 @@ public function method(): ?string /** * Retrieve a value or a collection of values. * - * @param string $key - * @param mixed|null $default + * @param string $key + * @param mixed|null $default * @return mixed */ public function get(string $key, mixed $default = null): mixed @@ -199,7 +199,7 @@ public function getId(): string|int /** * Set the request id * - * @param string|int $id + * @param string|int $id * @return void */ public function setId(string|int $id): void @@ -220,7 +220,7 @@ public function id(): string|int /** * Check if key is existing * - * @param string $key + * @param string $key * @return bool */ public function has(string $key): bool @@ -339,7 +339,7 @@ public function isDelete(): bool /** * Load the factory for FILES * - * @param string $key + * @param string $key * @return UploadedFile|Collection|null */ public function file(string $key): UploadedFile|Collection|null @@ -356,13 +356,15 @@ public function file(string $key): UploadedFile|Collection|null $collect = []; foreach ($files['name'] as $key => $name) { - $collect[] = new UploadedFile([ + $collect[] = new UploadedFile( + [ 'name' => $name, 'type' => $files['type'][$key], 'size' => $files['size'][$key], 'error' => $files['error'][$key], 'tmp_name' => $files['tmp_name'][$key], - ]); + ] + ); } return new Collection($collect); @@ -371,8 +373,8 @@ public function file(string $key): UploadedFile|Collection|null /** * Get previous request data * - * @param string $key - * @param mixed $fullback + * @param string $key + * @param mixed $fullback * @return mixed */ public function old(string $key, mixed $fullback): mixed @@ -425,7 +427,7 @@ public function isAjax(): bool /** * Check if a url matches with the pattern * - * @param string $match + * @param string $match * @return bool */ public function is(string $match): bool @@ -436,7 +438,7 @@ public function is(string $match): bool /** * Check if a url matches with the pattern * - * @param string $match + * @param string $match * @return bool */ public function isReferer(string $match): bool @@ -533,7 +535,7 @@ public function isSecure(): bool /** * Check the protocol of the request * - * @param string $protocol + * @param string $protocol * @return mixed */ public function isProtocol(string $protocol): bool @@ -583,21 +585,21 @@ public function session(): Session /** * Get auth user information * - * @param string|null $guard + * @param string|null $guard * @return Authentication|null */ public function user(?string $guard = null): ?Authentication { - return auth($guard)->user(); + return app_auth($guard)->user(); } /** * Get cookie * - * @param string|null $property + * @param string|null $property * @return string|array|object|null */ - public function cookie(string $property = null): string|array|object|null + public function cookie(?string $property = null): string|array|object|null { return cookie($property); } @@ -605,7 +607,7 @@ public function cookie(string $property = null): string|array|object|null /** * Retrieves the values contained in the exception table * - * @param array $exceptions + * @param array $exceptions * @return array */ public function only(array $exceptions = []): array @@ -628,7 +630,7 @@ public function only(array $exceptions = []): array /** * Retrieves the rest of values * - * @param array $ignores + * @param array $ignores * @return array */ public function ignore(array $ignores = []): array @@ -651,7 +653,7 @@ public function ignore(array $ignores = []): array /** * Validate incoming data * - * @param array $rule + * @param array $rule * @return Validate */ public function validate(array $rule): Validate @@ -662,8 +664,8 @@ public function validate(array $rule): Validate /** * Set the shared value in request bags * - * @param string $name - * @param mixed $value + * @param string $name + * @param mixed $value * @return void */ public function setBag(string $name, mixed $value): void @@ -674,7 +676,7 @@ public function setBag(string $name, mixed $value): void /** * Get the shared value in request bags * - * @param string $name + * @param string $name * @return mixed */ public function getBag(string $name): mixed @@ -695,7 +697,7 @@ public function getBags(): array /** * Set the shared value in request bags * - * @param array $bags + * @param array $bags * @return void */ public function setBags(array $bags): void @@ -706,7 +708,7 @@ public function setBags(array $bags): void /** * __call * - * @param $property + * @param $property * @return mixed */ public function __get($property) diff --git a/src/Http/Response.php b/src/Http/Response.php index 2adb8f1d..7f1989d1 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -63,8 +63,8 @@ class Response implements ResponseInterface * Response constructor. * * @param string $content - * @param int $code - * @param array $headers + * @param int $code + * @param array $headers */ private function __construct(string $content = '', int $code = 200, array $headers = []) { @@ -101,7 +101,7 @@ public function getCode(): int /** * Add http headers * - * @param array $headers + * @param array $headers * @return Response */ public function addHeaders(array $headers): Response @@ -114,9 +114,9 @@ public function addHeaders(array $headers): Response /** * Download the given file as an argument * - * @param string $file - * @param ?string $filename - * @param array $headers + * @param string $file + * @param ?string $filename + * @param array $headers * @return string */ public function download( @@ -153,8 +153,8 @@ public function download( /** * Add http header * - * @param string $key - * @param string $value + * @param string $key + * @param string $value * @return Response */ public function addHeader(string $key, string $value): Response @@ -210,7 +210,7 @@ public function getContent(): ?string /** * Get response message * - * @param string $content + * @param string $content * @return Response */ public function setContent(string $content): Response @@ -223,7 +223,7 @@ public function setContent(string $content): Response /** * Modify http headers * - * @param int $code + * @param int $code * @return mixed */ public function status(int $code): Response @@ -240,9 +240,9 @@ public function status(int $code): Response /** * Equivalent to an echo, except that it ends the application * - * @param mixed $data - * @param int $code - * @param array $headers + * @param mixed $data + * @param int $code + * @param array $headers * @return string */ public function send(mixed $data, int $code = 200, array $headers = []): string @@ -265,9 +265,9 @@ public function send(mixed $data, int $code = 200, array $headers = []): string /** * JSON response * - * @param mixed $data - * @param int $code - * @param array $headers + * @param mixed $data + * @param int $code + * @param array $headers * @return string */ public function json(mixed $data, int $code = 200, array $headers = []): string @@ -287,10 +287,10 @@ public function json(mixed $data, int $code = 200, array $headers = []): string /** * Make view rendering * - * @param string $template - * @param array $data - * @param int $code - * @param array $headers + * @param string $template + * @param array $data + * @param int $code + * @param array $headers * @return string * @throws */ @@ -310,7 +310,7 @@ public function render(string $template, array $data = [], int $code = 200, arra /** * Get headers * - * @param array $headers + * @param array $headers * @return Response */ public function withHeaders(array $headers): Response diff --git a/src/Http/ServerAccessControl.php b/src/Http/ServerAccessControl.php index b0dbcd4a..fc440ce9 100644 --- a/src/Http/ServerAccessControl.php +++ b/src/Http/ServerAccessControl.php @@ -28,7 +28,7 @@ public function __construct(Response $response) /** * Active Access-control-Allow-Origin * - * @param array $excepted + * @param array $excepted * @return ServerAccessControl * @throws */ @@ -47,8 +47,8 @@ public function allowOrigin(array $excepted): ServerAccessControl /** * The access control * - * @param string $allow - * @param string|null $excepted + * @param string $allow + * @param string|null $excepted * @return $this */ private function push(string $allow, ?string $excepted = null): ServerAccessControl @@ -65,7 +65,7 @@ private function push(string $allow, ?string $excepted = null): ServerAccessCont /** * Active Access-control-Allow-Methods * - * @param array $excepted + * @param array $excepted * @return ServerAccessControl * @throws ServerAccessControlException */ @@ -84,7 +84,7 @@ public function allowMethods(array $excepted): ServerAccessControl /** * Active Access-control-Allow-Headers * - * @param array $excepted + * @param array $excepted * @return ServerAccessControl * @throws ServerAccessControlException */ @@ -110,7 +110,7 @@ public function allowCredentials(): ServerAccessControl /** * Active Access-control-Max-Age * - * @param float|int $excepted + * @param float|int $excepted * @return ServerAccessControl * @throws ServerAccessControlException */ @@ -129,7 +129,7 @@ public function maxAge(float|int $excepted): ServerAccessControl /** * Active Access-control-Expose-Headers * - * @param array $excepted + * @param array $excepted * @return ServerAccessControl * @throws ServerAccessControlException */ diff --git a/src/Http/UploadedFile.php b/src/Http/UploadedFile.php index eacdf595..01a59546 100644 --- a/src/Http/UploadedFile.php +++ b/src/Http/UploadedFile.php @@ -111,7 +111,7 @@ public function getContent(): ?string /** * Move the uploader file to a directory. * - * @param string $to + * @param string $to * @param ?string $filename * @return bool * @throws diff --git a/src/Mail/Adapters/LogAdapter.php b/src/Mail/Adapters/LogAdapter.php index 92744d4f..a906988f 100644 --- a/src/Mail/Adapters/LogAdapter.php +++ b/src/Mail/Adapters/LogAdapter.php @@ -42,7 +42,7 @@ public function __construct(array $config = []) /** * Implement send email * - * @param Envelop $envelop + * @param Envelop $envelop * @return bool */ public function send(Envelop $envelop): bool @@ -53,9 +53,15 @@ public function send(Envelop $envelop): bool $content = "Date: " . date('r') . "\n"; $content .= $envelop->compileHeaders(); - $content .= "To: " . implode(', ', array_map(function ($to) { - return $to[0] ? "{$to[0]} <{$to[1]}>" : $to[1]; - }, $envelop->getTo())) . "\n"; + $content .= "To: " . implode( + ', ', + array_map( + function ($to) { + return $to[0] ? "{$to[0]} <{$to[1]}>" : $to[1]; + }, + $envelop->getTo() + ) + ) . "\n"; $content .= "Subject: " . $envelop->getSubject() . "\n"; $content .= $envelop->getMessage(); diff --git a/src/Mail/Adapters/NativeAdapter.php b/src/Mail/Adapters/NativeAdapter.php index 74a21ac7..4e8a8c91 100644 --- a/src/Mail/Adapters/NativeAdapter.php +++ b/src/Mail/Adapters/NativeAdapter.php @@ -42,7 +42,7 @@ public function __construct(array $config = []) /** * Switch on other define from * - * @param string $from + * @param string $from * @return NativeAdapter * @throws MailException */ @@ -63,7 +63,7 @@ public function on(string $from): NativeAdapter /** * Implement send email * - * @param Envelop $envelop + * @param Envelop $envelop * @return bool * @throws InvalidArgumentException */ diff --git a/src/Mail/Adapters/SesAdapter.php b/src/Mail/Adapters/SesAdapter.php index 13d7c54c..172a67d9 100644 --- a/src/Mail/Adapters/SesAdapter.php +++ b/src/Mail/Adapters/SesAdapter.php @@ -27,7 +27,7 @@ class SesAdapter implements MailAdapterInterface /** * SesAdapter constructor * - * @param array $config + * @param array $config * @return void */ public function __construct(private array $config) @@ -54,7 +54,7 @@ public function initializeSesClient(): SesClient /** * Send env$envelop * - * @param Envelop $envelop + * @param Envelop $envelop * @return bool */ public function send(Envelop $envelop): bool diff --git a/src/Mail/Adapters/SmtpAdapter.php b/src/Mail/Adapters/SmtpAdapter.php index ec562bab..7c4aeefd 100644 --- a/src/Mail/Adapters/SmtpAdapter.php +++ b/src/Mail/Adapters/SmtpAdapter.php @@ -120,7 +120,7 @@ public function __construct(array $config) /** * Start sending mail * - * @param Envelop $envelop + * @param Envelop $envelop * @return bool * @throws SocketException * @throws ErrorException @@ -151,7 +151,7 @@ public function send(Envelop $envelop): bool // SMTP command if ($envelop->getFrom() !== null) { - $this->write('MAIL FROM: <' . $envelop->getFrom() . '>', 250); + $this->write('MAIL FROM: ' . $envelop->getFrom(), 250); } elseif ($this->username !== null) { $this->write('MAIL FROM: <' . $this->username . '>', 250); } @@ -283,9 +283,9 @@ private function read(): int /** * Start an SMTP command * - * @param string $command - * @param ?int $code - * @param ?string $envelop + * @param string $command + * @param ?int $code + * @param ?string $envelop * @return int|null * @throws SmtpException */ diff --git a/src/Mail/Contracts/MailAdapterInterface.php b/src/Mail/Contracts/MailAdapterInterface.php index d53ed908..9a098881 100644 --- a/src/Mail/Contracts/MailAdapterInterface.php +++ b/src/Mail/Contracts/MailAdapterInterface.php @@ -11,7 +11,7 @@ interface MailAdapterInterface /** * Send mail by any driver * - * @param Envelop $envelop + * @param Envelop $envelop * @return bool */ public function send(Envelop $envelop): bool; diff --git a/src/Mail/Envelop.php b/src/Mail/Envelop.php index 65ad85c2..6d8ef156 100644 --- a/src/Mail/Envelop.php +++ b/src/Mail/Envelop.php @@ -160,7 +160,7 @@ public function to(string|array $to): Envelop /** * Format the email receiver * - * @param string $email + * @param string $email * @return array */ private function formatEmail(string $email): array @@ -185,7 +185,7 @@ private function formatEmail(string $email): array /** * Add an attachment file * - * @param string $file + * @param string $file * @return Envelop * @throws MailException */ @@ -228,7 +228,7 @@ public function compileHeaders(): string /** * Define the subject of the mail * - * @param string $subject + * @param string $subject * @return Envelop */ public function subject(string $subject): Envelop @@ -241,8 +241,8 @@ public function subject(string $subject): Envelop /** * Define the sender of the mail * - * @param string $from - * @param ?string $name + * @param string $from + * @param ?string $name * @return Envelop */ public function from(string $from, ?string $name = null): Envelop @@ -255,7 +255,7 @@ public function from(string $from, ?string $name = null): Envelop /** * Define the type of content in text/html * - * @param string $html + * @param string $html * @return Envelop */ public function html(string $html): Envelop @@ -266,8 +266,8 @@ public function html(string $html): Envelop /** * Add message body and set message type * - * @param string $message - * @param string $type + * @param string $message + * @param string $type * @return Envelop */ private function type(string $message, string $type): Envelop @@ -282,7 +282,7 @@ private function type(string $message, string $type): Envelop /** * Add message body * - * @param string $text + * @param string $text * @return Envelop */ public function text(string $text): Envelop @@ -295,7 +295,7 @@ public function text(string $text): Envelop /** * Adds blind carbon copy * - * @param string $mail + * @param string $mail * @param ?string $name * * @return Envelop @@ -312,7 +312,7 @@ public function addBcc(string $mail, ?string $name = null): Envelop /** * Add carbon copy * - * @param string $mail + * @param string $mail * @param ?string $name * * @return Envelop @@ -329,8 +329,8 @@ public function addCc(string $mail, ?string $name = null): Envelop /** * Add Reply-To * - * @param string $mail - * @param ?string $name + * @param string $mail + * @param ?string $name * @return Envelop */ public function addReplyTo(string $mail, ?string $name = null): Envelop @@ -345,7 +345,7 @@ public function addReplyTo(string $mail, ?string $name = null): Envelop /** * Add Return-Path * - * @param string $mail + * @param string $mail * @param ?string $name = null * * @return Envelop @@ -459,8 +459,8 @@ public function fromIsDefined(): bool /** * Set the view build * - * @param string $view - * @param array $data + * @param string $view + * @param array $data * @return $this */ public function view(string $view, array $data = []): Envelop @@ -475,7 +475,7 @@ public function view(string $view, array $data = []): Envelop * * @param string $message * @param string $type - * @see setEnvelop + * @see setEnvelop */ public function message(string $message, string $type = 'text/html'): void { diff --git a/src/Mail/Mail.php b/src/Mail/Mail.php index 2edeff59..52dafd5d 100644 --- a/src/Mail/Mail.php +++ b/src/Mail/Mail.php @@ -49,7 +49,7 @@ class Mail /** * Mail constructor * - * @param array $config + * @param array $config * @throws MailException */ public function __construct(array $config = []) @@ -60,7 +60,7 @@ public function __construct(array $config = []) /** * Configure la classe Mail * - * @param array $config + * @param array $config * @return MailAdapterInterface * @throws MailException */ @@ -107,10 +107,10 @@ public static function getInstance(): MailAdapterInterface /** * Send mail similar to the PHP mail function * - * @param string|array $to - * @param string $subject - * @param string $data - * @param array $headers + * @param string|array $to + * @param string $subject + * @param string $data + * @param array $headers * @return mixed */ public static function raw(string|array $to, string $subject, string $data, array $headers = []): mixed @@ -131,9 +131,9 @@ public static function raw(string|array $to, string $subject, string $data, arra /** * The method thad send the configured mail * - * @param string $view - * @param callable|array $data - * @param callable|null $cb + * @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): bool @@ -156,9 +156,9 @@ public static function send(string $view, callable|array $data, ?callable $cb = /** * Send env on queue * - * @param string $template - * @param array $data - * @param callable $cb + * @param string $template + * @param array $data + * @param callable $cb * @return void */ public static function queue(string $template, array $data, callable $cb): void @@ -175,10 +175,10 @@ public static function queue(string $template, array $data, callable $cb): void /** * Send env on specific queue * - * @param string $queue - * @param string $template - * @param array $data - * @param callable $cb + * @param string $queue + * @param string $template + * @param array $data + * @param callable $cb * @return void */ public static function queueOn(string $queue, string $template, array $data, callable $cb): void @@ -197,10 +197,10 @@ public static function queueOn(string $queue, string $template, array $data, cal /** * Send mail later * - * @param integer $delay - * @param string $template - * @param array $data - * @param callable $cb + * @param integer $delay + * @param string $template + * @param array $data + * @param callable $cb * @return void */ public static function later(int $delay, string $template, array $data, callable $cb): void @@ -219,11 +219,11 @@ public static function later(int $delay, string $template, array $data, callable /** * Send mail later on specific queue * - * @param integer $delay - * @param string $queue - * @param string $template - * @param array $data - * @param callable $cb + * @param integer $delay + * @param string $queue + * @param string $template + * @param array $data + * @param callable $cb * @return void */ public static function laterOn(int $delay, string $queue, string $template, array $data, callable $cb): void @@ -243,7 +243,7 @@ public static function laterOn(int $delay, string $queue, string $template, arra /** * Modify the smtp|mail|ses driver * - * @param string $driver + * @param string $driver * @return MailAdapterInterface * @throws MailException */ @@ -269,8 +269,8 @@ public static function setDriver(string $driver): MailAdapterInterface /** * Push new driver * - * @param string $name - * @param string $class_name + * @param string $name + * @param string $class_name * @return bool */ public function pushDriver(string $name, string $class_name): bool @@ -287,8 +287,8 @@ public function pushDriver(string $name, string $class_name): bool /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed * @throws ErrorException */ diff --git a/src/Mail/MailConfiguration.php b/src/Mail/MailConfiguration.php index e3cb9b28..c65dcc9f 100644 --- a/src/Mail/MailConfiguration.php +++ b/src/Mail/MailConfiguration.php @@ -14,9 +14,12 @@ class MailConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('mail', function () use ($config) { - return Mail::configure($config['mail']); - }); + $this->container->bind( + 'mail', + function () use ($config) { + return Mail::configure($config['mail']); + } + ); } /** diff --git a/src/Mail/MailQueueProducer.php b/src/Mail/MailQueueProducer.php index ba061b94..791d3a67 100644 --- a/src/Mail/MailQueueProducer.php +++ b/src/Mail/MailQueueProducer.php @@ -18,8 +18,8 @@ class MailQueueProducer extends ProducerService /** * MailQueueProducer constructor * - * @param string $view - * @param array $data + * @param string $view + * @param array $data * @param Envelop $message */ public function __construct( @@ -55,7 +55,7 @@ public function process(): void /** * Send the processing exception * - * @param Throwable $e + * @param Throwable $e * @return void */ public function onException(Throwable $e): void diff --git a/src/Mail/Security/DkimSigner.php b/src/Mail/Security/DkimSigner.php index 90f0b668..8c3a55c3 100644 --- a/src/Mail/Security/DkimSigner.php +++ b/src/Mail/Security/DkimSigner.php @@ -28,7 +28,7 @@ public function __construct(array $config) /** * Sign the email with DKIM * - * @param Envelop $envelop + * @param Envelop $envelop * @return string */ public function sign(Envelop $envelop): string @@ -61,7 +61,7 @@ private function loadPrivateKey() /** * Get headers to sign * - * @param Envelop $envelop + * @param Envelop $envelop * @return array */ private function getHeadersToSign(Envelop $envelop): array @@ -81,20 +81,26 @@ private function getHeadersToSign(Envelop $envelop): array /** * Format email addresses * - * @param array $addresses + * @param array $addresses * @return string */ private function formatAddresses(array $addresses): string { - return implode(', ', array_map(function ($address) { - return $address[0] ? "{$address[0]} <{$address[1]}>" : $address[1]; - }, $addresses)); + return implode( + ', ', + array_map( + function ($address) { + return $address[0] ? "{$address[0]} <{$address[1]}>" : $address[1]; + }, + $addresses + ) + ); } /** * Hash the message body * - * @param string $body + * @param string $body * @return string */ private function hashBody(string $body): string @@ -109,8 +115,8 @@ private function hashBody(string $body): string /** * Build the string to sign * - * @param array $headers - * @param string $bodyHash + * @param array $headers + * @param string $bodyHash * @return string */ private function buildSignatureString(array $headers, string $bodyHash): string @@ -128,9 +134,9 @@ private function buildSignatureString(array $headers, string $bodyHash): string /** * Build the DKIM header * - * @param array $headers - * @param string $signature - * @param string $bodyHash + * @param array $headers + * @param string $signature + * @param string $bodyHash * @return string */ private function buildDkimHeader(array $headers, string $signature, string $bodyHash): string diff --git a/src/Mail/Security/SpfChecker.php b/src/Mail/Security/SpfChecker.php index 0322f2cf..2162f02b 100644 --- a/src/Mail/Security/SpfChecker.php +++ b/src/Mail/Security/SpfChecker.php @@ -26,9 +26,9 @@ public function __construct(array $config) /** * Verify SPF record for a sender * - * @param string $ip - * @param string $sender - * @param string $helo + * @param string $ip + * @param string $sender + * @param string $helo * @return string */ public function verify(string $ip, string $sender, string $helo): string @@ -48,7 +48,7 @@ public function verify(string $ip, string $sender, string $helo): string /** * Extract domain from email address * - * @param string $email + * @param string $email * @return string */ private function extractDomain(string $email): string @@ -59,7 +59,7 @@ private function extractDomain(string $email): string /** * Get SPF record for domain * - * @param string $domain + * @param string $domain * @return string|null */ private function getSpfRecord(string $domain): ?string @@ -78,10 +78,10 @@ private function getSpfRecord(string $domain): ?string /** * Evaluate SPF record * - * @param string $spfRecord - * @param string $ip - * @param string $domain - * @param string $helo + * @param string $spfRecord + * @param string $ip + * @param string $domain + * @param string $helo * @return string */ private function evaluateSpf(string $spfRecord, string $ip, string $domain, string $helo): string @@ -102,10 +102,10 @@ private function evaluateSpf(string $spfRecord, string $ip, string $domain, stri /** * Check SPF mechanism * - * @param string $mechanism - * @param string $ip - * @param string $domain - * @param string $helo + * @param string $mechanism + * @param string $ip + * @param string $domain + * @param string $helo * @return string|null */ private function checkMechanism(string $mechanism, string $ip, string $domain, string $helo): ?string @@ -143,9 +143,9 @@ private function checkMechanism(string $mechanism, string $ip, string $domain, s /** * Check IPv4 mechanism * - * @param string $mechanism - * @param string $ip - * @param string $qualifier + * @param string $mechanism + * @param string $ip + * @param string $qualifier * @return string|null */ private function checkIp4(string $mechanism, string $ip, string $qualifier): ?string @@ -160,8 +160,8 @@ private function checkIp4(string $mechanism, string $ip, string $qualifier): ?st /** * Check if IP is in range * - * @param string $ip - * @param string $range + * @param string $ip + * @param string $range * @return bool */ private function ipInRange(string $ip, string $range): bool @@ -179,7 +179,7 @@ private function ipInRange(string $ip, string $range): bool /** * Get result based on qualifier * - * @param string $qualifier + * @param string $qualifier * @return string */ private function getQualifierResult(string $qualifier): string @@ -196,9 +196,9 @@ private function getQualifierResult(string $qualifier): string /** * Check IPv6 mechanism * - * @param string $mechanism - * @param string $ip - * @param string $qualifier + * @param string $mechanism + * @param string $ip + * @param string $qualifier * @return string|null */ private function checkIp6(string $mechanism, string $ip, string $qualifier): ?string @@ -213,10 +213,10 @@ private function checkIp6(string $mechanism, string $ip, string $qualifier): ?st /** * Check A record mechanism * - * @param string $mechanism - * @param string $ip - * @param string $domain - * @param string $qualifier + * @param string $mechanism + * @param string $ip + * @param string $domain + * @param string $qualifier * @return string|null */ private function checkA(string $mechanism, string $ip, string $domain, string $qualifier): ?string @@ -233,10 +233,10 @@ private function checkA(string $mechanism, string $ip, string $domain, string $q /** * Check MX record mechanism * - * @param string $mechanism - * @param string $ip - * @param string $domain - * @param string $qualifier + * @param string $mechanism + * @param string $ip + * @param string $domain + * @param string $qualifier * @return string|null */ private function checkMx(string $mechanism, string $ip, string $domain, string $qualifier): ?string diff --git a/src/Messaging/Adapters/DatabaseChannelAdapter.php b/src/Messaging/Adapters/DatabaseChannelAdapter.php index ca3c799b..9ad398f6 100644 --- a/src/Messaging/Adapters/DatabaseChannelAdapter.php +++ b/src/Messaging/Adapters/DatabaseChannelAdapter.php @@ -12,7 +12,7 @@ class DatabaseChannelAdapter implements ChannelAdapterInterface /** * Send the notification to database * - * @param Model $context + * @param Model $context * @param Messaging $message */ public function send(Model $context, Messaging $message): void @@ -23,12 +23,14 @@ public function send(Model $context, Messaging $message): void $database = $message->toDatabase($context); - Database::table('notifications')->insert([ + Database::table(config('messaging.notification.table') ?? 'notifications')->insert( + [ 'id' => str_uuid(), 'data' => $database['data'], 'concern_id' => $context->getKey(), 'concern_type' => get_class($context), - 'type' => $database['type'], - ]); + 'type' => $database['type'] ?? 'notification', + ] + ); } } diff --git a/src/Messaging/Adapters/MailChannelAdapter.php b/src/Messaging/Adapters/MailChannelAdapter.php index 59237185..74a925d7 100644 --- a/src/Messaging/Adapters/MailChannelAdapter.php +++ b/src/Messaging/Adapters/MailChannelAdapter.php @@ -12,8 +12,8 @@ class MailChannelAdapter implements ChannelAdapterInterface /** * Send the notification to mail * - * @param Model $context - * @param Messaging $message + * @param Model $context + * @param Messaging $message * @return void */ public function send(Model $context, Messaging $message): void diff --git a/src/Messaging/Adapters/SlackChannelAdapter.php b/src/Messaging/Adapters/SlackChannelAdapter.php index bbd2195a..0fdcfb54 100644 --- a/src/Messaging/Adapters/SlackChannelAdapter.php +++ b/src/Messaging/Adapters/SlackChannelAdapter.php @@ -13,8 +13,8 @@ class SlackChannelAdapter implements ChannelAdapterInterface /** * Send message via Slack * - * @param Model $context - * @param Messaging $message + * @param Model $context + * @param Messaging $message * @return void * @throws GuzzleException */ @@ -39,12 +39,15 @@ public function send(Model $context, Messaging $message): void $client = new Client(); try { - $client->post($webhook_url, [ + $client->post( + $webhook_url, + [ 'json' => $data['content'], 'headers' => [ 'Content-Type' => 'application/json' ] - ]); + ] + ); } catch (\Exception $e) { throw new \RuntimeException('Error while sending Slack message: ' . $e->getMessage()); } diff --git a/src/Messaging/Adapters/SmsChannelAdapter.php b/src/Messaging/Adapters/SmsChannelAdapter.php index 0ec6122a..bf5915e9 100644 --- a/src/Messaging/Adapters/SmsChannelAdapter.php +++ b/src/Messaging/Adapters/SmsChannelAdapter.php @@ -42,8 +42,8 @@ public function __construct() /** * Send message via SMS * - * @param Model $context - * @param Messaging $message + * @param Model $context + * @param Messaging $message * @return void */ public function send(Model $context, Messaging $message): void @@ -58,8 +58,8 @@ public function send(Model $context, Messaging $message): void /** * Send the message via SMS using Twilio * - * @param Model $context - * @param Messaging $message + * @param Model $context + * @param Messaging $message * @return void */ private function sendWithTwilio(Model $context, Messaging $message): void @@ -81,10 +81,13 @@ private function sendWithTwilio(Model $context, Messaging $message): void } try { - $this->client->messages->create($data['to'], [ + $this->client->messages->create( + $data['to'], + [ 'from' => $this->from_number, 'body' => $data['message'] - ]); + ] + ); } catch (\Exception $e) { throw new \RuntimeException('Error while sending SMS: ' . $e->getMessage()); } diff --git a/src/Messaging/Adapters/TelegramChannelAdapter.php b/src/Messaging/Adapters/TelegramChannelAdapter.php index 9be6546e..0becaf30 100644 --- a/src/Messaging/Adapters/TelegramChannelAdapter.php +++ b/src/Messaging/Adapters/TelegramChannelAdapter.php @@ -35,8 +35,8 @@ public function __construct() /** * Envoyer le message via Telegram * - * @param Model $context - * @param Messaging $message + * @param Model $context + * @param Messaging $message * @return void * @throws GuzzleException */ @@ -56,13 +56,16 @@ public function send(Model $context, Messaging $message): void $endpoint = "https://api.telegram.org/bot{$this->botToken}/sendMessage"; try { - $client->post($endpoint, [ + $client->post( + $endpoint, + [ 'json' => [ 'chat_id' => $data['chat_id'], 'text' => $data['message'], 'parse_mode' => $data['parse_mode'] ?? 'HTML' ] - ]); + ] + ); } catch (Exception $e) { throw new RuntimeException('Error while sending Telegram message: ' . $e->getMessage()); } diff --git a/src/Messaging/CanSendMessage.php b/src/Messaging/CanSendMessage.php index 692dfa62..94fca638 100644 --- a/src/Messaging/CanSendMessage.php +++ b/src/Messaging/CanSendMessage.php @@ -7,7 +7,7 @@ trait CanSendMessage /** * Send message from authenticate user * - * @param Messaging $message + * @param Messaging $message * @return void */ public function sendMessage(Messaging $message): void @@ -18,7 +18,7 @@ public function sendMessage(Messaging $message): void /** * Send message on queue * - * @param Messaging $message + * @param Messaging $message * @return void */ public function setMessageQueue(Messaging $message): void @@ -31,8 +31,8 @@ public function setMessageQueue(Messaging $message): void /** * Send message on specific queue * - * @param string $queue - * @param Messaging $message + * @param string $queue + * @param Messaging $message * @return void */ public function sendMessageQueueOn(string $queue, Messaging $message): void @@ -47,8 +47,8 @@ public function sendMessageQueueOn(string $queue, Messaging $message): void /** * Send mail later * - * @param integer $delay - * @param Messaging $message + * @param integer $delay + * @param Messaging $message * @return void */ public function sendMessageLater(int $delay, Messaging $message): void @@ -63,9 +63,9 @@ public function sendMessageLater(int $delay, Messaging $message): void /** * Send mail later on specific queue * - * @param integer $delay - * @param string $queue - * @param Messaging $message + * @param integer $delay + * @param string $queue + * @param Messaging $message * @return void */ public function sendMessageLaterOn(int $delay, string $queue, Messaging $message): void diff --git a/src/Messaging/Contracts/ChannelAdapterInterface.php b/src/Messaging/Contracts/ChannelAdapterInterface.php index bd4e2f04..7fb1c431 100644 --- a/src/Messaging/Contracts/ChannelAdapterInterface.php +++ b/src/Messaging/Contracts/ChannelAdapterInterface.php @@ -10,8 +10,8 @@ interface ChannelAdapterInterface /** * Send a message through the channel * - * @param Model $context - * @param Messaging $message + * @param Model $context + * @param Messaging $message * @return void */ public function send(Model $context, Messaging $message): void; diff --git a/src/Messaging/Messaging.php b/src/Messaging/Messaging.php index 38fd7c07..ec42aea3 100644 --- a/src/Messaging/Messaging.php +++ b/src/Messaging/Messaging.php @@ -28,7 +28,7 @@ abstract class Messaging /** * Push channels to the messaging * - * @param array $channels + * @param array $channels * @return array */ public static function pushChannels(array $channels): array @@ -41,7 +41,7 @@ public static function pushChannels(array $channels): array /** * Send notification to mail * - * @param Model $context + * @param Model $context * @return Envelop|null */ public function toMail(Model $context): ?Envelop @@ -52,7 +52,7 @@ public function toMail(Model $context): ?Envelop /** * Send notification to database * - * @param Model $context + * @param Model $context * @return array */ public function toDatabase(Model $context): array @@ -63,7 +63,7 @@ public function toDatabase(Model $context): array /** * Send notification to sms * - * @param Model $context + * @param Model $context * @return array{to: string, message: string} */ public function toSms(Model $context): array @@ -74,7 +74,7 @@ public function toSms(Model $context): array /** * Send notification to slack * - * @param Model $context + * @param Model $context * @return array{webhook_url: ?string, content: array} */ public function toSlack(Model $context): array @@ -85,7 +85,7 @@ public function toSlack(Model $context): array /** * Send notification to telegram * - * @param Model $context + * @param Model $context * @return array{message: string, chat_id: string, parse_mode: string} */ public function toTelegram(Model $context): array @@ -95,7 +95,8 @@ public function toTelegram(Model $context): array /** * Process the notification - * @param Model $context + * + * @param Model $context * @return void */ public function process(Model $context): void @@ -113,7 +114,7 @@ public function process(Model $context): void /** * Returns the available channels to be used * - * @param Model $context + * @param Model $context * @return array */ abstract public function channels(Model $context): array; diff --git a/src/Messaging/MessagingQueueProducer.php b/src/Messaging/MessagingQueueProducer.php index a4610d98..41d1dfe5 100644 --- a/src/Messaging/MessagingQueueProducer.php +++ b/src/Messaging/MessagingQueueProducer.php @@ -18,7 +18,7 @@ class MessagingQueueProducer extends ProducerService /** * MessagingQueueProducer constructor * - * @param Model $context + * @param Model $context * @param Messaging $message */ public function __construct( @@ -47,7 +47,7 @@ public function process(): void /** * Send the processing exception * - * @param Throwable $e + * @param Throwable $e * @return void */ public function onException(Throwable $e): void diff --git a/src/Middleware/AuthMiddleware.php b/src/Middleware/AuthMiddleware.php index 16a7e09a..f55efc9e 100644 --- a/src/Middleware/AuthMiddleware.php +++ b/src/Middleware/AuthMiddleware.php @@ -13,9 +13,9 @@ class AuthMiddleware implements BaseMiddleware /** * Handle an incoming request. * - * @param Request $request - * @param callable $next - * @param array $args + * @param Request $request + * @param callable $next + * @param array $args * @return Redirect */ public function process(Request $request, callable $next, array $args = []): mixed diff --git a/src/Middleware/BaseMiddleware.php b/src/Middleware/BaseMiddleware.php index 2606e12a..519c4694 100644 --- a/src/Middleware/BaseMiddleware.php +++ b/src/Middleware/BaseMiddleware.php @@ -11,9 +11,9 @@ interface BaseMiddleware /** * The handle method * - * @param Request $request - * @param callable $next - * @param array $args + * @param Request $request + * @param callable $next + * @param array $args * @return mixed */ public function process(Request $request, callable $next, array $args = []): mixed; diff --git a/src/Middleware/CsrfMiddleware.php b/src/Middleware/CsrfMiddleware.php index 15994ae8..7d32f54d 100644 --- a/src/Middleware/CsrfMiddleware.php +++ b/src/Middleware/CsrfMiddleware.php @@ -12,9 +12,9 @@ class CsrfMiddleware implements BaseMiddleware /** * Handle an incoming request. * - * @param Request $request - * @param callable $next - * @param array $args + * @param Request $request + * @param callable $next + * @param array $args * @throws */ public function process(Request $request, callable $next, array $args = []): mixed diff --git a/src/Queue/Adapters/BeanstalkdAdapter.php b/src/Queue/Adapters/BeanstalkdAdapter.php index 6fd117ec..4b2a340f 100644 --- a/src/Queue/Adapters/BeanstalkdAdapter.php +++ b/src/Queue/Adapters/BeanstalkdAdapter.php @@ -25,7 +25,7 @@ class BeanstalkdAdapter extends QueueAdapter /** * Configure Beanstalkd driver * - * @param array $config + * @param array $config * @return mixed */ public function configure(array $config): BeanstalkdAdapter @@ -50,7 +50,7 @@ public function configure(array $config): BeanstalkdAdapter /** * Get the size of the queue. * - * @param string|null $queue + * @param string|null $queue * @return int */ public function size(?string $queue = null): int @@ -63,7 +63,7 @@ public function size(?string $queue = null): int /** * Queue a job * - * @param ProducerService $producer + * @param ProducerService $producer * @return void * @throws ErrorException */ @@ -90,7 +90,7 @@ public function push(ProducerService $producer): void /** * Get the priority * - * @param int $priority + * @param int $priority * @return int */ public function getPriority(int $priority): int @@ -106,11 +106,11 @@ public function getPriority(int $priority): int /** * Run the worker * - * @param string|null $queue + * @param string|null $queue * @return void * @throws ErrorException */ - public function run(string $queue = null): void + public function run(?string $queue = null): void { // we want jobs from define queue only. $queue = $this->getQueue($queue); @@ -130,7 +130,7 @@ public function run(string $queue = null): void } catch (Throwable $e) { // Write the error log error_log($e->getMessage()); - app('logger')->error($e->getMessage(), $e->getTrace()); + logger()->error($e->getMessage(), $e->getTrace()); cache("job:failed:" . $job->getId(), $job->getData()); // Check if producer has been loaded @@ -157,7 +157,7 @@ public function run(string $queue = null): void /** * Flush the queue * - * @param string|null $queue + * @param string|null $queue * @return void * @throws ErrorException */ diff --git a/src/Queue/Adapters/DatabaseAdapter.php b/src/Queue/Adapters/DatabaseAdapter.php index ddf694a2..e1e0c433 100644 --- a/src/Queue/Adapters/DatabaseAdapter.php +++ b/src/Queue/Adapters/DatabaseAdapter.php @@ -21,7 +21,7 @@ class DatabaseAdapter extends QueueAdapter /** * Configure Beanstalkd driver * - * @param array $config + * @param array $config * @return mixed */ public function configure(array $config): DatabaseAdapter @@ -34,7 +34,7 @@ public function configure(array $config): DatabaseAdapter /** * Get the size of the queue. * - * @param string|null $queue + * @param string|null $queue * @return int * @throws QueryBuilderException */ @@ -48,12 +48,13 @@ public function size(?string $queue = null): int /** * Queue a job * - * @param ProducerService $producer + * @param ProducerService $producer * @return void */ public function push(ProducerService $producer): void { - $this->table->insert([ + $this->table->insert( + [ "id" => $this->generateId(), "queue" => $this->getQueue(), "payload" => base64_encode($this->serializeProducer($producer)), @@ -62,18 +63,19 @@ public function push(ProducerService $producer): void "available_at" => date("Y-m-d H:i:s", time() + $producer->getDelay()), "reserved_at" => null, "created_at" => date("Y-m-d H:i:s"), - ]); + ] + ); } /** * Run the worker * - * @param string|null $queue + * @param string|null $queue * @return void * @throws QueryBuilderException * @throws ErrorException */ - public function run(string $queue = null): void + public function run(?string $queue = null): void { // we want jobs from define queue only. $queue = $this->getQueue($queue); @@ -94,9 +96,11 @@ public function run(string $queue = null): void if (!is_null($job->reserved_at) && strtotime($job->reserved_at) < time()) { continue; } - $this->table->where("id", $job->id)->update([ + $this->table->where("id", $job->id)->update( + [ "status" => "processing", - ]); + ] + ); $this->execute($producer, $job); continue; } @@ -118,20 +122,24 @@ public function run(string $queue = null): void // Check if the job should be deleted if ($producer->jobShouldBeDelete() || $job->attempts <= 0) { - $this->table->where("id", $job->id)->update([ + $this->table->where("id", $job->id)->update( + [ "status" => "failed", - ]); + ] + ); $this->sleep(1); continue; } // Check if the job should be retried - $this->table->where("id", $job->id)->update([ + $this->table->where("id", $job->id)->update( + [ "status" => "reserved", "attempts" => $job->attempts - 1, "available_at" => date("Y-m-d H:i:s", time() + $producer->getDelay()), "reserved_at" => date("Y-m-d H:i:s", time() + $producer->getRetry()) - ]); + ] + ); $this->sleep(1); } @@ -141,23 +149,25 @@ public function run(string $queue = null): void /** * Process the next job on the queue. * - * @param ProducerService $producer - * @param mixed $job + * @param ProducerService $producer + * @param mixed $job * @throws QueryBuilderException */ private function execute(ProducerService $producer, mixed $job): void { call_user_func([$producer, "process"]); - $this->table->where("id", $job->id)->update([ + $this->table->where("id", $job->id)->update( + [ "status" => "done" - ]); + ] + ); $this->sleep($this->sleep ?? 5); } /** * Flush the queue table * - * @param ?string $queue + * @param ?string $queue * @return void * @throws QueryBuilderException */ diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index 0b379ced..c4c86aa1 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -44,7 +44,7 @@ abstract class QueueAdapter /** * Make adapter configuration * - * @param array $config + * @param array $config * @return QueueAdapter */ abstract public function configure(array $config): QueueAdapter; @@ -59,7 +59,7 @@ abstract public function push(ProducerService $producer): void; /** * Create producer serialization * - * @param ProducerService $producer + * @param ProducerService $producer * @return string */ public function serializeProducer( @@ -71,7 +71,7 @@ public function serializeProducer( /** * Create producer unserialize * - * @param string $producer + * @param string $producer * @return ProducerService */ public function unserializeProducer( @@ -83,7 +83,7 @@ public function unserializeProducer( /** * Sleep the process * - * @param int $seconds + * @param int $seconds * @return void */ public function sleep(int $seconds): void @@ -98,11 +98,11 @@ public function sleep(int $seconds): void /** * Launch the worker * - * @param integer $timeout - * @param integer $memory + * @param integer $timeout + * @param integer $memory * @return void */ - #[NoReturn] final public function work(int $timeout, int $memory): void + final public function work(int $timeout, int $memory): void { [$this->start_time, $jobs_processed] = [hrtime(true) / 1e9, 0]; @@ -160,7 +160,7 @@ public function run(?string $queue = null): void /** * Determine if the timeout is reached * - * @param int $timeout + * @param int $timeout * @return boolean */ protected function timeoutReached(int $timeout): bool @@ -171,10 +171,10 @@ protected function timeoutReached(int $timeout): bool /** * Kill the process. * - * @param int $status + * @param int $status * @return void */ - #[NoReturn] public function kill(int $status = 0): void + public function kill(int $status = 0): void { if (extension_loaded('posix')) { posix_kill(getmypid(), SIGKILL); @@ -186,7 +186,7 @@ protected function timeoutReached(int $timeout): bool /** * Determine if the memory is exceeded * - * @param int $memory_timit + * @param int $memory_timit * @return boolean */ private function memoryExceeded(int $memory_timit): bool @@ -197,7 +197,7 @@ private function memoryExceeded(int $memory_timit): bool /** * Set job tries * - * @param int $tries + * @param int $tries * @return void */ public function setTries(int $tries): void @@ -208,7 +208,7 @@ public function setTries(int $tries): void /** * Set sleep time * - * @param int $sleep + * @param int $sleep * @return void */ public function setSleep(int $sleep): void @@ -250,7 +250,7 @@ public function generateId(): string /** * Get the queue size * - * @param string $queue + * @param string $queue * @return int */ public function size(string $queue): int @@ -261,7 +261,7 @@ public function size(string $queue): int /** * Flush the queue * - * @param ?string $queue + * @param ?string $queue * @return void */ public function flush(?string $queue = null): void diff --git a/src/Queue/Adapters/SQSAdapter.php b/src/Queue/Adapters/SQSAdapter.php index c912da9e..491f91de 100644 --- a/src/Queue/Adapters/SQSAdapter.php +++ b/src/Queue/Adapters/SQSAdapter.php @@ -27,7 +27,7 @@ class SQSAdapter extends QueueAdapter /** * Configure the queue. * - * @param array $config + * @param array $config * @return QueueAdapter */ public function configure(array $config): QueueAdapter @@ -48,7 +48,7 @@ public function configure(array $config): QueueAdapter /** * Push a job onto the queue. * - * @param ProducerService $producer + * @param ProducerService $producer * @return void */ public function push(ProducerService $producer): void @@ -79,15 +79,17 @@ public function push(ProducerService $producer): void /** * Get the size of the queue. * - * @param string $queue + * @param string $queue * @return int */ public function size(string $queue): int { - $response = $this->sqs->getQueueAttributes([ + $response = $this->sqs->getQueueAttributes( + [ 'QueueUrl' => $this->getQueue($queue), 'AttributeNames' => ['ApproximateNumberOfMessages'], - ]); + ] + ); $attributes = $response->get('Attributes'); @@ -97,7 +99,7 @@ public function size(string $queue): int /** * Process the next job on the queue. * - * @param ?string $queue + * @param ?string $queue * @return void * @throws ErrorException */ @@ -108,13 +110,15 @@ public function run(?string $queue = null): void $delay = 5; try { - $result = $this->sqs->receiveMessage([ + $result = $this->sqs->receiveMessage( + [ 'AttributeNames' => ['SentTimestamp'], 'MaxNumberOfMessages' => 1, 'MessageAttributeNames' => ['All'], 'QueueUrl' => $this->config["url"], 'WaitTimeSeconds' => 20, - ]); + ] + ); $messages = $result->get('Messages'); if (empty($messages)) { $this->sleep(1); @@ -124,10 +128,12 @@ public function run(?string $queue = null): void $producer = $this->unserializeProducer(base64_decode($message["Body"])); $delay = $producer->getDelay(); call_user_func([$producer, "process"]); - $result = $this->sqs->deleteMessage([ + $result = $this->sqs->deleteMessage( + [ 'QueueUrl' => $this->config["url"], 'ReceiptHandle' => $message['ReceiptHandle'] - ]); + ] + ); } catch (AwsException $e) { // Write the error log error_log($e->getMessage()); @@ -152,19 +158,23 @@ public function run(?string $queue = null): void // Check if the job should be deleted if ($producer->jobShouldBeDelete()) { - $this->sqs->deleteMessage([ + $this->sqs->deleteMessage( + [ 'QueueUrl' => $this->config["url"], 'ReceiptHandle' => $message['ReceiptHandle'] - ]); + ] + ); } else { - $this->sqs->changeMessageVisibilityBatch([ + $this->sqs->changeMessageVisibilityBatch( + [ 'QueueUrl' => $this->config["url"], 'Entries' => [ 'Id' => $producer->getId(), 'ReceiptHandle' => $message['ReceiptHandle'], 'VisibilityTimeout' => $delay ], - ]); + ] + ); } $this->sleep(1); diff --git a/src/Queue/Adapters/SyncAdapter.php b/src/Queue/Adapters/SyncAdapter.php index 31da37e8..01662512 100644 --- a/src/Queue/Adapters/SyncAdapter.php +++ b/src/Queue/Adapters/SyncAdapter.php @@ -18,7 +18,7 @@ class SyncAdapter extends QueueAdapter /** * Configure SyncAdapter driver * - * @param array $config + * @param array $config * @return mixed */ public function configure(array $config): SyncAdapter @@ -31,7 +31,7 @@ public function configure(array $config): SyncAdapter /** * Queue a job * - * @param ProducerService $producer + * @param ProducerService $producer * @return void */ public function push(ProducerService $producer): void diff --git a/src/Queue/Connection.php b/src/Queue/Connection.php index 12746638..0ca991ff 100644 --- a/src/Queue/Connection.php +++ b/src/Queue/Connection.php @@ -50,8 +50,8 @@ public function __construct(array $config) /** * Push the new connection support in connectors management * - * @param string $name - * @param string $classname + * @param string $name + * @param string $classname * @return bool * @throws ErrorException */ @@ -71,7 +71,7 @@ public static function pushConnection(string $name, string $classname): bool /** * Set connection * - * @param string $connection + * @param string $connection * @return Connection */ public function setConnection(string $connection): Connection @@ -84,8 +84,8 @@ public function setConnection(string $connection): Connection /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed|null * @throws ErrorException */ diff --git a/src/Queue/ProducerService.php b/src/Queue/ProducerService.php index 375bb873..56c48d11 100644 --- a/src/Queue/ProducerService.php +++ b/src/Queue/ProducerService.php @@ -103,7 +103,7 @@ public function getAttempts(): int /** * Set the producer attempts * - * @param int $attempts + * @param int $attempts * @return void */ public function setAttempts(int $attempts): void @@ -124,7 +124,7 @@ final public function getRetry(): int /** * Set the producer retry * - * @param int $retry + * @param int $retry * @return void */ final public function setRetry(int $retry): void @@ -145,7 +145,7 @@ final public function getQueue(): string /** * Set the producer queue * - * @param string $queue + * @param string $queue * @return void */ final public function setQueue(string $queue): void @@ -196,7 +196,7 @@ public function jobShouldBeDelete(): bool /** * Get the job error * - * @param Throwable $e + * @param Throwable $e * @return void */ public function onException(Throwable $e) diff --git a/src/Queue/QueueConfiguration.php b/src/Queue/QueueConfiguration.php index f9e86657..82561eb2 100644 --- a/src/Queue/QueueConfiguration.php +++ b/src/Queue/QueueConfiguration.php @@ -15,9 +15,12 @@ class QueueConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('queue', function () use ($config) { - return new QueueConnection($config["worker"] ?? $config["queue"]); - }); + $this->container->bind( + 'queue', + function () use ($config) { + return new QueueConnection($config["worker"] ?? $config["queue"]); + } + ); } /** diff --git a/src/Queue/WorkerService.php b/src/Queue/WorkerService.php index b9177c7b..15b736c7 100644 --- a/src/Queue/WorkerService.php +++ b/src/Queue/WorkerService.php @@ -19,7 +19,7 @@ class WorkerService /** * Make connection base on default name * - * @param QueueAdapter $connection + * @param QueueAdapter $connection * @return void */ public function setConnection(QueueAdapter $connection): void @@ -30,14 +30,14 @@ public function setConnection(QueueAdapter $connection): void /** * Start the consumer * - * @param string $queue - * @param int $tries - * @param int $sleep - * @param int $timeout - * @param int $memory + * @param string $queue + * @param int $tries + * @param int $sleep + * @param int $timeout + * @param int $memory * @return void */ - #[NoReturn] public function run( + public function run( string $queue = "default", int $tries = 3, int $sleep = 5, diff --git a/src/Router/Resource.php b/src/Router/Resource.php index 14fb7528..6dea0103 100644 --- a/src/Router/Resource.php +++ b/src/Router/Resource.php @@ -53,9 +53,9 @@ class Resource * Make rest * * @param string $url - * @param mixed $controller - * @param array $where - * @param array $ignore_method + * @param mixed $controller + * @param array $where + * @param array $ignore_method */ public static function make(string $url, mixed $controller, array $where = [], array $ignore_method = []): void { @@ -73,10 +73,10 @@ public static function make(string $url, mixed $controller, array $where = [], a /** * Bind routing * - * @param string $url - * @param mixed $controller - * @param array $definition - * @param array $where + * @param string $url + * @param mixed $controller + * @param array $definition + * @param array $where * @throws */ private static function bind(string $url, mixed $controller, array $definition, array $where): void diff --git a/src/Router/Route.php b/src/Router/Route.php index 64e6e3f1..aaea9f9e 100644 --- a/src/Router/Route.php +++ b/src/Router/Route.php @@ -69,7 +69,7 @@ class Route * Route constructor * * @param string $path - * @param mixed $cb + * @param mixed $cb * * @throws */ @@ -97,7 +97,7 @@ public function getAction(): mixed /** * Add middleware * - * @param array|string $middleware + * @param array|string $middleware * @return Route */ public function middleware(array|string $middleware): Route @@ -121,11 +121,11 @@ public function middleware(array|string $middleware): Route /** * Add the url rules * - * @param array|string $where - * @param string|null $regex_constraint + * @param array|string $where + * @param string|null $regex_constraint * @return Route */ - public function where(array|string $where, string $regex_constraint = null): Route + public function where(array|string $where, ?string $regex_constraint = null): Route { $other_rule = is_array($where) ? $where : [$where => $regex_constraint]; @@ -164,7 +164,7 @@ public function call(): mixed /** * To give a name to the road * - * @param string $name + * @param string $name * @return Route */ public function name(string $name): Route @@ -214,7 +214,7 @@ public function getParameters(): array /** * Get a parameter element * - * @param string $key + * @param string $key * @return ?string */ public function getParameter(string $key): ?string @@ -226,7 +226,7 @@ public function getParameter(string $key): ?string * Lets check if the url of the query is * conform to that defined by the router * - * @param string $uri + * @param string $uri * @return bool */ public function match(string $uri): bool @@ -302,8 +302,8 @@ public function match(string $uri): bool /** * Check the url for the search * - * @param string $path - * @param string $uri + * @param string $path + * @param string $uri * @return bool */ private function checkRequestUri(string $path, string $uri): bool diff --git a/src/Router/Router.php b/src/Router/Router.php index 08bae6e1..9fe4d8ec 100644 --- a/src/Router/Router.php +++ b/src/Router/Router.php @@ -74,10 +74,10 @@ class Router /** * Router constructor * - * @param string $method + * @param string $method * @param ?string $magic_method - * @param string $base_route - * @param array $middlewares + * @param string $base_route + * @param array $middlewares */ protected function __construct( string $method, @@ -105,7 +105,7 @@ public function setBaseRoute(string $base_route): void * Set auto CSRF status * Note: Disable only you run on test env * - * @param bool $auto_csrf + * @param bool $auto_csrf * @return void */ public function setAutoCsrf(bool $auto_csrf): void @@ -116,8 +116,8 @@ public function setAutoCsrf(bool $auto_csrf): void /** * Add a prefix on the roads * - * @param string $prefix - * @param callable $cb + * @param string $prefix + * @param callable $cb * @return Router * @throws */ @@ -141,7 +141,7 @@ public function prefix(string $prefix, callable $cb): Router /** * Route mapper * - * @param array $definition + * @param array $definition * @throws RouterException */ public function route(array $definition): void @@ -186,9 +186,9 @@ public function route(array $definition): void /** * Add other HTTP verbs [PUT, DELETE, UPDATE, HEAD, PATCH] * - * @param string|array $methods - * @param string $path - * @param callable|array|string $cb + * @param string|array $methods + * @param string $path + * @param callable|array|string $cb * @return Route */ private function pushHttpVerb(string|array $methods, string $path, callable|string|array $cb): Route @@ -211,9 +211,9 @@ private function pushHttpVerb(string|array $methods, string $path, callable|stri /** * Start loading a route. * - * @param string|array $methods - * @param string $path - * @param callable|string|array $cb + * @param string|array $methods + * @param string $path + * @param callable|string|array $cb * @return Route */ private function routeLoader(string|array $methods, string $path, callable|string|array $cb): Route @@ -250,7 +250,7 @@ private function routeLoader(string|array $methods, string $path, callable|strin /** * Allows to associate a global middleware on a route * - * @param array|string $middlewares + * @param array|string $middlewares * @return Router */ public function middleware(array|string $middlewares): Router @@ -271,8 +271,8 @@ public function middleware(array|string $middlewares): Router * * GET, POST, DELETE, PUT, OPTIONS, PATCH * - * @param string $path - * @param callable|string|array $cb + * @param string $path + * @param callable|string|array $cb * @return Route * @throws */ @@ -286,8 +286,8 @@ public function any(string $path, callable|string|array $cb): Route /** * Add a GET route * - * @param string $path - * @param callable|string|array $cb + * @param string $path + * @param callable|string|array $cb * @return Route */ public function get(string $path, callable|string|array $cb): Route @@ -298,8 +298,8 @@ public function get(string $path, callable|string|array $cb): Route /** * Add a POST route * - * @param string $path - * @param callable|string|array $cb + * @param string $path + * @param callable|string|array $cb * @return Route */ public function post(string $path, callable|string|array $cb): Route @@ -320,8 +320,8 @@ public function post(string $path, callable|string|array $cb): Route /** * Add a DELETE route * - * @param string $path - * @param callable|string|array $cb + * @param string $path + * @param callable|string|array $cb * @return Route */ public function delete(string $path, callable|string|array $cb): Route @@ -332,8 +332,8 @@ public function delete(string $path, callable|string|array $cb): Route /** * Add a PUT route * - * @param string $path - * @param callable|string|array $cb + * @param string $path + * @param callable|string|array $cb * @return Route */ public function put(string $path, callable|string|array $cb): Route @@ -344,8 +344,8 @@ public function put(string $path, callable|string|array $cb): Route /** * Add a PATCH route * - * @param string $path - * @param callable|string|array $cb + * @param string $path + * @param callable|string|array $cb * @return Route */ public function patch(string $path, callable|string|array $cb): Route @@ -356,8 +356,8 @@ public function patch(string $path, callable|string|array $cb): Route /** * Add a OPTIONS route * - * @param string $path - * @param callable|string|array $cb + * @param string $path + * @param callable|string|array $cb * @return Route */ public function options(string $path, callable|string|array $cb): Route @@ -369,8 +369,8 @@ public function options(string $path, callable|string|array $cb): Route * Launch a callback function for each HTTP error code. * When the define code match with response code. * - * @param int $code - * @param callable|array|string $cb + * @param int $code + * @param callable|array|string $cb * @return Router */ public function code(int $code, callable|array|string $cb): Router @@ -383,9 +383,9 @@ public function code(int $code, callable|array|string $cb): Router /** * Match route de tout type de method * - * @param array $methods - * @param string $path - * @param callable|string|array $cb + * @param array $methods + * @param string $path + * @param callable|string|array $cb * @return Route */ public function match(array $methods, string $path, callable|string|array $cb): Route diff --git a/src/Security/Crypto.php b/src/Security/Crypto.php index 46edd38f..5d19f9ca 100644 --- a/src/Security/Crypto.php +++ b/src/Security/Crypto.php @@ -25,7 +25,7 @@ class Crypto /** * Set the key * - * @param string $key + * @param string $key * @param string|null $cipher */ public static function setKey(string $key, ?string $cipher = null): void @@ -40,7 +40,7 @@ public static function setKey(string $key, ?string $cipher = null): void /** * Encrypt data * - * @param string $data + * @param string $data * @return string|bool */ public static function encrypt(string $data): string|bool diff --git a/src/Security/CryptoConfiguration.php b/src/Security/CryptoConfiguration.php index 5b2f7d44..66ec9836 100644 --- a/src/Security/CryptoConfiguration.php +++ b/src/Security/CryptoConfiguration.php @@ -14,11 +14,14 @@ class CryptoConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('security', function () use ($config) { - Crypto::setkey($config['security.key'], $config['security.cipher']); + $this->container->bind( + 'security', + function () use ($config) { + Crypto::setkey($config['security.key'], $config['security.cipher']); - return Crypto::class; - }); + return Crypto::class; + } + ); } /** diff --git a/src/Security/Hash.php b/src/Security/Hash.php index 56393a63..608527b7 100644 --- a/src/Security/Hash.php +++ b/src/Security/Hash.php @@ -9,7 +9,7 @@ class Hash /** * Allows to have a value and when the hash has failed it returns false. * - * @param string $value + * @param string $value * @return string|int|null */ public static function create(string $value): string|int|null @@ -39,7 +39,7 @@ protected static function getHashConfig(): array /** * Allows to have a value and when the hash has failed it returns false. * - * @param string $value + * @param string $value * @return string|int|null */ public static function make(string $value): string|int|null @@ -52,8 +52,8 @@ public static function make(string $value): string|int|null /** * Allows you to check the hash by adding a value * - * @param string $value - * @param string $hash + * @param string $value + * @param string $hash * @return bool */ public static function check(string $value, string $hash): bool @@ -68,7 +68,7 @@ public static function check(string $value, string $hash): bool /** * Allows you to rehash a value. * - * @param string $hash + * @param string $hash * @return bool */ public static function needsRehash(string $hash): bool diff --git a/src/Security/Sanitize.php b/src/Security/Sanitize.php index 5de76487..a36729bb 100644 --- a/src/Security/Sanitize.php +++ b/src/Security/Sanitize.php @@ -9,8 +9,8 @@ class Sanitize /** * To clean the data * - * @param mixed $data - * @param bool $secure + * @param mixed $data + * @param bool $secure * @return mixed */ public static function make(mixed $data, bool $secure = false): mixed @@ -61,7 +61,7 @@ public static function make(mixed $data, bool $secure = false): mixed /** * Allows you to clean a string of characters * - * @param string $data + * @param string $data * @return string */ public static function data(string $data): string @@ -72,7 +72,7 @@ public static function data(string $data): string /** * Allows you to clean a string of characters * - * @param string $data + * @param string $data * @return string */ public static function secure(string $data): string diff --git a/src/Security/Tokenize.php b/src/Security/Tokenize.php index 1755c74c..f8079f74 100644 --- a/src/Security/Tokenize.php +++ b/src/Security/Tokenize.php @@ -20,7 +20,7 @@ class Tokenize /** * Get a csrf token generate * - * @param int|null $time + * @param int|null $time * @return ?array * @throws SessionException */ @@ -34,7 +34,7 @@ public static function csrf(int $time = null): ?array /** * Csrf token creator * - * @param int|null $time + * @param int|null $time * @return bool * @throws SessionException */ @@ -50,11 +50,14 @@ public static function makeCsrfToken(?int $time = null): bool $token = static::make(); - Session::getInstance()->add('__bow.csrf', [ + Session::getInstance()->add( + '__bow.csrf', + [ 'token' => $token, 'expire_at' => time() + static::$expire_at, 'field' => '' - ]); + ] + ); Session::getInstance()->add('_token', $token); @@ -78,8 +81,8 @@ public static function make(): string /** * Check if csrf token is valid * - * @param string $token - * @param bool $strict + * @param string $token + * @param bool $strict * @return bool * @throws SessionException */ @@ -107,7 +110,7 @@ public static function verify(string $token, bool $strict = false): bool /** * Check if the token expires * - * @param int|null $time + * @param int|null $time * @return bool * @throws SessionException */ diff --git a/src/Session/Adapters/ArrayAdapter.php b/src/Session/Adapters/ArrayAdapter.php index 2033cd30..d46010d1 100644 --- a/src/Session/Adapters/ArrayAdapter.php +++ b/src/Session/Adapters/ArrayAdapter.php @@ -30,7 +30,7 @@ public function close(): bool /** * Garbage collector * - * @param int $max_lifetime + * @param int $max_lifetime * @return int|false */ public function gc(int $max_lifetime): int|false @@ -47,7 +47,7 @@ public function gc(int $max_lifetime): int|false /** * Destroy session information * - * @param string $id + * @param string $id * @return bool */ public function destroy(string $id): bool @@ -60,8 +60,8 @@ public function destroy(string $id): bool /** * When the session start * - * @param string $path - * @param string $name + * @param string $path + * @param string $name * @return bool */ public function open(string $path, string $name): bool @@ -74,7 +74,7 @@ public function open(string $path, string $name): bool /** * Read the session information * - * @param string $id + * @param string $id * @return string */ public function read(string $id): string @@ -89,8 +89,8 @@ public function read(string $id): string /** * Write session information * - * @param string $id - * @param string $data + * @param string $id + * @param string $data * @return bool */ public function write(string $id, string $data): bool diff --git a/src/Session/Adapters/DatabaseAdapter.php b/src/Session/Adapters/DatabaseAdapter.php index 732515c5..8805c376 100644 --- a/src/Session/Adapters/DatabaseAdapter.php +++ b/src/Session/Adapters/DatabaseAdapter.php @@ -37,7 +37,7 @@ class DatabaseAdapter implements SessionHandlerInterface /** * Database constructor * - * @param array $options + * @param array $options * @param string $ip */ public function __construct(array $options, string $ip) @@ -60,7 +60,7 @@ public function close(): bool /** * Destroy session information * - * @param string $id + * @param string $id * @return bool * @throws QueryBuilderException */ @@ -85,7 +85,7 @@ private function sessions(): QueryBuilder /** * Garbage collector for cleans old sessions * - * @param int $max_lifetime + * @param int $max_lifetime * @return int|false * @throws QueryBuilderException */ @@ -101,8 +101,8 @@ public function gc(int $max_lifetime): int|false /** * When the session start * - * @param string $path - * @param string $name + * @param string $path + * @param string $name * @return bool */ public function open(string $path, string $name): bool @@ -113,7 +113,7 @@ public function open(string $path, string $name): bool /** * Read the session information * - * @param string $session_id + * @param string $session_id * @return string * @throws QueryBuilderException */ @@ -132,8 +132,8 @@ public function read(string $id): string /** * Write session information * - * @param string $id - * @param string $data + * @param string $id + * @param string $data * @return bool * @throws QueryBuilderException */ @@ -148,10 +148,12 @@ public function write(string $id, string $data): bool } // Update the session information - $update = $this->sessions()->where('id', $id)->update([ + $update = $this->sessions()->where('id', $id)->update( + [ 'data' => $data, 'id' => $id - ]); + ] + ); return (bool)$update; } @@ -159,8 +161,8 @@ public function write(string $id, string $data): bool /** * Get the insert data * - * @param string $session_id - * @param string $session_data + * @param string $session_id + * @param string $session_data * @return array */ private function data(string $session_id, string $session_data): array diff --git a/src/Session/Adapters/DurationTrait.php b/src/Session/Adapters/DurationTrait.php index 66928b0b..6aebd737 100644 --- a/src/Session/Adapters/DurationTrait.php +++ b/src/Session/Adapters/DurationTrait.php @@ -9,7 +9,7 @@ trait DurationTrait /** * Create the timestamp * - * @param int|null $max_lifetime + * @param int|null $max_lifetime * @return string */ private function createTimestamp(?int $max_lifetime = null): string diff --git a/src/Session/Adapters/FilesystemAdapter.php b/src/Session/Adapters/FilesystemAdapter.php index e020f1eb..0db41053 100644 --- a/src/Session/Adapters/FilesystemAdapter.php +++ b/src/Session/Adapters/FilesystemAdapter.php @@ -40,7 +40,7 @@ public function close(): bool /** * Destroy session information * - * @param string $id + * @param string $id * @return bool */ public function destroy(string $id): bool @@ -55,7 +55,7 @@ public function destroy(string $id): bool /** * Build the session file name * - * @param string $session_id + * @param string $session_id * @return string */ private function sessionFile(string $session_id): string @@ -66,7 +66,7 @@ private function sessionFile(string $session_id): string /** * Garbage collector * - * @param int $maxlifetime + * @param int $maxlifetime * @return int|false */ public function gc(int $maxlifetime): int|false @@ -83,8 +83,8 @@ public function gc(int $maxlifetime): int|false /** * When the session start * - * @param string $path - * @param string $name + * @param string $path + * @param string $name * @return bool */ public function open(string $path, string $name): bool @@ -99,7 +99,7 @@ public function open(string $path, string $name): bool /** * Read the session information * - * @param string $session_id + * @param string $session_id * @return string */ public function read(string $session_id): string @@ -110,8 +110,8 @@ public function read(string $session_id): string /** * Write session information * - * @param string $session_id - * @param string $session_data + * @param string $session_id + * @param string $session_data * @return bool */ public function write(string $session_id, string $session_data): bool diff --git a/src/Session/Cookie.php b/src/Session/Cookie.php index 58ca6d21..9b6ba773 100644 --- a/src/Session/Cookie.php +++ b/src/Session/Cookie.php @@ -28,8 +28,8 @@ public static function isEmpty(): bool /** * Allows you to retrieve a value or collection of cookie value. * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed */ public static function get(string $key, mixed $default = null): mixed @@ -48,8 +48,8 @@ public static function get(string $key, mixed $default = null): mixed /** * Check for existence of a key in the session collection * - * @param string $key - * @param bool $strict + * @param string $key + * @param bool $strict * @return bool */ public static function has(string $key, bool $strict = false): bool @@ -84,7 +84,7 @@ public static function all(): array /** * Delete an entry in the table * - * @param string $key + * @param string $key * @return string|bool|null */ public static function remove(string $key): string|bool|null @@ -111,9 +111,9 @@ public static function remove(string $key): string|bool|null /** * Add a value to the cookie table. * - * @param int|string $key - * @param mixed $data - * @param int $expiration + * @param int|string $key + * @param mixed $data + * @param int $expiration * @return bool */ public static function set( diff --git a/src/Session/Session.php b/src/Session/Session.php index 9aef80ee..5b29fa10 100644 --- a/src/Session/Session.php +++ b/src/Session/Session.php @@ -55,7 +55,7 @@ class Session implements CollectionInterface /** * Session constructor. * - * @param array $config + * @param array $config * @throws SessionException */ private function __construct(array $config) @@ -69,20 +69,23 @@ private function __construct(array $config) } // We merge configuration - $this->config = array_merge([ + $this->config = array_merge( + [ 'name' => 'Bow', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'save_path' => null, - ], $config); + ], + $config + ); } /** * Configure session instance * - * @param array $config + * @param array $config * @return Session * @throws SessionException */ @@ -272,7 +275,7 @@ private function initializeInternalSessionStorage(): void /** * Allows checking for the existence of a key in the session collection * - * @param string $key + * @param string $key * @return bool * @throws SessionException */ @@ -284,8 +287,8 @@ public function exists(string $key): bool /** * Allows checking for the existence of a key in the session collection * - * @param string|int $key - * @param bool $strict + * @param string|int $key + * @param bool $strict * @return bool * @throws SessionException */ @@ -363,8 +366,8 @@ private function filter(): array /** * Retrieves a value or value collection. * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed * @throws SessionException */ @@ -391,8 +394,8 @@ public function get(mixed $key, mixed $default = null): 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 */ @@ -410,9 +413,13 @@ public function flash(string|int $key, ?string $message = null): mixed $content = $flash[$key] ?? null; - $tmp = array_filter($flash, function ($i) use ($key) { - return $i != $key; - }, ARRAY_FILTER_USE_KEY); + $tmp = array_filter( + $flash, + function ($i) use ($key) { + return $i != $key; + }, + ARRAY_FILTER_USE_KEY + ); $_SESSION[static::CORE_SESSION_KEY['flash']] = $tmp; @@ -423,7 +430,7 @@ public function flash(string|int $key, ?string $message = null): mixed * The add alias * * @throws SessionException - * @see Session::add + * @see Session::add */ public function put(string|int $key, mixed $value, $next = false): mixed { @@ -433,9 +440,9 @@ public function put(string|int $key, mixed $value, $next = false): mixed /** * Add an entry to the collection * - * @param string|int $key - * @param mixed $data - * @param boolean $next + * @param string|int $key + * @param mixed $data + * @param boolean $next * @return mixed * @throws InvalidArgumentException|SessionException */ @@ -502,7 +509,7 @@ public function remove(string|int $key): mixed * set * * @param string|int $key - * @param mixed $value + * @param mixed $value * * @return mixed * @throws SessionException @@ -539,6 +546,7 @@ public function toArray(): array /** * Empty the flash system. + * * @throws SessionException */ public function clearFlash(): void diff --git a/src/Session/SessionConfiguration.php b/src/Session/SessionConfiguration.php index 1080f265..33fd86aa 100644 --- a/src/Session/SessionConfiguration.php +++ b/src/Session/SessionConfiguration.php @@ -15,16 +15,19 @@ class SessionConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('session', function () use ($config) { - $session = Session::configure((array)$config['session']); + $this->container->bind( + 'session', + function () use ($config) { + $session = Session::configure((array)$config['session']); - Tokenize::makeCsrfToken((int)$config['session.lifetime']); + Tokenize::makeCsrfToken((int)$config['session.lifetime']); - // Reboot the old request values - Session::getInstance()->add('__bow.old', []); + // Reboot the old request values + Session::getInstance()->add('__bow.old', []); - return $session; - }); + return $session; + } + ); } /** diff --git a/src/Storage/Contracts/FilesystemInterface.php b/src/Storage/Contracts/FilesystemInterface.php index 38a7ea9b..a4e1a186 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|null $location - * @param array $option + * @param UploadedFile $file + * @param string|null $location + * @param array $option * @return array|bool|string * @throws InvalidArgumentException */ @@ -23,8 +23,8 @@ public function store(UploadedFile $file, ?string $location = null, array $optio /** * Write following a file specify * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool */ public function append(string $file, string $content): bool; @@ -32,8 +32,8 @@ 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 */ @@ -42,8 +42,8 @@ public function prepend(string $file, string $content): bool; /** * Put other file content in given file * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool */ public function put(string $file, string $content): bool; @@ -51,7 +51,7 @@ public function put(string $file, string $content): bool; /** * Delete file * - * @param string $file + * @param string $file * @return bool */ public function delete(string $file): bool; @@ -59,7 +59,7 @@ public function delete(string $file): bool; /** * Alias sur readInDir * - * @param string $dirname + * @param string $dirname * @return array */ public function files(string $dirname): array; @@ -67,7 +67,7 @@ public function files(string $dirname): array; /** * Read the contents of the file * - * @param string $dirname + * @param string $dirname * @return array */ public function directories(string $dirname): array; @@ -75,8 +75,8 @@ public function directories(string $dirname): array; /** * Create a directory * - * @param string $dirname - * @param int $mode + * @param string $dirname + * @param int $mode * @return bool */ public function makeDirectory(string $dirname, int $mode = 0777): bool; @@ -84,7 +84,7 @@ public function makeDirectory(string $dirname, int $mode = 0777): bool; /** * Get file content * - * @param string $file + * @param string $file * @return ?string */ public function get(string $file): ?string; @@ -92,8 +92,8 @@ 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 + * @param string $target * @return bool */ public function copy(string $source, string $target): bool; @@ -101,8 +101,8 @@ public function copy(string $source, string $target): bool; /** * Rename or move a source file to a target file. * - * @param string $source - * @param string $target + * @param string $source + * @param string $target * @return bool */ public function move(string $source, string $target): bool; @@ -110,7 +110,7 @@ public function move(string $source, string $target): bool; /** * Check the existence of a file * - * @param string $file + * @param string $file * @return bool */ public function exists(string $file): bool; @@ -118,7 +118,7 @@ public function exists(string $file): bool; /** * isFile alias of is_file. * - * @param string $file + * @param string $file * @return bool */ public function isFile(string $file): bool; @@ -126,7 +126,7 @@ public function isFile(string $file): bool; /** * isDirectory alias of is_dir. * - * @param string $dirname + * @param string $dirname * @return bool */ public function isDirectory(string $dirname): bool; @@ -135,7 +135,7 @@ public function isDirectory(string $dirname): bool; * Resolves a path. * Give the absolute path of a path * - * @param string $file + * @param string $file * @return string */ public function path(string $file): string; diff --git a/src/Storage/Exception/ServiceNotFoundException.php b/src/Storage/Exception/ServiceNotFoundException.php index f8ecc7b9..e74936db 100644 --- a/src/Storage/Exception/ServiceNotFoundException.php +++ b/src/Storage/Exception/ServiceNotFoundException.php @@ -18,7 +18,7 @@ class ServiceNotFoundException extends ErrorException /** * Set the service name * - * @param string $service_name + * @param string $service_name * @return ServiceNotFoundException */ public function setService(string $service_name): ServiceNotFoundException diff --git a/src/Storage/Service/DiskFilesystemService.php b/src/Storage/Service/DiskFilesystemService.php index 98a9f5ee..38e4c7d6 100644 --- a/src/Storage/Service/DiskFilesystemService.php +++ b/src/Storage/Service/DiskFilesystemService.php @@ -51,13 +51,13 @@ public function getBaseDirectory(): string /** * Function to upload a file * - * @param UploadedFile $file + * @param UploadedFile $file * @param string|array|null $location - * @param array $option + * @param array $option * * @return array|bool|string */ - public function store(UploadedFile $file, string|array $location = null, array $option = []): array|bool|string + public function store(UploadedFile $file, $location = null, array $option = []): array|bool|string { if (is_array($location)) { $option = $location; @@ -103,7 +103,7 @@ public function put(string $file, string $content): bool * Resolves file path. * Give the absolute path of a path * - * @param string $file + * @param string $file * @return string */ public function path(string $file): string @@ -118,8 +118,8 @@ public function path(string $file): string /** * Create a directory * - * @param string $dirname - * @param int $mode + * @param string $dirname + * @param int $mode * @return bool */ public function makeDirectory(string $dirname, int $mode = 0777): bool @@ -177,7 +177,7 @@ public function files(string $dirname): array /** * List the folder of a folder passed as a parameter * - * @param string $dirname + * @param string $dirname * @return array */ public function directories(string $dirname): array @@ -188,8 +188,8 @@ public function directories(string $dirname): array /** * Renames or moves a source file to a target file. * - * @param string $source - * @param string $target + * @param string $source + * @param string $target * @return bool */ public function move(string $source, string $target): bool @@ -204,8 +204,8 @@ public function move(string $source, string $target): bool /** * 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 @@ -224,7 +224,7 @@ public function copy(string $source, string $target): bool /** * Check the existence of a file or directory * - * @param string $file + * @param string $file * @return bool */ public function exists(string $file): bool @@ -235,7 +235,7 @@ public function exists(string $file): bool /** * isFile alias of is_file. * - * @param string $file + * @param string $file * @return bool */ public function isFile(string $file): bool @@ -246,7 +246,7 @@ public function isFile(string $file): bool /** * isDirectory alias of is_dir. * - * @param string $dirname + * @param string $dirname * @return bool */ public function isDirectory(string $dirname): bool @@ -257,7 +257,7 @@ public function isDirectory(string $dirname): bool /** * Recover the contents of the file * - * @param string $file + * @param string $file * @return string|null */ public function get(string $file): ?string @@ -304,7 +304,7 @@ public function delete(string $file): bool /** * The file extension * - * @param string $filename + * @param string $filename * @return string|null */ public function extension(string $filename): ?string diff --git a/src/Storage/Service/FTPService.php b/src/Storage/Service/FTPService.php index 5f23b07b..dd2b1525 100644 --- a/src/Storage/Service/FTPService.php +++ b/src/Storage/Service/FTPService.php @@ -54,7 +54,7 @@ class FTPService implements ServiceInterface /** * FTPService constructor * - * @param array $config + * @param array $config * @return void */ private function __construct(array $config) @@ -137,7 +137,7 @@ public function disconnect(): void /** * Change path. * - * @param string|null $path + * @param string|null $path * @return void */ public function changePath(?string $path = null): void @@ -171,7 +171,7 @@ private function activePassiveMode(): void /** * Configure service * - * @param array $config + * @param array $config * @return FTPService */ public static function configure(array $config): FTPService @@ -199,8 +199,8 @@ public function getCurrentDirectory(): mixed * Store directly the upload file * * @param UploadedFile $file - * @param string|null $location - * @param array $option + * @param string|null $location + * @param array $option * * @return bool */ @@ -231,7 +231,7 @@ public function store(UploadedFile $file, ?string $location = null, array $optio /** * Write stream * - * @param string $file + * @param string $file * @param resource $resource * * @return bool @@ -254,8 +254,8 @@ public function getConnection(): FTPConnection /** * Append content a file. * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool */ public function append(string $file, string $content): bool @@ -277,8 +277,8 @@ 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 ResourceException */ @@ -304,7 +304,7 @@ public function prepend(string $file, string $content): bool /** * Get file content * - * @param string $file + * @param string $file * @return ?string * @throws ResourceException */ @@ -324,7 +324,7 @@ public function get(string $file): ?string /** * Read stream * - * @param string $path + * @param string $path * @return mixed * @throws ResourceException */ @@ -356,8 +356,8 @@ private function readStream(string $path): mixed /** * Put other file content in given file * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool * @throws ResourceException */ @@ -383,22 +383,27 @@ public function put(string $file, string $content): bool /** * List files in a directory * - * @param string $dirname + * @param string $dirname * @return array */ public function files(string $dirname = '.'): array { $listing = $this->listDirectoryContents($dirname); - return array_values(array_filter($listing, function ($item) { - return $item['type'] === 'file'; - })); + return array_values( + array_filter( + $listing, + function ($item) { + return $item['type'] === 'file'; + } + ) + ); } /** * List the directory content * - * @param string $directory + * @param string $directory * @return array */ protected function listDirectoryContents(string $directory = '.'): array @@ -417,7 +422,7 @@ protected function listDirectoryContents(string $directory = '.'): array /** * Normalize directory content listing * - * @param array $listing + * @param array $listing * @return array */ private function normalizeDirectoryListing(array $listing): array @@ -452,23 +457,28 @@ private function normalizeDirectoryListing(array $listing): array /** * List directories * - * @param string $dirname + * @param string $dirname * @return array */ public function directories(string $dirname = '.'): array { $listing = $this->listDirectoryContents($dirname); - return array_values(array_filter($listing, function ($item) { - return $item['type'] === 'directory'; - })); + return array_values( + array_filter( + $listing, + function ($item) { + return $item['type'] === 'directory'; + } + ) + ); } /** * Create a directory * - * @param string $dirname - * @param int $mode + * @param string $dirname + * @param int $mode * @return boolean */ public function makeDirectory(string $dirname, int $mode = 0777): bool @@ -493,7 +503,7 @@ public function makeDirectory(string $dirname, int $mode = 0777): bool /** * Create a directory. * - * @param string $directory + * @param string $directory * @return bool */ protected function makeActualDirectory(string $directory): bool @@ -503,9 +513,12 @@ protected function makeActualDirectory(string $directory): bool $directories = ftp_nlist($connection, '.') ?: []; // Remove unix characters from directory name - array_walk($directories, function ($dir_name, $key) { - return preg_match('~^\./.*~', $dir_name) ? substr($dir_name, 2) : $dir_name; - }); + array_walk( + $directories, + function ($dir_name, $key) { + return preg_match('~^\./.*~', $dir_name) ? substr($dir_name, 2) : $dir_name; + } + ); // Skip directory creation if it already exists if (in_array($directory, $directories, true)) { @@ -518,8 +531,8 @@ protected function makeActualDirectory(string $directory): bool /** * 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 * @throws ResourceException */ @@ -537,8 +550,8 @@ public function copy(string $source, string $target): bool /** * Rename or move a source file to a target file. * - * @param string $source - * @param string $target + * @param string $source + * @param string $target * @return bool */ public function move(string $source, string $target): bool @@ -549,16 +562,19 @@ public function move(string $source, string $target): bool /** * isFile alias of is_file. * - * @param string $file + * @param string $file * @return bool */ public function isFile(string $file): bool { $listing = $this->listDirectoryContents(); - $dirname_info = array_filter($listing, function ($item) use ($file) { - return $item['type'] === 'file' && $item['name'] === $file; - }); + $dirname_info = array_filter( + $listing, + function ($item) use ($file) { + return $item['type'] === 'file' && $item['name'] === $file; + } + ); return count($dirname_info) !== 0; } @@ -566,7 +582,7 @@ public function isFile(string $file): bool /** * isDirectory alias of is_dir. * - * @param string $dirname + * @param string $dirname * @return bool */ public function isDirectory(string $dirname): bool @@ -589,7 +605,7 @@ public function isDirectory(string $dirname): bool * Resolves a path. * Give the absolute path of a path * - * @param string $file + * @param string $file * @return string */ public function path(string $file): string @@ -604,16 +620,19 @@ public function path(string $file): string /** * Check that a file exists * - * @param string $file + * @param string $file * @return bool */ public function exists(string $file): bool { $listing = $this->listDirectoryContents(); - $dirname_info = array_filter($listing, function ($item) use ($file) { - return $item['name'] === $file; - }); + $dirname_info = array_filter( + $listing, + function ($item) use ($file) { + return $item['name'] === $file; + } + ); return count($dirname_info) !== 0; } @@ -621,7 +640,7 @@ public function exists(string $file): bool /** * Delete file * - * @param string $file + * @param string $file * @return bool */ public function delete(string $file): bool diff --git a/src/Storage/Service/S3Service.php b/src/Storage/Service/S3Service.php index 7ef7c63f..237106ce 100644 --- a/src/Storage/Service/S3Service.php +++ b/src/Storage/Service/S3Service.php @@ -34,7 +34,7 @@ class S3Service implements ServiceInterface /** * S3Service constructor * - * @param array $config + * @param array $config * @return void */ private function __construct(array $config) @@ -73,9 +73,9 @@ public static function getInstance(): S3Service /** * Function to upload a file * - * @param UploadedFile $file - * @param string|null $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 @@ -90,7 +90,7 @@ public function store(UploadedFile $file, ?string $location = null, array $optio * * @param string $file * @param string $content - * @param array $options + * @param array $options * * @return bool */ @@ -100,19 +100,21 @@ public function put(string $file, string $content, array $options = []): bool ? ['visibility' => $options] : (array)$options; - return (bool)$this->client->putObject([ + return (bool)$this->client->putObject( + [ 'Bucket' => $this->config['bucket'], 'Key' => $file, 'Body' => $content, "Visibility" => $options["visibility"] ?? 'public' - ]); + ] + ); } /** * 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 $file, string $content): bool @@ -127,15 +129,17 @@ public function append(string $file, string $content): bool /** * Recover the contents of the file * - * @param string $file + * @param string $file * @return ?string */ public function get(string $file): ?string { - $result = $this->client->getObject([ + $result = $this->client->getObject( + [ 'Bucket' => $this->config['bucket'], 'Key' => $file - ]); + ] + ); if (isset($result["Body"])) { return $result["Body"]->getContents(); @@ -147,8 +151,8 @@ public function get(string $file): ?string /** * Add content before the contents of the file * - * @param string $file - * @param string $content + * @param string $file + * @param string $content * @return bool * @throws */ @@ -164,14 +168,16 @@ public function prepend(string $file, string $content): bool /** * List the files of a folder passed as a parameter * - * @param string $dirname + * @param string $dirname * @return array */ public function files(string $dirname): array { - $result = $this->client->listObjects([ + $result = $this->client->listObjects( + [ "Bucket" => $dirname - ]); + ] + ); return array_map(fn($file) => $file["Key"], $result["Contents"]); } @@ -179,7 +185,7 @@ public function files(string $dirname): array /** * List the folder of a folder passed as a parameter * - * @param string $dirname + * @param string $dirname * @return array */ public function directories(string $dirname): array @@ -192,16 +198,18 @@ public function directories(string $dirname): array /** * Create a directory * - * @param string $dirname - * @param int $mode - * @param array $option + * @param string $dirname + * @param int $mode + * @param array $option * @return bool */ public function makeDirectory(string $dirname, int $mode = 0777, array $option = []): bool { - $result = $this->client->createBucket([ + $result = $this->client->createBucket( + [ "Bucket" => $dirname - ]); + ] + ); return isset($result["Location"]); } @@ -209,8 +217,8 @@ public function makeDirectory(string $dirname, int $mode = 0777, array $option = /** * Renames or moves a source file to a target file. * - * @param string $source - * @param string $target + * @param string $source + * @param string $target * @return bool */ public function move(string $source, string $target): bool @@ -225,15 +233,15 @@ public function move(string $source, string $target): bool /** * 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 { $content = $this->get($source); - - if($content === null){ + + if ($content === null) { return false; } @@ -245,21 +253,23 @@ public function copy(string $source, string $target): bool /** * Delete file or directory * - * @param string $file + * @param string $file * @return bool */ public function delete(string $file): bool { - return (bool)$this->client->deleteObject([ + return (bool)$this->client->deleteObject( + [ 'Bucket' => $this->config['bucket'], 'Key' => $file - ]); + ] + ); } /** * Check the existence of a file * - * @param string $file + * @param string $file * @return bool */ public function exists(string $file): bool @@ -270,7 +280,7 @@ public function exists(string $file): bool /** * isFile alias of is_file. * - * @param string $file + * @param string $file * @return bool */ public function isFile(string $file): bool @@ -283,7 +293,7 @@ public function isFile(string $file): bool /** * isDirectory alias of is_dir. * - * @param string $dirname + * @param string $dirname * @return bool */ public function isDirectory(string $dirname): bool @@ -297,7 +307,7 @@ public function isDirectory(string $dirname): bool * Resolves file path. * Give the absolute path of a path * - * @param string $file + * @param string $file * @return string */ public function path(string $file): string diff --git a/src/Storage/Storage.php b/src/Storage/Storage.php index 1ce4562d..67d3724e 100644 --- a/src/Storage/Storage.php +++ b/src/Storage/Storage.php @@ -44,7 +44,7 @@ class Storage /** * Mount service * - * @param string $service + * @param string $service * @return FTPService|S3Service * @throws ServiceConfigurationNotFoundException * @throws ServiceNotFoundException @@ -54,26 +54,32 @@ public static function service(string $service): S3Service|FTPService $config = static::$config['services'][$service] ?? null; if (is_null($config)) { - throw (new ServiceConfigurationNotFoundException(sprintf( - '"%s" configuration not found.', - $service - )))->setService($service); + throw (new ServiceConfigurationNotFoundException( + sprintf( + '"%s" configuration not found.', + $service + ) + ))->setService($service); } $driver = $config["driver"] ?? null; if (is_null($driver)) { - throw (new ServiceNotFoundException(sprintf( - '"%s" driver is not support.', - $driver - )))->setService($service); + throw (new ServiceNotFoundException( + sprintf( + '"%s" driver is not support.', + $driver + ) + ))->setService($service); } if (!array_key_exists($driver, self::$available_services_drivers)) { - throw (new ServiceNotFoundException(sprintf( - '"%s" is not registered as a service.', - $driver - )))->setService($service); + throw (new ServiceNotFoundException( + sprintf( + '"%s" is not registered as a service.', + $driver + ) + ))->setService($service); } $service_class = static::$available_services_drivers[$driver]; @@ -84,7 +90,7 @@ public static function service(string $service): S3Service|FTPService /** * Configure Storage * - * @param array $config + * @param array $config * @return FilesystemInterface * @throws */ @@ -147,8 +153,8 @@ public static function pushService(array $drivers): void /** * __callStatic * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed * @throws ErrorException */ @@ -172,8 +178,8 @@ public static function __callStatic(string $name, array $arguments) /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return mixed * @throws ErrorException */ diff --git a/src/Storage/StorageConfiguration.php b/src/Storage/StorageConfiguration.php index b525cde3..e7a14724 100644 --- a/src/Storage/StorageConfiguration.php +++ b/src/Storage/StorageConfiguration.php @@ -14,9 +14,12 @@ class StorageConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('storage', function () use ($config) { - return Storage::configure($config['storage']); - }); + $this->container->bind( + 'storage', + function () use ($config) { + return Storage::configure($config['storage']); + } + ); } /** diff --git a/src/Storage/Temporary.php b/src/Storage/Temporary.php index 92769fd5..dd46c2ad 100644 --- a/src/Storage/Temporary.php +++ b/src/Storage/Temporary.php @@ -25,7 +25,7 @@ class Temporary /** * Temporary Constructor * - * @param string $lock_filename + * @param string $lock_filename * @return void * @throws ResourceException */ diff --git a/src/Support/Arraydotify.php b/src/Support/Arraydotify.php index 01b3a9aa..dcd5ae5f 100644 --- a/src/Support/Arraydotify.php +++ b/src/Support/Arraydotify.php @@ -25,7 +25,7 @@ class Arraydotify implements ArrayAccess /** * Arraydotify constructor. * - * @param array $items + * @param array $items * @return void */ public function __construct(array $items = []) @@ -38,8 +38,8 @@ public function __construct(array $items = []) /** * Dotify action * - * @param array $items - * @param string $prepend + * @param array $items + * @param string $prepend * @return array */ private function dotify(array $items, string $prepend = ''): array @@ -54,10 +54,13 @@ private function dotify(array $items, string $prepend = ''): array $value = (array)$value; - $dot = array_merge($dot, $this->dotify( - $value, - $prepend . $key . '.' - )); + $dot = array_merge( + $dot, + $this->dotify( + $value, + $prepend . $key . '.' + ) + ); } return $dot; @@ -66,7 +69,7 @@ private function dotify(array $items, string $prepend = ''): array /** * Make array dotify * - * @param array $items + * @param array $items * @return Arraydotify */ public static function make(array $items = []): Arraydotify @@ -103,8 +106,8 @@ public function offsetExists($offset): bool /** * Find information to the origin array * - * @param array $origin - * @param string $segment + * @param array $origin + * @param string $segment * @return ?array */ private function find(array $origin, string $segment): ?array @@ -167,9 +170,9 @@ private function updateOrigin(): void /** * Transform the dot access to array access * - * @param mixed $array - * @param string $key - * @param mixed $value + * @param mixed $array + * @param string $key + * @param mixed $value * @return void */ private function dataSet(mixed &$array, string $key, mixed $value): void diff --git a/src/Support/Collection.php b/src/Support/Collection.php index 5396f95d..961f6856 100644 --- a/src/Support/Collection.php +++ b/src/Support/Collection.php @@ -130,7 +130,7 @@ public function count(): int /** * Chunk the storage content * - * @param int $chunk + * @param int $chunk * @return Collection */ public function chunk(int $chunk): Collection @@ -141,7 +141,7 @@ public function chunk(int $chunk): Collection /** * To retrieve a value or value collection form instance of collection. * - * @param string $key + * @param string $key * @return Collection */ public function collectify(string $key): Collection @@ -162,8 +162,8 @@ public function collectify(string $key): Collection /** * Check existence of a key in the session collection * - * @param int|string $key - * @param bool $strict + * @param int|string $key + * @param bool $strict * @return bool */ public function has(int|string $key, bool $strict = false): bool @@ -193,7 +193,7 @@ public function each(callable $cb): void /** * Merge the collection with a painting or other collection * - * @param Collection|array $array + * @param Collection|array $array * @return Collection * @throws ErrorException */ @@ -245,7 +245,7 @@ function ($value, $key) use (&$collection) { /** * Recursive walk of a table or object * - * @param array $data + * @param array $data * @param callable $cb */ private function recursive(array $data, callable $cb): void @@ -262,7 +262,7 @@ private function recursive(array $data, callable $cb): void /** * Map * - * @param callable $cb + * @param callable $cb * @return Collection */ public function map(callable $cb): Collection @@ -281,7 +281,7 @@ public function map(callable $cb): Collection /** * Filter * - * @param callable $cb + * @param callable $cb * @return Collection */ public function filter(callable $cb): Collection @@ -300,8 +300,8 @@ public function filter(callable $cb): Collection /** * Fill storage * - * @param mixed $data - * @param int $offset + * @param mixed $data + * @param int $offset * @return array */ public function fill(mixed $data, int $offset): array @@ -320,16 +320,19 @@ public function fill(mixed $data, int $offset): array /** * Reduce * - * @param callable $cb - * @param mixed|null $next + * @param callable $cb + * @param mixed|null $next * @return Collection */ public function reduce(callable $cb, mixed $next = null): Collection { foreach ($this->storage as $key => $current) { - $next = call_user_func_array($cb, [ + $next = call_user_func_array( + $cb, + [ $next, $current, $key, $this->storage - ]); + ] + ); } return $this; @@ -338,7 +341,7 @@ public function reduce(callable $cb, mixed $next = null): Collection /** * Implode * - * @param string $sep + * @param string $sep * @return string */ public function implode(string $sep): string @@ -349,7 +352,7 @@ public function implode(string $sep): string /** * Sum * - * @param callable|null $cb + * @param callable|null $cb * @return int|float */ public function sum(?callable $cb = null): int|float @@ -375,7 +378,7 @@ function ($value) use (&$sum) { /** * Max * - * @param ?callable $cb + * @param ?callable $cb * @return int|float */ public function max(?callable $cb = null): int|float @@ -386,8 +389,8 @@ public function max(?callable $cb = null): int|float /** * Aggregate Execute max|min * - * @param callable|null $cb - * @param string $type + * @param callable|null $cb + * @param string $type * @return int|float */ private function aggregate(string $type, ?callable $cb = null): float|int @@ -415,7 +418,7 @@ function ($value) use (&$data) { /** * Max * - * @param ?callable $cb + * @param ?callable $cb * @return int|float */ public function min(?callable $cb = null): float|int @@ -426,7 +429,7 @@ public function min(?callable $cb = null): float|int /** * Returns the key list and return an instance of Collection. * - * @param array $except + * @param array $except * @return Collection */ public function excepts(array $except): Collection @@ -448,7 +451,7 @@ function ($value, $key) use (&$data, $except) { /** * Ignore the key that is given to it and return an instance of Collection. * - * @param array $ignores + * @param array $ignores * @return Collection */ public function ignores(array $ignores): Collection @@ -480,9 +483,9 @@ public function reverse(): Collection /** * Update an existing value in the collection * - * @param string|integer $key - * @param mixed $data - * @param bool $override + * @param string|integer $key + * @param mixed $data + * @param bool $override * @return bool */ public function update(mixed $key, mixed $data, bool $override = false): bool @@ -563,8 +566,8 @@ public function all(): array /** * Add after the last item in the collection * - * @param mixed $value - * @param int|string $key + * @param mixed $value + * @param int|string $key * @return Collection */ public function push(mixed $value, mixed $key = null): Collection @@ -581,7 +584,7 @@ public function push(mixed $value, mixed $key = null): Collection /** * __get * - * @param mixed $name + * @param mixed $name * @return mixed */ public function __get(mixed $name) @@ -592,8 +595,8 @@ public function __get(mixed $name) /** * __set * - * @param mixed $name - * @param mixed $value + * @param mixed $name + * @param mixed $value * @return void */ public function __set(mixed $name, mixed $value) @@ -604,11 +607,11 @@ public function __set(mixed $name, mixed $value) /** * Allows to recover a value or value collection. * - * @param int|string|null $key - * @param mixed $default + * @param int|string|null $key + * @param mixed $default * @return mixed */ - public function get(int|string $key = null, mixed $default = null): mixed + public function get(?string $key = null, mixed $default = null): mixed { if (is_null($key)) { return $this->storage; @@ -634,7 +637,7 @@ public function get(int|string $key = null, mixed $default = null): mixed /** * __isset * - * @param mixed $name + * @param mixed $name * @return bool */ public function __isset(mixed $name) @@ -645,7 +648,7 @@ public function __isset(mixed $name) /** * __unset * - * @param mixed $name + * @param mixed $name * @return void */ public function __unset(mixed $name) @@ -656,7 +659,7 @@ public function __unset(mixed $name) /** * Delete an entry in the collection * - * @param string $key + * @param string $key * @return Collection */ public function delete(string $key): Collection @@ -679,7 +682,7 @@ public function __toString() /** * Get the data in JSON format * - * @param int $option + * @param int $option * @return string */ public function toJson(int $option = 0): string @@ -710,7 +713,7 @@ public function getIterator(): ArrayIterator /** * offsetExists * - * @param mixed $offset + * @param mixed $offset * @return bool */ public function offsetExists(mixed $offset): bool @@ -721,7 +724,7 @@ public function offsetExists(mixed $offset): bool /** * offsetGet * - * @param mixed $offset + * @param mixed $offset * @return mixed */ public function offsetGet(mixed $offset): mixed @@ -732,8 +735,8 @@ public function offsetGet(mixed $offset): mixed /** * offsetSet * - * @param mixed $offset - * @param mixed $value + * @param mixed $offset + * @param mixed $value * @return void */ public function offsetSet(mixed $offset, mixed $value): void @@ -744,8 +747,8 @@ public function offsetSet(mixed $offset, mixed $value): void /** * Modify an entry in the collection or the addition if not * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * @return mixed */ public function set(string $key, mixed $value): mixed @@ -764,7 +767,7 @@ public function set(string $key, mixed $value): mixed /** * offsetUnset * - * @param mixed $offset + * @param mixed $offset * @return void */ public function offsetUnset(mixed $offset): void diff --git a/src/Support/Env.php b/src/Support/Env.php index 380de443..959e8eba 100644 --- a/src/Support/Env.php +++ b/src/Support/Env.php @@ -37,7 +37,7 @@ public static function isLoaded(): bool /** * Load env file * - * @param string $filename + * @param string $filename * @return void * @throws */ @@ -90,7 +90,7 @@ public static function load(string $filename): void /** * Bind variable * - * @param array $envs + * @param array $envs * @return array */ private static function bindVariables(array $envs): array @@ -119,8 +119,8 @@ private static function bindVariables(array $envs): array /** * Retrieve information from the environment * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return mixed */ public static function get(string $key, mixed $default = null): mixed @@ -145,8 +145,8 @@ public static function get(string $key, mixed $default = null): mixed /** * Allows you to modify the information of the environment * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * @return mixed */ public static function set(string $key, mixed $value): bool diff --git a/src/Support/Log.php b/src/Support/Log.php index 8783d995..bc599707 100644 --- a/src/Support/Log.php +++ b/src/Support/Log.php @@ -15,8 +15,8 @@ class Log /** * Log * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return void */ public static function __callStatic(string $name, array $arguments = []) diff --git a/src/Support/LoggerService.php b/src/Support/LoggerService.php index eb74e2e3..d379da58 100644 --- a/src/Support/LoggerService.php +++ b/src/Support/LoggerService.php @@ -7,8 +7,8 @@ class LoggerService /** * Logger service * - * @param string $message - * @param array $context + * @param string $message + * @param array $context * @return void */ public function error(string $message, array $context = []): void @@ -19,8 +19,8 @@ public function error(string $message, array $context = []): void /** * Logger service * - * @param string $message - * @param array $context + * @param string $message + * @param array $context * @return void */ public function info(string $message, array $context = []): void @@ -31,8 +31,8 @@ public function info(string $message, array $context = []): void /** * Logger service * - * @param string $message - * @param array $context + * @param string $message + * @param array $context * @return void */ public function warning(string $message, array $context = []): void @@ -43,8 +43,8 @@ public function warning(string $message, array $context = []): void /** * Logger service * - * @param string $message - * @param array $context + * @param string $message + * @param array $context * @return void */ public function alert(string $message, array $context = []): void @@ -55,8 +55,8 @@ public function alert(string $message, array $context = []): void /** * Logger service * - * @param string $message - * @param array $context + * @param string $message + * @param array $context * @return void */ public function critical(string $message, array $context = []): void @@ -67,8 +67,8 @@ public function critical(string $message, array $context = []): void /** * Logger service * - * @param string $message - * @param array $context + * @param string $message + * @param array $context * @return void */ public function emergency(string $message, array $context = []): void diff --git a/src/Support/Serializes.php b/src/Support/Serializes.php index 266a5da9..ef42460f 100644 --- a/src/Support/Serializes.php +++ b/src/Support/Serializes.php @@ -52,7 +52,7 @@ public function __serialize() /** * Get the property value for the given property. * - * @param ReflectionProperty $property + * @param ReflectionProperty $property * @return mixed */ protected function getPropertyValue( @@ -64,7 +64,7 @@ protected function getPropertyValue( /** * Restore the model after serialization. * - * @param array $values + * @param array $values * @return void */ public function __unserialize(array $values): void diff --git a/src/Support/Str.php b/src/Support/Str.php index 73570d2e..91b4b0ba 100644 --- a/src/Support/Str.php +++ b/src/Support/Str.php @@ -12,7 +12,7 @@ class Str /** * camel * - * @param string $str + * @param string $str * @return string */ public static function camel(string $str): string @@ -36,17 +36,23 @@ public static function camel(string $str): string /** * Snake case * - * @param string $str - * @param string $delimiter + * @param string $str + * @param string $delimiter * @return string */ public static function snake(string $str, string $delimiter = '_'): string { $str = preg_replace('/\s+/u', $delimiter, $str); - $str = static::lower(preg_replace_callback('/([A-Z])/u', function ($math) use ($delimiter) { - return $delimiter . static::lower($math[1]); - }, $str)); + $str = static::lower( + preg_replace_callback( + '/([A-Z])/u', + function ($math) use ($delimiter) { + return $delimiter . static::lower($math[1]); + }, + $str + ) + ); return trim(preg_replace('/' . $delimiter . '{2,}/', $delimiter, $str), $delimiter); } @@ -54,7 +60,7 @@ public static function snake(string $str, string $delimiter = '_'): string /** * lower case * - * @param string $str + * @param string $str * @return string */ public static function lower(string $str): string @@ -65,7 +71,7 @@ public static function lower(string $str): string /** * Get str plural * - * @param string $str + * @param string $str * @return string */ public static function plural(string $str): string @@ -84,9 +90,9 @@ public static function plural(string $str): string /** * slice * - * @param string $str - * @param int $start - * @param int|null $length + * @param string $str + * @param int $start + * @param int|null $length * @return string */ public static function slice(string $str, int $start, ?int $length = null): string @@ -107,7 +113,7 @@ public static function slice(string $str, int $start, ?int $length = null): stri /** * Len * - * @param string $str + * @param string $str * @return int */ public static function len(string $str): int @@ -118,8 +124,8 @@ public static function len(string $str): int /** * Contains * - * @param string $search - * @param string $str + * @param string $search + * @param string $str * @return bool */ public static function contains(string $search, string $str): bool @@ -134,9 +140,9 @@ public static function contains(string $search, string $str): bool /** * Get the string position * - * @param string $search - * @param string $string - * @param int $offset + * @param string $search + * @param string $string + * @param int $offset * @return int */ public static function pos(string $search, string $string, int $offset = 0): int @@ -147,9 +153,9 @@ public static function pos(string $search, string $string, int $offset = 0): int /** * replace * - * @param string $pattern - * @param string $replaceBy - * @param string $str + * @param string $pattern + * @param string $replaceBy + * @param string $str * @return string */ public static function replace(string $pattern, string $replaceBy, string $str): string @@ -160,7 +166,7 @@ public static function replace(string $pattern, string $replaceBy, string $str): /** * capitalize * - * @param string $str + * @param string $str * @return string */ public static function capitalize(string $str): string @@ -171,8 +177,8 @@ public static function capitalize(string $str): string /** * Wordily * - * @param string $str - * @param string $sep + * @param string $str + * @param string $sep * @return array */ public static function wordily(string $str, string $sep = ' '): array @@ -183,9 +189,9 @@ public static function wordily(string $str, string $sep = ' '): array /** * split * - * @param string $pattern - * @param string $str - * @param int|null $limit + * @param string $pattern + * @param string $str + * @param int|null $limit * @return array */ public static function split(string $pattern, string $str, ?int $limit = null): array @@ -196,8 +202,8 @@ public static function split(string $pattern, string $str, ?int $limit = null): /** * Returns the number of characters in a string. * - * @param string $pattern - * @param string $str + * @param string $pattern + * @param string $str * @return int */ public static function count(string $pattern, string $str): int @@ -208,8 +214,8 @@ public static function count(string $pattern, string $str): int /** * Lists the string of characters in a specified number * - * @param string $str - * @param int $number + * @param string $str + * @param int $number * @return string */ public static function repeat(string $str, int $number): string @@ -220,7 +226,7 @@ public static function repeat(string $str, int $number): string /** * Randomize * - * @param int $size + * @param int $size * @return string */ public static function random(int $size = 16): string @@ -241,8 +247,8 @@ public static function uuid(): string /** * Alias of slugify * - * @param string $str - * @param string $delimiter + * @param string $str + * @param string $delimiter * @return string */ public static function slug(string $str, string $delimiter = '-'): string @@ -254,8 +260,8 @@ public static function slug(string $str, string $delimiter = '-'): string * slugify slug creator using a simple chain. * eg: 'I am a string of character' => 'i-am-a-chain-of-character' * - * @param string $str - * @param string $delimiter + * @param string $str + * @param string $delimiter * @return string */ public static function slugify(string $str, string $delimiter = '-'): string @@ -272,7 +278,7 @@ public static function slugify(string $str, string $delimiter = '-'): string /** * Alias of un-slugify * - * @param string $str + * @param string $str * @return string */ public static function unSlug(string $str): string @@ -283,7 +289,7 @@ public static function unSlug(string $str): string /** * un-slugify, Lets you undo a slug * - * @param string $str + * @param string $str * @return string */ public static function unSlugify(string $str): string @@ -296,7 +302,7 @@ public static function unSlugify(string $str): string * * eg: example@email.com => true * - * @param string $email + * @param string $email * @return bool */ public static function isMail(string $email): bool @@ -316,7 +322,7 @@ public static function isMail(string $email): bool * eg: http://example.com => true * eg: http:/example.com => false * - * @param string $domain + * @param string $domain * @return bool */ public static function isDomain(string $domain): bool @@ -330,7 +336,7 @@ public static function isDomain(string $domain): bool /** * Check if the string is in alphanumeric * - * @param string $str + * @param string $str * @return bool */ public static function isAlphaNum(string $str): bool @@ -341,7 +347,7 @@ public static function isAlphaNum(string $str): bool /** * Check if the string is in numeric * - * @param string $str + * @param string $str * @return bool */ public static function isNumeric(string $str): bool @@ -352,7 +358,7 @@ public static function isNumeric(string $str): bool /** * Check if the string is in alpha * - * @param string $str + * @param string $str * @return bool */ public static function isAlpha(string $str): bool @@ -363,7 +369,7 @@ public static function isAlpha(string $str): bool /** * Check if the string is in slug format * - * @param string $str + * @param string $str * @return bool */ public static function isSlug(string $str): bool @@ -374,7 +380,7 @@ public static function isSlug(string $str): bool /** * Check if the string is in uppercase * - * @param string $str + * @param string $str * @return bool */ public static function isUpper(string $str): bool @@ -385,7 +391,7 @@ public static function isUpper(string $str): bool /** * upper case * - * @param string $str + * @param string $str * @return string */ public static function upper(string $str): string @@ -396,7 +402,7 @@ public static function upper(string $str): string /** * Check if the string is lowercase * - * @param string $str + * @param string $str * @return bool */ public static function isLower(string $str): bool @@ -407,8 +413,8 @@ public static function isLower(string $str): bool /** * Returns a determined number of words in a string. * - * @param string $words - * @param int $len + * @param string $words + * @param int $len * @return string */ public static function words(string $words, int $len): string @@ -431,7 +437,7 @@ public static function words(string $words, int $len): string /** * Returns a string of words whose words are mixed. * - * @param string $words + * @param string $words * @return string */ public static function shuffleWords(string $words): string @@ -474,7 +480,7 @@ public static function forceInUTF8(): void /** * Enables to force the encoding in utf-8 * - * @param string $garbled_utf8_string + * @param string $garbled_utf8_string * @return string */ public static function fixUTF8(string $garbled_utf8_string): string @@ -485,8 +491,8 @@ public static function fixUTF8(string $garbled_utf8_string): string /** * __call * - * @param string $method - * @param array $arguments + * @param string $method + * @param array $arguments * @return mixed */ public function __call(string $method, array $arguments = []) diff --git a/src/Support/Util.php b/src/Support/Util.php index bb3593aa..527f21f2 100644 --- a/src/Support/Util.php +++ b/src/Support/Util.php @@ -31,7 +31,8 @@ public static function debug(): void $dumper = 'cli' === PHP_SAPI ? new CliDumper() : new HtmlDumper(); - $dumper->setStyles([ + $dumper->setStyles( + [ 'default' => 'background-color:#fff; color:#FF8400; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: normal', @@ -46,7 +47,8 @@ public static function debug(): void 'meta' => 'color:#B729D9', 'key' => 'color:#212', 'index' => 'color:#1200DA', - ]); + ] + ); $handler = function ($vars) use ($cloner, $dumper) { if (!is_array($vars)) { @@ -68,7 +70,7 @@ public static function debug(): void * * @return void */ - #[NoReturn] public static function dd(mixed $var): void + public static function dd(mixed $var): void { call_user_func_array([static::class, 'debug'], func_get_args()); @@ -99,7 +101,7 @@ public static function sep(): string /** * Function to secure the data. * - * @param array $data + * @param array $data * @return string */ public static function rangeField(array $data): string @@ -119,8 +121,8 @@ public static function rangeField(array $data): string /** * Data trainer. key => :value * - * @param array $data - * @param bool $byKey + * @param array $data + * @param bool $byKey * @return array */ public static function add2points(array $data, bool $byKey = false): array diff --git a/src/Support/helpers.php b/src/Support/helpers.php index 7bb49e19..a6d4ff78 100644 --- a/src/Support/helpers.php +++ b/src/Support/helpers.php @@ -49,7 +49,7 @@ * Application container * * @param ?string $key - * @param array $setting + * @param array $setting * @return mixed */ function app(?string $key = null, array $setting = []): mixed @@ -72,8 +72,8 @@ function app(?string $key = null, array $setting = []): mixed /** * Application configuration * - * @param ?string|null $key - * @param mixed|null $setting + * @param ?string|null $key + * @param mixed|null $setting * @return Loader|mixed * @throws */ @@ -131,8 +131,8 @@ function request(): Request /** * Allows to connect to another database and return the instance of the DB * - * @param string|null $name - * @param callable|null $cb + * @param string|null $name + * @param callable|null $cb * @return DB * @throws ConnectionException */ @@ -165,9 +165,9 @@ function db(string $name = null, callable $cb = null): DB /** * View alias of View::parse * - * @param string $template - * @param array|int $data - * @param int $code + * @param string $template + * @param array|int $data + * @param int $code * @return View */ function view(string $template, int|array $data = [], int $code = 200): View @@ -189,10 +189,10 @@ function view(string $template, int|array $data = [], int $code = 200): View /** * Table alias of DB::table * - * @param string $name - * @param ?string $connexion - * @return Bow\Database\QueryBuilder - * @throws ConnectionException + * @param string $name + * @param ?string $connexion + * @return Bow\Database\QueryBuilder + * @throws ConnectionException * @deprecated */ function table(string $name, string $connexion = null): QueryBuilder @@ -210,7 +210,7 @@ function table(string $name, string $connexion = null): QueryBuilder * Returns the last ID following an INSERT query * on a table whose ID is auto_increment. * - * @param string|null $name + * @param string|null $name * @return int */ function get_last_insert_id(string $name = null): int @@ -223,8 +223,8 @@ function get_last_insert_id(string $name = null): int /** * Table alias of DB::table * - * @param string $name - * @param string|null $connexion + * @param string $name + * @param string|null $connexion * @return Bow\Database\QueryBuilder * @throws ConnectionException */ @@ -244,8 +244,8 @@ function db_table(string $name, string $connexion = null): QueryBuilder * * db_select('SELECT * FROM users'); * - * @param string $sql - * @param array $data + * @param string $sql + * @param array $data * @return int|array|stdClass */ function db_select(string $sql, array $data = []): array|int|stdClass @@ -258,8 +258,8 @@ function db_select(string $sql, array $data = []): array|int|stdClass /** * Launches SELECT SQL Queries * - * @param string $sql - * @param array $data + * @param string $sql + * @param array $data * @return int|array|StdClass */ function db_select_one(string $sql, array $data = []): array|int|StdClass @@ -272,8 +272,8 @@ function db_select_one(string $sql, array $data = []): array|int|StdClass /** * Launches INSERT SQL Queries * - * @param string $sql - * @param array $data + * @param string $sql + * @param array $data * @return int */ function db_insert(string $sql, array $data = []): int @@ -286,8 +286,8 @@ function db_insert(string $sql, array $data = []): int /** * Launches DELETE type SQL queries * - * @param string $sql - * @param array $data + * @param string $sql + * @param array $data * @return int */ function db_delete(string $sql, array $data = []): int @@ -300,8 +300,8 @@ function db_delete(string $sql, array $data = []): int /** * Launches UPDATE SQL Queries * - * @param string $sql - * @param array $data + * @param string $sql + * @param array $data * @return int */ function db_update(string $sql, array $data = []): int @@ -314,7 +314,7 @@ function db_update(string $sql, array $data = []): int /** * Launches CREATE TABLE, ALTER TABLE, RENAME, DROP TABLE SQL Query * - * @param string $sql + * @param string $sql * @return int */ function db_statement(string $sql): int @@ -333,9 +333,12 @@ function db_statement(string $sql): int */ function debug(): void { - array_map(function ($x) { - call_user_func_array([Util::class, 'debug'], [$x]); - }, secure(func_get_args())); + array_map( + function ($x) { + call_user_func_array([Util::class, 'debug'], [$x]); + }, + secure(func_get_args()) + ); } } @@ -355,7 +358,7 @@ function sep(): string /** * Create a new token * - * @param int|null $time + * @param int|null $time * @return ?array * @throws SessionException */ @@ -414,7 +417,7 @@ function csrf_field(): string /** * Create hidden http method field * - * @param string $method + * @param string $method * @return string */ function method_field(string $method): string @@ -441,8 +444,8 @@ function gen_csrf_token(): string /** * Check the token value * - * @param string $token - * @param bool $strict + * @param string $token + * @param bool $strict * @return bool * @throws SessionException */ @@ -456,7 +459,7 @@ function verify_csrf(string $token, bool $strict = false): bool /** * Check if token is expired by time * - * @param string|null $time + * @param string|null $time * @return bool * @throws SessionException */ @@ -470,9 +473,9 @@ function csrf_time_is_expired(string $time = null): bool /** * Make json response * - * @param array|object $data - * @param int $code - * @param array $headers + * @param array|object $data + * @param int $code + * @param array $headers * @return string */ function json(array|object $data, int $code = 200, array $headers = []): string @@ -485,9 +488,9 @@ function json(array|object $data, int $code = 200, array $headers = []): string /** * Download file * - * @param string $file - * @param null|string $filename - * @param array $headers + * @param string $file + * @param null|string $filename + * @param array $headers * @return string */ function download(string $file, ?string $filename = null, array $headers = []): string @@ -500,7 +503,7 @@ function download(string $file, ?string $filename = null, array $headers = []): /** * Set status code * - * @param int $code + * @param int $code * @return mixed */ function set_status_code(int $code): mixed @@ -513,7 +516,7 @@ function set_status_code(int $code): mixed /** * Sanitize data * - * @param mixed $data + * @param mixed $data * @return mixed */ function sanitize(mixed $data): mixed @@ -530,7 +533,7 @@ function sanitize(mixed $data): mixed /** * Secure data with sanitize it * - * @param mixed $data + * @param mixed $data * @return mixed */ function secure(mixed $data): mixed @@ -547,8 +550,8 @@ function secure(mixed $data): mixed /** * Update http headers * - * @param string $key - * @param string $value + * @param string $key + * @param string $value * @return void */ function set_header(string $key, string $value): void @@ -561,7 +564,7 @@ function set_header(string $key, string $value): void /** * Get http header * - * @param string $key + * @param string $key * @return string|null */ function get_header(string $key): ?string @@ -574,7 +577,7 @@ function get_header(string $key): ?string /** * Make redirect response * - * @param string|null $path + * @param string|null $path * @return Redirect */ function redirect(string $path = null): Redirect @@ -593,8 +596,8 @@ function redirect(string $path = null): Redirect /** * Build url * - * @param string|array|null $url - * @param array $parameters + * @param string|array|null $url + * @param array $parameters * @return string */ function url(string|array $url = null, array $parameters = []): string @@ -635,7 +638,7 @@ function pdo(): PDO /** * Set PDO instance * - * @param PDO $pdo + * @param PDO $pdo * @return PDO */ function set_pdo(PDO $pdo): PDO @@ -651,7 +654,7 @@ function set_pdo(PDO $pdo): PDO /** * Create new Collection instance * - * @param array $data + * @param array $data * @return Collection */ function collect(array $data = []): Collection @@ -664,7 +667,7 @@ function collect(array $data = []): Collection /** * Encrypt data * - * @param string $data + * @param string $data * @return string */ function encrypt(string $data): string @@ -677,7 +680,7 @@ function encrypt(string $data): string /** * Decrypt data * - * @param string $data + * @param string $data * @return string */ function decrypt(string $data): string @@ -758,8 +761,8 @@ function event(): mixed /** * Flash session * - * @param string $key - * @param string $message + * @param string $key + * @param string $message * @return mixed * @throws SessionException */ @@ -774,9 +777,9 @@ function flash(string $key, string $message): mixed /** * Send email * - * @param null|string $view - * @param array $data - * @param callable|null $cb + * @param null|string $view + * @param array $data + * @param callable|null $cb * @return MailAdapterInterface|bool */ function email( @@ -796,10 +799,10 @@ function email( /** * Send raw email * - * @param string $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 @@ -812,8 +815,8 @@ function raw_email(string $to, string $subject, string $message, array $headers /** * Session help * - * @param array|string|null $value - * @param mixed $default + * @param array|string|null $value + * @param mixed $default * @return mixed * @throws SessionException */ @@ -840,9 +843,9 @@ function session(array|string $value = null, mixed $default = null): mixed /** * Cooke alias * - * @param string|null $key - * @param mixed $data - * @param int $expiration + * @param string|null $key + * @param mixed $data + * @param int $expiration * @return string|array|object|null */ function cookie( @@ -866,9 +869,9 @@ function cookie( /** * Validate the information on the well-defined criterion * - * @param array $inputs - * @param array $rules - * @param array $messages + * @param array $inputs + * @param array $rules + * @param array $messages * @return Validate */ function validator(array $inputs, array $rules, array $messages = []): Validate @@ -881,9 +884,9 @@ function validator(array $inputs, array $rules, array $messages = []): Validate /** * Get Route by name * - * @param string $name - * @param bool|array $data - * @param bool $absolute + * @param string $name + * @param bool|array $data + * @param bool $absolute * @return string */ function route(string $name, bool|array $data = [], bool $absolute = false): string @@ -952,7 +955,7 @@ function e(?string $value = null): string /** * Service loader * - * @param string $service + * @param string $service * @return FTPService|S3Service * @throws ServiceConfigurationNotFoundException * @throws ServiceNotFoundException @@ -967,7 +970,7 @@ function storage_service(string $service): S3Service|FTPService /** * Alias on the mount method * - * @param string $disk + * @param string $disk * @return DiskFilesystemService * @throws DiskNotFoundException */ @@ -982,8 +985,8 @@ 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 */ @@ -1007,7 +1010,7 @@ function cache(string $key = null, mixed $value = null, int $ttl = null): mixed /** * Make redirection to back * - * @param int $status + * @param int $status * @return Redirect */ function redirect_back(int $status = 302): Redirect @@ -1032,8 +1035,8 @@ function app_now(): Carbon /** * Alias on the class Hash. * - * @param string $data - * @param mixed $hash_value + * @param string $data + * @param mixed $hash_value * @return bool|string */ function app_hash(string $data, string $hash_value = null): bool|string @@ -1050,9 +1053,9 @@ function app_hash(string $data, string $hash_value = null): bool|string /** * Alias on the class Hash. * - * @param string $data - * @param mixed $hash_value - * @return bool|string + * @param string $data + * @param mixed $hash_value + * @return bool|string * @deprecated */ function bow_hash(string $data, string $hash_value = null): bool|string @@ -1065,9 +1068,9 @@ function bow_hash(string $data, string $hash_value = null): bool|string /** * Make translation * - * @param string|null $key - * @param array $data - * @param bool $choose + * @param string|null $key + * @param array $data + * @param bool $choose * @return string|Translator */ function app_trans( @@ -1092,9 +1095,9 @@ function app_trans( /** * Alias of trans * - * @param string $key - * @param array $data - * @param bool $choose + * @param string $key + * @param array $data + * @param bool $choose * @return string|Translator */ function t( @@ -1110,9 +1113,9 @@ function t( /** * Alias of trans * - * @param string $key - * @param array $data - * @param bool $choose + * @param string $key + * @param array $data + * @param bool $choose * @return string|Translator */ function __( @@ -1128,8 +1131,8 @@ function __( /** * Gets the app environment variable * - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * @return ?string */ function app_env(string $key, mixed $default = null): ?string @@ -1146,7 +1149,7 @@ function app_env(string $key, mixed $default = null): ?string /** * Gets the app assets * - * @param string $filename + * @param string $filename * @return string */ function app_assets(string $filename): string @@ -1159,8 +1162,8 @@ function app_assets(string $filename): string /** * Abort bow execution * - * @param int $code - * @param string $message + * @param int $code + * @param string $message * @return Response * @throws HttpException */ @@ -1178,9 +1181,9 @@ function app_abort(int $code = 500, string $message = ''): Response /** * Abort bow execution if condition is true * - * @param boolean $boolean - * @param int $code - * @param string $message + * @param boolean $boolean + * @param int $code + * @param string $message * @return Response|null * @throws HttpException */ @@ -1237,8 +1240,8 @@ function client_locale(): string /** * Get old request value * - * @param string $key - * @param mixed $fullback + * @param string $key + * @param mixed $fullback * @return mixed */ function old(string $key, mixed $fullback = null): mixed @@ -1251,9 +1254,9 @@ function old(string $key, mixed $fullback = null): mixed /** * Recovery of the guard * - * @param string|null $guard - * @return GuardContract - * @throws AuthenticationException + * @param string|null $guard + * @return GuardContract + * @throws AuthenticationException * @deprecated */ function auth(string $guard = null): GuardContract @@ -1272,7 +1275,7 @@ function auth(string $guard = null): GuardContract /** * Recovery of the guard * - * @param string|null $guard + * @param string|null $guard * @return GuardContract * @throws AuthenticationException */ @@ -1317,8 +1320,8 @@ function app_logger(): Logger /** * Slugify * - * @param string $str - * @param string $sep + * @param string $str + * @param string $sep * @return string */ function str_slug(string $str, string $sep = '-'): string @@ -1331,7 +1334,7 @@ function str_slug(string $str, string $sep = '-'): string /** * Check if the email is valid * - * @param string $email + * @param string $email * @return bool */ function str_is_mail(string $email): bool @@ -1356,7 +1359,7 @@ function str_uuid(): string /** * Check if the string is domain * - * @param string $domain + * @param string $domain * @return bool * @throws */ @@ -1370,7 +1373,7 @@ function str_is_domain(string $domain): bool /** * Check if string is slug * - * @param string $slug + * @param string $slug * @return string */ function str_is_slug(string $slug): string @@ -1383,7 +1386,7 @@ function str_is_slug(string $slug): string /** * Check if the string is alpha * - * @param string $string + * @param string $string * @return bool * @throws */ @@ -1397,7 +1400,7 @@ function str_is_alpha(string $string): bool /** * Check if the string is lower * - * @param string $string + * @param string $string * @return bool */ function str_is_lower(string $string): bool @@ -1410,7 +1413,7 @@ function str_is_lower(string $string): bool /** * Check if the string is upper * - * @param string $string + * @param string $string * @return bool */ function str_is_upper(string $string): bool @@ -1423,7 +1426,7 @@ function str_is_upper(string $string): bool /** * Check if string is alphanumeric * - * @param string $slug + * @param string $slug * @return bool * @throws */ @@ -1437,7 +1440,7 @@ function str_is_alpha_num(string $slug): bool /** * Shuffle words * - * @param string $words + * @param string $words * @return string */ function str_shuffle_words(string $words): string @@ -1450,8 +1453,8 @@ function str_shuffle_words(string $words): string /** * Return the array contains the word of the passed string * - * @param string $words - * @param string $sep + * @param string $words + * @param string $sep * @return array */ function str_wordily(string $words, string $sep = ''): array @@ -1464,7 +1467,7 @@ function str_wordily(string $words, string $sep = ''): array /** * Transform text to str_plural * - * @param string $slug + * @param string $slug * @return string */ function str_plural(string $slug): string @@ -1477,7 +1480,7 @@ function str_plural(string $slug): string /** * Transform text to camel case * - * @param string $slug + * @param string $slug * @return string */ function str_camel(string $slug): string @@ -1490,7 +1493,7 @@ function str_camel(string $slug): string /** * Transform text to snake case * - * @param string $slug + * @param string $slug * @return string */ function str_snake(string $slug): string @@ -1503,8 +1506,8 @@ function str_snake(string $slug): string /** * Check if string contain another string * - * @param string $search - * @param string $string + * @param string $search + * @param string $string * @return bool */ function str_contains(string $search, string $string): bool @@ -1517,7 +1520,7 @@ function str_contains(string $search, string $string): bool /** * Capitalize * - * @param string $slug + * @param string $slug * @return string */ function str_capitalize(string $slug): string @@ -1530,7 +1533,7 @@ function str_capitalize(string $slug): string /** * Random string * - * @param string $string + * @param string $string * @return string */ function str_random(string $string): string @@ -1555,7 +1558,7 @@ function str_force_in_utf8(): void /** * Force output string to utf8 * - * @param string $string + * @param string $string * @return string */ function str_fix_utf8(string $string): string @@ -1568,8 +1571,8 @@ function str_fix_utf8(string $string): string /** * Make programmatic seeding * - * @param string $name - * @param array $data + * @param string $name + * @param array $data * @return int|array * @throws ErrorException */ @@ -1590,7 +1593,7 @@ function db_seed(string $name, array $data = []): int|array throw new ErrorException('[' . $name . '] seeder file not found'); } - $seeds = require $filename; + $seeds = include $filename; $seeds = array_merge($seeds, []); $collections = []; @@ -1613,7 +1616,7 @@ function db_seed(string $name, array $data = []): int|array /** * Determine if the given value is "blank". * - * @param mixed $value + * @param mixed $value * @return bool */ function is_blank(mixed $value): bool diff --git a/src/Testing/Features/FeatureHelper.php b/src/Testing/Features/FeatureHelper.php index a306a9fb..22c37889 100644 --- a/src/Testing/Features/FeatureHelper.php +++ b/src/Testing/Features/FeatureHelper.php @@ -12,7 +12,7 @@ trait FeatureHelper /** * Get fake instance * - * @see https://github.com/fzaninotto/Faker for all documentation + * @see https://github.com/fzaninotto/Faker for all documentation * @return Generator */ public function faker(): Generator diff --git a/src/Testing/Features/SeedingHelper.php b/src/Testing/Features/SeedingHelper.php index 40db63ef..a98754d3 100644 --- a/src/Testing/Features/SeedingHelper.php +++ b/src/Testing/Features/SeedingHelper.php @@ -11,8 +11,8 @@ trait SeedingHelper /** * Seed alias * - * @param string $seeder - * @param array $data + * @param string $seeder + * @param array $data * @return int * @throws ErrorException */ diff --git a/src/Testing/KernelTesting.php b/src/Testing/KernelTesting.php index 9badc418..5381d7fb 100644 --- a/src/Testing/KernelTesting.php +++ b/src/Testing/KernelTesting.php @@ -13,7 +13,7 @@ class KernelTesting extends ConfigurationLoader /** * Set the loading configuration * - * @param array $configurations + * @param array $configurations * @return void */ public static function withConfigurations(array $configurations): void @@ -24,7 +24,7 @@ public static function withConfigurations(array $configurations): void /** * Set the loading events * - * @param array $events + * @param array $events * @return void */ public static function withEvents(array $events): void @@ -35,7 +35,7 @@ public static function withEvents(array $events): void /** * Set the loading middlewares * - * @param array $middlewares + * @param array $middlewares * @return void */ public static function withMiddlewares(array $middlewares): void diff --git a/src/Testing/Response.php b/src/Testing/Response.php index 03a54635..b42eea97 100644 --- a/src/Testing/Response.php +++ b/src/Testing/Response.php @@ -49,7 +49,7 @@ public function getContent(): string /** * Check if the content is json format * - * @param string $message + * @param string $message * @return Response */ public function assertJson(string $message = ''): Response @@ -63,8 +63,8 @@ public function assertJson(string $message = ''): Response * Check if the content is json format and the parsed data is * some to the content * - * @param array $data - * @param string $message + * @param array $data + * @param string $message * @return Response */ public function assertExactJson(array $data, string $message = ''): Response @@ -214,8 +214,8 @@ public function assertContentTypeXml(string $message = ''): Response /** * Check the status code * - * @param int $code - * @param string $message + * @param int $code + * @param string $message * @return Response */ public function assertStatus(int $code, string $message = ''): Response @@ -226,8 +226,8 @@ public function assertStatus(int $code, string $message = ''): Response } /** - * @param string $key - * @param string $message + * @param string $key + * @param string $message * @return Response */ public function assertKeyExists(string $key, string $message = ''): Response @@ -241,8 +241,8 @@ public function assertKeyExists(string $key, string $message = ''): Response /** * @param string|int $key - * @param string $value - * @param string $message + * @param string $value + * @param string $message * * @return Response */ @@ -262,7 +262,7 @@ public function assertKeyMatchValue(string|int $key, mixed $value, string $messa /** * Check if the content contains the parsed text * - * @param string $text + * @param string $text * @return Response */ public function assertContains(string $text): Response @@ -275,8 +275,8 @@ public function assertContains(string $text): Response /** * __call * - * @param string $method - * @param array $params + * @param string $method + * @param array $params * @return mixed */ public function __call(string $method, array $params = []) diff --git a/src/Testing/TestCase.php b/src/Testing/TestCase.php index d0a7106a..5189f4b9 100644 --- a/src/Testing/TestCase.php +++ b/src/Testing/TestCase.php @@ -33,7 +33,7 @@ class TestCase extends PHPUnitTestCase /** * Add attachment * - * @param array $attach + * @param array $attach * @return TestCase */ public function attach(array $attach): TestCase @@ -46,7 +46,7 @@ public function attach(array $attach): TestCase /** * Specify the additional headers * - * @param array $headers + * @param array $headers * @return TestCase */ public function withHeaders(array $headers): TestCase @@ -59,8 +59,8 @@ public function withHeaders(array $headers): TestCase /** * Specify the additional header * - * @param string $key - * @param string $value + * @param string $key + * @param string $value * @return TestCase */ public function withHeader(string $key, string $value): TestCase @@ -73,8 +73,8 @@ public function withHeader(string $key, string $value): TestCase /** * Get request * - * @param string $url - * @param array $param + * @param string $url + * @param array $param * @return Response * @throws Exception */ @@ -100,8 +100,8 @@ private function getBaseUrl(): string /** * Post Request * - * @param string $url - * @param array $param + * @param string $url + * @param array $param * @return Response * @throws Exception */ @@ -121,16 +121,19 @@ public function post(string $url, array $param = []): Response /** * Delete Request * - * @param string $url - * @param array $param + * @param string $url + * @param array $param * @return Response * @throws Exception */ public function delete(string $url, array $param = []): Response { - $param = array_merge([ + $param = array_merge( + [ '_method' => 'DELETE' - ], $param); + ], + $param + ); return $this->put($url, $param); } @@ -138,8 +141,8 @@ public function delete(string $url, array $param = []): Response /** * Put Request * - * @param string $url - * @param array $param + * @param string $url + * @param array $param * @return Response * @throws Exception */ @@ -155,16 +158,19 @@ public function put(string $url, array $param = []): Response /** * Patch Request * - * @param string $url - * @param array $param + * @param string $url + * @param array $param * @return Response * @throws Exception */ public function patch(string $url, array $param = []): Response { - $param = array_merge([ + $param = array_merge( + [ '_method' => 'PATCH' - ], $param); + ], + $param + ); return $this->put($url, $param); } @@ -172,9 +178,9 @@ public function patch(string $url, array $param = []): Response /** * Initialize Response action * - * @param string $method - * @param string $url - * @param array $params + * @param string $method + * @param string $url + * @param array $params * @return Response */ public function visit(string $method, string $url, array $params = []): Response diff --git a/src/Translate/Translator.php b/src/Translate/Translator.php index a26a7b58..a9021f43 100644 --- a/src/Translate/Translator.php +++ b/src/Translate/Translator.php @@ -36,7 +36,7 @@ class Translator * * @param string $lang * @param string $directory - * @param bool $auto_detected + * @param bool $auto_detected */ public function __construct(string $lang, string $directory, bool $auto_detected = false) { @@ -96,7 +96,7 @@ public static function isLocale(string $locale): bool * Make singleton translation * * @param string $key - * @param array $data + * @param array $data * * @return string */ @@ -109,8 +109,8 @@ public static function single(string $key, array $data = []): string * Allows translation * * @param string $key - * @param array $data - * @param bool $plural + * @param array $data + * @param bool $plural * * @return string */ @@ -128,7 +128,7 @@ public static function translate(string $key, array $data = [], bool $plural = f return $key; } - $contents = require $translation_filename; + $contents = include $translation_filename; if (!is_array($contents)) { return $key; @@ -163,8 +163,8 @@ public static function translate(string $key, array $data = [], bool $plural = f /** * Str formatter * - * @param string $str - * @param array $values + * @param string $str + * @param array $values * @return string */ private static function format(string $str, array $values = []): string @@ -182,8 +182,8 @@ private static function format(string $str, array $values = []): string /** * Make plural translation * - * @param string $key - * @param array $data + * @param string $key + * @param array $data * @return string */ public static function plural(string $key, array $data = []): string @@ -214,8 +214,8 @@ public static function getLocale(): string /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return string */ public function __call(string $name, array $arguments) diff --git a/src/Translate/TranslatorConfiguration.php b/src/Translate/TranslatorConfiguration.php index 8130d656..54bde04f 100644 --- a/src/Translate/TranslatorConfiguration.php +++ b/src/Translate/TranslatorConfiguration.php @@ -14,22 +14,25 @@ class TranslatorConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('translate', function () use ($config) { - $auto_detected = $config['translate.auto_detected'] ?? false; - $lang = $config['translate.lang']; - $dictionary = $config['translate.dictionary']; + $this->container->bind( + 'translate', + function () use ($config) { + $auto_detected = $config['translate.auto_detected'] ?? false; + $lang = $config['translate.lang']; + $dictionary = $config['translate.dictionary']; - if ($auto_detected) { - $lang = app("request")->lang(); - if (is_string($lang)) { - $lang = strtolower($lang); - } else { - $lang = $config['translate.lang']; + if ($auto_detected) { + $lang = app("request")->lang(); + if (is_string($lang)) { + $lang = strtolower($lang); + } else { + $lang = $config['translate.lang']; + } } - } - return Translator::configure($lang, $dictionary); - }); + return Translator::configure($lang, $dictionary); + } + ); } /** diff --git a/src/Validation/Exception/ValidationException.php b/src/Validation/Exception/ValidationException.php index af43179e..fca41615 100644 --- a/src/Validation/Exception/ValidationException.php +++ b/src/Validation/Exception/ValidationException.php @@ -19,7 +19,7 @@ class ValidationException extends HttpException * ValidationException constructor * * @param string $message - * @param array $errors + * @param array $errors * @param string $status */ public function __construct( diff --git a/src/Validation/FieldLexical.php b/src/Validation/FieldLexical.php index 7136bce8..fe1144a0 100644 --- a/src/Validation/FieldLexical.php +++ b/src/Validation/FieldLexical.php @@ -11,8 +11,8 @@ trait FieldLexical /** * Get error debugging information * - * @param string $key - * @param string|array|int|float $value + * @param string $key + * @param string|array|int|float $value * @return ?string */ private function lexical(string $key, string|array|int|float $value): ?string @@ -48,8 +48,8 @@ private function lexical(string $key, string|array|int|float $value): ?string /** * Normalize beneficiaries * - * @param array $attribute - * @param string $lexical + * @param array $attribute + * @param string $lexical * @return string */ private function parseAttribute(array $attribute, string $lexical): ?string @@ -67,8 +67,8 @@ private function parseAttribute(array $attribute, string $lexical): ?string /** * Parse the translate content * - * @param string $key - * @param array $data + * @param string $key + * @param array $data * @return string */ private function parseFromTranslate(string $key, array $data) diff --git a/src/Validation/RequestValidation.php b/src/Validation/RequestValidation.php index a12d962b..3f54ff3f 100644 --- a/src/Validation/RequestValidation.php +++ b/src/Validation/RequestValidation.php @@ -164,8 +164,8 @@ protected function throwError(): void /** * __call * - * @param string $name - * @param array $arguments + * @param string $name + * @param array $arguments * @return Request */ public function __call(string $name, array $arguments) @@ -182,7 +182,7 @@ public function __call(string $name, array $arguments) /** * __get * - * @param string $name + * @param string $name * @return string */ public function __get(string $name) diff --git a/src/Validation/Rules/DatabaseRule.php b/src/Validation/Rules/DatabaseRule.php index 5c9d756e..dcbcf77c 100644 --- a/src/Validation/Rules/DatabaseRule.php +++ b/src/Validation/Rules/DatabaseRule.php @@ -14,8 +14,8 @@ trait DatabaseRule * * [exists:table,column] Check that the contents of a table field exist * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void * @throws QueryBuilderException */ @@ -30,9 +30,9 @@ protected function compileExists(string $key, string $masque): void $exists = count($parts) == 1 ? Database::table($parts[0]) - ->where($key, $this->inputs[$key])->exists() + ->where($key, $this->inputs[$key])->exists() : Database::table($parts[0]) - ->where($parts[1], $this->inputs[$key])->exists(); + ->where($parts[1], $this->inputs[$key])->exists(); if (!$exists) { $this->last_message = $this->lexical('exists', $key); @@ -51,8 +51,8 @@ protected function compileExists(string $key, string $masque): void * * [!exists:table,column] Checks that the contents of the field of a table do not exist * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void * @throws QueryBuilderException */ @@ -67,9 +67,9 @@ protected function compileNotExists(string $key, string $masque): void $exists = count($parts) == 1 ? Database::table($parts[0]) - ->where($key, $this->inputs[$key])->exists() + ->where($key, $this->inputs[$key])->exists() : Database::table($parts[0]) - ->where($parts[1], $this->inputs[$key])->exists(); + ->where($parts[1], $this->inputs[$key])->exists(); if ($exists) { $this->last_message = $this->lexical('not_exists', $key); @@ -88,8 +88,8 @@ protected function compileNotExists(string $key, string $masque): void * * [unique:table,column] Check that the contents of the field of a table is a single value * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void * @throws QueryBuilderException */ diff --git a/src/Validation/Rules/DatetimeRule.php b/src/Validation/Rules/DatetimeRule.php index b549116f..0fbee3f5 100644 --- a/src/Validation/Rules/DatetimeRule.php +++ b/src/Validation/Rules/DatetimeRule.php @@ -11,8 +11,8 @@ trait DatetimeRule * * [date] Check that the field's content is a valid date * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileDate(string $key, string $masque): void @@ -40,8 +40,8 @@ protected function compileDate(string $key, string $masque): void * * [datetime] Check that the contents of the field is a valid date time * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileDateTime(string $key, string $masque): void diff --git a/src/Validation/Rules/EmailRule.php b/src/Validation/Rules/EmailRule.php index 55c81912..9bd0e6a8 100644 --- a/src/Validation/Rules/EmailRule.php +++ b/src/Validation/Rules/EmailRule.php @@ -13,8 +13,8 @@ trait EmailRule * * [email] Check that the content of the field is an email * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileEmail(string $key, string $masque): void diff --git a/src/Validation/Rules/NumericRule.php b/src/Validation/Rules/NumericRule.php index 82b1d784..05bd3729 100644 --- a/src/Validation/Rules/NumericRule.php +++ b/src/Validation/Rules/NumericRule.php @@ -11,8 +11,8 @@ trait NumericRule * * [number] Check that the contents of the field is a number * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileNumber(string $key, string $masque): void @@ -40,8 +40,8 @@ protected function compileNumber(string $key, string $masque): void * * [int] Check that the contents of the field is an integer number * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileInt(string $key, string $masque): void @@ -69,8 +69,8 @@ protected function compileInt(string $key, string $masque): void * * [float] Check that the field content is a float number * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileFloat(string $key, string $masque): void diff --git a/src/Validation/Rules/RegexRule.php b/src/Validation/Rules/RegexRule.php index 7dba3168..7e1f3cb1 100644 --- a/src/Validation/Rules/RegexRule.php +++ b/src/Validation/Rules/RegexRule.php @@ -11,8 +11,8 @@ trait RegexRule * * Check that the contents of the field with a regular expression * - * @param string $key - * @param string|int|float $masque + * @param string $key + * @param string|int|float $masque * @return void */ protected function compileRegex(string $key, string|int|float $masque): void diff --git a/src/Validation/Rules/StringRule.php b/src/Validation/Rules/StringRule.php index fea39024..1fe6b97a 100644 --- a/src/Validation/Rules/StringRule.php +++ b/src/Validation/Rules/StringRule.php @@ -12,8 +12,8 @@ trait StringRule /** * Compile Required Rule * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileRequired(string $key, string $masque): void @@ -47,8 +47,8 @@ protected function compileRequired(string $key, string $masque): void /** * Compile Required Rule * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void * @throws ValidationException */ @@ -99,8 +99,8 @@ protected function compileRequiredIf(string $key, string $masque): void /** * Compile Empty Rule * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileEmpty(string $key, string $masque): void @@ -122,8 +122,8 @@ protected function compileEmpty(string $key, string $masque): void * * [alphanum] Check that the field content is an alphanumeric string * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileAlphaNum(string $key, string $masque): void @@ -151,8 +151,8 @@ protected function compileAlphaNum(string $key, string $masque): void * * [in:(value, ...)] Check that the contents of the field are equal to the defined value * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileIn(string $key, string $masque): void @@ -171,10 +171,13 @@ protected function compileIn(string $key, string $masque): void return; } - $this->last_message = $this->lexical('in', [ + $this->last_message = $this->lexical( + 'in', + [ 'attribute' => $key, 'value' => implode(", ", $values) - ]); + ] + ); $this->fails = true; @@ -190,8 +193,8 @@ protected function compileIn(string $key, string $masque): void * [size:value] Check that the contents of the field is a number * of character equal to the defined value * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileSize(string $key, string $masque): void @@ -208,10 +211,13 @@ protected function compileSize(string $key, string $masque): void $this->fails = true; - $this->last_message = $this->lexical('size', [ + $this->last_message = $this->lexical( + 'size', + [ 'attribute' => $key, 'length' => $length - ]); + ] + ); $this->errors[$key][] = [ "masque" => $masque, @@ -224,8 +230,8 @@ protected function compileSize(string $key, string $masque): void * * [lower] Check that the content of the field is a string in miniscule * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileLower(string $key, string $masque): void @@ -253,8 +259,8 @@ protected function compileLower(string $key, string $masque): void * * [upper] Check that the contents of the field is a string in uppercase * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileUpper(string $key, string $masque): void @@ -282,8 +288,8 @@ protected function compileUpper(string $key, string $masque): void * * [alpha] Check that the field content is an alpha * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileAlpha(string $key, string $masque): void @@ -312,8 +318,8 @@ protected function compileAlpha(string $key, string $masque): void * [min:value] Check that the content of the field is a number of * minimal character following the defined value * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileMin(string $key, string $masque): void @@ -330,10 +336,13 @@ protected function compileMin(string $key, string $masque): void $this->fails = true; - $this->last_message = $this->lexical('min', [ + $this->last_message = $this->lexical( + 'min', + [ 'attribute' => $key, 'length' => $length - ]); + ] + ); $this->errors[$key][] = [ "masque" => $masque, @@ -347,8 +356,8 @@ protected function compileMin(string $key, string $masque): void * [max:value] Check that the content of the field is a number of * maximum character following the defined value * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileMax(string $key, string $masque): void @@ -365,10 +374,13 @@ protected function compileMax(string $key, string $masque): void $this->fails = true; - $this->last_message = $this->lexical('max', [ + $this->last_message = $this->lexical( + 'max', + [ 'attribute' => $key, 'length' => $length - ]); + ] + ); $this->errors[$key][] = [ "masque" => $masque, @@ -381,8 +393,8 @@ protected function compileMax(string $key, string $masque): void * * [same:value] Check that the field contents are equal to the mask value * - * @param string $key - * @param string $masque + * @param string $key + * @param string $masque * @return void */ protected function compileSame(string $key, string $masque): void @@ -397,10 +409,13 @@ protected function compileSame(string $key, string $masque): void return; } - $this->last_message = $this->lexical('same', [ + $this->last_message = $this->lexical( + 'same', + [ 'attribute' => $key, 'value' => $value - ]); + ] + ); $this->fails = true; $this->errors[$key][] = [ diff --git a/src/Validation/Validate.php b/src/Validation/Validate.php index 105e60af..63827577 100644 --- a/src/Validation/Validate.php +++ b/src/Validation/Validate.php @@ -46,9 +46,9 @@ class Validate /** * Validate constructor. * - * @param bool $fails + * @param bool $fails * @param ?string $message - * @param array $corrupted_fields + * @param array $corrupted_fields * * @return void */ diff --git a/src/Validation/Validator.php b/src/Validation/Validator.php index 63ab0a4d..8b3fe593 100644 --- a/src/Validation/Validator.php +++ b/src/Validation/Validator.php @@ -100,7 +100,7 @@ class Validator */ public function __construct() { - $this->lexical = require __DIR__ . '/stubs/lexical.php'; + $this->lexical = include __DIR__ . '/stubs/lexical.php'; } /** diff --git a/src/View/Engine/PHPEngine.php b/src/View/Engine/PHPEngine.php index 4636d4b0..f9ad622c 100644 --- a/src/View/Engine/PHPEngine.php +++ b/src/View/Engine/PHPEngine.php @@ -19,7 +19,7 @@ class PHPEngine extends EngineAbstract /** * PHPEngine constructor. * - * @param array $config + * @param array $config * @return void */ public function __construct(array $config) @@ -65,14 +65,14 @@ public function render(string $filename, array $data = []): string /** * include the execute filename * - * @param string $filename + * @param string $filename * @return string */ private function includeFile(string $filename): string { ob_start(); - require $filename; + include $filename; return ob_get_clean(); } diff --git a/src/View/Engine/TwigEngine.php b/src/View/Engine/TwigEngine.php index f57beead..dd06ff44 100644 --- a/src/View/Engine/TwigEngine.php +++ b/src/View/Engine/TwigEngine.php @@ -29,7 +29,7 @@ class TwigEngine extends EngineAbstract /** * TwigEngine constructor. * - * @param array $config + * @param array $config * @return Environment * @throws ApplicationException */ diff --git a/src/View/EngineAbstract.php b/src/View/EngineAbstract.php index 588053ae..56844cc7 100644 --- a/src/View/EngineAbstract.php +++ b/src/View/EngineAbstract.php @@ -67,7 +67,7 @@ abstract class EngineAbstract * Make template rendering * * @param string $filename - * @param array $data + * @param array $data * * @return string */ @@ -93,7 +93,7 @@ public function getName(): string /** * Check if the define file exists * - * @param string $filename + * @param string $filename * @return bool */ public function fileExists(string $filename): bool @@ -106,7 +106,7 @@ public function fileExists(string $filename): bool /** * Normalize the file * - * @param string $filename + * @param string $filename * @return string */ private function normalizeFilename(string $filename): string @@ -117,8 +117,8 @@ private function normalizeFilename(string $filename): string /** * Check the parsed file * - * @param string $filename - * @param bool $extended + * @param string $filename + * @param bool $extended * @return string * @throws ViewException */ diff --git a/src/View/View.php b/src/View/View.php index 375c2591..25eb1542 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -57,8 +57,8 @@ class View implements ResponseInterface /** * View constructor. * - * @param array $config - * @return void + * @param array $config + * @return void * @throws ViewException */ public function __construct(array $config) @@ -87,7 +87,7 @@ public function __construct(array $config) /** * Load view configuration * - * @param array $config + * @param array $config * @return void */ public static function configure(array $config): void @@ -98,8 +98,8 @@ public static function configure(array $config): void /** * Parse the view * - * @param string $viewname - * @param array $data + * @param string $viewname + * @param array $data * @return View */ public static function parse(string $view, array $data = []): View @@ -139,8 +139,8 @@ public static function getInstance(): View /** * Add a template engine * - * @param string $name - * @param string $engine + * @param string $name + * @param string $engine * @return bool * @throws ViewException */ @@ -165,7 +165,7 @@ public static function pushEngine(string $name, string $engine): bool * __callStatic * * @param string $name - * @param array $arguments + * @param array $arguments * * @return mixed */ @@ -198,7 +198,7 @@ public function getEngine(): Environment|Tintin /** * Set Engine * - * @param string $engine + * @param string $engine * @return View */ public function setEngine(string $engine): View @@ -211,7 +211,7 @@ public function setEngine(string $engine): View } /** - * @param string $extension + * @param string $extension * @return View */ public function setExtension(string $extension): View @@ -248,7 +248,7 @@ public function sendContent(): void /** * Check if the define file exists * - * @param string $filename + * @param string $filename * @return bool */ public function fileExists(string $filename): bool @@ -270,7 +270,7 @@ public function __toString() * __call * * @param string $method - * @param array $arguments + * @param array $arguments * * @return mixed */ diff --git a/src/View/ViewConfiguration.php b/src/View/ViewConfiguration.php index 507a47cf..64376d5b 100644 --- a/src/View/ViewConfiguration.php +++ b/src/View/ViewConfiguration.php @@ -14,11 +14,14 @@ class ViewConfiguration extends Configuration */ public function create(Loader $config): void { - $this->container->bind('view', function () use ($config) { - View::configure($config["view"]); + $this->container->bind( + 'view', + function () use ($config) { + View::configure($config["view"]); - return View::getInstance(); - }); + return View::getInstance(); + } + ); } /** diff --git a/tests/Application/ApplicationTest.php b/tests/Application/ApplicationTest.php index 0f9602dc..e008ce54 100644 --- a/tests/Application/ApplicationTest.php +++ b/tests/Application/ApplicationTest.php @@ -4,6 +4,7 @@ use Bow\Application\Application; use Bow\Container\Capsule; +use Bow\Http\Exception\BadRequestException; use Bow\Http\Request; use Bow\Http\Response; use Bow\Router\Exception\RouterException; @@ -87,6 +88,11 @@ public function test_send_application_with_404_status() $app->send(); } + /** + * @throws BadRequestException + * @throws \ReflectionException + * @throws RouterException + */ public function test_send_application_with_matched_route() { $response = Mockery::mock(Response::class); diff --git a/tests/Database/Query/ModelQueryTest.php b/tests/Database/Query/ModelQueryTest.php index af26f2cd..73872598 100644 --- a/tests/Database/Query/ModelQueryTest.php +++ b/tests/Database/Query/ModelQueryTest.php @@ -147,6 +147,7 @@ public function test_insert_by_create_method(string $name) $next_id = PetModelStub::all()->count() + 1; $insert_result = PetModelStub::create(['name' => 'Tor']); + $insert_result->persist(); $select_result = PetModelStub::retrieveBy('id', $next_id)->first(); $this->assertInstanceOf(PetModelStub::class, $insert_result); diff --git a/tests/Messaging/MessagingTest.php b/tests/Messaging/MessagingTest.php index 90f6fa89..840636b5 100644 --- a/tests/Messaging/MessagingTest.php +++ b/tests/Messaging/MessagingTest.php @@ -2,14 +2,15 @@ namespace Bow\Tests\Messaging; -use Bow\Database\Barry\Model; +use Bow\View\View; use Bow\Mail\Envelop; +use Bow\Database\Database; +use Bow\Database\Barry\Model; +use PHPUnit\Framework\TestCase; use Bow\Tests\Config\TestingConfiguration; use Bow\Tests\Messaging\Stubs\TestMessage; -use Bow\Tests\Messaging\Stubs\TestNotifiableModel; -use Bow\View\View; use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; +use Bow\Tests\Messaging\Stubs\TestNotifiableModel; class MessagingTest extends TestCase { @@ -22,6 +23,7 @@ public static function setUpBeforeClass(): void // Initialize queue connection $config = TestingConfiguration::getConfig(); + Database::configure($config["database"]); View::configure($config["view"]); } diff --git a/tests/Queue/EventQueueTest.php b/tests/Queue/EventQueueTest.php index 481b85b1..8b574cf7 100644 --- a/tests/Queue/EventQueueTest.php +++ b/tests/Queue/EventQueueTest.php @@ -18,7 +18,7 @@ class EventQueueTest extends TestCase { - private static $connection; + private static Connection $connection; public static function setUpBeforeClass(): void { diff --git a/tests/Queue/QueueTest.php b/tests/Queue/QueueTest.php index dbbec331..90d3ee81 100644 --- a/tests/Queue/QueueTest.php +++ b/tests/Queue/QueueTest.php @@ -81,7 +81,7 @@ public function test_instance_of_adapter($connection) * @param string $connection * @return void */ - public function test_push_service_adapter($connection) + public function test_push_service_adapter(string $connection) { $adapter = static::$connection->setConnection($connection)->getAdapter(); $filename = TESTING_RESOURCE_BASE_DIRECTORY . "/{$connection}_producer.txt"; diff --git a/tests/Support/stubs/env.json b/tests/Support/stubs/env.json index 14108d3d..568af09e 100644 --- a/tests/Support/stubs/env.json +++ b/tests/Support/stubs/env.json @@ -1,3 +1,7 @@ { - "APP_NAME": "papac" + "APP_NAME": "papac", + "API": { + "URL": "https://localhost:8000", + "KEY": "key" + } } diff --git a/tests/Translate/TranslationTest.php b/tests/Translate/TranslationTest.php index a31fd938..a47a98b4 100644 --- a/tests/Translate/TranslationTest.php +++ b/tests/Translate/TranslationTest.php @@ -15,7 +15,7 @@ public static function setUpBeforeClass(): void public function test_fr_welcome_message() { - $this->assertEquals(Translator::translate('welcome.message'), 'bow framework'); + $this->assertEquals(Translator::translate('welcome.message'), 'Bow framework'); } public function test_fr_user_name() @@ -47,7 +47,7 @@ public function test_en_welcome_message() public function test_en_user_name() { Translator::setLocale("en"); - $this->assertEquals(Translator::translate('welcome.user.name'), 'Frank'); + $this->assertEquals(Translator::translate('welcome.user.name'), 'Franck'); } public function test_en_plurial() diff --git a/tests/Translate/stubs/en/welcome.php b/tests/Translate/stubs/en/welcome.php index 2de162ba..74d33c4d 100644 --- a/tests/Translate/stubs/en/welcome.php +++ b/tests/Translate/stubs/en/welcome.php @@ -3,7 +3,7 @@ return [ 'message' => 'Bow framework', 'user' => [ - 'name' => 'Frank' + 'name' => 'Franck' ], 'plurial' => 'User|Users', 'hello' => 'Hello {name}' diff --git a/tests/Translate/stubs/fr/welcome.php b/tests/Translate/stubs/fr/welcome.php index 31472021..8265bb62 100644 --- a/tests/Translate/stubs/fr/welcome.php +++ b/tests/Translate/stubs/fr/welcome.php @@ -1,7 +1,7 @@ 'bow framework', + 'message' => 'Bow framework', 'user' => [ 'name' => 'Franck' ],