diff --git a/.github/workflows/fix-php-code-style-issues.yml b/.github/workflows/fix-php-code-style-issues.yml index 584be23..f38f8aa 100644 --- a/.github/workflows/fix-php-code-style-issues.yml +++ b/.github/workflows/fix-php-code-style-issues.yml @@ -1,6 +1,12 @@ name: Check & fix styling -on: [push] +on: + push: + branches: + - 'main' + pull_request: + branches: + - 'main' permissions: contents: write @@ -15,12 +21,13 @@ jobs: with: ref: ${{ github.head_ref }} - - name: Run PHP CS Fixer - uses: docker://oskarstark/php-cs-fixer-ga - with: - args: --config=.php-cs-fixer.dist.php --allow-risky=yes + - name: Install Composer packages + run: composer update --ansi --no-interaction + + - name: Run PHP-CS-Fixer Lint + run: vendor/bin/php-cs-fixer fix - name: Commit changes uses: stefanzweifel/git-auto-commit-action@v5 with: - commit_message: Fix styling \ No newline at end of file + commit_message: Fix styling diff --git a/phpstan-baseline.php b/phpstan-baseline.php index 3512857..f2c5285 100644 --- a/phpstan-baseline.php +++ b/phpstan-baseline.php @@ -19,6 +19,24 @@ 'count' => 1, 'path' => __DIR__ . '/src/Commands/Run.php', ]; +$ignoreErrors[] = [ + 'message' => '#^Cannot call method startOfMinute\\(\\) on BlitzPHP\\\\Utilities\\\\Date\\|string\\.$#', + 'identifier' => 'method.nonObject', + 'count' => 2, + 'path' => __DIR__ . '/src/Commands/Work.php', +]; +$ignoreErrors[] = [ + 'message' => '#^While loop condition is always true\\.$#', + 'identifier' => 'while.alwaysTrue', + 'count' => 1, + 'path' => __DIR__ . '/src/Commands/Work.php', +]; +$ignoreErrors[] = [ + 'message' => '#^Parameter \\#1 \\$name of function service expects class\\-string\\, string given\\.$#', + 'identifier' => 'argument.type', + 'count' => 1, + 'path' => __DIR__ . '/src/Task.php', +]; $ignoreErrors[] = [ 'message' => '#^Parameter \\#1 \\$name of function service expects class\\-string\\, string given\\.$#', 'identifier' => 'argument.type', diff --git a/spec/FrequenciesTrait.spec.php b/spec/FrequenciesTrait.spec.php index 671df7c..0d89870 100644 --- a/spec/FrequenciesTrait.spec.php +++ b/spec/FrequenciesTrait.spec.php @@ -44,10 +44,10 @@ $this->class->daily('4:08 pm'); expect('08 16 * * *')->toBe($this->class->getExpression()); - $this->class->at('4:08 pm'); + $this->class->at('4:08 pm'); expect('08 16 * * *')->toBe($this->class->getExpression()); - $this->class->at('04:28'); + $this->class->at('04:28'); expect('28 4 * * *')->toBe($this->class->getExpression()); }); @@ -241,16 +241,16 @@ $this->class->everyHour(3); $this->assertSame('0 */3 * * *', $this->class->getExpression()); - $this->class->everyTwoHours(); + $this->class->everyTwoHours(); $this->assertSame('0 */2 * * *', $this->class->getExpression()); - $this->class->everyThreeHours(); + $this->class->everyThreeHours(); $this->assertSame('0 */3 * * *', $this->class->getExpression()); - $this->class->everyFourHours(); + $this->class->everyFourHours(); $this->assertSame('0 */4 * * *', $this->class->getExpression()); - $this->class->everySixHours(); + $this->class->everySixHours(); $this->assertSame('0 */6 * * *', $this->class->getExpression()); }); @@ -300,19 +300,19 @@ $this->class->everyMinute(15); $this->assertSame('*/15 * * * *', $this->class->getExpression()); - $this->class->everyTwoMinutes(); + $this->class->everyTwoMinutes(); $this->assertSame('*/2 * * * *', $this->class->getExpression()); - $this->class->everyThreeMinutes(); + $this->class->everyThreeMinutes(); $this->assertSame('*/3 * * * *', $this->class->getExpression()); - $this->class->everyFourMinutes(); + $this->class->everyFourMinutes(); $this->assertSame('*/4 * * * *', $this->class->getExpression()); - $this->class->everyTenMinutes(); + $this->class->everyTenMinutes(); $this->assertSame('*/10 * * * *', $this->class->getExpression()); - $this->class->everyThirtyMinutes(); + $this->class->everyThirtyMinutes(); $this->assertSame('*/30 * * * *', $this->class->getExpression()); }); @@ -340,9 +340,9 @@ $this->assertSame('* * 1,15 * *', $this->class->getExpression()); }); - it('testLastDayOfMonth', function () { + it('testLastDayOfMonth', function () { $this->class->lastDayOfMonth(); - $lastDay = Date::now()->endOfMonth()->getDay(); + $lastDay = Date::now()->endOfMonth()->getDay(); $this->assertSame('0 0 ' . $lastDay . ' * *', $this->class->getExpression()); }); @@ -359,7 +359,7 @@ $this->assertSame('* * * 1-7 *', $this->class->getExpression()); }); - it('testBetween', function () { + it('testBetween', function () { $this->class->between('10:00', '12:30'); $this->assertSame('0-30 10-12 * * *', $this->class->getExpression()); diff --git a/spec/HooksTrait.spec.php b/spec/HooksTrait.spec.php index 9a2aca6..c7c0c67 100644 --- a/spec/HooksTrait.spec.php +++ b/spec/HooksTrait.spec.php @@ -15,37 +15,37 @@ describe('HookTrait', function () { it('testAfter et testBefore', function () { - expect(file_exists($path = __DIR__.'/test-hook.txt'))->toBeFalsy(); + expect(file_exists($path = __DIR__ . '/test-hook.txt'))->toBeFalsy(); - $task = new Task('closure', fn() => 'Hello'); - $task->before(function() use($path) { - file_put_contents($path, 'before'); - }); + $task = new Task('closure', fn () => 'Hello'); + $task->before(function () use ($path) { + file_put_contents($path, 'before'); + }); - $task->after(function() use($path) { - file_put_contents($path, 'after', FILE_APPEND); - }); + $task->after(function () use ($path) { + file_put_contents($path, 'after', FILE_APPEND); + }); - $result = $task->run(); + $result = $task->run(); - expect(file_exists($path))->toBeTruthy(); - $content = file_get_contents($path); + expect(file_exists($path))->toBeTruthy(); + $content = file_get_contents($path); - expect(str_contains($content, 'before'))->toBeTruthy(); - expect(str_contains($content, 'after'))->toBeTruthy(); - expect($result)->toBe('Hello'); + expect(str_contains($content, 'before'))->toBeTruthy(); + expect(str_contains($content, 'after'))->toBeTruthy(); + expect($result)->toBe('Hello'); - unlink($path); + unlink($path); }); - it('sendOutputTo', function () { - $task = new Task('closure', function() { - echo 'Hello'; + it('sendOutputTo', function () { + $task = new Task('closure', function () { + echo 'Hello'; - return 'world'; + return 'world'; }); - $task->sendOutputTo($path = __DIR__ . '/output.txt'); + $task->sendOutputTo($path = __DIR__ . '/output.txt'); $result = $task->run(); @@ -54,16 +54,16 @@ expect($result)->toBe('world'); unlink($path); - }); + }); - it('appendOutputTo', function () { - $task = new Task('closure', function() { - echo 'Hello'; - }); + it('appendOutputTo', function () { + $task = new Task('closure', function () { + echo 'Hello'; + }); - $task->appendOutputTo($path = __DIR__ . '/output.txt'); + $task->appendOutputTo($path = __DIR__ . '/output.txt'); - file_put_contents($path, 'World'); + file_put_contents($path, 'World'); $task->run(); @@ -71,33 +71,33 @@ expect(file_get_contents($path))->toBe('WorldHello'); unlink($path); - }); + }); - it('onSuccess', function () { - $task = new Task('closure', fn() => 'Hello'); + it('onSuccess', function () { + $task = new Task('closure', fn () => 'Hello'); - expect(file_exists($path = __DIR__.'/test-hook.txt'))->toBeFalsy(); + expect(file_exists($path = __DIR__ . '/test-hook.txt'))->toBeFalsy(); - $task->onSuccess(function() use($path) { + $task->onSuccess(function () use ($path) { file_put_contents($path, 'Success!'); }); $task->run(); - expect(file_exists($path))->toBeTruthy(); - expect(file_get_contents($path))->toBe('Success!'); + expect(file_exists($path))->toBeTruthy(); + expect(file_get_contents($path))->toBe('Success!'); - unlink($path); - }); + unlink($path); + }); - it('onFailure', function () { - $task = new Task('closure', function() { + it('onFailure', function () { + $task = new Task('closure', function () { throw new Exception('Error'); }); - expect(file_exists($path = __DIR__.'/test-hook.txt'))->toBeFalsy(); + expect(file_exists($path = __DIR__ . '/test-hook.txt'))->toBeFalsy(); - $task->onFailure(function() use($path) { + $task->onFailure(function () use ($path) { file_put_contents($path, 'Failure!'); }); @@ -106,15 +106,15 @@ expect(file_exists($path))->toBeTruthy(); expect(file_get_contents($path))->toBe('Failure!'); - unlink($path); - }); + unlink($path); + }); - it('onFailure lorsqu\'il y\'a pas exception mais on renvoie un code d\'erreur', function () { - $task = new Task('closure', fn() => EXIT_ERROR); + it('onFailure lorsqu\'il y\'a pas exception mais on renvoie un code d\'erreur', function () { + $task = new Task('closure', fn () => EXIT_ERROR); - expect(file_exists($path = __DIR__.'/test-hook.txt'))->toBeFalsy(); + expect(file_exists($path = __DIR__ . '/test-hook.txt'))->toBeFalsy(); - $task->onFailure(function() use($path) { + $task->onFailure(function () use ($path) { file_put_contents($path, 'Failure!'); }); @@ -123,17 +123,17 @@ expect(file_exists($path))->toBeTruthy(); expect(file_get_contents($path))->toBe('Failure!'); - unlink($path); - }); + unlink($path); + }); - it('onFailure avec recuperation de l\'exception', function () { - $task = new Task('closure', function() { + it('onFailure avec recuperation de l\'exception', function () { + $task = new Task('closure', function () { throw new Exception('Error'); }); - expect(file_exists($path = __DIR__.'/test-hook.txt'))->toBeFalsy(); + expect(file_exists($path = __DIR__ . '/test-hook.txt'))->toBeFalsy(); - $task->onFailure(function(Throwable $e) use($path) { + $task->onFailure(function (Throwable $e) use ($path) { file_put_contents($path, $e->getMessage()); }); @@ -142,6 +142,6 @@ expect(file_exists($path))->toBeTruthy(); expect(file_get_contents($path))->toBe('Error'); - unlink($path); - }); + unlink($path); + }); }); diff --git a/spec/Scheduler.spec.php b/spec/Scheduler.spec.php index a4e8993..0a9a18c 100644 --- a/spec/Scheduler.spec.php +++ b/spec/Scheduler.spec.php @@ -94,7 +94,7 @@ public function __invoke(Container $container) expect('shell')->toBe($task->getType()); }); - it('Peut sauvegarder un evenement', function () { + it('Peut sauvegarder un evenement', function () { $task = $this->scheduler->event('foo.bar'); expect($task)->toBeAnInstanceOf(Task::class); @@ -102,7 +102,7 @@ public function __invoke(Container $container) expect('event')->toBe($task->getType()); }); - it('Peut sauvegarder un appel d\'URL', function () { + it('Peut sauvegarder un appel d\'URL', function () { $task = $this->scheduler->url('http://localhost'); expect($task)->toBeAnInstanceOf(Task::class); diff --git a/spec/Task.spec.php b/spec/Task.spec.php index ad021df..66a220a 100644 --- a/spec/Task.spec.php +++ b/spec/Task.spec.php @@ -69,9 +69,9 @@ it('__set', function () { $task = new Task('command', 'foo:bar'); - $task->fake = 'foo:bar'; + $task->fake = 'foo:bar'; - $attributes = ReflectionHelper::getPrivateProperty($task, 'attributes'); + $attributes = ReflectionHelper::getPrivateProperty($task, 'attributes'); expect($attributes)->toBe(['fake' => 'foo:bar']); }); @@ -137,44 +137,44 @@ expect($task->lastRun()->format('Y-m-d H:i:s'))->toBe($date); }); - it('Peut executer une commande shell', function () { - expect(file_exists($path = __DIR__ . '/test.php'))->toBeFalsy(); + it('Peut executer une commande shell', function () { + expect(file_exists($path = __DIR__ . '/test.php'))->toBeFalsy(); - $task = new Task('shell', 'cp ' . __FILE__ . ' ' . $path); - $task->run(); + $task = new Task('shell', 'cp ' . __FILE__ . ' ' . $path); + $task->run(); - expect(file_exists($path))->toBeTruthy(); + expect(file_exists($path))->toBeTruthy(); - $task = new Task('shell', 'rm ' . $path); - $task->run(); + $task = new Task('shell', 'rm ' . $path); + $task->run(); - expect(file_exists($path))->toBeFalsy(); - }); + expect(file_exists($path))->toBeFalsy(); + }); - it('Peut executer un evenement', function () { - expect(file_exists($path = __DIR__ . '/test.txt'))->toBeFalsy(); + it('Peut executer un evenement', function () { + expect(file_exists($path = __DIR__ . '/test.txt'))->toBeFalsy(); - service('event')->on($event = 'test.event', function() use($path) { - file_put_contents($path, 'event.txt'); - }); + service('event')->on($event = 'test.event', function () use ($path) { + file_put_contents($path, 'event.txt'); + }); - $task = new Task('event', $event); - $task->run(); + $task = new Task('event', $event); + $task->run(); - expect(file_exists($path))->toBeTruthy(); - expect(file_get_contents($path))->toBe('event.txt'); + expect(file_exists($path))->toBeTruthy(); + expect(file_get_contents($path))->toBe('event.txt'); - unlink($path); - }); + unlink($path); + }); - it('Peut executer une URL', function () { - skipIf(! Helpers::isConnected()); + it('Peut executer une URL', function () { + skipIf(! Helpers::isConnected()); - $task = new Task('url', 'https://raw.githubusercontent.com/blitz-php/tasks/refs/heads/main/composer.json'); - $result = $task->run(); - $result = json_decode($result, true); + $task = new Task('url', 'https://raw.githubusercontent.com/blitz-php/tasks/refs/heads/main/composer.json'); + $result = $task->run(); + $result = json_decode($result, true); - expect($result)->toContainKey('name'); - expect($result['name'])->toBe('blitz-php/tasks'); - }); + expect($result)->toContainKey('name'); + expect($result['name'])->toBe('blitz-php/tasks'); + }); }); diff --git a/src/Commands/Work.php b/src/Commands/Work.php index 77666ae..8d5adcc 100644 --- a/src/Commands/Work.php +++ b/src/Commands/Work.php @@ -1,5 +1,14 @@ + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + namespace BlitzPHP\Tasks\Commands; use BlitzPHP\Utilities\Date; @@ -25,14 +34,16 @@ class Work extends TaskCommand protected $description = 'Démarre le planificateur de tâche et l\'exécute localement.'; /** - * {@inheritDoc} + * @var list */ protected $required = [ 'symfony/process:^7.2', ]; - /** + /** * {@inheritDoc} + * + * @return void */ public function execute(array $params) { @@ -41,9 +52,9 @@ public function execute(array $params) [$lastExecutionStartedAt, $executions] = [Date::now()->subMinutes(10), []]; $command = sprintf( - '%s %s %s', - escapeshellarg(PHP_BINARY), - escapeshellarg(base_path('klinge')), + '%s %s %s', + escapeshellarg(PHP_BINARY), + escapeshellarg(base_path('klinge')), 'tasks:run' ); @@ -54,7 +65,7 @@ public function execute(array $params) while (true) { usleep(100 * 1000); - if (intval(Date::now()->getSecond()) === 0 && ! Date::now()->startOfMinute()->equalTo($lastExecutionStartedAt)) { + if ((int) (Date::now()->getSecond()) === 0 && ! Date::now()->startOfMinute()->equalTo($lastExecutionStartedAt)) { $executions[] = $execution = Process::fromShellCommandline($command); $execution->start(); @@ -63,7 +74,7 @@ public function execute(array $params) } foreach ($executions as $key => $execution) { - $output = $execution->getIncrementalOutput(). $execution->getIncrementalErrorOutput(); + $output = $execution->getIncrementalOutput() . $execution->getIncrementalErrorOutput(); $this->write(ltrim($output, "\n"))->eol(); diff --git a/src/CronExpression.php b/src/CronExpression.php index 39c0f83..2e23d50 100644 --- a/src/CronExpression.php +++ b/src/CronExpression.php @@ -27,7 +27,7 @@ class CronExpression */ protected string $timezone; - /** + /** * Le fuseau horaire global à utiliser. */ private string $globalTimezone; @@ -51,24 +51,24 @@ class CronExpression */ public function __construct(?string $timezone = null) { - if (null === $globalTimezone = config('tasks.timezone')) { - $globalTimezone = config('app.timezone'); - } + if (null === $globalTimezone = config('tasks.timezone')) { + $globalTimezone = config('app.timezone'); + } - $this->globalTimezone = $globalTimezone; + $this->globalTimezone = $globalTimezone; $this->setTimezone($timezone); } - /** - * Définit le fuseau horaire global pour toutes les tâches de construction. - */ - public function setTimezone(?string $timezone = null): self - { - $this->timezone = $timezone ?? $this->globalTimezone; + /** + * Définit le fuseau horaire global pour toutes les tâches de construction. + */ + public function setTimezone(?string $timezone = null): self + { + $this->timezone = $timezone ?? $this->globalTimezone; - return $this; - } + return $this; + } /** * Vérifie si l'expression cron doit être exécutée. Permet d'utiliser un fuseau horaire personnalisé pour une tâche spécifique diff --git a/src/FrequenciesTrait.php b/src/FrequenciesTrait.php index ca2e581..ba9042d 100644 --- a/src/FrequenciesTrait.php +++ b/src/FrequenciesTrait.php @@ -68,7 +68,7 @@ public function at(string $time): self return $this->daily($time); } - /** + /** * S'exécute tous les jours à minuit, sauf si une chaîne d'heure est transmise (comme 04:08pm) */ public function daily(?string $time = null): self @@ -85,16 +85,16 @@ public function daily(?string $time = null): self return $this; } - /** + /** * S'execute entre une temps de debut et de fin */ public function between(string $startTime, string $endTime): self { - [$minStart, $hourStart] = array_map('intval', $this->parseTime($startTime)); - [$minEnd, $hourEnd] = array_map('intval', $this->parseTime($endTime)); + [$minStart, $hourStart] = array_map('intval', $this->parseTime($startTime)); + [$minEnd, $hourEnd] = array_map('intval', $this->parseTime($endTime)); - $this->betweenHours($hourStart, $hourEnd); - $this->betweenMinutes($minStart, $minEnd); + $this->betweenHours($hourStart, $hourEnd); + $this->betweenMinutes($minStart, $minEnd); return $this; } @@ -133,7 +133,7 @@ public function everyHour(int $hour = 1, $minute = null): self return $this; } - /** + /** * S'exécute toutes les 2 heures * * @param int|string|null $minute @@ -143,7 +143,7 @@ public function everyTwoHours($minute = null): self return $this->everyHour(2, $minute); } - /** + /** * S'exécute toutes les 3 heures * * @param int|string|null $minute @@ -153,7 +153,7 @@ public function everyThreeHours($minute = null): self return $this->everyHour(3, $minute); } - /** + /** * S'exécute toutes les 4 heures * * @param int|string|null $minute @@ -163,7 +163,7 @@ public function everyFourHours($minute = null): self return $this->everyHour(4, $minute); } - /** + /** * S'exécute toutes les 6 heures * * @param int|string|null $minute @@ -175,10 +175,12 @@ public function everySixHours($minute = null): self /** * S'execute toutes les heures impaires + * + * @param int|string|null $minute */ public function everyOddHour($minute = null): self { - $this->expression['min'] = $minute ?? '0'; + $this->expression['min'] = $minute ?? '0'; $this->expression['hour'] = '1-23/2'; return $this; @@ -233,7 +235,7 @@ public function everyTwoMinutes(): self /** * S'execute toutes les 3 minutes */ - public function everyThreeMinutes() + public function everyThreeMinutes(): self { return $this->everyMinute(3); } @@ -241,7 +243,7 @@ public function everyThreeMinutes() /** * S'execute toutes les 4 minutes */ - public function everyFourMinutes() + public function everyFourMinutes(): self { return $this->everyMinute(4); } @@ -259,7 +261,7 @@ public function everyFiveMinutes(): self */ public function everyTenMinutes(): self { - return $this->everyMinute(10); + return $this->everyMinute(10); } /** @@ -384,10 +386,10 @@ public function monthly(?string $time = null): self return $this->monthlyOn(1, $time); } - /** + /** * S'execute mensuellement à un jour et une heure donnés. * - * @param int<1, 31> $dayOfMonth + * @param int<1, 31> $dayOfMonth */ public function monthlyOn(int $dayOfMonth = 1, ?string $time = null): self { @@ -423,11 +425,11 @@ public function daysOfMonth($days): self /** * S'execute le dernier jours du mois */ - public function lastDayOfMonth(?string $time = null) + public function lastDayOfMonth(?string $time = null): self { $this->daily($time); - return $this->daysOfMonth(Date::now()->endOfMonth()->getDay()); + return $this->daysOfMonth((int) Date::now()->endOfMonth()->getDay()); } /** @@ -476,11 +478,11 @@ public function quarterly(?string $time = null): self return $this->quarterlyOn(1, $time); } - /** + /** * S'execute tous les trimestres à un jour et une heure donnés. */ - public function quarterlyOn(int $dayOfQuarter = 1, ?string $time = null) - { + public function quarterlyOn(int $dayOfQuarter = 1, ?string $time = null): self + { $min = $hour = 0; if (! empty($time)) { @@ -504,10 +506,10 @@ public function yearly(?string $time = null): self return $this->yearlyOn(1, 1, $time); } - /** + /** * S'execute chaque année à un mois, un jour et une heure donnés. * - * @param int<1, 31> $dayOfMonth + * @param int<1, 31> $dayOfMonth */ public function yearlyOn(int $month = 1, int $dayOfMonth = 1, ?string $time = null): self { diff --git a/src/HooksTrait.php b/src/HooksTrait.php index 2998dab..735529d 100644 --- a/src/HooksTrait.php +++ b/src/HooksTrait.php @@ -18,59 +18,57 @@ use BlitzPHP\Utilities\Iterable\Arr; use BlitzPHP\Utilities\String\Stringable; use Closure; +use LogicException; use Throwable; -/** - * - */ trait HooksTrait { - /** + /** * L'emplacement où la sortie doit être envoyée. */ public ?string $location = null; - /** - * Code de sortie de la tache - */ - protected ?int $exitCode = null; + /** + * Code de sortie de la tache + */ + protected ?int $exitCode = null; - /** + /** * Exception levée lors de l'exécution de la tâche. */ - protected ?Throwable $exception = null; + protected ?Throwable $exception = null; - /** + /** * Indique si la sortie doit être ajoutée. */ public bool $shouldAppendOutput = false; /** * Tableau de rappels à exécuter avant l'execution de la tâche. - * - * @var list + * + * @var list */ protected array $beforeCallbacks = []; /** * Tableau de rappels à exécuter après l'execution de la tâche. - * - * @var list + * + * @var list */ protected $afterCallbacks = []; - /** + /** * Met la sortie de la tâche dans un fichier donné. */ public function sendOutputTo(string $location, bool $append = false): self { - $this->location = $location; - $this->shouldAppendOutput = $append; + $this->location = $location; + $this->shouldAppendOutput = $append; return $this; } - /** + /** * Ajoute la sortie de la tâche à la fin d'un fichier donné. */ public function appendOutputTo(string $location): self @@ -78,12 +76,12 @@ public function appendOutputTo(string $location): self return $this->sendOutputTo($location, true); } - /** + /** * Envoi le resultat de l'execution de la tache par mail. * - * @param array|mixed $addresses + * @param array|mixed $addresses * - * @throws \LogicException + * @throws LogicException */ public function emailOutputTo($addresses, bool $onlyIfOutputExists = false): self { @@ -99,9 +97,9 @@ public function emailOutputTo($addresses, bool $onlyIfOutputExists = false): sel /** * Envoi le resultat de l'execution de la tache par mail si un resultat existe dans la sortie. * - * @param array|mixed $addresses + * @param array|mixed $addresses * - * @throws \LogicException + * @throws LogicException */ public function emailWrittenOutputTo($addresses): self { @@ -111,7 +109,7 @@ public function emailWrittenOutputTo($addresses): self /** * Envoi le resultat de l'execution de la tache par mail si l'operation a echouée. * - * @param array|mixed $addresses + * @param array|mixed $addresses */ public function emailOutputOnFailure($addresses): self { @@ -124,7 +122,7 @@ public function emailOutputOnFailure($addresses): self }); } - /** + /** * Enregistre un callback à appeler avant l'opération. */ public function before(Closure $callback): self @@ -152,7 +150,7 @@ public function then(Closure $callback): self return $this; } - /** + /** * Enregistre un callback à appeler si l'opération se deroulle avec succes. */ public function onSuccess(Closure $callback): self @@ -164,7 +162,7 @@ public function onSuccess(Closure $callback): self }); } - /** + /** * Enregistre un callback à appeler si l'opération ne se deroulle pas correctement. */ public function onFailure(Closure $callback): self @@ -176,62 +174,60 @@ public function onFailure(Closure $callback): self }); } - /** - * Procede a l'execution de la tache - */ - protected function process(ContainerInterface $container, $method): mixed - { - ob_start(); + /** + * Procede a l'execution de la tache + */ + protected function process(ContainerInterface $container, string $method): mixed + { + ob_start(); - $result = $this->start($this->container, $method); + $result = $this->start($this->container, $method); - // if (! $this->runInBackground) { - $result = $this->finish($this->container, $result); + $result = $this->finish($this->container, $result); - ob_end_flush(); + ob_end_flush(); - return $result; - // } - } + return $result; + } - /** + /** * Demarre l'execution de la tache - * - * @return mixed Le resultat de l'execution de la tache + * + * @return mixed Le resultat de l'execution de la tache * * @throws Throwable */ - protected function start(ContainerInterface $container, string $runMethod): mixed + protected function start(ContainerInterface $container, string $runMethod) { try { $this->callBeforeCallbacks($container); return $this->execute($container, $runMethod); } catch (Throwable $e) { - $this->registerException($e); + $this->registerException($e); } } - /** + /** * Execute la tache. - * - * @return mixed Le resultat de l'execution de la tache + * + * @return mixed Le resultat de l'execution de la tache */ protected function execute(ContainerInterface $container, string $runMethod): mixed { - try { - $result = $this->{$runMethod}(); - - if (is_int($result)) { - $this->exitCode = $result; - } else { - $this->exitCode = EXIT_SUCCESS; - } - } catch (Throwable $e) { - $this->registerException($e); - } - - return $result ?? null; + try { + $result = $this->{$runMethod}(); + + if (is_int($result)) { + $this->exitCode = $result; + } else { + $this->exitCode = EXIT_SUCCESS; + } + } catch (Throwable $e) { + $this->registerException($e); + } + + return $result ?? null; } /** @@ -242,28 +238,28 @@ protected function finish(ContainerInterface $container, mixed $result): mixed try { $output = $this->callAfterCallbacks($container, $result); } finally { - if (isset($output) && $output !== '' && $this->location !== null) { - @file_put_contents($this->location, $output, $this->shouldAppendOutput ? FILE_APPEND : 0); - } + if (isset($output) && $output !== '' && $this->location !== null) { + @file_put_contents($this->location, $output, $this->shouldAppendOutput ? FILE_APPEND : 0); + } } - return $result; + return $result; } /** - * Ensure that the command output is being captured. - * - * @return void + * S'assurer que les résultats de la tâche sont capturés. */ - protected function ensureOutputIsBeingCaptured() + protected function ensureOutputIsBeingCaptured(): void { - if (is_null($this->output) || $this->output == $this->getDefaultOutput()) { - $this->sendOutputTo(storage_path('logs/schedule-'.sha1($this->mutexName()).'.log')); + if (null === $this->location) { + $this->sendOutputTo(storage_path('logs/task-' . sha1($this->name) . '.log')); } } /** * Envoie du résultat de l'execution de la tache par mail aux destinataires. + * + * @param list $addresses Liste des addresses a qui le mail sera envoyer */ protected function emailOutput(MailerInterface $mailer, array $addresses, bool $onlyIfOutputExists = false): void { @@ -273,7 +269,7 @@ protected function emailOutput(MailerInterface $mailer, array $addresses, bool $ return; } - $mailer->to($addresses)->subject($this->getEmailSubject())->text($text)->send(); + $mailer->to($addresses)->subject($this->getEmailSubject())->text($text)->send(); } /** @@ -281,10 +277,10 @@ protected function emailOutput(MailerInterface $mailer, array $addresses, bool $ */ protected function getEmailSubject(): string { - return "Sortie de la tâche planifiée pour [{$this->command}]"; + return "Sortie de la tâche planifiée pour [{$this->name}]"; } - /** + /** * Appelle tous les callbacks qui doivent être lancer "avant" l'exécution de la tâche. */ protected function callBeforeCallbacks(ContainerInterface $container): void @@ -294,27 +290,30 @@ protected function callBeforeCallbacks(ContainerInterface $container): void } } - /** + /** * Appelle tous les callbacks qui doivent être lancer "apres" l'exécution de la tâche. */ protected function callAfterCallbacks(ContainerInterface $container, mixed $result = null): string { - $parameters = ['result' => $result]; + $parameters = ['result' => $result]; - if ('' !== $output = ob_get_contents() ?: '') { - $parameters['output'] = new Stringable($output); - } + if ('' !== $output = ob_get_contents() ?: '') { + $parameters['output'] = new Stringable($output); + } foreach ($this->afterCallbacks as $callback) { $container->call($callback, $parameters); } - return $output; + return $output; } - protected function registerException(Throwable $e) - { - $this->exception = $e; - $this->exitCode = EXIT_ERROR; - } + /** + * Marque l'exception en cours et définit le code de sortie à EXIT_ERROR. + */ + protected function registerException(Throwable $e): void + { + $this->exception = $e; + $this->exitCode = EXIT_ERROR; + } } diff --git a/src/Scheduler.php b/src/Scheduler.php index d374544..6b5ca4d 100644 --- a/src/Scheduler.php +++ b/src/Scheduler.php @@ -18,19 +18,13 @@ */ class Scheduler { - const SUNDAY = 0; - - const MONDAY = 1; - - const TUESDAY = 2; - - const WEDNESDAY = 3; - - const THURSDAY = 4; - - const FRIDAY = 5; - - const SATURDAY = 6; + public const SUNDAY = 0; + public const MONDAY = 1; + public const TUESDAY = 2; + public const WEDNESDAY = 3; + public const THURSDAY = 4; + public const FRIDAY = 5; + public const SATURDAY = 6; /** * @var list @@ -57,6 +51,8 @@ public function call(callable $func): Task /** * Planifie l'execution d'une commande. + * + * @param list $parameters Parameters eventuels a transmettre aux commande. */ public function command(string $command, array $parameters = []): Task { @@ -90,7 +86,8 @@ public function url(string $url): Task } /** - * @param mixed $action + * @param mixed $action + * @param list $parameters Parameters eventuels a transmettre aux taches. */ protected function createTask(string $type, $action, array $parameters = []): Task { diff --git a/src/Task.php b/src/Task.php index 95a7480..6e9eb37 100644 --- a/src/Task.php +++ b/src/Task.php @@ -35,7 +35,7 @@ class Task { use FrequenciesTrait; - use HooksTrait; + use HooksTrait; /** * Types d'action supportés @@ -57,7 +57,7 @@ class Task */ protected array $environments = []; - /** + /** * Timezone dans lequel la tâche doit être traitée. */ protected ?string $timezone = null; @@ -69,11 +69,12 @@ class Task */ protected array $attributes = []; - protected ContainerInterface $container; + protected ContainerInterface $container; /** - * @param string $type Type de l'action en cours. - * @param mixed $action Le contenu actuel qu'on souhaite executer. + * @param string $type Type de l'action en cours. + * @param mixed $action Le contenu actuel qu'on souhaite executer. + * @param list $parameters Parametres eventuels de l'action * * @throws TasksException */ @@ -83,7 +84,7 @@ public function __construct(protected string $type, protected mixed $action, pro throw TasksException::invalidTaskType($type); } - $this->container = service('container'); + $this->container = service('container'); } /** @@ -126,7 +127,7 @@ public function run() throw TasksException::invalidTaskType($this->type); } - return $this->process($this->container, $method); + return $this->process($this->container, $method); } /** @@ -159,18 +160,18 @@ public function environments(string ...$environments): self return $this; } - /** - * Définit le fuseau horaire pour l'exécution de la tâche. - * - * @param string $timezone L'identifiant du fuseau horaire à utiliser pour la tâche. - * Il doit s'agir d'une chaîne de caractères PHP valide (par exemple, 'America/New_York', 'Europe/Paris'). - */ - public function timezone(string $timezone): self - { - $this->timezone = $timezone; + /** + * Définit le fuseau horaire pour l'exécution de la tâche. + * + * @param string $timezone L'identifiant du fuseau horaire à utiliser pour la tâche. + * Il doit s'agir d'une chaîne de caractères PHP valide (par exemple, 'America/New_York', 'Europe/Paris'). + */ + public function timezone(string $timezone): self + { + $this->timezone = $timezone; - return $this; - } + return $this; + } /** * Renvoie la date à laquelle cette tâche a été exécutée pour la dernière fois. @@ -212,7 +213,10 @@ protected function runsInEnvironment(string $environment): bool */ protected function runCommand(): string { - return command($this->getAction()); + if (class_exists($command = $this->getAction())) { + } + + return command($command); } /**