| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <?php
- declare(strict_types=1);
- namespace SixShop\System\Hook;
- use ReflectionClass;
- use ReflectionMethod;
- use SixShop\Core\Attribute\Cron;
- use SixShop\Core\Attribute\Hook;
- use SixShop\Core\Helper;
- use SixShop\System\Event\CrontabWorkerStartEvent;
- use SixShop\System\Event\GetCronJobsEvent;
- use SixShop\System\ExtensionManager;
- use think\App;
- use Workerman\Crontab\Crontab;
- use function SixShop\Core\extension_name_list;
- class GatheringCrontabEventHook
- {
- public function __construct(private App $app)
- {
- }
- /**
- * @throws \ReflectionException
- */
- #[Hook(CrontabWorkerStartEvent::class)]
- public function onWorkerStart(): void
- {
- $extensionManager = $this->app->make(ExtensionManager::class);
- $event = new GetCronJobsEvent();
- foreach (extension_name_list() as $extensionName) {
- $extension = $extensionManager->getExtension($extensionName);
- if ($extension->available()) {
- $cronJobs = $extension->getCronJobs();
- foreach ($cronJobs as $cronJobClass) {
- $event->push($cronJobClass);
- }
- }
- }
- $this->app->event->trigger($event);
- foreach ($event as $cronJobClass) {
- $ref = new ReflectionClass($cronJobClass);
- foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
- $attributes = $method->getAttributes(Cron::class);
- foreach ($attributes as $attribute) {
- $cronInstance = $attribute->newInstance();
- $name = $cronInstance->name ?: $cronJobClass . '@' . $method->getName();
- new Crontab($cronInstance->rule, [$this->app->make($cronJobClass), $method->getName()], $name);
- }
- }
- }
- }
- }
|