From 87e3b8ec008f0cfa989530a11b497243d8d30894 Mon Sep 17 00:00:00 2001 From: roxblnfk Date: Fri, 13 Dec 2024 18:31:34 +0400 Subject: [PATCH 1/3] Update metafiles --- .editorconfig | 14 ++++- .php-cs-fixer.dist.php | 13 ++++ .styleci.yml | 73 ---------------------- composer.json | 138 ++++++++++++++++++++++------------------- psalm.xml | 12 ++-- 5 files changed, 105 insertions(+), 145 deletions(-) create mode 100644 .php-cs-fixer.dist.php delete mode 100644 .styleci.yml diff --git a/.editorconfig b/.editorconfig index 9866c39..55de6f8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,3 @@ -# editorconfig.org - root = true [*] @@ -9,3 +7,15 @@ insert_final_newline = true indent_style = space indent_size = 4 trim_trailing_whitespace = true + +[*.{yml, yaml, sh, conf, neon*}] +indent_size = 2 + +[*.http] +end_of_line = crlf + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..5151cbe --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,13 @@ +include(__DIR__ . '/src') + ->include(__DIR__ . '/tests') + ->include(__FILE__) + ->cache('./runtime/php-cs-fixer.cache') + ->allowRisky() + ->build(); diff --git a/.styleci.yml b/.styleci.yml deleted file mode 100644 index 6fde134..0000000 --- a/.styleci.yml +++ /dev/null @@ -1,73 +0,0 @@ -preset: psr12 -risky: true - -version: 8 - -enabled: - - alpha_ordered_traits - - array_indentation - - array_push - - combine_consecutive_issets - - combine_consecutive_unsets - - combine_nested_dirname - - declare_strict_types - - dir_constant - - fully_qualified_strict_types - - function_to_constant - - is_null - - magic_constant_casing - - magic_method_casing - - method_separation - - modernize_types_casting - - native_function_casing - - native_function_type_declaration_casing - - no_alias_functions - - no_empty_comment - - no_empty_phpdoc - - no_empty_statement - - no_extra_block_blank_lines - - no_short_bool_cast - - no_superfluous_elseif - - no_unneeded_control_parentheses - - no_unneeded_curly_braces - - no_unneeded_final_method - - no_unset_cast - - no_unused_imports - - no_unused_lambda_imports - - no_useless_else - - no_useless_return - - normalize_index_brace - - php_unit_dedicate_assert - - php_unit_dedicate_assert_internal_type - - php_unit_expectation - - php_unit_mock - - php_unit_mock_short_will_return - - php_unit_namespaced - - php_unit_no_expectation_annotation - - phpdoc_no_empty_return - - phpdoc_no_useless_inheritdoc - - phpdoc_order - - phpdoc_property - - phpdoc_scalar - - phpdoc_separation - - phpdoc_singular_inheritdoc - - phpdoc_trim - - phpdoc_trim_consecutive_blank_line_separation - - phpdoc_type_to_var - - phpdoc_types - - phpdoc_types_order - - print_to_echo - - regular_callable_call - - return_assignment - - self_accessor - - self_static_accessor - - set_type_to_cast - - short_array_syntax - - short_list_syntax - - simplified_if_return - - single_quote - - standardize_not_equals - - ternary_to_null_coalescing - - trailing_comma_in_multiline_array - - unalign_double_arrow - - unalign_equals diff --git a/composer.json b/composer.json index 279b88a..be49b2e 100644 --- a/composer.json +++ b/composer.json @@ -1,67 +1,75 @@ { - "name": "spiral-packages/scheduler", - "description": "The scheduler is a package for spiral framework. It will help to managing scheduled tasks on your server.", - "keywords": [ - "spiral-packages", - "spiral", - "scheduler" - ], - "homepage": "https://github.com/spiral-packages/scheduler", - "license": "MIT", - "authors": [ - { - "name": "butschster", - "email": "butschster@gmail.com", - "role": "PHP web developer" - } - ], - "require": { - "php": ">=8.1", - "butschster/cron-expression-generator": "^1.10", - "nesbot/carbon": "^2.52 || ^3.0", - "psr/event-dispatcher": "^1", - "spiral/core": "^3.14", - "spiral/boot": "^3.14", - "spiral/cache": "^3.14", - "spiral/queue": "^3.14", - "spiral/snapshots": "^3.14", - "spiral/attributes": "^2.8 || ^3.0", - "symfony/process": "^6.0 || ^7.0" - }, - "require-dev": { - "spiral/dumper": "^3.3", - "spiral/framework": "^3.14", - "spiral/testing": "^2.8.2", - "vimeo/psalm": "^4.9 || ^5.26" - }, - "autoload": { - "psr-4": { - "Spiral\\Scheduler\\": "src" - } - }, - "autoload-dev": { - "psr-4": { - "Spiral\\Scheduler\\Tests\\App\\": "tests/app", - "Spiral\\Scheduler\\Tests\\": "tests/src" - } - }, - "scripts": { - "test": "vendor/bin/phpunit", - "psalm": "vendor/bin/psalm" - }, - "config": { - "sort-packages": true, - "allow-plugins": { - "spiral/composer-publish-plugin": true - } - }, - "extra": { - "spiral": { - "bootloaders": [ - "Spiral\\Scheduler\\Bootloader\\SchedulerBootloader" - ] - } - }, - "minimum-stability": "dev", - "prefer-stable": true + "name": "spiral-packages/scheduler", + "description": "The scheduler is a package for spiral framework. It will help to managing scheduled tasks on your server.", + "keywords": [ + "spiral-packages", + "spiral", + "scheduler" + ], + "homepage": "https://github.com/spiral-packages/scheduler", + "license": "MIT", + "authors": [ + { + "name": "butschster", + "email": "butschster@gmail.com", + "role": "PHP web developer" + }, + { + "name": "roxblnfk", + "email": "roxblnfk@gmail.com" + } + ], + "require": { + "php": ">=8.1", + "butschster/cron-expression-generator": "^1.10", + "nesbot/carbon": "^2.52 || ^3.0", + "psr/event-dispatcher": "^1", + "spiral/core": "^3.14", + "spiral/boot": "^3.14", + "spiral/cache": "^3.14", + "spiral/queue": "^3.14", + "spiral/snapshots": "^3.14", + "spiral/attributes": "^2.8 || ^3.0", + "symfony/process": "^6.0 || ^7.0" + }, + "require-dev": { + "spiral/code-style": "^2.2", + "spiral/dumper": "^3.3", + "spiral/framework": "^3.14", + "spiral/testing": "^2.8.3", + "vimeo/psalm": "^4.9 || ^5.26" + }, + "autoload": { + "psr-4": { + "Spiral\\Scheduler\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Spiral\\Scheduler\\Tests\\App\\": "tests/app", + "Spiral\\Scheduler\\Tests\\": "tests/src" + } + }, + "scripts": { + "cs:diff": "php-cs-fixer fix --dry-run -v --diff", + "cs:fix": "php-cs-fixer fix -v", + "psalm": "psalm", + "psalm:baseline": "psalm --set-baseline=psalm-baseline.xml", + "test": "phpunit --color=always" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "spiral/composer-publish-plugin": true + } + }, + "extra": { + "spiral": { + "bootloaders": [ + "Spiral\\Scheduler\\Bootloader\\SchedulerBootloader" + ] + } + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/psalm.xml b/psalm.xml index 0cc5c5c..a4a3016 100644 --- a/psalm.xml +++ b/psalm.xml @@ -1,9 +1,11 @@ - From 028d7fbd8f11a93a85923552cf3312dd8ddf87d3 Mon Sep 17 00:00:00 2001 From: roxblnfk Date: Fri, 13 Dec 2024 18:32:33 +0400 Subject: [PATCH 2/3] Apply styles; add cs fix workflow; generate psalm baseline --- .github/workflows/cs-fix.yml | 16 ++ psalm-baseline.xml | 199 ++++++++++++++++++ src/Attribute/Schedule.php | 8 +- src/Bootloader/SchedulerBootloader.php | 22 +- src/CommandBuilder.php | 23 +- src/CommandRunner.php | 9 +- src/Commands/ScheduleFinishCommand.php | 5 +- src/Commands/ScheduleRunCommand.php | 4 +- src/Commands/ScheduleWorkCommand.php | 8 +- src/Event/BackgroundJobFinished.php | 5 +- src/Event/JobFailed.php | 5 +- src/Event/JobFinished.php | 5 +- src/Event/JobStarting.php | 5 +- src/EveryMinuteCommandRunner.php | 9 +- src/Exception/CommandRunnerException.php | 5 +- src/Exception/SchedulerException.php | 5 +- src/Job/CallbackJob.php | 13 +- src/Job/CommandJob.php | 32 +-- src/Job/Job.php | 104 ++++----- src/JobHandler.php | 5 +- src/JobRegistryInterface.php | 1 - src/JobsLocator.php | 11 +- src/Mutex/CacheJobMutex.php | 5 +- src/PeriodicCommandRunnerInterface.php | 2 +- src/ProcessFactory.php | 7 +- src/ProcessUtils.php | 14 +- src/Schedule.php | 21 +- src/Testing/FakeJobHandler.php | 8 +- src/Testing/FakeJobMutex.php | 12 +- src/Testing/FakeJobRegistry.php | 13 +- src/Testing/InteractsWithSchedule.php | 8 +- .../Jobs/AnotherSimpleJobWithAttribute.php | 6 +- tests/app/Jobs/JobWithoutAttributes.php | 5 +- tests/app/Jobs/SimpleJobWithAttribute.php | 6 +- tests/app/config/scheduler.php | 4 +- .../Bootloader/SchedulerBootloaderTest.php | 28 +-- tests/src/CommandBuilderTest.php | 42 ++-- tests/src/CommandRunnerTest.php | 18 +- .../Commands/ScheduleFinishCommandTest.php | 20 +- .../src/Commands/ScheduleListCommandTest.php | 6 +- tests/src/Commands/ScheduleRunCommandTest.php | 14 +- .../src/Commands/ScheduleWorkCommandTest.php | 6 +- tests/src/Config/SchedulerConfigTest.php | 8 +- tests/src/Job/CallbackJobTest.php | 42 ++-- tests/src/Job/CommandJobTest.php | 34 +-- tests/src/JobHandlerTest.php | 10 +- tests/src/JobRegistryTest.php | 18 +- tests/src/JobsLocatorTest.php | 4 +- tests/src/Mutex/CacheJobMutexTest.php | 24 +-- tests/src/ProcessFactoryTest.php | 2 +- tests/src/ScheduleTest.php | 47 ++--- tests/src/TestCase.php | 4 +- 52 files changed, 561 insertions(+), 376 deletions(-) create mode 100644 .github/workflows/cs-fix.yml create mode 100644 psalm-baseline.xml diff --git a/.github/workflows/cs-fix.yml b/.github/workflows/cs-fix.yml new file mode 100644 index 0000000..db5860c --- /dev/null +++ b/.github/workflows/cs-fix.yml @@ -0,0 +1,16 @@ +--- + +on: # yamllint disable-line rule:truthy + push: + branches: + - '*' + +name: Fix Code Style + +jobs: + cs-fix: + permissions: + contents: write + uses: spiral/gh-actions/.github/workflows/cs-fix.yml@master + +... diff --git a/psalm-baseline.xml b/psalm-baseline.xml new file mode 100644 index 0000000..acf0d66 --- /dev/null +++ b/psalm-baseline.xml @@ -0,0 +1,199 @@ + + + + + + get(JobMutexInterface::class)]]> + + + + + + + + getExpressionAliases()]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + container]]> + + + + + + + + + output]]> + + + + + + + + + container]]> + + + + + + + + + + + + + + + + + + + + + + config['cacheStorage'] ?? null]]> + config['cacheStorage'] ?? null]]> + config['expression']['aliases'] ?? null]]> + config['expression']['aliases'] ?? null]]> + config['queueConnection'] ?? null]]> + config['queueConnection'] ?? null]]> + + + + + getIncrementalErrorOutput()]]> + getIncrementalOutput()]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + description]]> + + + name]]> + + + + + + + + + + + + + + + + + + + + + + runAs]]> + + + + + + + + + + + + + + + + + + + created[$id]]]> + + + + + + + + + + registered]]> + + + diff --git a/src/Attribute/Schedule.php b/src/Attribute/Schedule.php index 439288c..b643927 100644 --- a/src/Attribute/Schedule.php +++ b/src/Attribute/Schedule.php @@ -4,10 +4,9 @@ namespace Spiral\Scheduler\Attribute; -use Attribute; use Doctrine\Common\Annotations\Annotation\NamedArgumentConstructor; -#[Attribute(Attribute::TARGET_CLASS), NamedArgumentConstructor] +#[\Attribute(\Attribute::TARGET_CLASS), NamedArgumentConstructor] class Schedule { public function __construct( @@ -17,7 +16,6 @@ public function __construct( public readonly ?string $runAs = null, public readonly bool|int $withoutOverlapping = false, public readonly bool $runInBackground = false, - public readonly array $parameters = [] - ) { - } + public readonly array $parameters = [], + ) {} } diff --git a/src/Bootloader/SchedulerBootloader.php b/src/Bootloader/SchedulerBootloader.php index 4216f75..03b8b94 100644 --- a/src/Bootloader/SchedulerBootloader.php +++ b/src/Bootloader/SchedulerBootloader.php @@ -39,7 +39,6 @@ class SchedulerBootloader extends Bootloader TokenizerBootloader::class, CacheBootloader::class, ]; - protected const SINGLETONS = [ JobHandlerInterface::class => JobHandler::class, PeriodicCommandRunnerInterface::class => EveryMinuteCommandRunner::class, @@ -52,18 +51,17 @@ class SchedulerBootloader extends Bootloader ]; public function __construct( - private readonly ConfiguratorInterface $config - ) { - } + private readonly ConfiguratorInterface $config, + ) {} public function init( EnvironmentInterface $env, AbstractKernel $kernel, - ConsoleBootloader $console + ConsoleBootloader $console, ): void { $this->initConfig($env); - $kernel->booting(static function (SchedulerConfig $config) { + $kernel->booting(static function (SchedulerConfig $config): void { foreach ($config->getExpressionAliases() as $alias => $expression) { if (! CronExpression::supportsAlias($alias)) { CronExpression::registerAlias($alias, $expression); @@ -87,7 +85,7 @@ private function initSchedule( FactoryInterface $container, ProcessFactory $processFactory, JobRegistryInterface $registry, - CommandRunner $commandRunner + CommandRunner $commandRunner, ): Schedule { return new Schedule( $container, @@ -100,23 +98,23 @@ private function initSchedule( private function initJobsLocator( ClassesInterface $classes, - JobMutexInterface $mutex + JobMutexInterface $mutex, ): JobsLocatorInterface { return new JobsLocator($classes, new AttributeReader(), $mutex); } private function initEventMutex( CacheStorageProviderInterface $provider, - SchedulerConfig $config + SchedulerConfig $config, ): JobMutexInterface { return new CacheJobMutex( $provider->storage( - $config->getCacheStorage() - ) + $config->getCacheStorage(), + ), ); } - private function initConfig(EnvironmentInterface $env) + private function initConfig(EnvironmentInterface $env): void { $this->config->setDefaults(SchedulerConfig::CONFIG, [ 'cacheStorage' => $env->get('SCHEDULER_MUTEX_CACHE_STORAGE'), diff --git a/src/CommandBuilder.php b/src/CommandBuilder.php index 6306a6e..d982089 100644 --- a/src/CommandBuilder.php +++ b/src/CommandBuilder.php @@ -7,21 +7,20 @@ final class CommandBuilder { public function __construct( - private readonly CommandRunner $commandRunner - ) { - } + private readonly CommandRunner $commandRunner, + ) {} public function buildForegroundCommand( string $command, bool $appendOutput = false, string $output = '/dev/null', - ?string $user = null + ?string $user = null, ): string { $output = ProcessUtils::escapeArgument($output); return $this->ensureCorrectUser( - $command.($appendOutput ? ' >> ' : ' > ').$output.' 2>&1', - $user + $command . ($appendOutput ? ' >> ' : ' > ') . $output . ' 2>&1', + $user, ); } @@ -30,18 +29,18 @@ public function buildBackgroundCommand( string $id, bool $appendOutput = false, string $output = '/dev/null', - ?string $user = null + ?string $user = null, ): string { $output = ProcessUtils::escapeArgument($output); $redirect = $appendOutput ? ' >> ' : ' > '; - $finished = $this->commandRunner->formatCommandString('schedule:finish').' "'.$id.'"'; + $finished = $this->commandRunner->formatCommandString('schedule:finish') . ' "' . $id . '"'; return $this->ensureCorrectUser( - '('.$command.$redirect.$output.' 2>&1 ; '.$finished.' "$?") > ' - .ProcessUtils::escapeArgument('/dev/null').' 2>&1 &', - $user + '(' . $command . $redirect . $output . ' 2>&1 ; ' . $finished . ' "$?") > ' + . ProcessUtils::escapeArgument('/dev/null') . ' 2>&1 &', + $user, ); } @@ -50,6 +49,6 @@ public function buildBackgroundCommand( */ protected function ensureCorrectUser(string $command, ?string $user = null): string { - return $user ? 'sudo -u '.$user.' -- sh -c \''.$command.'\'' : $command; + return $user ? 'sudo -u ' . $user . ' -- sh -c \'' . $command . '\'' : $command; } } diff --git a/src/CommandRunner.php b/src/CommandRunner.php index d520bc5..8d0886d 100644 --- a/src/CommandRunner.php +++ b/src/CommandRunner.php @@ -10,13 +10,10 @@ final class CommandRunner { public function __construct( - private readonly PhpExecutableFinder $phpFinder - ) { - } + private readonly PhpExecutableFinder $phpFinder, + ) {} - public function run(string $command): void - { - } + public function run(string $command): void {} /** * Determine the proper PHP executable. diff --git a/src/Commands/ScheduleFinishCommand.php b/src/Commands/ScheduleFinishCommand.php index 6b482b0..b1d946a 100644 --- a/src/Commands/ScheduleFinishCommand.php +++ b/src/Commands/ScheduleFinishCommand.php @@ -8,7 +8,6 @@ use Spiral\Console\Command; use Spiral\Scheduler\Event\BackgroundJobFinished; use Spiral\Scheduler\JobRegistryInterface; -use Symfony\Component\Console\Input\InputArgument; final class ScheduleFinishCommand extends Command { @@ -17,7 +16,7 @@ final class ScheduleFinishCommand extends Command public function perform( JobRegistryInterface $registry, - EventDispatcherInterface $dispatcher = null + ?EventDispatcherInterface $dispatcher = null, ): int { $id = $this->argument('id'); $exitCode = $this->argument('code') ?? 0; @@ -27,7 +26,7 @@ public function perform( continue; } - $job->finish($this->container, (int)$exitCode); + $job->finish($this->container, (int) $exitCode); $dispatcher?->dispatch(new BackgroundJobFinished($job)); } diff --git a/src/Commands/ScheduleRunCommand.php b/src/Commands/ScheduleRunCommand.php index 11b51b3..8c6ff1f 100644 --- a/src/Commands/ScheduleRunCommand.php +++ b/src/Commands/ScheduleRunCommand.php @@ -33,8 +33,8 @@ public function perform( \sprintf( '[%s] Running scheduled: `%s`', \date('c'), - $job->getDescription() ?? $job->getSystemDescription() - ) + $job->getDescription() ?? $job->getSystemDescription(), + ), ); $jobHandler->handle($job); diff --git a/src/Commands/ScheduleWorkCommand.php b/src/Commands/ScheduleWorkCommand.php index 376b63e..44a9330 100644 --- a/src/Commands/ScheduleWorkCommand.php +++ b/src/Commands/ScheduleWorkCommand.php @@ -13,18 +13,18 @@ final class ScheduleWorkCommand extends Command protected const DESCRIPTION = 'Start the schedule worker'; public function perform( - PeriodicCommandRunnerInterface $runner + PeriodicCommandRunnerInterface $runner, ): int { $this->info('Schedule worker started successfully.'); $runner->run( 'schedule:run', - function (string $message) { + function (string $message): void { $this->writeln($message); }, - function (string $message) { + function (string $message): void { $this->error($message); - } + }, ); return self::SUCCESS; diff --git a/src/Event/BackgroundJobFinished.php b/src/Event/BackgroundJobFinished.php index ffa2ab4..3abf0f5 100644 --- a/src/Event/BackgroundJobFinished.php +++ b/src/Event/BackgroundJobFinished.php @@ -9,7 +9,6 @@ final class BackgroundJobFinished { public function __construct( - public readonly Job $job - ) { - } + public readonly Job $job, + ) {} } diff --git a/src/Event/JobFailed.php b/src/Event/JobFailed.php index 03a6aaa..4ee6b05 100644 --- a/src/Event/JobFailed.php +++ b/src/Event/JobFailed.php @@ -10,7 +10,6 @@ final class JobFailed { public function __construct( public readonly Job $job, - public readonly \Throwable $exception - ) { - } + public readonly \Throwable $exception, + ) {} } diff --git a/src/Event/JobFinished.php b/src/Event/JobFinished.php index ccf893a..c2f3842 100644 --- a/src/Event/JobFinished.php +++ b/src/Event/JobFinished.php @@ -10,7 +10,6 @@ final class JobFinished { public function __construct( public readonly Job $job, - public readonly float $runtime - ) { - } + public readonly float $runtime, + ) {} } diff --git a/src/Event/JobStarting.php b/src/Event/JobStarting.php index fedee0d..90b6b67 100644 --- a/src/Event/JobStarting.php +++ b/src/Event/JobStarting.php @@ -9,7 +9,6 @@ final class JobStarting { public function __construct( - public readonly Job $job - ) { - } + public readonly Job $job, + ) {} } diff --git a/src/EveryMinuteCommandRunner.php b/src/EveryMinuteCommandRunner.php index 0a8c2d9..1fe1432 100644 --- a/src/EveryMinuteCommandRunner.php +++ b/src/EveryMinuteCommandRunner.php @@ -15,11 +15,10 @@ class EveryMinuteCommandRunner implements PeriodicCommandRunnerInterface public function __construct( private readonly ProcessFactory $processFactory, private readonly CommandRunner $runner, - private readonly SchedulerConfig $config - ) { - } + private readonly SchedulerConfig $config, + ) {} - public function run(string $command, \Closure $onSuccess = null, \Closure $onError = null): void + public function run(string $command, ?\Closure $onSuccess = null, ?\Closure $onError = null): void { while (true) { // Wait 100ms before checking if the process should be executed @@ -28,7 +27,7 @@ public function run(string $command, \Closure $onSuccess = null, \Closure $onErr if ($this->shouldProcessBeExecuted()) { $this->executions[] = $execution = $this->processFactory ->createFromShellCommandline( - $this->runner->formatCommandString($command) + $this->runner->formatCommandString($command), ); $execution->start(); diff --git a/src/Exception/CommandRunnerException.php b/src/Exception/CommandRunnerException.php index d2267d6..7e6492b 100644 --- a/src/Exception/CommandRunnerException.php +++ b/src/Exception/CommandRunnerException.php @@ -4,7 +4,4 @@ namespace Spiral\Scheduler\Exception; -class CommandRunnerException extends SchedulerException -{ - -} +class CommandRunnerException extends SchedulerException {} diff --git a/src/Exception/SchedulerException.php b/src/Exception/SchedulerException.php index 8c50d19..9f17404 100644 --- a/src/Exception/SchedulerException.php +++ b/src/Exception/SchedulerException.php @@ -4,7 +4,4 @@ namespace Spiral\Scheduler\Exception; -class SchedulerException extends \Exception -{ - -} +class SchedulerException extends \Exception {} diff --git a/src/Job/CallbackJob.php b/src/Job/CallbackJob.php index a193cea..0450bd4 100644 --- a/src/Job/CallbackJob.php +++ b/src/Job/CallbackJob.php @@ -11,7 +11,6 @@ use Spiral\Scheduler\CommandUtils; use Spiral\Scheduler\Config\SchedulerConfig; use Spiral\Scheduler\Mutex\JobMutexInterface; -use Throwable; final class CallbackJob extends Job { @@ -22,7 +21,7 @@ public function __construct( CronExpression $expression, protected ?string $description, private readonly \Closure $callback, - private readonly array $parameters = [] + private readonly array $parameters = [], ) { parent::__construct($mutex, $expression); } @@ -48,7 +47,7 @@ public function run(ContainerInterface $container): void $queue->pushCallable(static function ( InvokerInterface $invoker, - JobMutexInterface $mutex + JobMutexInterface $mutex, ) use ($callback, $params, $id): void { $invoker->invoke($callback, $params); $mutex->forget($id); @@ -58,7 +57,7 @@ public function run(ContainerInterface $container): void $invoker->invoke($callback, $params); $this->removeMutex(); } - } catch (Throwable $e) { + } catch (\Throwable $e) { $this->removeMutex(); throw $e; } @@ -66,12 +65,12 @@ public function run(ContainerInterface $container): void public function getId(): string { - return 'schedule-'.\sha1($this->getExpression().$this->description); + return 'schedule-' . \sha1($this->getExpression() . $this->description); } public function getSystemDescription(): string { - return 'Callback job: '.$this->getId(); + return 'Callback job: ' . $this->getId(); } public function getName(): string @@ -80,7 +79,7 @@ public function getName(): string return $this->name; } - return 'callback: '.CommandUtils::compileParameters(array_keys($this->parameters)); + return 'callback: ' . CommandUtils::compileParameters(\array_keys($this->parameters)); } public function setName(string $name): self diff --git a/src/Job/CommandJob.php b/src/Job/CommandJob.php index acb7c1e..4c1300d 100644 --- a/src/Job/CommandJob.php +++ b/src/Job/CommandJob.php @@ -17,7 +17,7 @@ public function __construct( private readonly ProcessFactory $processFactory, JobMutexInterface $mutex, CronExpression $expression, - private readonly string $command + private readonly string $command, ) { parent::__construct($mutex, $expression); } @@ -41,6 +41,19 @@ public function run(ContainerInterface $container): void : $this->runCommandInForeground($container); } + /** + * Get the id for the scheduled command. + */ + public function getId(): string + { + return 'schedule-' . \sha1($this->getExpression() . $this->command); + } + + public function getSystemDescription(): string + { + return $this->buildCommand(); + } + /** * Run the command in the foreground. */ @@ -73,19 +86,6 @@ private function runCommandInBackground(ContainerInterface $container): void } } - /** - * Get the id for the scheduled command. - */ - public function getId(): string - { - return 'schedule-'.\sha1($this->getExpression().$this->command); - } - - public function getSystemDescription(): string - { - return $this->buildCommand(); - } - private function buildCommand(): string { if ($this->runInBackground) { @@ -94,7 +94,7 @@ private function buildCommand(): string id: $this->getId(), appendOutput: $this->shouldAppendOutput, output: $this->output, - user: $this->user + user: $this->user, ); } @@ -102,7 +102,7 @@ private function buildCommand(): string command: $this->command, appendOutput: $this->shouldAppendOutput, output: $this->output, - user: $this->user + user: $this->user, ); } } diff --git a/src/Job/Job.php b/src/Job/Job.php index 34d4260..ba49354 100644 --- a/src/Job/Job.php +++ b/src/Job/Job.php @@ -13,14 +13,18 @@ use Butschster\CronExpression\Traits\Weeks; use Butschster\CronExpression\Traits\Years; use Cron\CronExpression; -use DateTimeInterface; use Psr\Container\ContainerInterface; use Spiral\Core\InvokerInterface; use Spiral\Scheduler\Mutex\JobMutexInterface; abstract class Job { - use Minutes, Hours, Days, Weeks, Months, Years; + use Minutes; + use Hours; + use Days; + use Weeks; + use Months; + use Years; public const SUNDAY = 0; public const MONDAY = 1; @@ -29,7 +33,6 @@ abstract class Job public const THURSDAY = 4; public const FRIDAY = 5; public const SATURDAY = 6; - public const JAN = 1; public const FEB = 2; public const MAR = 3; @@ -106,9 +109,8 @@ abstract class Job public function __construct( protected readonly JobMutexInterface $mutex, - protected CronExpression $expression - ) { - } + protected CronExpression $expression, + ) {} /** * Set the human-friendly description of the job. @@ -135,7 +137,7 @@ public function runAs(string $user): self */ public function getExpression(): string { - return (string)$this->expression; + return (string) $this->expression; } /** @@ -245,33 +247,6 @@ public function then(\Closure $callback): self return $this; } - /** - * Call all of the "before" callbacks for the job. - */ - final protected function callBeforeCallbacks(ContainerInterface $container): void - { - $invoker = $container->get(InvokerInterface::class); - - foreach ($this->beforeCallbacks as $callback) { - $invoker->invoke($callback); - } - } - - /** - * Call all of the "after" callbacks for the job. - */ - final protected function callAfterCallbacks(ContainerInterface $container): void - { - $invoker = $container->get(InvokerInterface::class); - - foreach ($this->afterCallbacks as $callback) { - $invoker->invoke($callback, [ - 'exitCode' => $this->exitCode, - 'job' => $this, - ]); - } - } - /** * Call all of the "after" callbacks for the job. */ @@ -313,13 +288,57 @@ public function isDue(\DateTimeInterface $date): bool return $this->expression->isDue($date); } - public function on(DateTimeInterface $time): self + public function on(\DateTimeInterface $time): self { $this->set(new DateTime($time)); return $this; } + /** + * @internal + */ + abstract public function run(ContainerInterface $container): void; + + abstract public function getSystemDescription(): string; + + /** + * Get the id for the scheduled command. + */ + abstract public function getId(): string; + + /** + * Get the id for the scheduled command. + */ + abstract public function getName(): string; + + /** + * Call all of the "before" callbacks for the job. + */ + final protected function callBeforeCallbacks(ContainerInterface $container): void + { + $invoker = $container->get(InvokerInterface::class); + + foreach ($this->beforeCallbacks as $callback) { + $invoker->invoke($callback); + } + } + + /** + * Call all of the "after" callbacks for the job. + */ + final protected function callAfterCallbacks(ContainerInterface $container): void + { + $invoker = $container->get(InvokerInterface::class); + + foreach ($this->afterCallbacks as $callback) { + $invoker->invoke($callback, [ + 'exitCode' => $this->exitCode, + 'job' => $this, + ]); + } + } + /** * Delete the mutex for the job. */ @@ -342,19 +361,4 @@ private function set(PartValueInterface ...$values): self return $this; } - - /** @internal */ - abstract public function run(ContainerInterface $container): void; - - abstract public function getSystemDescription(): string; - - /** - * Get the id for the scheduled command. - */ - abstract public function getId(): string; - - /** - * Get the id for the scheduled command. - */ - abstract public function getName(): string; } diff --git a/src/JobHandler.php b/src/JobHandler.php index 84ba602..8b78b9e 100644 --- a/src/JobHandler.php +++ b/src/JobHandler.php @@ -17,9 +17,8 @@ final class JobHandler implements JobHandlerInterface public function __construct( private readonly ContainerInterface $container, private readonly ?SnapshotterInterface $snapshotter = null, - private readonly ?EventDispatcherInterface $dispatcher = null - ) { - } + private readonly ?EventDispatcherInterface $dispatcher = null, + ) {} public function handle(Job $job): void { diff --git a/src/JobRegistryInterface.php b/src/JobRegistryInterface.php index bf842a7..fbcfb01 100644 --- a/src/JobRegistryInterface.php +++ b/src/JobRegistryInterface.php @@ -11,7 +11,6 @@ interface JobRegistryInterface public function register(Job $job): void; /** - * @param \DateTimeInterface $date * @return iterable */ public function getDueJobs(\DateTimeInterface $date): iterable; diff --git a/src/JobsLocator.php b/src/JobsLocator.php index b36c477..5a117e4 100644 --- a/src/JobsLocator.php +++ b/src/JobsLocator.php @@ -19,8 +19,7 @@ public function __construct( private readonly ClassesInterface $classes, private readonly ReaderInterface $reader, private readonly JobMutexInterface $mutex, - ) { - } + ) {} public function getJobs(): array { @@ -42,17 +41,17 @@ private function createJob(\ReflectionClass $class, ScheduleAttribute $schedule) $job = new CallbackJob( $this->mutex, new CronExpression( - $schedule->expression + $schedule->expression, ), $schedule->description, - static function (FactoryInterface $factory, InvokerInterface $invoker) use ($className, $parameters) { + static function (FactoryInterface $factory, InvokerInterface $invoker) use ($className, $parameters): void { $object = $factory->make($className); $invoker->invoke([ $object, \method_exists($object, 'run') ? 'run' : '__invoke', ], $parameters); - } + }, ); if ($schedule->name) { @@ -65,7 +64,7 @@ static function (FactoryInterface $factory, InvokerInterface $invoker) use ($cla if ($schedule->withoutOverlapping === true) { $job->withoutOverlapping(); - } else if(\is_int($schedule->withoutOverlapping)) { + } elseif (\is_int($schedule->withoutOverlapping)) { $job->withoutOverlapping($schedule->withoutOverlapping); } diff --git a/src/Mutex/CacheJobMutex.php b/src/Mutex/CacheJobMutex.php index f551f4c..d5bf222 100644 --- a/src/Mutex/CacheJobMutex.php +++ b/src/Mutex/CacheJobMutex.php @@ -9,9 +9,8 @@ final class CacheJobMutex implements JobMutexInterface { public function __construct( - private readonly CacheInterface $cache - ) { - } + private readonly CacheInterface $cache, + ) {} /** * TODO: use real mutexes diff --git a/src/PeriodicCommandRunnerInterface.php b/src/PeriodicCommandRunnerInterface.php index ae41557..c96958d 100644 --- a/src/PeriodicCommandRunnerInterface.php +++ b/src/PeriodicCommandRunnerInterface.php @@ -6,5 +6,5 @@ interface PeriodicCommandRunnerInterface { - public function run(string $command, \Closure $onSuccess = null, \Closure $onError = null): void; + public function run(string $command, ?\Closure $onSuccess = null, ?\Closure $onError = null): void; } diff --git a/src/ProcessFactory.php b/src/ProcessFactory.php index ef1ca1a..7610a41 100644 --- a/src/ProcessFactory.php +++ b/src/ProcessFactory.php @@ -10,16 +10,15 @@ class ProcessFactory { public function __construct( - private readonly DirectoriesInterface $dirs - ) { - } + private readonly DirectoriesInterface $dirs, + ) {} public function createFromShellCommandline(string $command): Process { return Process::fromShellCommandline( command: $command, cwd: $this->dirs->get('root'), - timeout: null + timeout: null, ); } } diff --git a/src/ProcessUtils.php b/src/ProcessUtils.php index 541efdb..500b0f9 100644 --- a/src/ProcessUtils.php +++ b/src/ProcessUtils.php @@ -16,7 +16,7 @@ public static function escapeArgument(string $argument): string // @see https://bugs.php.net/bug.php?id=43784 // @see https://bugs.php.net/bug.php?id=49446 if ('\\' === DIRECTORY_SEPARATOR) { - if ('' === $argument) { + if ($argument === '') { return '""'; } @@ -24,14 +24,14 @@ public static function escapeArgument(string $argument): string $quote = false; foreach (\preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { - if ('"' === $part) { + if ($part === '"') { $escapedArgument .= '\\"'; } elseif (self::isSurroundedBy($part, '%')) { // Avoid environment variable expansion - $escapedArgument .= '^%"'.\substr($part, 1, -1).'"^%'; + $escapedArgument .= '^%"' . \substr($part, 1, -1) . '"^%'; } else { // escape trailing backslash - if (str_ends_with($part, '\\')) { + if (\str_ends_with($part, '\\')) { $part .= '\\'; } $quote = true; @@ -40,13 +40,13 @@ public static function escapeArgument(string $argument): string } if ($quote) { - $escapedArgument = '"'.$escapedArgument.'"'; + $escapedArgument = '"' . $escapedArgument . '"'; } return $escapedArgument; } - return "'".\str_replace("'", "'\\''", $argument)."'"; + return "'" . \str_replace("'", "'\\''", $argument) . "'"; } /** @@ -54,6 +54,6 @@ public static function escapeArgument(string $argument): string */ protected static function isSurroundedBy(string $arg, string $char): bool { - return 2 < \strlen($arg) && $char === $arg[0] && $char === $arg[\strlen($arg) - 1]; + return \strlen($arg) > 2 && $char === $arg[0] && $char === $arg[\strlen($arg) - 1]; } } diff --git a/src/Schedule.php b/src/Schedule.php index 269ac2d..37b0609 100644 --- a/src/Schedule.php +++ b/src/Schedule.php @@ -4,7 +4,6 @@ namespace Spiral\Scheduler; -use Closure; use Cron\CronExpression; use Spiral\Console\Command; use Spiral\Core\FactoryInterface; @@ -16,22 +15,20 @@ final class Schedule { private const DEFAULT_EXPRESSION = '* * * * *'; - public function __construct( private readonly FactoryInterface $factory, private readonly ProcessFactory $processFactory, private readonly JobRegistryInterface $jobs, private readonly CommandRunner $commandRunner, - private readonly JobMutexInterface $jobMutex - ) { - } + private readonly JobMutexInterface $jobMutex, + ) {} /** * Add a new console command to the schedule. */ - public function command(string $commandName, array $parameters = [], string $description = null): CommandJob + public function command(string $commandName, array $parameters = [], ?string $description = null): CommandJob { - if (class_exists($commandName)) { + if (\class_exists($commandName)) { /** @var Command $command */ $command = $this->factory->make($commandName); @@ -44,7 +41,7 @@ public function command(string $commandName, array $parameters = [], string $des return $this->exec( $this->commandRunner->formatCommandString($commandName), $parameters, - $description + $description, ); } @@ -54,7 +51,7 @@ public function command(string $commandName, array $parameters = [], string $des public function exec(string $command, array $parameters = [], ?string $description = null): CommandJob { if (\count($parameters)) { - $command .= ' '.CommandUtils::compileParameters($parameters); + $command .= ' ' . CommandUtils::compileParameters($parameters); } $job = new CommandJob( @@ -62,7 +59,7 @@ public function exec(string $command, array $parameters = [], ?string $descripti processFactory: $this->processFactory, mutex: $this->jobMutex, expression: $this->createCronExpression(), - command: $command + command: $command, ); $job->description($description); @@ -71,14 +68,14 @@ public function exec(string $command, array $parameters = [], ?string $descripti return $job; } - public function call(string $description, Closure $callback, array $parameters = []): CallbackJob + public function call(string $description, \Closure $callback, array $parameters = []): CallbackJob { $job = new CallbackJob( mutex: $this->jobMutex, expression: $this->createCronExpression(), description: $description, callback: $callback, - parameters: $parameters + parameters: $parameters, ); $this->jobs->register($job); diff --git a/src/Testing/FakeJobHandler.php b/src/Testing/FakeJobHandler.php index d8da912..9002caf 100644 --- a/src/Testing/FakeJobHandler.php +++ b/src/Testing/FakeJobHandler.php @@ -16,7 +16,7 @@ public function assertHandled(\Closure $callback): void { TestCase::assertTrue( \count($this->getHandledJobs($callback)) > 0, - 'The expected job was not handled.' + 'The expected job was not handled.', ); } @@ -25,7 +25,7 @@ public function assertHandledTotalJobs(int $totalJobs): void $count = \count($this->handled); TestCase::assertTrue( $count === $totalJobs, - \sprintf('Scheduler handled {%d} jobs instead of {%d} times.', $count, $totalJobs) + \sprintf('Scheduler handled {%d} jobs instead of {%d} times.', $count, $totalJobs), ); } @@ -34,7 +34,7 @@ public function assertHandledJob(Job $job): void TestCase::assertContains( $job, $this->handled, - \sprintf('The expected job [%s] was not handled.', $job->getId()) + \sprintf('The expected job [%s] was not handled.', $job->getId()), ); } @@ -43,7 +43,7 @@ public function assertNotHandledJob(Job $job): void TestCase::assertNotContains( $job, $this->handled, - \sprintf('The expected job [%s] was handled unexpectedly.', $job->getId()) + \sprintf('The expected job [%s] was handled unexpectedly.', $job->getId()), ); } diff --git a/src/Testing/FakeJobMutex.php b/src/Testing/FakeJobMutex.php index 810a29a..7979656 100644 --- a/src/Testing/FakeJobMutex.php +++ b/src/Testing/FakeJobMutex.php @@ -12,12 +12,12 @@ final class FakeJobMutex implements JobMutexInterface private array $created = []; private array $deleted = []; - public function assertCreated(string $id, int $minutes = null): void + public function assertCreated(string $id, ?int $minutes = null): void { TestCase::assertArrayHasKey( $id, $this->created, - \sprintf('The expected [%s] job mutex was not created.', $id) + \sprintf('The expected [%s] job mutex was not created.', $id), ); if ($minutes !== null) { @@ -28,8 +28,8 @@ public function assertCreated(string $id, int $minutes = null): void 'The expected [%s] job mutex jas different ttl [%d], but expected [%d].', $id, $this->created[$id], - $minutes - ) + $minutes, + ), ); } } @@ -41,7 +41,7 @@ public function assertNothingCreated(): void TestCase::assertSame( 0, $count, - \sprintf('%d unexpected mutexes were created.', $count) + \sprintf('%d unexpected mutexes were created.', $count), ); } @@ -52,7 +52,7 @@ public function assertForgotten(string $id): void TestCase::assertArrayHasKey( $id, $this->deleted, - \sprintf('The expected [%s] job mutex was not forgotten.', $id) + \sprintf('The expected [%s] job mutex was not forgotten.', $id), ); } diff --git a/src/Testing/FakeJobRegistry.php b/src/Testing/FakeJobRegistry.php index e973fb1..6e89fd9 100644 --- a/src/Testing/FakeJobRegistry.php +++ b/src/Testing/FakeJobRegistry.php @@ -17,11 +17,11 @@ public function register(Job $job): void $this->registered[] = $job; } - public function assertRegistered(\Closure $callback) + public function assertRegistered(\Closure $callback): void { TestCase::assertTrue( \count($this->getRegisteredJobs($callback)) > 0, - 'The expected job was not dispatched.' + 'The expected job was not dispatched.', ); } @@ -30,7 +30,7 @@ public function assertRegisteredJob(Job $job): void TestCase::assertContains( $job, $this->getJobs(), - \sprintf('The expected [%s] job was not registered.', $job->getName()) + \sprintf('The expected [%s] job was not registered.', $job->getName()), ); } @@ -39,14 +39,11 @@ public function assertNotRegisteredJob(Job $job): void TestCase::assertNotContains( $job, $this->getJobs(), - \sprintf('The expected [%s] job was registered.', $job->getName()) + \sprintf('The expected [%s] job was registered.', $job->getName()), ); } - public function getDueJobs(\DateTimeInterface $date): iterable - { - - } + public function getDueJobs(\DateTimeInterface $date): iterable {} public function getJobs(): array { diff --git a/src/Testing/InteractsWithSchedule.php b/src/Testing/InteractsWithSchedule.php index 015169c..7788d05 100644 --- a/src/Testing/InteractsWithSchedule.php +++ b/src/Testing/InteractsWithSchedule.php @@ -20,7 +20,7 @@ public function runScheduler(string $expression) { $date = (new Generator())->cron($expression)->getExpression()->getNextRunDate(); - $this->runScoped(static function () use ($date) { + $this->runScoped(static function () use ($date): void { Carbon::setTestNow(Carbon::parse($date)); $command = new ScheduleRunCommand(); @@ -39,7 +39,7 @@ public function fakeScheduleJobHandler(): FakeJobHandler { $this->getContainer()->bindSingleton( JobHandlerInterface::class, - $handler = new FakeJobHandler() + $handler = new FakeJobHandler(), ); return $handler; @@ -49,7 +49,7 @@ public function fakeScheduleJobRegistry(): FakeJobRegistry { $this->getContainer()->bindSingleton( JobRegistryInterface::class, - $registry = new FakeJobRegistry() + $registry = new FakeJobRegistry(), ); return $registry; @@ -59,7 +59,7 @@ public function fakeScheduleJobMutex(): FakeJobMutex { $this->getContainer()->bindSingleton( JobMutexInterface::class, - $mutex = new FakeJobMutex() + $mutex = new FakeJobMutex(), ); return $mutex; diff --git a/tests/app/Jobs/AnotherSimpleJobWithAttribute.php b/tests/app/Jobs/AnotherSimpleJobWithAttribute.php index 636e7d1..831a89b 100644 --- a/tests/app/Jobs/AnotherSimpleJobWithAttribute.php +++ b/tests/app/Jobs/AnotherSimpleJobWithAttribute.php @@ -9,11 +9,9 @@ #[Schedule( name: 'Another simple job', expression: '@everyFifteenMinutes', - description: 'Another simple job description' + description: 'Another simple job description', )] final class AnotherSimpleJobWithAttribute { - public function __invoke() - { - } + public function __invoke(): void {} } diff --git a/tests/app/Jobs/JobWithoutAttributes.php b/tests/app/Jobs/JobWithoutAttributes.php index 32229cc..cefa266 100644 --- a/tests/app/Jobs/JobWithoutAttributes.php +++ b/tests/app/Jobs/JobWithoutAttributes.php @@ -4,7 +4,4 @@ namespace Spiral\Scheduler\Tests\App\Jobs; -class JobWithoutAttributes -{ - -} +class JobWithoutAttributes {} diff --git a/tests/app/Jobs/SimpleJobWithAttribute.php b/tests/app/Jobs/SimpleJobWithAttribute.php index f4c1c1e..d9a3c82 100644 --- a/tests/app/Jobs/SimpleJobWithAttribute.php +++ b/tests/app/Jobs/SimpleJobWithAttribute.php @@ -9,11 +9,9 @@ #[Schedule( name: 'Simple job', expression: '@everySixHours', - description: 'Simple job description' + description: 'Simple job description', )] final class SimpleJobWithAttribute { - public function __invoke() - { - } + public function __invoke(): void {} } diff --git a/tests/app/config/scheduler.php b/tests/app/config/scheduler.php index 5969552..fefae81 100644 --- a/tests/app/config/scheduler.php +++ b/tests/app/config/scheduler.php @@ -10,8 +10,8 @@ 'timezone' => 'UTC', 'expression' => [ 'aliases' => [ - '@everySixHours' => (string)$generator->everySixHours(), - '@everyFifteenMinutes' => (string)$generator->everyFifteenMinutes(), + '@everySixHours' => (string) $generator->everySixHours(), + '@everyFifteenMinutes' => (string) $generator->everyFifteenMinutes(), ], ], ]; diff --git a/tests/src/Bootloader/SchedulerBootloaderTest.php b/tests/src/Bootloader/SchedulerBootloaderTest.php index a4ccd44..f001e95 100644 --- a/tests/src/Bootloader/SchedulerBootloaderTest.php +++ b/tests/src/Bootloader/SchedulerBootloaderTest.php @@ -19,61 +19,61 @@ final class SchedulerBootloaderTest extends TestCase { - public function testPeriodicCommandRunner() + public function testPeriodicCommandRunner(): void { $this->assertContainerBoundAsSingleton( PeriodicCommandRunnerInterface::class, - EveryMinuteCommandRunner::class + EveryMinuteCommandRunner::class, ); } - public function testSchedule() + public function testSchedule(): void { $this->assertContainerBoundAsSingleton( Schedule::class, - Schedule::class + Schedule::class, ); } - public function testJobMutex() + public function testJobMutex(): void { $this->assertContainerBoundAsSingleton( JobMutexInterface::class, - CacheJobMutex::class + CacheJobMutex::class, ); } - public function testJobsLocator() + public function testJobsLocator(): void { $this->assertContainerBoundAsSingleton( JobsLocatorInterface::class, - JobsLocator::class + JobsLocator::class, ); $this->assertContainerBoundAsSingleton( JobsLocator::class, - JobsLocator::class + JobsLocator::class, ); } - public function testJobRegistry() + public function testJobRegistry(): void { $this->assertContainerBoundAsSingleton( JobRegistryInterface::class, - JobRegistry::class + JobRegistry::class, ); $this->assertContainerBoundAsSingleton( JobRegistry::class, - JobRegistry::class + JobRegistry::class, ); } - public function testJobHandler() + public function testJobHandler(): void { $this->assertContainerBoundAsSingleton( JobHandlerInterface::class, - JobHandler::class + JobHandler::class, ); } } diff --git a/tests/src/CommandBuilderTest.php b/tests/src/CommandBuilderTest.php index 8896998..6253252 100644 --- a/tests/src/CommandBuilderTest.php +++ b/tests/src/CommandBuilderTest.php @@ -12,24 +12,11 @@ final class CommandBuilderTest extends TestCase { private CommandBuilder $builder; - protected function setUp(): void - { - parent::setUp(); - - $this->builder = new CommandBuilder( - new CommandRunner( - $finder = $this->mockContainer(PhpExecutableFinder::class) - ) - ); - - $finder->shouldReceive('find')->with(false)->andReturn('/usr/bin/php'); - } - public function testBuildForegroundCommand(): void { $this->assertSame( "foo:bar > '/dev/null' 2>&1", - $this->builder->buildForegroundCommand('foo:bar') + $this->builder->buildForegroundCommand('foo:bar'), ); } @@ -37,7 +24,7 @@ public function testBuildForegroundCommandWithAppendOutput(): void { $this->assertSame( "foo:bar >> '/dev/null' 2>&1", - $this->builder->buildForegroundCommand('foo:bar', appendOutput: true) + $this->builder->buildForegroundCommand('foo:bar', appendOutput: true), ); } @@ -45,7 +32,7 @@ public function testBuildForegroundCommandWithOutput(): void { $this->assertSame( "foo:bar > '/foo/bar' 2>&1", - $this->builder->buildForegroundCommand('foo:bar', output: '/foo/bar') + $this->builder->buildForegroundCommand('foo:bar', output: '/foo/bar'), ); } @@ -53,7 +40,7 @@ public function testBuildForegroundCommandWithUser(): void { $this->assertSame( "sudo -u root -- sh -c 'foo:bar > '/dev/null' 2>&1'", - $this->builder->buildForegroundCommand('foo:bar', user: 'root') + $this->builder->buildForegroundCommand('foo:bar', user: 'root'), ); } @@ -61,7 +48,7 @@ public function testBuildBackgroundCommand(): void { $this->assertSame( "(foo:bar > '/dev/null' 2>&1 ; /usr/bin/php app.php schedule:finish \"foo-id\" \"$?\") > '/dev/null' 2>&1 &", - $this->builder->buildBackgroundCommand('foo:bar', 'foo-id') + $this->builder->buildBackgroundCommand('foo:bar', 'foo-id'), ); } @@ -69,7 +56,7 @@ public function testBuildBackgroundCommandWithAppendOutput(): void { $this->assertSame( "(foo:bar >> '/dev/null' 2>&1 ; /usr/bin/php app.php schedule:finish \"foo-id\" \"$?\") > '/dev/null' 2>&1 &", - $this->builder->buildBackgroundCommand('foo:bar', 'foo-id', appendOutput: true) + $this->builder->buildBackgroundCommand('foo:bar', 'foo-id', appendOutput: true), ); } @@ -77,7 +64,7 @@ public function testBuildBackgroundCommandWithOutput(): void { $this->assertSame( "(foo:bar > '/foo/bar' 2>&1 ; /usr/bin/php app.php schedule:finish \"foo-id\" \"$?\") > '/dev/null' 2>&1 &", - $this->builder->buildBackgroundCommand('foo:bar', 'foo-id', output: '/foo/bar') + $this->builder->buildBackgroundCommand('foo:bar', 'foo-id', output: '/foo/bar'), ); } @@ -85,7 +72,20 @@ public function testBuildBackgroundCommandWithUser(): void { $this->assertSame( "sudo -u root -- sh -c '(foo:bar > '/dev/null' 2>&1 ; /usr/bin/php app.php schedule:finish \"foo-id\" \"$?\") > '/dev/null' 2>&1 &'", - $this->builder->buildBackgroundCommand('foo:bar', 'foo-id', user: 'root') + $this->builder->buildBackgroundCommand('foo:bar', 'foo-id', user: 'root'), ); } + + protected function setUp(): void + { + parent::setUp(); + + $this->builder = new CommandBuilder( + new CommandRunner( + $finder = $this->mockContainer(PhpExecutableFinder::class), + ), + ); + + $finder->shouldReceive('find')->with(false)->andReturn('/usr/bin/php'); + } } diff --git a/tests/src/CommandRunnerTest.php b/tests/src/CommandRunnerTest.php index 18b1f96..e3c721e 100644 --- a/tests/src/CommandRunnerTest.php +++ b/tests/src/CommandRunnerTest.php @@ -13,15 +13,6 @@ final class CommandRunnerTest extends TestCase private CommandRunner $runner; private \Mockery\MockInterface $finder; - protected function setUp(): void - { - parent::setUp(); - - $this->runner = new CommandRunner( - $this->finder = \Mockery::mock(PhpExecutableFinder::class) - ); - } - public function testGetsPhpBinary(): void { $this->finder->shouldReceive('find')->once()->andReturn('/path/to/php'); @@ -36,4 +27,13 @@ public function testNonExistPhpBinaryShouldThrowAnException(): void $this->finder->shouldReceive('find')->once()->andReturnFalse(); $this->runner->phpBinary(); } + + protected function setUp(): void + { + parent::setUp(); + + $this->runner = new CommandRunner( + $this->finder = \Mockery::mock(PhpExecutableFinder::class), + ); + } } diff --git a/tests/src/Commands/ScheduleFinishCommandTest.php b/tests/src/Commands/ScheduleFinishCommandTest.php index 5074b98..9f197c0 100644 --- a/tests/src/Commands/ScheduleFinishCommandTest.php +++ b/tests/src/Commands/ScheduleFinishCommandTest.php @@ -19,14 +19,7 @@ final class ScheduleFinishCommandTest extends TestCase { private \Mockery\MockInterface $registry; - protected function setUp(): void - { - parent::setUp(); - - $this->registry = $this->mockContainer(JobRegistryInterface::class); - } - - public function testFoundJobShouldBeFinished() + public function testFoundJobShouldBeFinished(): void { $events = $this->mockContainer(EventDispatcherInterface::class); @@ -35,7 +28,7 @@ public function testFoundJobShouldBeFinished() $job2 = m::mock(Job::class), ]); - $events->shouldReceive('dispatch')->withArgs(function (mixed $event) use ($job1) { + $events->shouldReceive('dispatch')->withArgs(static function (mixed $event) use ($job1) { return match (true) { $event instanceof CommandStarting => $event->command instanceof ScheduleFinishCommand, $event instanceof BackgroundJobFinished => $event->job === $job1, @@ -43,7 +36,7 @@ public function testFoundJobShouldBeFinished() && $event->command instanceof ScheduleFinishCommand, $event instanceof InterceptorCalling, $event instanceof \Spiral\Core\Event\InterceptorCalling => true, - default => false + default => false, }; }); @@ -54,4 +47,11 @@ public function testFoundJobShouldBeFinished() $this->runCommand('schedule:finish', ['id' => 'foo-id', 'code' => 200]); } + + protected function setUp(): void + { + parent::setUp(); + + $this->registry = $this->mockContainer(JobRegistryInterface::class); + } } diff --git a/tests/src/Commands/ScheduleListCommandTest.php b/tests/src/Commands/ScheduleListCommandTest.php index 0f1574a..5278d1d 100644 --- a/tests/src/Commands/ScheduleListCommandTest.php +++ b/tests/src/Commands/ScheduleListCommandTest.php @@ -15,14 +15,16 @@ public function testEmptyList(): void $registry->shouldReceive('getJobs')->andReturn([]); $this->assertConsoleCommandOutputContainsStrings( - 'schedule:list', strings: ['No scheduled jobs registered.'] + 'schedule:list', + strings: ['No scheduled jobs registered.'], ); } public function testRegisteredJobs(): void { $this->assertConsoleCommandOutputContainsStrings( - 'schedule:list', strings: ['Simple job', 'Another simple job'] + 'schedule:list', + strings: ['Simple job', 'Another simple job'], ); } } diff --git a/tests/src/Commands/ScheduleRunCommandTest.php b/tests/src/Commands/ScheduleRunCommandTest.php index 72c63a0..02eab25 100644 --- a/tests/src/Commands/ScheduleRunCommandTest.php +++ b/tests/src/Commands/ScheduleRunCommandTest.php @@ -17,7 +17,8 @@ public function testNoScheduledJobs(): void $registry->shouldReceive('getDueJobs')->andReturn([]); $this->assertConsoleCommandOutputContainsStrings( - 'schedule:run', strings: ['No scheduled jobs are ready to run.'] + 'schedule:run', + strings: ['No scheduled jobs are ready to run.'], ); } @@ -39,17 +40,18 @@ public function testDueJobsShouldBeRun(): void $handler = $this->fakeScheduleJobHandler(); $this->assertConsoleCommandOutputContainsStrings( - 'schedule:run', strings: ['Running scheduled: `Job description`'] + 'schedule:run', + strings: ['Running scheduled: `Job description`'], ); $handler->assertHandledJob($job2); $handler->assertNotHandledJob($job1); } - public function testHandleJobByExpression() + public function testHandleJobByExpression(): void { $scheduler = $this->runScheduler('@everyFifteenMinutes'); - $scheduler->assertHandled(function (Job $job) { + $scheduler->assertHandled(static function (Job $job) { return $job->getName() === 'Another simple job'; }); $scheduler->assertHandledTotalJobs(1); @@ -57,10 +59,10 @@ public function testHandleJobByExpression() // $scheduler = $this->runScheduler('@everySixHours'); - $scheduler->assertHandled(function (Job $job) { + $scheduler->assertHandled(static function (Job $job) { return $job->getName() === 'Another simple job'; }); - $scheduler->assertHandled(function (Job $job) { + $scheduler->assertHandled(static function (Job $job) { return $job->getName() === 'Simple job'; }); $scheduler->assertHandledTotalJobs(2); diff --git a/tests/src/Commands/ScheduleWorkCommandTest.php b/tests/src/Commands/ScheduleWorkCommandTest.php index 56d981f..6507194 100644 --- a/tests/src/Commands/ScheduleWorkCommandTest.php +++ b/tests/src/Commands/ScheduleWorkCommandTest.php @@ -13,7 +13,7 @@ public function testWorker(): void { $runner = $this->mockContainer(PeriodicCommandRunnerInterface::class); $runner->shouldReceive('run')->once()->withSomeOfArgs('schedule:run')->andReturnUsing( - function (string $command, \Closure $onSuccess, \Closure $onError) { + static function (string $command, \Closure $onSuccess, \Closure $onError): void { foreach ([1, 2] as $tick) { if ($tick === 1) { $onSuccess('Job handled'); @@ -23,11 +23,11 @@ function (string $command, \Closure $onSuccess, \Closure $onError) { $onError('Job error'); } } - } + }, ); $this->assertConsoleCommandOutputContainsStrings('schedule:work', [], [ - 'Schedule worker started successfully.', 'Job handled', 'Job error' + 'Schedule worker started successfully.', 'Job handled', 'Job error', ]); } } diff --git a/tests/src/Config/SchedulerConfigTest.php b/tests/src/Config/SchedulerConfigTest.php index a26e4e4..96744da 100644 --- a/tests/src/Config/SchedulerConfigTest.php +++ b/tests/src/Config/SchedulerConfigTest.php @@ -12,7 +12,7 @@ final class SchedulerConfigTest extends TestCase public function testGetsTimezone(): void { $config = new SchedulerConfig([ - 'timezone' => 'UTC' + 'timezone' => 'UTC', ]); $this->assertSame('UTC', $config->getTimezone()->getName()); @@ -21,7 +21,7 @@ public function testGetsTimezone(): void public function testGetsTimezoneCanReturnNull(): void { $config = new SchedulerConfig([ - 'timezone' => null + 'timezone' => null, ]); $this->assertNull($config->getTimezone()); } @@ -36,7 +36,7 @@ public function testGetsDefaultTimezone(): void public function testGetsCacheStorage(): void { $config = new SchedulerConfig([ - 'cacheStorage' => 'foo' + 'cacheStorage' => 'foo', ]); $this->assertSame('foo', $config->getCacheStorage()); } @@ -50,7 +50,7 @@ public function testGetsCacheStorageCanReturnNull(): void public function testGetsQueueConnection(): void { $config = new SchedulerConfig([ - 'queueConnection' => 'bar' + 'queueConnection' => 'bar', ]); $this->assertSame('bar', $config->getQueueConnection()); } diff --git a/tests/src/Job/CallbackJobTest.php b/tests/src/Job/CallbackJobTest.php index 675c245..89f4c70 100644 --- a/tests/src/Job/CallbackJobTest.php +++ b/tests/src/Job/CallbackJobTest.php @@ -19,25 +19,6 @@ final class CallbackJobTest extends TestCase private CallbackJob $job; private m\MockInterface $mutex; - protected function setUp(): void - { - parent::setUp(); - - $this->pinger = $this->mockContainer(PingerInterface::class); - - $this->job = new CallbackJob( - $this->mutex = $this->mockContainer(JobMutexInterface::class), - new CronExpression('* * * * *'), - 'Callable job description', - function (PingerInterface $pinger, string $url) { - $pinger->ping($url); - }, - [ - 'url' => 'https://site.com', - ] - ); - } - public function testGetsId(): void { $this->assertSame('schedule-64ec6d2de2e52435fdb2cb0676597ed557c88810', $this->job->getId()); @@ -82,7 +63,7 @@ public function testRunInBackground(): void ->once() ->with('queue-test') ->andReturn($queue = m::mock(QueueInterface::class)); - $queue->shouldReceive('pushCallable')->once()->andReturnUsing(function (\Closure $closure) { + $queue->shouldReceive('pushCallable')->once()->andReturnUsing(function (\Closure $closure): void { $this->getContainer()->invoke($closure); }); @@ -110,7 +91,7 @@ public function testRunInBackgroundWithoutOverlapping(): void ->once() ->with('queue-test') ->andReturn($queue = m::mock(QueueInterface::class)); - $queue->shouldReceive('pushCallable')->once()->andReturnUsing(function (\Closure $closure) { + $queue->shouldReceive('pushCallable')->once()->andReturnUsing(function (\Closure $closure): void { $this->getContainer()->invoke($closure); }); @@ -132,4 +113,23 @@ public function testWithoutOverlapping(): void $this->pinger->shouldReceive('ping')->once()->with('https://site.com')->andReturnTrue(); $this->job->withoutOverlapping(1500)->run($this->getContainer()); } + + protected function setUp(): void + { + parent::setUp(); + + $this->pinger = $this->mockContainer(PingerInterface::class); + + $this->job = new CallbackJob( + $this->mutex = $this->mockContainer(JobMutexInterface::class), + new CronExpression('* * * * *'), + 'Callable job description', + static function (PingerInterface $pinger, string $url): void { + $pinger->ping($url); + }, + [ + 'url' => 'https://site.com', + ], + ); + } } diff --git a/tests/src/Job/CommandJobTest.php b/tests/src/Job/CommandJobTest.php index 2264c9c..94bb80a 100644 --- a/tests/src/Job/CommandJobTest.php +++ b/tests/src/Job/CommandJobTest.php @@ -21,23 +21,6 @@ final class CommandJobTest extends TestCase private m\MockInterface $processFactory; private m\MockInterface $mutex; - protected function setUp(): void - { - parent::setUp(); - - $this->job = new CommandJob( - new CommandBuilder(new CommandRunner( - $finder = m::mock(PhpExecutableFinder::class) - )), - $this->processFactory = m::mock(ProcessFactory::class), - $this->mutex = m::mock(JobMutexInterface::class), - new CronExpression('* * * * *'), - 'foo:bar' - ); - - $finder->shouldReceive('find')->andReturn('/usr/bin/php'); - } - public function testGetsId(): void { $this->assertSame('schedule-6a31f94cad6c051f7fc2c0bcef19cbcded3f7330', $this->job->getId()); @@ -120,4 +103,21 @@ public function testRunWithoutOverlappingWithFiredJob(): void $this->assertSame(1600, $this->job->getExpiresAt()); } + + protected function setUp(): void + { + parent::setUp(); + + $this->job = new CommandJob( + new CommandBuilder(new CommandRunner( + $finder = m::mock(PhpExecutableFinder::class), + )), + $this->processFactory = m::mock(ProcessFactory::class), + $this->mutex = m::mock(JobMutexInterface::class), + new CronExpression('* * * * *'), + 'foo:bar', + ); + + $finder->shouldReceive('find')->andReturn('/usr/bin/php'); + } } diff --git a/tests/src/JobHandlerTest.php b/tests/src/JobHandlerTest.php index e7fa8d7..d1e8900 100644 --- a/tests/src/JobHandlerTest.php +++ b/tests/src/JobHandlerTest.php @@ -17,7 +17,7 @@ final class JobHandlerTest extends TestCase public function testHandleJob(): void { $handler = new JobHandler( - $this->getContainer() + $this->getContainer(), ); $job = \Mockery::mock(Job::class); @@ -34,11 +34,11 @@ public function testHandleJobWithSnapshotterAndEventBus(): void $events = $this->mockContainer(EventDispatcherInterface::class), ); - $events->shouldReceive('dispatch')->once()->withArgs(function ($job) { + $events->shouldReceive('dispatch')->once()->withArgs(static function ($job) { return $job instanceof JobStarting; }); - $events->shouldReceive('dispatch')->once()->withArgs(function ($job) { + $events->shouldReceive('dispatch')->once()->withArgs(static function ($job) { return $job instanceof JobFinished; }); @@ -56,11 +56,11 @@ public function testHandleFailedJobShouldThrowAnException(): void $events = $this->mockContainer(EventDispatcherInterface::class), ); - $events->shouldReceive('dispatch')->once()->withArgs(function ($job) { + $events->shouldReceive('dispatch')->once()->withArgs(static function ($job) { return $job instanceof JobStarting; }); - $events->shouldReceive('dispatch')->once()->withArgs(function ($job) { + $events->shouldReceive('dispatch')->once()->withArgs(static function ($job) { return $job instanceof JobFailed; }); diff --git a/tests/src/JobRegistryTest.php b/tests/src/JobRegistryTest.php index 710463c..014ff68 100644 --- a/tests/src/JobRegistryTest.php +++ b/tests/src/JobRegistryTest.php @@ -12,13 +12,6 @@ final class JobRegistryTest extends TestCase { private JobRegistry $registry; - protected function setUp(): void - { - parent::setUp(); - - $this->registry = new JobRegistry(); - } - public function testJobShouldBeRegistered(): void { $this->assertCount(0, $this->registry->getJobs()); @@ -26,7 +19,7 @@ public function testJobShouldBeRegistered(): void $this->assertCount(1, $this->registry->getJobs()); } - public function testGetsGueJobs() + public function testGetsGueJobs(): void { $date = new \DateTimeImmutable(); @@ -39,10 +32,17 @@ public function testGetsGueJobs() $this->registry->register($job3 = m::mock(Job::class)); $job3->shouldReceive('isDue')->once()->with($date)->andReturnTrue(); - $jobs = iterator_to_array($this->registry->getDueJobs($date)); + $jobs = \iterator_to_array($this->registry->getDueJobs($date)); $this->assertCount(2, $jobs); $this->assertContains($job1, $jobs); $this->assertContains($job3, $jobs); } + + protected function setUp(): void + { + parent::setUp(); + + $this->registry = new JobRegistry(); + } } diff --git a/tests/src/JobsLocatorTest.php b/tests/src/JobsLocatorTest.php index c85f408..52c7a14 100644 --- a/tests/src/JobsLocatorTest.php +++ b/tests/src/JobsLocatorTest.php @@ -14,12 +14,12 @@ final class JobsLocatorTest extends TestCase { - public function testLocateJobs() + public function testLocateJobs(): void { $locator = new JobsLocator( $classes = $this->mockContainer(ClassesInterface::class), new AttributeReader(), - $this->mockContainer(JobMutexInterface::class) + $this->mockContainer(JobMutexInterface::class), ); $classes->shouldReceive('getClasses')->once()->andReturn([ diff --git a/tests/src/Mutex/CacheJobMutexTest.php b/tests/src/Mutex/CacheJobMutexTest.php index 2de0282..0cca30e 100644 --- a/tests/src/Mutex/CacheJobMutexTest.php +++ b/tests/src/Mutex/CacheJobMutexTest.php @@ -14,15 +14,7 @@ final class CacheJobMutexTest extends TestCase private \Mockery\MockInterface $cache; private CacheJobMutex $mutex; - protected function setUp(): void - { - parent::setUp(); - - $this->cache = $this->mockContainer(CacheInterface::class); - $this->mutex = new CacheJobMutex($this->cache); - } - - public function testCreates() + public function testCreates(): void { $this->cache->shouldReceive('set')->with('job-id', true, 100 * 60)->andReturnTrue(); $this->cache->shouldReceive('has')->with('job-id')->andReturnFalse(); @@ -30,22 +22,30 @@ public function testCreates() $this->assertTrue($this->mutex->create('job-id', 100)); } - public function testCreatesShouldReturnFalseIfJobIdExist() + public function testCreatesShouldReturnFalseIfJobIdExist(): void { $this->cache->shouldReceive('has')->with('job-id')->andReturnTrue(); $this->assertFalse($this->mutex->create('job-id', 100)); } - public function testExists() + public function testExists(): void { $this->cache->shouldReceive('has')->with('job-id')->andReturnTrue(); $this->assertTrue($this->mutex->exists('job-id')); } #[DoesNotPerformAssertions] - public function testForget() + public function testForget(): void { $this->cache->shouldReceive('delete')->with('job-id'); $this->mutex->forget('job-id'); } + + protected function setUp(): void + { + parent::setUp(); + + $this->cache = $this->mockContainer(CacheInterface::class); + $this->mutex = new CacheJobMutex($this->cache); + } } diff --git a/tests/src/ProcessFactoryTest.php b/tests/src/ProcessFactoryTest.php index 57db92d..1b19a12 100644 --- a/tests/src/ProcessFactoryTest.php +++ b/tests/src/ProcessFactoryTest.php @@ -12,7 +12,7 @@ final class ProcessFactoryTest extends TestCase public function testCreatesFromShellCommandline(): void { $factory = new ProcessFactory( - $dirs = $this->mockContainer(DirectoriesInterface::class) + $dirs = $this->mockContainer(DirectoriesInterface::class), ); $dirs->shouldReceive('get')->once()->with('root')->andReturn('/path/to/project'); diff --git a/tests/src/ScheduleTest.php b/tests/src/ScheduleTest.php index 44e6831..fa69e39 100644 --- a/tests/src/ScheduleTest.php +++ b/tests/src/ScheduleTest.php @@ -17,26 +17,7 @@ final class ScheduleTest extends TestCase private Schedule $schedule; private FakeJobRegistry $registry; - protected function setUp(): void - { - parent::setUp(); - - $this->registry = $this->fakeScheduleJobRegistry(); - - $this->schedule = new Schedule( - $this->getContainer(), - $this->mockContainer(ProcessFactory::class), - $this->registry, - new CommandRunner( - $finder = $this->mockContainer(PhpExecutableFinder::class) - ), - $this->mockContainer(JobMutexInterface::class) - ); - - $finder->shouldReceive('find')->andReturn('/usr/bin/php'); - } - - public function testRegisterCommand() + public function testRegisterCommand(): void { $job = $this->schedule ->command('foo:bar', ['baz' => 'biz'], 'Simple job') @@ -49,7 +30,7 @@ public function testRegisterCommand() $this->registry->assertRegisteredJob($job); } - public function testRegisterCommandByClassname() + public function testRegisterCommandByClassname(): void { $job = $this->schedule ->command(SimpleCommand::class, ['baz' => 'biz'], 'Simple job') @@ -62,11 +43,10 @@ public function testRegisterCommandByClassname() $this->registry->assertRegisteredJob($job); } - public function testRegisterCallableJob() + public function testRegisterCallableJob(): void { $job = $this->schedule - ->call('Simple callable job', static function () { - }, ['baz' => 'biz']) + ->call('Simple callable job', static function (): void {}, ['baz' => 'biz']) ->everyFourMinutes(); $this->assertSame('callback: \'baz\'', $job->getName()); @@ -75,4 +55,23 @@ public function testRegisterCallableJob() $this->registry->assertRegisteredJob($job); } + + protected function setUp(): void + { + parent::setUp(); + + $this->registry = $this->fakeScheduleJobRegistry(); + + $this->schedule = new Schedule( + $this->getContainer(), + $this->mockContainer(ProcessFactory::class), + $this->registry, + new CommandRunner( + $finder = $this->mockContainer(PhpExecutableFinder::class), + ), + $this->mockContainer(JobMutexInterface::class), + ); + + $finder->shouldReceive('find')->andReturn('/usr/bin/php'); + } } diff --git a/tests/src/TestCase.php b/tests/src/TestCase.php index 0b189a9..addc7c8 100644 --- a/tests/src/TestCase.php +++ b/tests/src/TestCase.php @@ -1,5 +1,7 @@ Date: Fri, 13 Dec 2024 18:36:12 +0400 Subject: [PATCH 3/3] Psalm: suppress MissingClassConstType --- psalm.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/psalm.xml b/psalm.xml index a4a3016..12db8e1 100644 --- a/psalm.xml +++ b/psalm.xml @@ -14,6 +14,7 @@ +