This commit is contained in:
2026-05-01 23:40:14 +08:00
commit b8f599a617
3867 changed files with 478663 additions and 0 deletions
+262
View File
@@ -0,0 +1,262 @@
<?php
namespace Illuminate\Events;
use Illuminate\Bus\Queueable;
use Illuminate\Container\Container;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Queue\Job;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class CallQueuedListener implements ShouldQueue
{
use InteractsWithQueue, Queueable;
/**
* The listener class name.
*
* @var class-string
*/
public $class;
/**
* The listener method.
*
* @var string
*/
public $method;
/**
* The data to be passed to the listener.
*
* @var array
*/
public $data;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries;
/**
* The maximum number of exceptions allowed, regardless of attempts.
*
* @var int
*/
public $maxExceptions;
/**
* The number of seconds to wait before retrying a job that encountered an uncaught exception.
*
* @var int
*/
public $backoff;
/**
* The timestamp indicating when the job should timeout.
*
* @var int
*/
public $retryUntil;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout;
/**
* Indicates if the job should fail if the timeout is exceeded.
*
* @var bool
*/
public $failOnTimeout = false;
/**
* Indicates if the job should be encrypted.
*
* @var bool
*/
public $shouldBeEncrypted = false;
/**
* Indicates if the job should be deleted when models are missing.
*
* @var bool
*/
public $deleteWhenMissingModels;
/**
* Indicates if the listener should be unique.
*/
public bool $shouldBeUnique = false;
/**
* Indicates if the listener should be unique until processing begins.
*/
public bool $shouldBeUniqueUntilProcessing = false;
/**
* The unique ID of the listener.
*/
public mixed $uniqueId = null;
/**
* The number of seconds the unique lock should be maintained.
*/
public ?int $uniqueFor = null;
/**
* Create a new job instance.
*
* @param class-string $class
* @param string $method
* @param array $data
*/
public function __construct($class, $method, $data)
{
$this->data = $data;
$this->class = $class;
$this->method = $method;
}
/**
* Handle the queued job.
*
* @param \Illuminate\Container\Container $container
* @return void
*/
public function handle(Container $container)
{
$this->prepareData();
$handler = $this->setJobInstanceIfNecessary(
$this->job, $container->make($this->class)
);
$handler->{$this->method}(...array_values($this->data));
}
/**
* Determine if the listener should be unique.
*/
public function shouldBeUnique(): bool
{
return $this->shouldBeUnique;
}
/**
* Determine if the listener should be unique until processing begins.
*/
public function shouldBeUniqueUntilProcessing(): bool
{
return $this->shouldBeUniqueUntilProcessing;
}
/**
* Get the unique ID for the listener.
*/
public function uniqueId(): mixed
{
return $this->uniqueId;
}
/**
* Get the number of seconds the unique lock should be maintained.
*/
public function uniqueFor(): ?int
{
return $this->uniqueFor;
}
/**
* Get the cache store used to manage unique locks.
*/
public function uniqueVia(): ?Cache
{
$listener = Container::getInstance()->make($this->class);
if (! method_exists($listener, 'uniqueVia')) {
return null;
}
$this->prepareData();
return $listener->uniqueVia(...array_values($this->data));
}
/**
* Set the job instance of the given class if necessary.
*
* @param \Illuminate\Contracts\Queue\Job $job
* @param object $instance
* @return object
*/
protected function setJobInstanceIfNecessary(Job $job, $instance)
{
if (isset(class_uses_recursive($instance)[InteractsWithQueue::class])) {
$instance->setJob($job);
}
return $instance;
}
/**
* Call the failed method on the job instance.
*
* The event instance and the exception will be passed.
*
* @param \Throwable $e
* @return void
*/
public function failed($e)
{
$this->prepareData();
$handler = Container::getInstance()->make($this->class);
$parameters = array_merge(array_values($this->data), [$e]);
if (method_exists($handler, 'failed')) {
$handler->failed(...$parameters);
}
}
/**
* Unserialize the data if needed.
*
* @return void
*/
protected function prepareData()
{
if (is_string($this->data)) {
$this->data = unserialize($this->data);
}
}
/**
* Get the display name for the queued job.
*
* @return string
*/
public function displayName()
{
return $this->class;
}
/**
* Prepare the instance for cloning.
*
* @return void
*/
public function __clone()
{
$this->data = array_map(function ($data) {
return is_object($data) ? clone $data : $data;
}, $this->data);
}
}
+901
View File
@@ -0,0 +1,901 @@
<?php
namespace Illuminate\Events;
use Closure;
use Exception;
use Illuminate\Bus\UniqueLock;
use Illuminate\Container\Container;
use Illuminate\Contracts\Broadcasting\Factory as BroadcastFactory;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Container\Container as ContainerContract;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Connection;
use Illuminate\Queue\Attributes\Delay;
use Illuminate\Queue\Attributes\DeleteWhenMissingModels;
use Illuminate\Queue\Attributes\FailOnTimeout;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Queue as QueueAttribute;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Queue\Concerns\ResolvesQueueRoutes;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\ReadsClassAttributes;
use Illuminate\Support\Traits\ReflectsClosures;
use ReflectionClass;
use function Illuminate\Support\enum_value;
class Dispatcher implements DispatcherContract
{
use Macroable, ReadsClassAttributes, ReflectsClosures, ResolvesQueueRoutes;
/**
* The IoC container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* The registered event listeners.
*
* @var array<string, callable|array|class-string|null>
*/
protected $listeners = [];
/**
* The wildcard listeners.
*
* @var array<string, \Closure|string>
*/
protected $wildcards = [];
/**
* The cached wildcard listeners.
*
* @var array<string, \Closure|string>
*/
protected $wildcardsCache = [];
/**
* The queue resolver instance.
*
* @var callable(): \Illuminate\Contracts\Queue\Queue
*/
protected $queueResolver;
/**
* The database transaction manager resolver instance.
*
* @var callable
*/
protected $transactionManagerResolver;
/**
* The currently deferred events.
*
* @var array
*/
protected $deferredEvents = [];
/**
* Indicates if events should be deferred.
*
* @var bool
*/
protected $deferringEvents = false;
/**
* The specific events to defer (null means defer all events).
*
* @var string[]|null
*/
protected $eventsToDefer = null;
/**
* Create a new event dispatcher instance.
*/
public function __construct(?ContainerContract $container = null)
{
$this->container = $container ?: new Container;
}
/**
* Register an event listener with the dispatcher.
*
* @param \Illuminate\Events\QueuedClosure|callable|array|class-string|string $events
* @param \Illuminate\Events\QueuedClosure|callable|array|class-string|null $listener
* @return void
*/
public function listen($events, $listener = null)
{
if ($events instanceof Closure) {
return (new Collection($this->firstClosureParameterTypes($events)))
->each(function ($event) use ($events) {
$this->listen($event, $events);
});
} elseif ($events instanceof QueuedClosure) {
return (new Collection($this->firstClosureParameterTypes($events->closure)))
->each(function ($event) use ($events) {
$this->listen($event, $events->resolve());
});
} elseif ($listener instanceof QueuedClosure) {
$listener = $listener->resolve();
}
foreach ((array) $events as $event) {
if (str_contains($event, '*')) {
$this->setupWildcardListen($event, $listener);
} else {
$this->listeners[$event][] = $listener;
}
}
}
/**
* Setup a wildcard listener callback.
*
* @param string $event
* @param \Closure|string $listener
* @return void
*/
protected function setupWildcardListen($event, $listener)
{
$this->wildcards[$event][] = $listener;
$this->wildcardsCache = [];
}
/**
* Determine if a given event has listeners.
*
* @param string $eventName
* @return bool
*/
public function hasListeners($eventName)
{
return isset($this->listeners[$eventName]) ||
isset($this->wildcards[$eventName]) ||
$this->hasWildcardListeners($eventName);
}
/**
* Determine if the given event has any wildcard listeners.
*
* @param string $eventName
* @return bool
*/
public function hasWildcardListeners($eventName)
{
foreach ($this->wildcards as $key => $listeners) {
if (Str::is($key, $eventName)) {
return true;
}
}
return false;
}
/**
* Register an event and payload to be fired later.
*
* @param string $event
* @param object|array $payload
* @return void
*/
public function push($event, $payload = [])
{
$this->listen($event.'_pushed', function () use ($event, $payload) {
$this->dispatch($event, $payload);
});
}
/**
* Flush a set of pushed events.
*
* @param string $event
* @return void
*/
public function flush($event)
{
$this->dispatch($event.'_pushed');
}
/**
* Register an event subscriber with the dispatcher.
*
* @param object|string $subscriber
* @return void
*/
public function subscribe($subscriber)
{
$subscriber = $this->resolveSubscriber($subscriber);
$events = $subscriber->subscribe($this);
if (is_array($events)) {
foreach ($events as $event => $listeners) {
foreach (Arr::wrap($listeners) as $listener) {
if (is_string($listener) && method_exists($subscriber, $listener)) {
$this->listen($event, [get_class($subscriber), $listener]);
continue;
}
$this->listen($event, $listener);
}
}
}
}
/**
* Resolve the subscriber instance.
*
* @param object|class-string $subscriber
* @return ($subscriber is object ? object : mixed)
*/
protected function resolveSubscriber($subscriber)
{
if (is_string($subscriber)) {
return $this->container->make($subscriber);
}
return $subscriber;
}
/**
* Fire an event until the first non-null response is returned.
*
* @param string|object $event
* @param mixed $payload
* @return array|null
*/
public function until($event, $payload = [])
{
return $this->dispatch($event, $payload, true);
}
/**
* Fire an event and call the listeners.
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return array|null
*/
public function dispatch($event, $payload = [], $halt = false)
{
// When the given "event" is actually an object, we will assume it is an event
// object, and use the class as the event name and this event itself as the
// payload to the handler, which makes object-based events quite simple.
[$isEventObject, $parsedEvent, $parsedPayload] = [
is_object($event),
...$this->parseEventAndPayload($event, $payload),
];
if ($this->shouldDeferEvent($parsedEvent)) {
$this->deferredEvents[] = func_get_args();
return null;
}
// If the event is not intended to be dispatched unless the current database
// transaction is successful, we'll register a callback which will handle
// dispatching this event on the next successful DB transaction commit.
if ($isEventObject &&
$parsedPayload[0] instanceof ShouldDispatchAfterCommit &&
! is_null($transactions = $this->resolveTransactionManager())) {
$transactions->addCallback(
fn () => $this->invokeListeners($parsedEvent, $parsedPayload, $halt)
);
return null;
}
return $this->invokeListeners($parsedEvent, $parsedPayload, $halt);
}
/**
* Broadcast an event and call its listeners.
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return array|null
*/
protected function invokeListeners($event, $payload, $halt = false)
{
if ($this->shouldBroadcast($payload)) {
$this->broadcastEvent($payload[0]);
}
$responses = [];
foreach ($this->getListeners($event) as $listener) {
$response = $listener($event, $payload);
// If a response is returned from the listener and event halting is enabled
// we will just return this response, and not call the rest of the event
// listeners. Otherwise we will add the response on the response list.
if ($halt && ! is_null($response)) {
return $response;
}
// If a boolean false is returned from a listener, we will stop propagating
// the event to any further listeners down in the chain, else we keep on
// looping through the listeners and firing every one in our sequence.
if ($response === false) {
break;
}
$responses[] = $response;
}
return $halt ? null : $responses;
}
/**
* Parse the given event and payload and prepare them for dispatching.
*
* @param mixed $event
* @param mixed $payload
* @return array{string, array}
*/
protected function parseEventAndPayload($event, $payload)
{
if (is_object($event)) {
[$payload, $event] = [[$event], get_class($event)];
}
return [$event, Arr::wrap($payload)];
}
/**
* Determine if the payload has a broadcastable event.
*
* @return bool
*/
protected function shouldBroadcast(array $payload)
{
return isset($payload[0]) &&
$payload[0] instanceof ShouldBroadcast &&
$this->broadcastWhen($payload[0]);
}
/**
* Check if the event should be broadcasted by the condition.
*
* @param mixed $event
* @return bool
*/
protected function broadcastWhen($event)
{
return method_exists($event, 'broadcastWhen')
? $event->broadcastWhen()
: true;
}
/**
* Broadcast the given event class.
*
* @param \Illuminate\Contracts\Broadcasting\ShouldBroadcast $event
* @return void
*/
protected function broadcastEvent($event)
{
$this->container->make(BroadcastFactory::class)->queue($event);
}
/**
* Get all of the listeners for a given event name.
*
* @param string $eventName
* @return array
*/
public function getListeners($eventName)
{
$listeners = array_merge(
$this->prepareListeners($eventName),
$this->wildcardsCache[$eventName] ?? $this->getWildcardListeners($eventName)
);
return class_exists($eventName, false)
? $this->addInterfaceListeners($eventName, $listeners)
: $listeners;
}
/**
* Get the wildcard listeners for the event.
*
* @param string $eventName
* @return array
*/
protected function getWildcardListeners($eventName)
{
$wildcards = [];
foreach ($this->wildcards as $key => $listeners) {
if (Str::is($key, $eventName)) {
foreach ($listeners as $listener) {
$wildcards[] = $this->makeListener($listener, true);
}
}
}
return $this->wildcardsCache[$eventName] = $wildcards;
}
/**
* Add the listeners for the event's interfaces to the given array.
*
* @param string $eventName
* @return array
*/
protected function addInterfaceListeners($eventName, array $listeners = [])
{
foreach (class_implements($eventName) as $interface) {
if (isset($this->listeners[$interface])) {
foreach ($this->prepareListeners($interface) as $names) {
$listeners = array_merge($listeners, (array) $names);
}
}
}
return $listeners;
}
/**
* Prepare the listeners for a given event.
*
* @return \Closure[]
*/
protected function prepareListeners(string $eventName)
{
$listeners = [];
foreach ($this->listeners[$eventName] ?? [] as $listener) {
$listeners[] = $this->makeListener($listener);
}
return $listeners;
}
/**
* Register an event listener with the dispatcher.
*
* @param \Closure|string|array{class-string, string} $listener
* @param bool $wildcard
* @return \Closure
*/
public function makeListener($listener, $wildcard = false)
{
if (is_string($listener)) {
return $this->createClassListener($listener, $wildcard);
}
if (is_array($listener) && isset($listener[0]) && is_string($listener[0])) {
return $this->createClassListener($listener, $wildcard);
}
return function ($event, $payload) use ($listener, $wildcard) {
if ($wildcard) {
return $listener($event, $payload);
}
return $listener(...array_values($payload));
};
}
/**
* Create a class based listener using the IoC container.
*
* @param string $listener
* @param bool $wildcard
* @return \Closure
*/
public function createClassListener($listener, $wildcard = false)
{
return function ($event, $payload) use ($listener, $wildcard) {
if ($wildcard) {
return call_user_func($this->createClassCallable($listener), $event, $payload);
}
$callable = $this->createClassCallable($listener);
return $callable(...array_values($payload));
};
}
/**
* Create the class based event callable.
*
* @param array{class-string, string}|string $listener
* @return callable
*/
protected function createClassCallable($listener)
{
[$class, $method] = is_array($listener)
? $listener
: $this->parseClassCallable($listener);
if (! method_exists($class, $method)) {
$method = '__invoke';
}
if ($this->handlerShouldBeQueued($class)) {
return $this->createQueuedHandlerCallable($class, $method);
}
$listener = $this->container->make($class);
return $this->handlerShouldBeDispatchedAfterDatabaseTransactions($listener)
&& ! in_array($method, ['creating', 'updating', 'saving', 'deleting', 'restoring', 'forceDeleting'])
? $this->createCallbackForListenerRunningAfterCommits($listener, $method)
: [$listener, $method];
}
/**
* Parse the class listener into class and method.
*
* @param string $listener
* @return array{class-string, string}
*/
protected function parseClassCallable($listener)
{
return Str::parseCallback($listener, 'handle');
}
/**
* Determine if the event handler class should be queued.
*
* @param class-string $class
* @return bool
*
* @phpstan-assert-if-true class-string<\Illuminate\Contracts\Queue\ShouldQueue> $class
*/
protected function handlerShouldBeQueued($class)
{
try {
return (new ReflectionClass($class))->implementsInterface(
ShouldQueue::class
);
} catch (Exception) {
return false;
}
}
/**
* Create a callable for putting an event handler on the queue.
*
* @param class-string $class
* @param string $method
* @return \Closure(): void
*/
protected function createQueuedHandlerCallable($class, $method)
{
return function () use ($class, $method) {
$arguments = array_map(function ($a) {
return is_object($a) ? clone $a : $a;
}, func_get_args());
if ($this->handlerWantsToBeQueued($class, $arguments)) {
$this->queueHandler($class, $method, $arguments);
}
};
}
/**
* Determine if the given event handler should be dispatched after all database transactions have committed.
*
* @param mixed $listener
* @return bool
*/
protected function handlerShouldBeDispatchedAfterDatabaseTransactions($listener)
{
return (($listener->afterCommit ?? null) ||
$listener instanceof ShouldHandleEventsAfterCommit) &&
$this->resolveTransactionManager();
}
/**
* Create a callable for dispatching a listener after database transactions.
*
* @param mixed $listener
* @param string $method
* @return \Closure
*/
protected function createCallbackForListenerRunningAfterCommits($listener, $method)
{
return function () use ($method, $listener) {
$payload = func_get_args();
$this->resolveTransactionManager()->addCallback(
function () use ($listener, $method, $payload) {
$listener->$method(...$payload);
}
);
};
}
/**
* Determine if the event handler wants to be queued.
*
* @param class-string $class
* @param array $arguments
* @return bool
*/
protected function handlerWantsToBeQueued($class, $arguments)
{
$instance = $this->container->make($class);
if (method_exists($instance, 'shouldQueue')) {
return $instance->shouldQueue($arguments[0]);
}
return true;
}
/**
* Queue the handler class.
*
* @param string $class
* @param string $method
* @param array $arguments
* @return void
*/
protected function queueHandler($class, $method, $arguments)
{
[$listener, $job] = $this->createListenerAndJob($class, $method, $arguments);
if ($job->shouldBeUnique &&
! (new UniqueLock($this->container->make(Cache::class)))->acquire($job)) {
return;
}
$connectionName = method_exists($listener, 'viaConnection')
? (isset($arguments[0]) ? $listener->viaConnection($arguments[0]) : $listener->viaConnection())
: $this->getAttributeValue($listener, Connection::class, 'connection');
$connection = $this->resolveQueue()->connection(
$connectionName ?? $this->resolveConnectionFromQueueRoute($listener) ?? null
);
$queue = method_exists($listener, 'viaQueue')
? (isset($arguments[0]) ? $listener->viaQueue($arguments[0]) : $listener->viaQueue())
: $this->getAttributeValue($listener, QueueAttribute::class, 'queue');
$delay = method_exists($listener, 'withDelay')
? (isset($arguments[0]) ? $listener->withDelay($arguments[0]) : $listener->withDelay())
: $this->getAttributeValue($listener, Delay::class, 'delay');
if (is_null($queue)) {
$queue = $this->resolveQueueFromQueueRoute($listener) ?? null;
}
is_null($delay)
? $connection->pushOn(enum_value($queue), $job)
: $connection->laterOn(enum_value($queue), $delay, $job);
}
/**
* Create the listener and job for a queued listener.
*
* @template TListener
*
* @param class-string<TListener> $class
* @param string $method
* @param array $arguments
* @return array{TListener, mixed}
*/
protected function createListenerAndJob($class, $method, $arguments)
{
$listener = (new ReflectionClass($class))->newInstanceWithoutConstructor();
return [$listener, $this->propagateListenerOptions(
$listener, new CallQueuedListener($class, $method, $arguments)
)];
}
/**
* Propagate listener options to the job.
*
* @param mixed $listener
* @param \Illuminate\Events\CallQueuedListener $job
* @return \Illuminate\Events\CallQueuedListener
*/
protected function propagateListenerOptions($listener, $job)
{
return tap($job, function ($job) use ($listener) {
$data = array_values($job->data);
if ($listener instanceof ShouldQueueAfterCommit) {
$job->afterCommit = true;
} else {
$job->afterCommit = property_exists($listener, 'afterCommit') ? $listener->afterCommit : null;
}
$job->backoff = method_exists($listener, 'backoff') ? $listener->backoff(...$data) : $this->getAttributeValue($listener, Backoff::class, 'backoff');
$job->maxExceptions = $this->getAttributeValue($listener, MaxExceptions::class, 'maxExceptions');
$job->retryUntil = method_exists($listener, 'retryUntil') ? $listener->retryUntil(...$data) : null;
$job->shouldBeEncrypted = $listener instanceof ShouldBeEncrypted;
$job->timeout = $this->getAttributeValue($listener, Timeout::class, 'timeout');
$job->failOnTimeout = $this->getAttributeValue($listener, FailOnTimeout::class, 'failOnTimeout') ?? false;
$job->deleteWhenMissingModels = $this->getAttributeValue($listener, DeleteWhenMissingModels::class, 'deleteWhenMissingModels') ?? false;
$job->tries = method_exists($listener, 'tries') ? $listener->tries(...$data) : $this->getAttributeValue($listener, Tries::class, 'tries');
$job->messageGroup = method_exists($listener, 'messageGroup') ? $listener->messageGroup(...$data) : ($listener->messageGroup ?? null);
$job->withDeduplicator(method_exists($listener, 'deduplicator')
? $listener->deduplicator(...$data)
: (method_exists($listener, 'deduplicationId') ? $listener->deduplicationId(...) : null)
);
$job->through(array_merge(
method_exists($listener, 'middleware') ? $listener->middleware(...$data) : [],
$listener->middleware ?? []
));
$job->shouldBeUnique = $listener instanceof ShouldBeUnique;
$job->shouldBeUniqueUntilProcessing = $listener instanceof ShouldBeUniqueUntilProcessing;
if ($job->shouldBeUnique) {
$job->uniqueId = method_exists($listener, 'uniqueId')
? $listener->uniqueId(...$data)
: ($listener->uniqueId ?? null);
$job->uniqueFor = method_exists($listener, 'uniqueFor')
? $listener->uniqueFor(...$data)
: ($this->getAttributeValue($listener, UniqueFor::class, 'uniqueFor') ?? 0);
}
});
}
/**
* Remove a set of listeners from the dispatcher.
*
* @param string $event
* @return void
*/
public function forget($event)
{
if (str_contains($event, '*')) {
unset($this->wildcards[$event]);
} else {
unset($this->listeners[$event]);
}
foreach ($this->wildcardsCache as $key => $listeners) {
if (Str::is($event, $key)) {
unset($this->wildcardsCache[$key]);
}
}
}
/**
* Forget all of the pushed listeners.
*
* @return void
*/
public function forgetPushed()
{
foreach ($this->listeners as $key => $value) {
if (str_ends_with($key, '_pushed')) {
$this->forget($key);
}
}
}
/**
* Get the queue implementation from the resolver.
*
* @return \Illuminate\Contracts\Queue\Queue
*/
protected function resolveQueue()
{
return call_user_func($this->queueResolver);
}
/**
* Set the queue resolver implementation.
*
* @param callable(): \Illuminate\Contracts\Queue\Queue $resolver
* @return $this
*/
public function setQueueResolver(callable $resolver)
{
$this->queueResolver = $resolver;
return $this;
}
/**
* Get the database transaction manager implementation from the resolver.
*
* @return \Illuminate\Database\DatabaseTransactionsManager|null
*/
protected function resolveTransactionManager()
{
return call_user_func($this->transactionManagerResolver);
}
/**
* Set the database transaction manager resolver implementation.
*
* @param (callable(): (\Illuminate\Database\DatabaseTransactionsManager|null)) $resolver
* @return $this
*/
public function setTransactionManagerResolver(callable $resolver)
{
$this->transactionManagerResolver = $resolver;
return $this;
}
/**
* Execute the given callback while deferring events, then dispatch all deferred events.
*
* @template TResult
*
* @param callable(): TResult $callback
* @param string[]|null $events
* @return TResult
*/
public function defer(callable $callback, ?array $events = null)
{
$wasDeferring = $this->deferringEvents;
$previousDeferredEvents = $this->deferredEvents;
$previousEventsToDefer = $this->eventsToDefer;
$this->deferringEvents = true;
$this->deferredEvents = [];
$this->eventsToDefer = $events;
try {
$result = $callback();
$this->deferringEvents = false;
foreach ($this->deferredEvents as $args) {
$this->dispatch(...$args);
}
return $result;
} finally {
$this->deferringEvents = $wasDeferring;
$this->deferredEvents = $previousDeferredEvents;
$this->eventsToDefer = $previousEventsToDefer;
}
}
/**
* Determine if the given event should be deferred.
*
* @return bool
*/
protected function shouldDeferEvent(string $event)
{
return $this->deferringEvents && ($this->eventsToDefer === null || in_array($event, $this->eventsToDefer));
}
/**
* Gets the raw, unprepared listeners.
*
* @return array
*/
public function getRawListeners()
{
return $this->listeners;
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Illuminate\Events;
use Illuminate\Contracts\Queue\Factory as QueueFactoryContract;
use Illuminate\Support\ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('events', function ($app) {
return (new Dispatcher($app))->setQueueResolver(function () {
return app(QueueFactoryContract::class);
})->setTransactionManagerResolver(function () {
return app()->bound('db.transactions')
? app('db.transactions')
: null;
});
});
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace Illuminate\Events;
use Illuminate\Support\Collection;
class InvokeQueuedClosure
{
/**
* Handle the event.
*
* @param \Laravel\SerializableClosure\SerializableClosure $closure
* @param array $arguments
* @return void
*/
public function handle($closure, array $arguments)
{
call_user_func($closure->getClosure(), ...$arguments);
}
/**
* Handle a job failure.
*
* @param \Laravel\SerializableClosure\SerializableClosure $closure
* @param array $arguments
* @param array $catchCallbacks
* @param \Throwable $exception
* @return void
*/
public function failed($closure, array $arguments, array $catchCallbacks, $exception)
{
$arguments[] = $exception;
(new Collection($catchCallbacks))->each->__invoke(...$arguments);
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Taylor Otwell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+143
View File
@@ -0,0 +1,143 @@
<?php
namespace Illuminate\Events;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Support\Traits\ForwardsCalls;
class NullDispatcher implements DispatcherContract
{
use ForwardsCalls;
/**
* The underlying event dispatcher instance.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected $dispatcher;
/**
* Create a new event dispatcher instance that does not fire.
*
* @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
*/
public function __construct(DispatcherContract $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Don't fire an event.
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return void
*/
public function dispatch($event, $payload = [], $halt = false)
{
//
}
/**
* Don't register an event and payload to be fired later.
*
* @param string $event
* @param array $payload
* @return void
*/
public function push($event, $payload = [])
{
//
}
/**
* Don't dispatch an event.
*
* @param string|object $event
* @param mixed $payload
* @return mixed
*/
public function until($event, $payload = [])
{
//
}
/**
* Register an event listener with the dispatcher.
*
* @param \Closure|string|array $events
* @param \Closure|string|array|null $listener
* @return void
*/
public function listen($events, $listener = null)
{
$this->dispatcher->listen($events, $listener);
}
/**
* Determine if a given event has listeners.
*
* @param string $eventName
* @return bool
*/
public function hasListeners($eventName)
{
return $this->dispatcher->hasListeners($eventName);
}
/**
* Register an event subscriber with the dispatcher.
*
* @param object|string $subscriber
* @return void
*/
public function subscribe($subscriber)
{
$this->dispatcher->subscribe($subscriber);
}
/**
* Flush a set of pushed events.
*
* @param string $event
* @return void
*/
public function flush($event)
{
$this->dispatcher->flush($event);
}
/**
* Remove a set of listeners from the dispatcher.
*
* @param string $event
* @return void
*/
public function forget($event)
{
$this->dispatcher->forget($event);
}
/**
* Forget all of the queued listeners.
*
* @return void
*/
public function forgetPushed()
{
$this->dispatcher->forgetPushed();
}
/**
* Dynamically pass method calls to the underlying dispatcher.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->forwardDecoratedCallTo($this->dispatcher, $method, $parameters);
}
}
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace Illuminate\Events;
use Closure;
use Illuminate\Support\Collection;
use Laravel\SerializableClosure\SerializableClosure;
use function Illuminate\Support\enum_value;
class QueuedClosure
{
/**
* The underlying Closure.
*
* @var \Closure
*/
public $closure;
/**
* The name of the connection the job should be sent to.
*
* @var string|null
*/
public $connection;
/**
* The name of the queue the job should be sent to.
*
* @var string|null
*/
public $queue;
/**
* The job "group" the job should be sent to.
*
* @var string|null
*/
public $messageGroup;
/**
* The job deduplicator callback the job should use to generate the deduplication ID.
*
* @var \Laravel\SerializableClosure\SerializableClosure|null
*/
public $deduplicator;
/**
* The number of seconds before the job should be made available.
*
* @var \DateTimeInterface|\DateInterval|int|null
*/
public $delay;
/**
* All of the "catch" callbacks for the queued closure.
*
* @var array
*/
public $catchCallbacks = [];
/**
* Create a new queued closure event listener resolver.
*
* @param \Closure $closure
*/
public function __construct(Closure $closure)
{
$this->closure = $closure;
}
/**
* Set the desired connection for the job.
*
* @param \UnitEnum|string|null $connection
* @return $this
*/
public function onConnection($connection)
{
$this->connection = enum_value($connection);
return $this;
}
/**
* Set the desired queue for the job.
*
* @param \UnitEnum|string|null $queue
* @return $this
*/
public function onQueue($queue)
{
$this->queue = enum_value($queue);
return $this;
}
/**
* Set the desired job "group".
*
* This feature is only supported by some queues, such as Amazon SQS.
*
* @param \UnitEnum|string $group
* @return $this
*/
public function onGroup($group)
{
$this->messageGroup = enum_value($group);
return $this;
}
/**
* Set the desired job deduplicator callback.
*
* This feature is only supported by some queues, such as Amazon SQS FIFO.
*
* @param callable|null $deduplicator
* @return $this
*/
public function withDeduplicator($deduplicator)
{
$this->deduplicator = $deduplicator instanceof Closure
? new SerializableClosure($deduplicator)
: $deduplicator;
return $this;
}
/**
* Set the desired delay in seconds for the job.
*
* @param \DateTimeInterface|\DateInterval|int|null $delay
* @return $this
*/
public function delay($delay)
{
$this->delay = $delay;
return $this;
}
/**
* Specify a callback that should be invoked if the queued listener job fails.
*
* @param \Closure $closure
* @return $this
*/
public function catch(Closure $closure)
{
$this->catchCallbacks[] = $closure;
return $this;
}
/**
* Resolve the actual event listener callback.
*
* @return \Closure
*/
public function resolve()
{
return function (...$arguments) {
dispatch(new CallQueuedListener(InvokeQueuedClosure::class, 'handle', [
'closure' => new SerializableClosure($this->closure),
'arguments' => $arguments,
'catch' => (new Collection($this->catchCallbacks))
->map(fn ($callback) => new SerializableClosure($callback))
->all(),
]))
->onConnection($this->connection)
->onQueue($this->queue)
->delay($this->delay)
->onGroup($this->messageGroup)
->withDeduplicator($this->deduplicator);
};
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"name": "illuminate/events",
"description": "The Illuminate Events package.",
"license": "MIT",
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"require": {
"php": "^8.3",
"illuminate/bus": "^13.0",
"illuminate/collections": "^13.0",
"illuminate/container": "^13.0",
"illuminate/contracts": "^13.0",
"illuminate/macroable": "^13.0",
"illuminate/support": "^13.0"
},
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Illuminate\\Events\\": ""
},
"files": [
"functions.php"
]
},
"config": {
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-master": "13.0.x-dev"
}
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace Illuminate\Events;
use Closure;
if (! function_exists('Illuminate\Events\queueable')) {
/**
* Create a new queued Closure event listener.
*
* @param \Closure $closure
*/
function queueable(Closure $closure): QueuedClosure
{
return new QueuedClosure($closure);
}
}