Reintroduce Webklex IMAP for ticket processing as PHP-IMAP is no longer being developed. This is optional for now and considered beta can be found in cron/ticket_email_parser.php

This commit is contained in:
johnnyq
2025-09-10 14:27:46 -04:00
parent 981fb9585d
commit ce7d84aa2f
2035 changed files with 174115 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
<?php
namespace Illuminate\Support;
class AggregateServiceProvider extends ServiceProvider
{
/**
* The provider class names.
*
* @var array
*/
protected $providers = [];
/**
* An array of the service provider instances.
*
* @var array
*/
protected $instances = [];
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->instances = [];
foreach ($this->providers as $provider) {
$this->instances[] = $this->app->register($provider);
}
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
$provides = [];
foreach ($this->providers as $provider) {
$instance = $this->app->resolveProvider($provider);
$provides = array_merge($provides, $instance->provides());
}
return $provides;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Illuminate\Support;
use Closure;
class Benchmark
{
/**
* Measure a callable or array of callables over the given number of iterations.
*
* @param \Closure|array $benchmarkables
* @param int $iterations
* @return array|float
*/
public static function measure(Closure|array $benchmarkables, int $iterations = 1): array|float
{
return Collection::wrap($benchmarkables)->map(function ($callback) use ($iterations) {
return Collection::range(1, $iterations)->map(function () use ($callback) {
gc_collect_cycles();
$start = hrtime(true);
$callback();
return (hrtime(true) - $start) / 1_000_000;
})->average();
})->when(
$benchmarkables instanceof Closure,
fn ($c) => $c->first(),
fn ($c) => $c->all(),
);
}
/**
* Measure a callable once and return the result and duration in milliseconds.
*
* @template TReturn of mixed
*
* @param (callable(): TReturn) $callback
* @return array{0: TReturn, 1: float}
*/
public static function value(callable $callback): array
{
gc_collect_cycles();
$start = hrtime(true);
$result = $callback();
return [$result, (hrtime(true) - $start) / 1_000_000];
}
/**
* Measure a callable or array of callables over the given number of iterations, then dump and die.
*
* @param \Closure|array $benchmarkables
* @param int $iterations
* @return never
*/
public static function dd(Closure|array $benchmarkables, int $iterations = 1): never
{
$result = (new Collection(static::measure(Arr::wrap($benchmarkables), $iterations)))
->map(fn ($average) => number_format($average, 3).'ms')
->when($benchmarkables instanceof Closure, fn ($c) => $c->first(), fn ($c) => $c->all());
dd($result);
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Illuminate\Support;
use Carbon\Carbon as BaseCarbon;
use Carbon\CarbonImmutable as BaseCarbonImmutable;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\Dumpable;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Uid\Ulid;
class Carbon extends BaseCarbon
{
use Conditionable, Dumpable;
/**
* {@inheritdoc}
*/
public static function setTestNow(mixed $testNow = null): void
{
BaseCarbon::setTestNow($testNow);
BaseCarbonImmutable::setTestNow($testNow);
}
/**
* Create a Carbon instance from a given ordered UUID or ULID.
*/
public static function createFromId(Uuid|Ulid|string $id): static
{
if (is_string($id)) {
$id = Ulid::isValid($id) ? Ulid::fromString($id) : Uuid::fromString($id);
}
return static::createFromInterface($id->getDateTime());
}
}

View File

@@ -0,0 +1,254 @@
<?php
namespace Illuminate\Support;
use Closure;
use Illuminate\Filesystem\Filesystem;
use RuntimeException;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
class Composer
{
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* The working path to regenerate from.
*
* @var string|null
*/
protected $workingPath;
/**
* Create a new Composer manager instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
* @param string|null $workingPath
*/
public function __construct(Filesystem $files, $workingPath = null)
{
$this->files = $files;
$this->workingPath = $workingPath;
}
/**
* Determine if the given Composer package is installed.
*
* @param string $package
* @return bool
*
* @throws \RuntimeException
*/
public function hasPackage($package)
{
$composer = json_decode(file_get_contents($this->findComposerFile()), true);
return array_key_exists($package, $composer['require'] ?? [])
|| array_key_exists($package, $composer['require-dev'] ?? []);
}
/**
* Install the given Composer packages into the application.
*
* @param array<int, string> $packages
* @param bool $dev
* @param \Closure|\Symfony\Component\Console\Output\OutputInterface|null $output
* @param string|null $composerBinary
* @return bool
*/
public function requirePackages(array $packages, bool $dev = false, Closure|OutputInterface|null $output = null, $composerBinary = null)
{
$command = (new Collection([
...$this->findComposer($composerBinary),
'require',
...$packages,
]))
->when($dev, function ($command) {
$command->push('--dev');
})->all();
return 0 === $this->getProcess($command, ['COMPOSER_MEMORY_LIMIT' => '-1'])
->run(
$output instanceof OutputInterface
? function ($type, $line) use ($output) {
$output->write(' '.$line);
} : $output
);
}
/**
* Remove the given Composer packages from the application.
*
* @param array<int, string> $packages
* @param bool $dev
* @param \Closure|\Symfony\Component\Console\Output\OutputInterface|null $output
* @param string|null $composerBinary
* @return bool
*/
public function removePackages(array $packages, bool $dev = false, Closure|OutputInterface|null $output = null, $composerBinary = null)
{
$command = (new Collection([
...$this->findComposer($composerBinary),
'remove',
...$packages,
]))
->when($dev, function ($command) {
$command->push('--dev');
})->all();
return 0 === $this->getProcess($command, ['COMPOSER_MEMORY_LIMIT' => '-1'])
->run(
$output instanceof OutputInterface
? function ($type, $line) use ($output) {
$output->write(' '.$line);
} : $output
);
}
/**
* Modify the "composer.json" file contents using the given callback.
*
* @param callable(array):array $callback
* @return void
*
* @throws \RuntimeException
*/
public function modify(callable $callback)
{
$composerFile = $this->findComposerFile();
$composer = json_decode(file_get_contents($composerFile), true, 512, JSON_THROW_ON_ERROR);
file_put_contents(
$composerFile,
json_encode(
call_user_func($callback, $composer),
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
)
);
}
/**
* Regenerate the Composer autoloader files.
*
* @param string|array $extra
* @param string|null $composerBinary
* @return int
*/
public function dumpAutoloads($extra = '', $composerBinary = null)
{
$extra = $extra ? (array) $extra : [];
$command = array_merge($this->findComposer($composerBinary), ['dump-autoload'], $extra);
return $this->getProcess($command)->run();
}
/**
* Regenerate the optimized Composer autoloader files.
*
* @param string|null $composerBinary
* @return int
*/
public function dumpOptimized($composerBinary = null)
{
return $this->dumpAutoloads('--optimize', $composerBinary);
}
/**
* Get the Composer binary / command for the environment.
*
* @param string|null $composerBinary
* @return array
*/
public function findComposer($composerBinary = null)
{
if (! is_null($composerBinary) && $this->files->exists($composerBinary)) {
return [$this->phpBinary(), $composerBinary];
} elseif ($this->files->exists($this->workingPath.'/composer.phar')) {
return [$this->phpBinary(), 'composer.phar'];
}
return ['composer'];
}
/**
* Get the path to the "composer.json" file.
*
* @return string
*
* @throws \RuntimeException
*/
protected function findComposerFile()
{
$composerFile = "{$this->workingPath}/composer.json";
if (! file_exists($composerFile)) {
throw new RuntimeException("Unable to locate `composer.json` file at [{$this->workingPath}].");
}
return $composerFile;
}
/**
* Get the PHP binary.
*
* @return string
*/
protected function phpBinary()
{
return php_binary();
}
/**
* Get a new Symfony process instance.
*
* @param array $command
* @param array $env
* @return \Symfony\Component\Process\Process
*/
protected function getProcess(array $command, array $env = [])
{
return (new Process($command, $this->workingPath, $env))->setTimeout(null);
}
/**
* Set the working path used by the class.
*
* @param string $path
* @return $this
*/
public function setWorkingPath($path)
{
$this->workingPath = realpath($path);
return $this;
}
/**
* Get the version of Composer.
*
* @return string|null
*/
public function getVersion()
{
$command = array_merge($this->findComposer(), ['-V', '--no-ansi']);
$process = $this->getProcess($command);
$process->run();
$output = $process->getOutput();
if (preg_match('/(\d+(\.\d+){2})/', $output, $version)) {
return $version[1];
}
return explode(' ', $output)[2] ?? null;
}
}

View File

@@ -0,0 +1,191 @@
<?php
namespace Illuminate\Support;
use InvalidArgumentException;
class ConfigurationUrlParser
{
/**
* The drivers aliases map.
*
* @var array
*/
protected static $driverAliases = [
'mssql' => 'sqlsrv',
'mysql2' => 'mysql', // RDS
'postgres' => 'pgsql',
'postgresql' => 'pgsql',
'sqlite3' => 'sqlite',
'redis' => 'tcp',
'rediss' => 'tls',
];
/**
* Parse the database configuration, hydrating options using a database configuration URL if possible.
*
* @param array|string $config
* @return array
*/
public function parseConfiguration($config)
{
if (is_string($config)) {
$config = ['url' => $config];
}
$url = Arr::pull($config, 'url');
if (! $url) {
return $config;
}
$rawComponents = $this->parseUrl($url);
$decodedComponents = $this->parseStringsToNativeTypes(
array_map(rawurldecode(...), $rawComponents)
);
return array_merge(
$config,
$this->getPrimaryOptions($decodedComponents),
$this->getQueryOptions($rawComponents)
);
}
/**
* Get the primary database connection options.
*
* @param array $url
* @return array
*/
protected function getPrimaryOptions($url)
{
return array_filter([
'driver' => $this->getDriver($url),
'database' => $this->getDatabase($url),
'host' => $url['host'] ?? null,
'port' => $url['port'] ?? null,
'username' => $url['user'] ?? null,
'password' => $url['pass'] ?? null,
], fn ($value) => ! is_null($value));
}
/**
* Get the database driver from the URL.
*
* @param array $url
* @return string|null
*/
protected function getDriver($url)
{
$alias = $url['scheme'] ?? null;
if (! $alias) {
return;
}
return static::$driverAliases[$alias] ?? $alias;
}
/**
* Get the database name from the URL.
*
* @param array $url
* @return string|null
*/
protected function getDatabase($url)
{
$path = $url['path'] ?? null;
return $path && $path !== '/' ? substr($path, 1) : null;
}
/**
* Get all of the additional database options from the query string.
*
* @param array $url
* @return array
*/
protected function getQueryOptions($url)
{
$queryString = $url['query'] ?? null;
if (! $queryString) {
return [];
}
$query = [];
parse_str($queryString, $query);
return $this->parseStringsToNativeTypes($query);
}
/**
* Parse the string URL to an array of components.
*
* @param string $url
* @return array
*
* @throws \InvalidArgumentException
*/
protected function parseUrl($url)
{
$url = preg_replace('#^(sqlite3?):///#', '$1://null/', $url);
$parsedUrl = parse_url($url);
if ($parsedUrl === false) {
throw new InvalidArgumentException('The database configuration URL is malformed.');
}
return $parsedUrl;
}
/**
* Convert string casted values to their native types.
*
* @param mixed $value
* @return mixed
*/
protected function parseStringsToNativeTypes($value)
{
if (is_array($value)) {
return array_map($this->parseStringsToNativeTypes(...), $value);
}
if (! is_string($value)) {
return $value;
}
$parsedValue = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE) {
return $parsedValue;
}
return $value;
}
/**
* Get all of the current drivers' aliases.
*
* @return array
*/
public static function getDriverAliases()
{
return static::$driverAliases;
}
/**
* Add the given driver alias to the driver aliases array.
*
* @param string $alias
* @param string $driver
* @return void
*/
public static function addDriverAlias($alias, $driver)
{
static::$driverAliases[$alias] = $driver;
}
}

View File

@@ -0,0 +1,250 @@
<?php
namespace Illuminate\Support;
use Carbon\Factory;
use InvalidArgumentException;
/**
* @see https://carbon.nesbot.com/docs/
* @see https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Factory.php
*
* @method bool canBeCreatedFromFormat(?string $date, string $format)
* @method \Illuminate\Support\Carbon|null create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null)
* @method \Illuminate\Support\Carbon createFromDate($year = null, $month = null, $day = null, $timezone = null)
* @method \Illuminate\Support\Carbon|null createFromFormat($format, $time, $timezone = null)
* @method \Illuminate\Support\Carbon|null createFromIsoFormat(string $format, string $time, $timezone = null, ?string $locale = 'en', ?\Symfony\Contracts\Translation\TranslatorInterface $translator = null)
* @method \Illuminate\Support\Carbon|null createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null)
* @method \Illuminate\Support\Carbon|null createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null)
* @method \Illuminate\Support\Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null)
* @method \Illuminate\Support\Carbon createFromTimeString(string $time, \DateTimeZone|string|int|null $timezone = null)
* @method \Illuminate\Support\Carbon createFromTimestamp(string|int|float $timestamp, \DateTimeZone|string|int|null $timezone = null)
* @method \Illuminate\Support\Carbon createFromTimestampMs(string|int|float $timestamp, \DateTimeZone|string|int|null $timezone = null)
* @method \Illuminate\Support\Carbon createFromTimestampMsUTC($timestamp)
* @method \Illuminate\Support\Carbon createFromTimestampUTC(string|int|float $timestamp)
* @method \Illuminate\Support\Carbon createMidnightDate($year = null, $month = null, $day = null, $timezone = null)
* @method \Illuminate\Support\Carbon|null createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null)
* @method \Illuminate\Support\Carbon createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null)
* @method void disableHumanDiffOption($humanDiffOption)
* @method void enableHumanDiffOption($humanDiffOption)
* @method mixed executeWithLocale(string $locale, callable $func)
* @method \Illuminate\Support\Carbon fromSerialized($value)
* @method array getAvailableLocales()
* @method array getAvailableLocalesInfo()
* @method array getDays()
* @method ?string getFallbackLocale()
* @method array getFormatsToIsoReplacements()
* @method int getHumanDiffOptions()
* @method array getIsoUnits()
* @method array|false getLastErrors()
* @method string getLocale()
* @method int getMidDayAt()
* @method string getTimeFormatByPrecision(string $unitPrecision)
* @method string|\Closure|null getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null)
* @method \Illuminate\Support\Carbon|null getTestNow()
* @method \Symfony\Contracts\Translation\TranslatorInterface getTranslator()
* @method int getWeekEndsAt(?string $locale = null)
* @method int getWeekStartsAt(?string $locale = null)
* @method array getWeekendDays()
* @method bool hasFormat(string $date, string $format)
* @method bool hasFormatWithModifiers(string $date, string $format)
* @method bool hasMacro($name)
* @method bool hasRelativeKeywords(?string $time)
* @method bool hasTestNow()
* @method \Illuminate\Support\Carbon instance(\DateTimeInterface $date)
* @method bool isImmutable()
* @method bool isModifiableUnit($unit)
* @method bool isMutable()
* @method bool isStrictModeEnabled()
* @method bool localeHasDiffOneDayWords(string $locale)
* @method bool localeHasDiffSyntax(string $locale)
* @method bool localeHasDiffTwoDayWords(string $locale)
* @method bool localeHasPeriodSyntax($locale)
* @method bool localeHasShortUnits(string $locale)
* @method void macro(string $name, ?callable $macro)
* @method \Illuminate\Support\Carbon|null make($var, \DateTimeZone|string|null $timezone = null)
* @method void mixin(object|string $mixin)
* @method \Illuminate\Support\Carbon now(\DateTimeZone|string|int|null $timezone = null)
* @method \Illuminate\Support\Carbon parse(\DateTimeInterface|\Carbon\WeekDay|\Carbon\Month|string|int|float|null $time, \DateTimeZone|string|int|null $timezone = null)
* @method \Illuminate\Support\Carbon parseFromLocale(string $time, ?string $locale = null, \DateTimeZone|string|int|null $timezone = null)
* @method string pluralUnit(string $unit)
* @method \Illuminate\Support\Carbon|null rawCreateFromFormat(string $format, string $time, $timezone = null)
* @method \Illuminate\Support\Carbon rawParse(\DateTimeInterface|\Carbon\WeekDay|\Carbon\Month|string|int|float|null $time, \DateTimeZone|string|int|null $timezone = null)
* @method void resetMonthsOverflow()
* @method void resetToStringFormat()
* @method void resetYearsOverflow()
* @method void serializeUsing($callback)
* @method void setFallbackLocale(string $locale)
* @method void setHumanDiffOptions($humanDiffOptions)
* @method void setLocale(string $locale)
* @method void setMidDayAt($hour)
* @method void setTestNow(mixed $testNow = null)
* @method void setTestNowAndTimezone(mixed $testNow = null, $timezone = null)
* @method void setToStringFormat(string|\Closure|null $format)
* @method void setTranslator(\Symfony\Contracts\Translation\TranslatorInterface $translator)
* @method void setWeekEndsAt($day)
* @method void setWeekStartsAt($day)
* @method void setWeekendDays($days)
* @method bool shouldOverflowMonths()
* @method bool shouldOverflowYears()
* @method string singularUnit(string $unit)
* @method void sleep(int|float $seconds)
* @method \Illuminate\Support\Carbon today(\DateTimeZone|string|int|null $timezone = null)
* @method \Illuminate\Support\Carbon tomorrow(\DateTimeZone|string|int|null $timezone = null)
* @method string translateTimeString(string $timeString, ?string $from = null, ?string $to = null, int $mode = \Carbon\CarbonInterface::TRANSLATE_ALL)
* @method string translateWith(\Symfony\Contracts\Translation\TranslatorInterface $translator, string $key, array $parameters = [], $number = null)
* @method void useMonthsOverflow($monthsOverflow = true)
* @method void useStrictMode($strictModeEnabled = true)
* @method void useYearsOverflow($yearsOverflow = true)
* @method mixed withTestNow(mixed $testNow, callable $callback)
* @method static withTimeZone(\DateTimeZone|string|int|null $timezone)
* @method \Illuminate\Support\Carbon yesterday(\DateTimeZone|string|int|null $timezone = null)
*/
class DateFactory
{
/**
* The default class that will be used for all created dates.
*
* @var string
*/
const DEFAULT_CLASS_NAME = Carbon::class;
/**
* The type (class) of dates that should be created.
*
* @var string
*/
protected static $dateClass;
/**
* This callable may be used to intercept date creation.
*
* @var callable
*/
protected static $callable;
/**
* The Carbon factory that should be used when creating dates.
*
* @var object
*/
protected static $factory;
/**
* Use the given handler when generating dates (class name, callable, or factory).
*
* @param mixed $handler
* @return mixed
*
* @throws \InvalidArgumentException
*/
public static function use($handler)
{
if (is_callable($handler) && is_object($handler)) {
return static::useCallable($handler);
} elseif (is_string($handler)) {
return static::useClass($handler);
} elseif ($handler instanceof Factory) {
return static::useFactory($handler);
}
throw new InvalidArgumentException('Invalid date creation handler. Please provide a class name, callable, or Carbon factory.');
}
/**
* Use the default date class when generating dates.
*
* @return void
*/
public static function useDefault()
{
static::$dateClass = null;
static::$callable = null;
static::$factory = null;
}
/**
* Execute the given callable on each date creation.
*
* @param callable $callable
* @return void
*/
public static function useCallable(callable $callable)
{
static::$callable = $callable;
static::$dateClass = null;
static::$factory = null;
}
/**
* Use the given date type (class) when generating dates.
*
* @param string $dateClass
* @return void
*/
public static function useClass($dateClass)
{
static::$dateClass = $dateClass;
static::$factory = null;
static::$callable = null;
}
/**
* Use the given Carbon factory when generating dates.
*
* @param object $factory
* @return void
*/
public static function useFactory($factory)
{
static::$factory = $factory;
static::$dateClass = null;
static::$callable = null;
}
/**
* Handle dynamic calls to generate dates.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \RuntimeException
*/
public function __call($method, $parameters)
{
$defaultClassName = static::DEFAULT_CLASS_NAME;
// Using callable to generate dates...
if (static::$callable) {
return call_user_func(static::$callable, $defaultClassName::$method(...$parameters));
}
// Using Carbon factory to generate dates...
if (static::$factory) {
return static::$factory->$method(...$parameters);
}
$dateClass = static::$dateClass ?: $defaultClassName;
// Check if the date can be created using the public class method...
if (method_exists($dateClass, $method) ||
method_exists($dateClass, 'hasMacro') && $dateClass::hasMacro($method)) {
return $dateClass::$method(...$parameters);
}
// If that fails, create the date with the default class...
$date = $defaultClassName::$method(...$parameters);
// If the configured class has an "instance" method, we'll try to pass our date into there...
if (method_exists($dateClass, 'instance')) {
return $dateClass::instance($date);
}
// Otherwise, assume the configured class has a DateTime compatible constructor...
return new $dateClass($date->format('Y-m-d H:i:s.u'), $date->getTimezone());
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Illuminate\Support;
class DefaultProviders
{
/**
* The current providers.
*
* @var array
*/
protected $providers;
/**
* Create a new default provider collection.
*/
public function __construct(?array $providers = null)
{
$this->providers = $providers ?: [
\Illuminate\Auth\AuthServiceProvider::class,
\Illuminate\Broadcasting\BroadcastServiceProvider::class,
\Illuminate\Bus\BusServiceProvider::class,
\Illuminate\Cache\CacheServiceProvider::class,
\Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
\Illuminate\Concurrency\ConcurrencyServiceProvider::class,
\Illuminate\Cookie\CookieServiceProvider::class,
\Illuminate\Database\DatabaseServiceProvider::class,
\Illuminate\Encryption\EncryptionServiceProvider::class,
\Illuminate\Filesystem\FilesystemServiceProvider::class,
\Illuminate\Foundation\Providers\FoundationServiceProvider::class,
\Illuminate\Hashing\HashServiceProvider::class,
\Illuminate\Mail\MailServiceProvider::class,
\Illuminate\Notifications\NotificationServiceProvider::class,
\Illuminate\Pagination\PaginationServiceProvider::class,
\Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
\Illuminate\Pipeline\PipelineServiceProvider::class,
\Illuminate\Queue\QueueServiceProvider::class,
\Illuminate\Redis\RedisServiceProvider::class,
\Illuminate\Session\SessionServiceProvider::class,
\Illuminate\Translation\TranslationServiceProvider::class,
\Illuminate\Validation\ValidationServiceProvider::class,
\Illuminate\View\ViewServiceProvider::class,
];
}
/**
* Merge the given providers into the provider collection.
*
* @param array $providers
* @return static
*/
public function merge(array $providers)
{
$this->providers = array_merge($this->providers, $providers);
return new static($this->providers);
}
/**
* Replace the given providers with other providers.
*
* @param array $replacements
* @return static
*/
public function replace(array $replacements)
{
$current = new Collection($this->providers);
foreach ($replacements as $from => $to) {
$key = $current->search($from);
$current = is_int($key) ? $current->replace([$key => $to]) : $current;
}
return new static($current->values()->toArray());
}
/**
* Disable the given providers.
*
* @param array $providers
* @return static
*/
public function except(array $providers)
{
return new static((new Collection($this->providers))
->reject(fn ($p) => in_array($p, $providers))
->values()
->toArray());
}
/**
* Convert the provider collection to an array.
*
* @return array
*/
public function toArray()
{
return $this->providers;
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Illuminate\Support\Defer;
use Illuminate\Support\Str;
class DeferredCallback
{
/**
* Create a new deferred callback instance.
*
* @param callable $callback
*/
public function __construct(public $callback, public ?string $name = null, public bool $always = false)
{
$this->name = $name ?? (string) Str::uuid();
}
/**
* Specify the name of the deferred callback so it can be cancelled later.
*
* @param string $name
* @return $this
*/
public function name(string $name): static
{
$this->name = $name;
return $this;
}
/**
* Indicate that the deferred callback should run even on unsuccessful requests and jobs.
*
* @param bool $always
* @return $this
*/
public function always(bool $always = true): static
{
$this->always = $always;
return $this;
}
/**
* Invoke the deferred callback.
*
* @return void
*/
public function __invoke(): void
{
call_user_func($this->callback);
}
}

View File

@@ -0,0 +1,157 @@
<?php
namespace Illuminate\Support\Defer;
use ArrayAccess;
use Closure;
use Countable;
use Illuminate\Support\Collection;
class DeferredCallbackCollection implements ArrayAccess, Countable
{
/**
* All of the deferred callbacks.
*
* @var array
*/
protected array $callbacks = [];
/**
* Get the first callback in the collection.
*
* @return callable
*/
public function first()
{
return array_values($this->callbacks)[0];
}
/**
* Invoke the deferred callbacks.
*
* @return void
*/
public function invoke(): void
{
$this->invokeWhen(fn () => true);
}
/**
* Invoke the deferred callbacks if the given truth test evaluates to true.
*
* @param \Closure|null $when
* @return void
*/
public function invokeWhen(?Closure $when = null): void
{
$when ??= fn () => true;
$this->forgetDuplicates();
foreach ($this->callbacks as $index => $callback) {
if ($when($callback)) {
rescue($callback);
}
unset($this->callbacks[$index]);
}
}
/**
* Remove any deferred callbacks with the given name.
*
* @param string $name
* @return void
*/
public function forget(string $name): void
{
$this->callbacks = (new Collection($this->callbacks))
->reject(fn ($callback) => $callback->name === $name)
->values()
->all();
}
/**
* Remove any duplicate callbacks.
*
* @return $this
*/
protected function forgetDuplicates(): static
{
$this->callbacks = (new Collection($this->callbacks))
->reverse()
->unique(fn ($c) => $c->name)
->reverse()
->values()
->all();
return $this;
}
/**
* Determine if the collection has a callback with the given key.
*
* @param mixed $offset
* @return bool
*/
public function offsetExists(mixed $offset): bool
{
$this->forgetDuplicates();
return isset($this->callbacks[$offset]);
}
/**
* Get the callback with the given key.
*
* @param mixed $offset
* @return mixed
*/
public function offsetGet(mixed $offset): mixed
{
$this->forgetDuplicates();
return $this->callbacks[$offset];
}
/**
* Set the callback with the given key.
*
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet(mixed $offset, mixed $value): void
{
if (is_null($offset)) {
$this->callbacks[] = $value;
} else {
$this->callbacks[$offset] = $value;
}
}
/**
* Remove the callback with the given key from the collection.
*
* @param mixed $offset
* @return void
*/
public function offsetUnset(mixed $offset): void
{
$this->forgetDuplicates();
unset($this->callbacks[$offset]);
}
/**
* Determine how many callbacks are in the collection.
*
* @return int
*/
public function count(): int
{
$this->forgetDuplicates();
return count($this->callbacks);
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace Illuminate\Support;
use BackedEnum;
use Illuminate\Contracts\Support\DeferringDisplayableValue;
use Illuminate\Contracts\Support\Htmlable;
class EncodedHtmlString extends HtmlString
{
/**
* The HTML string.
*
* @var \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null
*/
protected $html;
/**
* The callback that should be used to encode the HTML strings.
*
* @var callable|null
*/
protected static $encodeUsingFactory;
/**
* Create a new encoded HTML string instance.
*
* @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null $html
* @param bool $doubleEncode
*/
public function __construct($html = '', protected bool $doubleEncode = true)
{
parent::__construct($html);
}
/**
* Convert the special characters in the given value.
*
* @internal
*
* @param string|null $value
* @param int $withQuote
* @param bool $doubleEncode
* @return string
*/
public static function convert($value, bool $withQuote = true, bool $doubleEncode = true)
{
$flag = $withQuote ? ENT_QUOTES : ENT_NOQUOTES;
return htmlspecialchars($value ?? '', $flag | ENT_SUBSTITUTE, 'UTF-8', $doubleEncode);
}
/**
* Get the HTML string.
*
* @return string
*/
#[\Override]
public function toHtml()
{
$value = $this->html;
if ($value instanceof DeferringDisplayableValue) {
$value = $value->resolveDisplayableValue();
}
if ($value instanceof Htmlable) {
return $value->toHtml();
}
if ($value instanceof BackedEnum) {
$value = $value->value;
}
return (static::$encodeUsingFactory ?? function ($value, $doubleEncode) {
return static::convert($value, doubleEncode: $doubleEncode);
})($value, $this->doubleEncode);
}
/**
* Set the callable that will be used to encode the HTML strings.
*
* @param callable|null $factory
* @return void
*/
public static function encodeUsing(?callable $factory = null)
{
static::$encodeUsingFactory = $factory;
}
/**
* Flush the class's global state.
*
* @return void
*/
public static function flushState()
{
static::$encodeUsingFactory = null;
}
}

View File

@@ -0,0 +1,310 @@
<?php
namespace Illuminate\Support;
use Closure;
use Dotenv\Repository\Adapter\PutenvAdapter;
use Dotenv\Repository\RepositoryBuilder;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Filesystem\Filesystem;
use PhpOption\Option;
use RuntimeException;
class Env
{
/**
* Indicates if the putenv adapter is enabled.
*
* @var bool
*/
protected static $putenv = true;
/**
* The environment repository instance.
*
* @var \Dotenv\Repository\RepositoryInterface|null
*/
protected static $repository;
/**
* The list of custom adapters for loading environment variables.
*
* @var array<Closure>
*/
protected static $customAdapters = [];
/**
* Enable the putenv adapter.
*
* @return void
*/
public static function enablePutenv()
{
static::$putenv = true;
static::$repository = null;
}
/**
* Disable the putenv adapter.
*
* @return void
*/
public static function disablePutenv()
{
static::$putenv = false;
static::$repository = null;
}
/**
* Register a custom adapter creator Closure.
*/
public static function extend(Closure $callback, ?string $name = null): void
{
if (! is_null($name)) {
static::$customAdapters[$name] = $callback;
} else {
static::$customAdapters[] = $callback;
}
static::$repository = null;
}
/**
* Get the environment repository instance.
*
* @return \Dotenv\Repository\RepositoryInterface
*/
public static function getRepository()
{
if (static::$repository === null) {
$builder = RepositoryBuilder::createWithDefaultAdapters();
if (static::$putenv) {
$builder = $builder->addAdapter(PutenvAdapter::class);
}
foreach (static::$customAdapters as $adapter) {
$builder = $builder->addAdapter($adapter());
}
static::$repository = $builder->immutable()->make();
}
return static::$repository;
}
/**
* Get the value of an environment variable.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get($key, $default = null)
{
return self::getOption($key)->getOrCall(fn () => value($default));
}
/**
* Get the value of a required environment variable.
*
* @param string $key
* @return mixed
*
* @throws \RuntimeException
*/
public static function getOrFail($key)
{
return self::getOption($key)->getOrThrow(new RuntimeException("Environment variable [$key] has no value."));
}
/**
* Write an array of key-value pairs to the environment file.
*
* @param array $variables
* @param string $pathToFile
* @param bool $overwrite
* @return void
*
* @throws RuntimeException
* @throws FileNotFoundException
*/
public static function writeVariables(array $variables, string $pathToFile, bool $overwrite = false): void
{
$filesystem = new Filesystem;
if ($filesystem->missing($pathToFile)) {
throw new RuntimeException("The file [{$pathToFile}] does not exist.");
}
$lines = explode(PHP_EOL, $filesystem->get($pathToFile));
foreach ($variables as $key => $value) {
$lines = self::addVariableToEnvContents($key, $value, $lines, $overwrite);
}
$filesystem->put($pathToFile, implode(PHP_EOL, $lines));
}
/**
* Write a single key-value pair to the environment file.
*
* @param string $key
* @param mixed $value
* @param string $pathToFile
* @param bool $overwrite
* @return void
*
* @throws RuntimeException
* @throws FileNotFoundException
*/
public static function writeVariable(string $key, mixed $value, string $pathToFile, bool $overwrite = false): void
{
$filesystem = new Filesystem;
if ($filesystem->missing($pathToFile)) {
throw new RuntimeException("The file [{$pathToFile}] does not exist.");
}
$envContent = $filesystem->get($pathToFile);
$lines = explode(PHP_EOL, $envContent);
$lines = self::addVariableToEnvContents($key, $value, $lines, $overwrite);
$filesystem->put($pathToFile, implode(PHP_EOL, $lines));
}
/**
* Add a variable to the environment file contents.
*
* @param string $key
* @param mixed $value
* @param array $envLines
* @param bool $overwrite
* @return array
*/
protected static function addVariableToEnvContents(string $key, mixed $value, array $envLines, bool $overwrite): array
{
$prefix = explode('_', $key)[0].'_';
$lastPrefixIndex = -1;
$shouldQuote = preg_match('/^[a-zA-z0-9]+$/', $value) === 0;
$lineToAddVariations = [
$key.'='.(is_string($value) ? self::prepareQuotedValue($value) : $value),
$key.'='.$value,
];
$lineToAdd = $shouldQuote ? $lineToAddVariations[0] : $lineToAddVariations[1];
if ($value === '') {
$lineToAdd = $key.'=';
}
foreach ($envLines as $index => $line) {
if (str_starts_with($line, $prefix)) {
$lastPrefixIndex = $index;
}
if (in_array($line, $lineToAddVariations)) {
// This exact line already exists, so we don't need to add it again.
return $envLines;
}
if ($line === $key.'=') {
// If the value is empty, we can replace it with the new value.
$envLines[$index] = $lineToAdd;
return $envLines;
}
if (str_starts_with($line, $key.'=')) {
if (! $overwrite) {
return $envLines;
}
$envLines[$index] = $lineToAdd;
return $envLines;
}
}
if ($lastPrefixIndex === -1) {
if (count($envLines) && $envLines[count($envLines) - 1] !== '') {
$envLines[] = '';
}
return array_merge($envLines, [$lineToAdd]);
}
return array_merge(
array_slice($envLines, 0, $lastPrefixIndex + 1),
[$lineToAdd],
array_slice($envLines, $lastPrefixIndex + 1)
);
}
/**
* Get the possible option for this environment variable.
*
* @param string $key
* @return \PhpOption\Option|\PhpOption\Some
*/
protected static function getOption($key)
{
return Option::fromValue(static::getRepository()->get($key))
->map(function ($value) {
switch (strtolower($value)) {
case 'true':
case '(true)':
return true;
case 'false':
case '(false)':
return false;
case 'empty':
case '(empty)':
return '';
case 'null':
case '(null)':
return;
}
if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) {
return $matches[2];
}
return $value;
});
}
/**
* Wrap a string in quotes, choosing double or single quotes.
*
* @param string $input
* @return string
*/
protected static function prepareQuotedValue(string $input)
{
return strpos($input, '"') !== false
? "'".self::addSlashesExceptFor($input, ['"'])."'"
: '"'.self::addSlashesExceptFor($input, ["'"]).'"';
}
/**
* Escape a string using addslashes, excluding the specified characters from being escaped.
*
* @param string $value
* @param array $except
* @return string
*/
protected static function addSlashesExceptFor(string $value, array $except = [])
{
$escaped = addslashes($value);
foreach ($except as $character) {
$escaped = str_replace('\\'.$character, $character, $escaped);
}
return $escaped;
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Illuminate\Support\Exceptions;
use RuntimeException;
class MathException extends RuntimeException
{
//
}

View File

@@ -0,0 +1,162 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Foundation\Configuration\ApplicationBuilder configure(string|null $basePath = null)
* @method static string inferBasePath()
* @method static string version()
* @method static void bootstrapWith(string[] $bootstrappers)
* @method static void afterLoadingEnvironment(\Closure $callback)
* @method static void beforeBootstrapping(string $bootstrapper, \Closure $callback)
* @method static void afterBootstrapping(string $bootstrapper, \Closure $callback)
* @method static bool hasBeenBootstrapped()
* @method static \Illuminate\Foundation\Application setBasePath(string $basePath)
* @method static string path(string $path = '')
* @method static \Illuminate\Foundation\Application useAppPath(string $path)
* @method static string basePath(string $path = '')
* @method static string bootstrapPath(string $path = '')
* @method static string getBootstrapProvidersPath()
* @method static \Illuminate\Foundation\Application useBootstrapPath(string $path)
* @method static string configPath(string $path = '')
* @method static \Illuminate\Foundation\Application useConfigPath(string $path)
* @method static string databasePath(string $path = '')
* @method static \Illuminate\Foundation\Application useDatabasePath(string $path)
* @method static string langPath(string $path = '')
* @method static \Illuminate\Foundation\Application useLangPath(string $path)
* @method static string publicPath(string $path = '')
* @method static \Illuminate\Foundation\Application usePublicPath(string $path)
* @method static string storagePath(string $path = '')
* @method static \Illuminate\Foundation\Application useStoragePath(string $path)
* @method static string resourcePath(string $path = '')
* @method static string viewPath(string $path = '')
* @method static string joinPaths(string $basePath, string $path = '')
* @method static string environmentPath()
* @method static \Illuminate\Foundation\Application useEnvironmentPath(string $path)
* @method static \Illuminate\Foundation\Application loadEnvironmentFrom(string $file)
* @method static string environmentFile()
* @method static string environmentFilePath()
* @method static string|bool environment(string|array ...$environments)
* @method static bool isLocal()
* @method static bool isProduction()
* @method static string detectEnvironment(\Closure $callback)
* @method static bool runningInConsole()
* @method static bool runningConsoleCommand(string|array ...$commands)
* @method static bool runningUnitTests()
* @method static bool hasDebugModeEnabled()
* @method static void registered(callable $callback)
* @method static void registerConfiguredProviders()
* @method static \Illuminate\Support\ServiceProvider register(\Illuminate\Support\ServiceProvider|string $provider, bool $force = false)
* @method static \Illuminate\Support\ServiceProvider|null getProvider(\Illuminate\Support\ServiceProvider|string $provider)
* @method static array getProviders(\Illuminate\Support\ServiceProvider|string $provider)
* @method static \Illuminate\Support\ServiceProvider resolveProvider(string $provider)
* @method static void loadDeferredProviders()
* @method static void loadDeferredProvider(string $service)
* @method static void registerDeferredProvider(string $provider, string|null $service = null)
* @method static object|mixed make(string $abstract, array $parameters = [])
* @method static bool bound(string $abstract)
* @method static bool isBooted()
* @method static void boot()
* @method static void booting(callable $callback)
* @method static void booted(callable $callback)
* @method static \Symfony\Component\HttpFoundation\Response handle(\Symfony\Component\HttpFoundation\Request $request, int $type = 1, bool $catch = true)
* @method static void handleRequest(\Illuminate\Http\Request $request)
* @method static int handleCommand(\Symfony\Component\Console\Input\InputInterface $input)
* @method static bool shouldMergeFrameworkConfiguration()
* @method static \Illuminate\Foundation\Application dontMergeFrameworkConfiguration()
* @method static bool shouldSkipMiddleware()
* @method static string getCachedServicesPath()
* @method static string getCachedPackagesPath()
* @method static bool configurationIsCached()
* @method static string getCachedConfigPath()
* @method static bool routesAreCached()
* @method static string getCachedRoutesPath()
* @method static bool eventsAreCached()
* @method static string getCachedEventsPath()
* @method static \Illuminate\Foundation\Application addAbsoluteCachePathPrefix(string $prefix)
* @method static \Illuminate\Contracts\Foundation\MaintenanceMode maintenanceMode()
* @method static bool isDownForMaintenance()
* @method static never abort(int $code, string $message = '', array $headers = [])
* @method static \Illuminate\Foundation\Application terminating(callable|string $callback)
* @method static void terminate()
* @method static array getLoadedProviders()
* @method static bool providerIsLoaded(string $provider)
* @method static array getDeferredServices()
* @method static void setDeferredServices(array $services)
* @method static bool isDeferredService(string $service)
* @method static void addDeferredServices(array $services)
* @method static void removeDeferredServices(array $services)
* @method static void provideFacades(string $namespace)
* @method static string getLocale()
* @method static string currentLocale()
* @method static string getFallbackLocale()
* @method static void setLocale(string $locale)
* @method static void setFallbackLocale(string $fallbackLocale)
* @method static bool isLocale(string $locale)
* @method static void registerCoreContainerAliases()
* @method static void flush()
* @method static string getNamespace()
* @method static \Illuminate\Contracts\Container\ContextualBindingBuilder when(array|string $concrete)
* @method static void whenHasAttribute(string $attribute, \Closure $handler)
* @method static bool has(string $id)
* @method static bool isShared(string $abstract)
* @method static bool isAlias(string $name)
* @method static void bind(\Closure|string $abstract, \Closure|string|null $concrete = null, bool $shared = false)
* @method static bool hasMethodBinding(string $method)
* @method static void bindMethod(array|string $method, \Closure $callback)
* @method static mixed callMethodBinding(string $method, mixed $instance)
* @method static void addContextualBinding(string $concrete, \Closure|string $abstract, \Closure|string $implementation)
* @method static void bindIf(\Closure|string $abstract, \Closure|string|null $concrete = null, bool $shared = false)
* @method static void singleton(\Closure|string $abstract, \Closure|string|null $concrete = null)
* @method static void singletonIf(\Closure|string $abstract, \Closure|string|null $concrete = null)
* @method static void scoped(\Closure|string $abstract, \Closure|string|null $concrete = null)
* @method static void scopedIf(\Closure|string $abstract, \Closure|string|null $concrete = null)
* @method static void extend(string $abstract, \Closure $closure)
* @method static mixed instance(string $abstract, mixed $instance)
* @method static void tag(array|string $abstracts, mixed $tags)
* @method static iterable tagged(string $tag)
* @method static void alias(string $abstract, string $alias)
* @method static mixed rebinding(string $abstract, \Closure $callback)
* @method static mixed refresh(string $abstract, mixed $target, string $method)
* @method static \Closure wrap(\Closure $callback, array $parameters = [])
* @method static mixed call(callable|string $callback, array $parameters = [], string|null $defaultMethod = null)
* @method static \Closure|\Closure factory(string $abstract)
* @method static object|mixed makeWith(string|callable $abstract, array $parameters = [])
* @method static object|mixed get(string $id)
* @method static object build(\Closure|string $concrete)
* @method static mixed resolveFromAttribute(\ReflectionAttribute $attribute)
* @method static void beforeResolving(\Closure|string $abstract, \Closure|null $callback = null)
* @method static void resolving(\Closure|string $abstract, \Closure|null $callback = null)
* @method static void afterResolving(\Closure|string $abstract, \Closure|null $callback = null)
* @method static void afterResolvingAttribute(string $attribute, \Closure $callback)
* @method static void fireAfterResolvingAttributeCallbacks(\ReflectionAttribute[] $attributes, mixed $object)
* @method static string|null currentlyResolving()
* @method static array getBindings()
* @method static string getAlias(string $abstract)
* @method static void forgetExtenders(string $abstract)
* @method static void forgetInstance(string $abstract)
* @method static void forgetInstances()
* @method static void forgetScopedInstances()
* @method static void resolveEnvironmentUsing(callable|string|null $callback)
* @method static bool currentEnvironmentIs(array|string $environments)
* @method static \Illuminate\Foundation\Application getInstance()
* @method static \Illuminate\Contracts\Container\Container|\Illuminate\Foundation\Application setInstance(\Illuminate\Contracts\Container\Container|null $container = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Foundation\Application
*/
class App extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'app';
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
/**
* @method static int handle(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface|null $output = null)
* @method static void terminate(\Symfony\Component\Console\Input\InputInterface $input, int $status)
* @method static void whenCommandLifecycleIsLongerThan(\DateTimeInterface|\Carbon\CarbonInterval|float|int $threshold, callable $handler)
* @method static \Illuminate\Support\Carbon|null commandStartedAt()
* @method static \Illuminate\Console\Scheduling\Schedule resolveConsoleSchedule()
* @method static \Illuminate\Foundation\Console\ClosureCommand command(string $signature, \Closure $callback)
* @method static void registerCommand(\Symfony\Component\Console\Command\Command $command)
* @method static int call(\Symfony\Component\Console\Command\Command|string $command, array $parameters = [], \Symfony\Component\Console\Output\OutputInterface|null $outputBuffer = null)
* @method static \Illuminate\Foundation\Bus\PendingDispatch queue(string $command, array $parameters = [])
* @method static array all()
* @method static string output()
* @method static void bootstrap()
* @method static void bootstrapWithoutBootingProviders()
* @method static void setArtisan(\Illuminate\Console\Application|null $artisan)
* @method static \Illuminate\Foundation\Console\Kernel addCommands(array $commands)
* @method static \Illuminate\Foundation\Console\Kernel addCommandPaths(array $paths)
* @method static \Illuminate\Foundation\Console\Kernel addCommandRoutePaths(array $paths)
*
* @see \Illuminate\Foundation\Console\Kernel
*/
class Artisan extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return ConsoleKernelContract::class;
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Illuminate\Support\Facades;
use Laravel\Ui\UiServiceProvider;
use RuntimeException;
/**
* @method static \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard guard(string|null $name = null)
* @method static \Illuminate\Auth\SessionGuard createSessionDriver(string $name, array $config)
* @method static \Illuminate\Auth\TokenGuard createTokenDriver(string $name, array $config)
* @method static string getDefaultDriver()
* @method static void shouldUse(string $name)
* @method static void setDefaultDriver(string $name)
* @method static \Illuminate\Auth\AuthManager viaRequest(string $driver, callable $callback)
* @method static \Closure userResolver()
* @method static \Illuminate\Auth\AuthManager resolveUsersUsing(\Closure $userResolver)
* @method static \Illuminate\Auth\AuthManager extend(string $driver, \Closure $callback)
* @method static \Illuminate\Auth\AuthManager provider(string $name, \Closure $callback)
* @method static bool hasResolvedGuards()
* @method static \Illuminate\Auth\AuthManager forgetGuards()
* @method static \Illuminate\Auth\AuthManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static \Illuminate\Contracts\Auth\UserProvider|null createUserProvider(string|null $provider = null)
* @method static string getDefaultUserProvider()
* @method static bool check()
* @method static bool guest()
* @method static \Illuminate\Contracts\Auth\Authenticatable|null user()
* @method static int|string|null id()
* @method static bool validate(array $credentials = [])
* @method static bool hasUser()
* @method static \Illuminate\Contracts\Auth\Guard setUser(\Illuminate\Contracts\Auth\Authenticatable $user)
* @method static bool attempt(array $credentials = [], bool $remember = false)
* @method static bool once(array $credentials = [])
* @method static void login(\Illuminate\Contracts\Auth\Authenticatable $user, bool $remember = false)
* @method static \Illuminate\Contracts\Auth\Authenticatable|false loginUsingId(mixed $id, bool $remember = false)
* @method static \Illuminate\Contracts\Auth\Authenticatable|false onceUsingId(mixed $id)
* @method static bool viaRemember()
* @method static void logout()
* @method static \Symfony\Component\HttpFoundation\Response|null basic(string $field = 'email', array $extraConditions = [])
* @method static \Symfony\Component\HttpFoundation\Response|null onceBasic(string $field = 'email', array $extraConditions = [])
* @method static bool attemptWhen(array $credentials = [], array|callable|null $callbacks = null, bool $remember = false)
* @method static void logoutCurrentDevice()
* @method static \Illuminate\Contracts\Auth\Authenticatable|null logoutOtherDevices(string $password)
* @method static void attempting(mixed $callback)
* @method static \Illuminate\Contracts\Auth\Authenticatable getLastAttempted()
* @method static string getName()
* @method static string getRecallerName()
* @method static \Illuminate\Auth\SessionGuard setRememberDuration(int $minutes)
* @method static \Illuminate\Contracts\Cookie\QueueingFactory getCookieJar()
* @method static void setCookieJar(\Illuminate\Contracts\Cookie\QueueingFactory $cookie)
* @method static \Illuminate\Contracts\Events\Dispatcher getDispatcher()
* @method static void setDispatcher(\Illuminate\Contracts\Events\Dispatcher $events)
* @method static \Illuminate\Contracts\Session\Session getSession()
* @method static \Illuminate\Contracts\Auth\Authenticatable|null getUser()
* @method static \Symfony\Component\HttpFoundation\Request getRequest()
* @method static \Illuminate\Auth\SessionGuard setRequest(\Symfony\Component\HttpFoundation\Request $request)
* @method static \Illuminate\Support\Timebox getTimebox()
* @method static \Illuminate\Contracts\Auth\Authenticatable authenticate()
* @method static \Illuminate\Auth\SessionGuard forgetUser()
* @method static \Illuminate\Contracts\Auth\UserProvider getProvider()
* @method static void setProvider(\Illuminate\Contracts\Auth\UserProvider $provider)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Auth\AuthManager
* @see \Illuminate\Auth\SessionGuard
*/
class Auth extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'auth';
}
/**
* Register the typical authentication routes for an application.
*
* @param array $options
* @return void
*
* @throws \RuntimeException
*/
public static function routes(array $options = [])
{
if (! static::$app->providerIsLoaded(UiServiceProvider::class)) {
throw new RuntimeException('In order to use the Auth::routes() method, please install the laravel/ui package.');
}
static::$app->make('router')->auth($options);
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static void compile(string|null $path = null)
* @method static string getPath()
* @method static void setPath(string $path)
* @method static string compileString(string $value)
* @method static string render(string $string, array $data = [], bool $deleteCachedView = false)
* @method static string renderComponent(\Illuminate\View\Component $component)
* @method static string stripParentheses(string $expression)
* @method static void extend(callable $compiler)
* @method static array getExtensions()
* @method static void if(string $name, callable $callback)
* @method static bool check(string $name, mixed ...$parameters)
* @method static void component(string $class, string|null $alias = null, string $prefix = '')
* @method static void components(array $components, string $prefix = '')
* @method static array getClassComponentAliases()
* @method static void anonymousComponentPath(string $path, string|null $prefix = null)
* @method static void anonymousComponentNamespace(string $directory, string|null $prefix = null)
* @method static void componentNamespace(string $namespace, string $prefix)
* @method static array getAnonymousComponentPaths()
* @method static array getAnonymousComponentNamespaces()
* @method static array getClassComponentNamespaces()
* @method static void aliasComponent(string $path, string|null $alias = null)
* @method static void include(string $path, string|null $alias = null)
* @method static void aliasInclude(string $path, string|null $alias = null)
* @method static void bindDirective(string $name, callable $handler)
* @method static void directive(string $name, callable $handler, bool $bind = false)
* @method static array getCustomDirectives()
* @method static \Illuminate\View\Compilers\BladeCompiler prepareStringsForCompilationUsing(callable $callback)
* @method static void precompiler(callable $precompiler)
* @method static string usingEchoFormat(string $format, callable $callback)
* @method static void setEchoFormat(string $format)
* @method static void withDoubleEncoding()
* @method static void withoutDoubleEncoding()
* @method static void withoutComponentTags()
* @method static string getCompiledPath(string $path)
* @method static bool isExpired(string $path)
* @method static string newComponentHash(string $component)
* @method static string compileClassComponentOpening(string $component, string $alias, string $data, string $hash)
* @method static string compileEndComponentClass()
* @method static mixed sanitizeComponentAttribute(mixed $value)
* @method static string compileEndOnce()
* @method static void stringable(string|callable $class, callable|null $handler = null)
* @method static string compileEchos(string $value)
* @method static string applyEchoHandler(string $value)
*
* @see \Illuminate\View\Compilers\BladeCompiler
*/
class Blade extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'blade.compiler';
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Contracts\Broadcasting\Factory as BroadcastingFactoryContract;
/**
* @method static void routes(array|null $attributes = null)
* @method static void userRoutes(array|null $attributes = null)
* @method static void channelRoutes(array|null $attributes = null)
* @method static string|null socket(\Illuminate\Http\Request|null $request = null)
* @method static \Illuminate\Broadcasting\AnonymousEvent on(\Illuminate\Broadcasting\Channel|array|string $channels)
* @method static \Illuminate\Broadcasting\AnonymousEvent private(string $channel)
* @method static \Illuminate\Broadcasting\AnonymousEvent presence(string $channel)
* @method static \Illuminate\Broadcasting\PendingBroadcast event(mixed $event = null)
* @method static void queue(mixed $event)
* @method static mixed connection(string|null $driver = null)
* @method static mixed driver(string|null $name = null)
* @method static \Pusher\Pusher pusher(array $config)
* @method static \Ably\AblyRest ably(array $config)
* @method static string getDefaultDriver()
* @method static void setDefaultDriver(string $name)
* @method static void purge(string|null $name = null)
* @method static \Illuminate\Broadcasting\BroadcastManager extend(string $driver, \Closure $callback)
* @method static \Illuminate\Contracts\Foundation\Application getApplication()
* @method static \Illuminate\Broadcasting\BroadcastManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static \Illuminate\Broadcasting\BroadcastManager forgetDrivers()
* @method static mixed auth(\Illuminate\Http\Request $request)
* @method static mixed validAuthenticationResponse(\Illuminate\Http\Request $request, mixed $result)
* @method static void broadcast(array $channels, string $event, array $payload = [])
* @method static array|null resolveAuthenticatedUser(\Illuminate\Http\Request $request)
* @method static void resolveAuthenticatedUserUsing(\Closure $callback)
* @method static \Illuminate\Broadcasting\Broadcasters\Broadcaster channel(\Illuminate\Contracts\Broadcasting\HasBroadcastChannel|string $channel, callable|string $callback, array $options = [])
* @method static \Illuminate\Support\Collection getChannels()
*
* @see \Illuminate\Broadcasting\BroadcastManager
* @see \Illuminate\Broadcasting\Broadcasters\Broadcaster
*/
class Broadcast extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return BroadcastingFactoryContract::class;
}
}

View File

@@ -0,0 +1,103 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Bus\BatchRepository;
use Illuminate\Contracts\Bus\Dispatcher as BusDispatcherContract;
use Illuminate\Foundation\Bus\PendingChain;
use Illuminate\Support\Testing\Fakes\BusFake;
/**
* @method static mixed dispatch(mixed $command)
* @method static mixed dispatchSync(mixed $command, mixed $handler = null)
* @method static mixed dispatchNow(mixed $command, mixed $handler = null)
* @method static \Illuminate\Bus\Batch|null findBatch(string $batchId)
* @method static \Illuminate\Bus\PendingBatch batch(\Illuminate\Support\Collection|mixed $jobs)
* @method static \Illuminate\Foundation\Bus\PendingChain chain(\Illuminate\Support\Collection|array|null $jobs = null)
* @method static bool hasCommandHandler(mixed $command)
* @method static mixed getCommandHandler(mixed $command)
* @method static mixed dispatchToQueue(mixed $command)
* @method static void dispatchAfterResponse(mixed $command, mixed $handler = null)
* @method static \Illuminate\Bus\Dispatcher pipeThrough(array $pipes)
* @method static \Illuminate\Bus\Dispatcher map(array $map)
* @method static \Illuminate\Bus\Dispatcher withDispatchingAfterResponses()
* @method static \Illuminate\Bus\Dispatcher withoutDispatchingAfterResponses()
* @method static \Illuminate\Support\Testing\Fakes\BusFake except(array|string $jobsToDispatch)
* @method static void assertDispatched(string|\Closure $command, callable|int|null $callback = null)
* @method static void assertDispatchedOnce(string|\Closure $command, int $times = null)
* @method static void assertDispatchedTimes(string|\Closure $command, int $times = 1)
* @method static void assertNotDispatched(string|\Closure $command, callable|null $callback = null)
* @method static void assertNothingDispatched()
* @method static void assertDispatchedSync(string|\Closure $command, callable|int|null $callback = null)
* @method static void assertDispatchedSyncTimes(string|\Closure $command, int $times = 1)
* @method static void assertNotDispatchedSync(string|\Closure $command, callable|null $callback = null)
* @method static void assertDispatchedAfterResponse(string|\Closure $command, callable|int|null $callback = null)
* @method static void assertDispatchedAfterResponseTimes(string|\Closure $command, int $times = 1)
* @method static void assertNotDispatchedAfterResponse(string|\Closure $command, callable|null $callback = null)
* @method static void assertChained(array $expectedChain)
* @method static void assertNothingChained()
* @method static void assertDispatchedWithoutChain(string|\Closure $command, callable|null $callback = null)
* @method static \Illuminate\Support\Testing\Fakes\ChainedBatchTruthTest chainedBatch(\Closure $callback)
* @method static void assertBatched(callable $callback)
* @method static void assertBatchCount(int $count)
* @method static void assertNothingBatched()
* @method static void assertNothingPlaced()
* @method static \Illuminate\Support\Collection dispatched(string $command, callable|null $callback = null)
* @method static \Illuminate\Support\Collection dispatchedSync(string $command, callable|null $callback = null)
* @method static \Illuminate\Support\Collection dispatchedAfterResponse(string $command, callable|null $callback = null)
* @method static \Illuminate\Support\Collection batched(callable $callback)
* @method static bool hasDispatched(string $command)
* @method static bool hasDispatchedSync(string $command)
* @method static bool hasDispatchedAfterResponse(string $command)
* @method static \Illuminate\Bus\Batch dispatchFakeBatch(string $name = '')
* @method static \Illuminate\Bus\Batch recordPendingBatch(\Illuminate\Bus\PendingBatch $pendingBatch)
* @method static \Illuminate\Support\Testing\Fakes\BusFake serializeAndRestore(bool $serializeAndRestore = true)
* @method static array dispatchedBatches()
*
* @see \Illuminate\Bus\Dispatcher
* @see \Illuminate\Support\Testing\Fakes\BusFake
*/
class Bus extends Facade
{
/**
* Replace the bound instance with a fake.
*
* @param array|string $jobsToFake
* @param \Illuminate\Bus\BatchRepository|null $batchRepository
* @return \Illuminate\Support\Testing\Fakes\BusFake
*/
public static function fake($jobsToFake = [], ?BatchRepository $batchRepository = null)
{
$actualDispatcher = static::isFake()
? static::getFacadeRoot()->dispatcher
: static::getFacadeRoot();
return tap(new BusFake($actualDispatcher, $jobsToFake, $batchRepository), function ($fake) {
static::swap($fake);
});
}
/**
* Dispatch the given chain of jobs.
*
* @param mixed $jobs
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public static function dispatchChain($jobs)
{
$jobs = is_array($jobs) ? $jobs : func_get_args();
return (new PendingChain(array_shift($jobs), $jobs))
->dispatch();
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return BusDispatcherContract::class;
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Contracts\Cache\Repository store(string|null $name = null)
* @method static \Illuminate\Contracts\Cache\Repository driver(string|null $driver = null)
* @method static \Illuminate\Contracts\Cache\Repository memo(string|null $driver = null)
* @method static \Illuminate\Contracts\Cache\Repository resolve(string $name)
* @method static \Illuminate\Cache\Repository build(array $config)
* @method static \Illuminate\Cache\Repository repository(\Illuminate\Contracts\Cache\Store $store, array $config = [])
* @method static void refreshEventDispatcher()
* @method static string getDefaultDriver()
* @method static void setDefaultDriver(string $name)
* @method static \Illuminate\Cache\CacheManager forgetDriver(array|string|null $name = null)
* @method static void purge(string|null $name = null)
* @method static \Illuminate\Cache\CacheManager extend(string $driver, \Closure $callback)
* @method static \Illuminate\Cache\CacheManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static bool has(array|string $key)
* @method static bool missing(string $key)
* @method static mixed get(array|string $key, mixed $default = null)
* @method static array many(array $keys)
* @method static iterable getMultiple(iterable $keys, mixed $default = null)
* @method static mixed pull(array|string $key, mixed $default = null)
* @method static bool put(array|string $key, mixed $value, \DateTimeInterface|\DateInterval|int|null $ttl = null)
* @method static bool set(string $key, mixed $value, null|int|\DateInterval $ttl = null)
* @method static bool putMany(array $values, \DateTimeInterface|\DateInterval|int|null $ttl = null)
* @method static bool setMultiple(iterable $values, null|int|\DateInterval $ttl = null)
* @method static bool add(string $key, mixed $value, \DateTimeInterface|\DateInterval|int|null $ttl = null)
* @method static int|bool increment(string $key, mixed $value = 1)
* @method static int|bool decrement(string $key, mixed $value = 1)
* @method static bool forever(string $key, mixed $value)
* @method static mixed remember(string $key, \Closure|\DateTimeInterface|\DateInterval|int|null $ttl, \Closure $callback)
* @method static mixed sear(string $key, \Closure $callback)
* @method static mixed rememberForever(string $key, \Closure $callback)
* @method static mixed flexible(string $key, array $ttl, callable $callback, array|null $lock = null, bool $alwaysDefer = false)
* @method static bool forget(string $key)
* @method static bool delete(string $key)
* @method static bool deleteMultiple(iterable $keys)
* @method static bool clear()
* @method static \Illuminate\Cache\TaggedCache tags(mixed $names)
* @method static string|null getName()
* @method static bool supportsTags()
* @method static int|null getDefaultCacheTime()
* @method static \Illuminate\Cache\Repository setDefaultCacheTime(int|null $seconds)
* @method static \Illuminate\Contracts\Cache\Store getStore()
* @method static \Illuminate\Cache\Repository setStore(\Illuminate\Contracts\Cache\Store $store)
* @method static \Illuminate\Contracts\Events\Dispatcher|null getEventDispatcher()
* @method static void setEventDispatcher(\Illuminate\Contracts\Events\Dispatcher $events)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
* @method static bool flush()
* @method static string getPrefix()
* @method static \Illuminate\Contracts\Cache\Lock lock(string $name, int $seconds = 0, string|null $owner = null)
* @method static \Illuminate\Contracts\Cache\Lock restoreLock(string $name, string $owner)
*
* @see \Illuminate\Cache\CacheManager
* @see \Illuminate\Cache\Repository
*/
class Cache extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'cache';
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Concurrency\ConcurrencyManager;
/**
* @method static mixed driver(string|null $name = null)
* @method static \Illuminate\Concurrency\ProcessDriver createProcessDriver(array $config)
* @method static \Illuminate\Concurrency\ForkDriver createForkDriver(array $config)
* @method static \Illuminate\Concurrency\SyncDriver createSyncDriver(array $config)
* @method static string getDefaultInstance()
* @method static void setDefaultInstance(string $name)
* @method static array getInstanceConfig(string $name)
* @method static mixed instance(string|null $name = null)
* @method static \Illuminate\Concurrency\ConcurrencyManager forgetInstance(array|string|null $name = null)
* @method static void purge(string|null $name = null)
* @method static \Illuminate\Concurrency\ConcurrencyManager extend(string $name, \Closure $callback)
* @method static \Illuminate\Concurrency\ConcurrencyManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static array run(\Closure|array $tasks)
* @method static \Illuminate\Support\Defer\DeferredCallback defer(\Closure|array $tasks)
*
* @see \Illuminate\Concurrency\ConcurrencyManager
*/
class Concurrency extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return ConcurrencyManager::class;
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static bool has(string $key)
* @method static mixed get(array|string $key, mixed $default = null)
* @method static array getMany(array $keys)
* @method static string string(string $key, \Closure|string|null $default = null)
* @method static int integer(string $key, \Closure|int|null $default = null)
* @method static float float(string $key, \Closure|float|null $default = null)
* @method static bool boolean(string $key, \Closure|bool|null $default = null)
* @method static array array(string $key, \Closure|array|null $default = null)
* @method static \Illuminate\Support\Collection collection(string $key, \Closure|array|null $default = null)
* @method static void set(array|string $key, mixed $value = null)
* @method static void prepend(string $key, mixed $value)
* @method static void push(string $key, mixed $value)
* @method static array all()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Config\Repository
*/
class Config extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'config';
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static bool has(string $key)
* @method static bool missing(string $key)
* @method static bool hasHidden(string $key)
* @method static bool missingHidden(string $key)
* @method static array all()
* @method static array allHidden()
* @method static mixed get(string $key, mixed $default = null)
* @method static mixed getHidden(string $key, mixed $default = null)
* @method static mixed pull(string $key, mixed $default = null)
* @method static mixed pullHidden(string $key, mixed $default = null)
* @method static array only(array $keys)
* @method static array onlyHidden(array $keys)
* @method static array except(array $keys)
* @method static array exceptHidden(array $keys)
* @method static \Illuminate\Log\Context\Repository add(string|array $key, mixed $value = null)
* @method static \Illuminate\Log\Context\Repository addHidden(string|array $key, mixed $value = null)
* @method static mixed remember(string $key, mixed $value)
* @method static mixed rememberHidden(string $key, mixed $value)
* @method static \Illuminate\Log\Context\Repository forget(string|array $key)
* @method static \Illuminate\Log\Context\Repository forgetHidden(string|array $key)
* @method static \Illuminate\Log\Context\Repository addIf(string $key, mixed $value)
* @method static \Illuminate\Log\Context\Repository addHiddenIf(string $key, mixed $value)
* @method static \Illuminate\Log\Context\Repository push(string $key, mixed ...$values)
* @method static mixed pop(string $key)
* @method static \Illuminate\Log\Context\Repository pushHidden(string $key, mixed ...$values)
* @method static mixed popHidden(string $key)
* @method static \Illuminate\Log\Context\Repository increment(string $key, int $amount = 1)
* @method static \Illuminate\Log\Context\Repository decrement(string $key, int $amount = 1)
* @method static bool stackContains(string $key, mixed $value, bool $strict = false)
* @method static bool hiddenStackContains(string $key, mixed $value, bool $strict = false)
* @method static mixed scope(callable $callback, array $data = [], array $hidden = [])
* @method static bool isEmpty()
* @method static \Illuminate\Log\Context\Repository dehydrating(callable $callback)
* @method static \Illuminate\Log\Context\Repository hydrated(callable $callback)
* @method static \Illuminate\Log\Context\Repository handleUnserializeExceptionsUsing(callable|null $callback)
* @method static \Illuminate\Log\Context\Repository flush()
* @method static \Illuminate\Log\Context\Repository|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Log\Context\Repository|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static \Illuminate\Database\Eloquent\Model restoreModel(\Illuminate\Contracts\Database\ModelIdentifier $value)
*
* @see \Illuminate\Log\Context\Repository
*/
class Context extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return \Illuminate\Log\Context\Repository::class;
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Symfony\Component\HttpFoundation\Cookie make(string $name, string $value, int $minutes = 0, string|null $path = null, string|null $domain = null, bool|null $secure = null, bool $httpOnly = true, bool $raw = false, string|null $sameSite = null)
* @method static \Symfony\Component\HttpFoundation\Cookie forever(string $name, string $value, string|null $path = null, string|null $domain = null, bool|null $secure = null, bool $httpOnly = true, bool $raw = false, string|null $sameSite = null)
* @method static \Symfony\Component\HttpFoundation\Cookie forget(string $name, string|null $path = null, string|null $domain = null)
* @method static bool hasQueued(string $key, string|null $path = null)
* @method static \Symfony\Component\HttpFoundation\Cookie|null queued(string $key, mixed $default = null, string|null $path = null)
* @method static void queue(mixed ...$parameters)
* @method static void expire(string $name, string|null $path = null, string|null $domain = null)
* @method static void unqueue(string $name, string|null $path = null)
* @method static \Illuminate\Cookie\CookieJar setDefaultPathAndDomain(string $path, string|null $domain, bool|null $secure = false, string|null $sameSite = null)
* @method static \Symfony\Component\HttpFoundation\Cookie[] getQueuedCookies()
* @method static \Illuminate\Cookie\CookieJar flushQueuedCookies()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Cookie\CookieJar
*/
class Cookie extends Facade
{
/**
* Determine if a cookie exists on the request.
*
* @param string $key
* @return bool
*/
public static function has($key)
{
return ! is_null(static::$app['request']->cookie($key, null));
}
/**
* Retrieve a cookie from the request.
*
* @param string|null $key
* @param mixed $default
* @return string|array|null
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->cookie($key, $default);
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'cookie';
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static bool supported(string $key, string $cipher)
* @method static string generateKey(string $cipher)
* @method static string encrypt(mixed $value, bool $serialize = true)
* @method static string encryptString(string $value)
* @method static mixed decrypt(string $payload, bool $unserialize = true)
* @method static string decryptString(string $payload)
* @method static string getKey()
* @method static array getAllKeys()
* @method static array getPreviousKeys()
* @method static \Illuminate\Encryption\Encrypter previousKeys(array $keys)
*
* @see \Illuminate\Encryption\Encrypter
*/
class Crypt extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'encrypter';
}
}

View File

@@ -0,0 +1,148 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Database\Console\Migrations\FreshCommand;
use Illuminate\Database\Console\Migrations\RefreshCommand;
use Illuminate\Database\Console\Migrations\ResetCommand;
use Illuminate\Database\Console\Migrations\RollbackCommand;
use Illuminate\Database\Console\WipeCommand;
/**
* @method static \Illuminate\Database\Connection connection(\UnitEnum|string|null $name = null)
* @method static \Illuminate\Database\ConnectionInterface build(array $config)
* @method static string calculateDynamicConnectionName(array $config)
* @method static \Illuminate\Database\ConnectionInterface connectUsing(\UnitEnum|string $name, array $config, bool $force = false)
* @method static void purge(\UnitEnum|string|null $name = null)
* @method static void disconnect(\UnitEnum|string|null $name = null)
* @method static \Illuminate\Database\Connection reconnect(\UnitEnum|string|null $name = null)
* @method static mixed usingConnection(\UnitEnum|string $name, callable $callback)
* @method static string getDefaultConnection()
* @method static void setDefaultConnection(string $name)
* @method static string[] supportedDrivers()
* @method static string[] availableDrivers()
* @method static void extend(string $name, callable $resolver)
* @method static void forgetExtension(string $name)
* @method static array getConnections()
* @method static void setReconnector(callable $reconnector)
* @method static \Illuminate\Database\DatabaseManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
* @method static void useDefaultQueryGrammar()
* @method static void useDefaultSchemaGrammar()
* @method static void useDefaultPostProcessor()
* @method static \Illuminate\Database\Schema\Builder getSchemaBuilder()
* @method static \Illuminate\Database\Query\Builder table(\Closure|\Illuminate\Database\Query\Builder|\Illuminate\Contracts\Database\Query\Expression|\UnitEnum|string $table, string|null $as = null)
* @method static \Illuminate\Database\Query\Builder query()
* @method static mixed selectOne(string $query, array $bindings = [], bool $useReadPdo = true)
* @method static mixed scalar(string $query, array $bindings = [], bool $useReadPdo = true)
* @method static array selectFromWriteConnection(string $query, array $bindings = [])
* @method static array select(string $query, array $bindings = [], bool $useReadPdo = true)
* @method static array selectResultSets(string $query, array $bindings = [], bool $useReadPdo = true)
* @method static \Generator cursor(string $query, array $bindings = [], bool $useReadPdo = true)
* @method static bool insert(string $query, array $bindings = [])
* @method static int update(string $query, array $bindings = [])
* @method static int delete(string $query, array $bindings = [])
* @method static bool statement(string $query, array $bindings = [])
* @method static int affectingStatement(string $query, array $bindings = [])
* @method static bool unprepared(string $query)
* @method static int|null threadCount()
* @method static array[] pretend(\Closure $callback)
* @method static mixed withoutPretending(\Closure $callback)
* @method static void bindValues(\PDOStatement $statement, array $bindings)
* @method static array prepareBindings(array $bindings)
* @method static void logQuery(string $query, array $bindings, float|null $time = null)
* @method static void whenQueryingForLongerThan(\DateTimeInterface|\Carbon\CarbonInterval|float|int $threshold, callable $handler)
* @method static void allowQueryDurationHandlersToRunAgain()
* @method static float totalQueryDuration()
* @method static void resetTotalQueryDuration()
* @method static void reconnectIfMissingConnection()
* @method static \Illuminate\Database\Connection beforeStartingTransaction(\Closure $callback)
* @method static \Illuminate\Database\Connection beforeExecuting(\Closure $callback)
* @method static void listen(\Closure $callback)
* @method static \Illuminate\Contracts\Database\Query\Expression raw(mixed $value)
* @method static string escape(string|float|int|bool|null $value, bool $binary = false)
* @method static bool hasModifiedRecords()
* @method static void recordsHaveBeenModified(bool $value = true)
* @method static \Illuminate\Database\Connection setRecordModificationState(bool $value)
* @method static void forgetRecordModificationState()
* @method static \Illuminate\Database\Connection useWriteConnectionWhenReading(bool $value = true)
* @method static \PDO getPdo()
* @method static \PDO|\Closure|null getRawPdo()
* @method static \PDO getReadPdo()
* @method static \PDO|\Closure|null getRawReadPdo()
* @method static \Illuminate\Database\Connection setPdo(\PDO|\Closure|null $pdo)
* @method static \Illuminate\Database\Connection setReadPdo(\PDO|\Closure|null $pdo)
* @method static string|null getName()
* @method static string|null getNameWithReadWriteType()
* @method static mixed getConfig(string|null $option = null)
* @method static string getDriverName()
* @method static string getDriverTitle()
* @method static \Illuminate\Database\Query\Grammars\Grammar getQueryGrammar()
* @method static \Illuminate\Database\Connection setQueryGrammar(\Illuminate\Database\Query\Grammars\Grammar $grammar)
* @method static \Illuminate\Database\Schema\Grammars\Grammar getSchemaGrammar()
* @method static \Illuminate\Database\Connection setSchemaGrammar(\Illuminate\Database\Schema\Grammars\Grammar $grammar)
* @method static \Illuminate\Database\Query\Processors\Processor getPostProcessor()
* @method static \Illuminate\Database\Connection setPostProcessor(\Illuminate\Database\Query\Processors\Processor $processor)
* @method static \Illuminate\Contracts\Events\Dispatcher getEventDispatcher()
* @method static \Illuminate\Database\Connection setEventDispatcher(\Illuminate\Contracts\Events\Dispatcher $events)
* @method static void unsetEventDispatcher()
* @method static \Illuminate\Database\Connection setTransactionManager(\Illuminate\Database\DatabaseTransactionsManager $manager)
* @method static void unsetTransactionManager()
* @method static bool pretending()
* @method static array[] getQueryLog()
* @method static array getRawQueryLog()
* @method static void flushQueryLog()
* @method static void enableQueryLog()
* @method static void disableQueryLog()
* @method static bool logging()
* @method static string getDatabaseName()
* @method static \Illuminate\Database\Connection setDatabaseName(string $database)
* @method static \Illuminate\Database\Connection setReadWriteType(string|null $readWriteType)
* @method static string getTablePrefix()
* @method static \Illuminate\Database\Connection setTablePrefix(string $prefix)
* @method static mixed withoutTablePrefix(\Closure $callback)
* @method static string getServerVersion()
* @method static void resolverFor(string $driver, \Closure $callback)
* @method static \Closure|null getResolver(string $driver)
* @method static mixed transaction(\Closure $callback, int $attempts = 1)
* @method static void beginTransaction()
* @method static void commit()
* @method static void rollBack(int|null $toLevel = null)
* @method static int transactionLevel()
* @method static void afterCommit(callable $callback)
*
* @see \Illuminate\Database\DatabaseManager
*/
class DB extends Facade
{
/**
* Indicate if destructive Artisan commands should be prohibited.
*
* Prohibits: db:wipe, migrate:fresh, migrate:refresh, migrate:reset, and migrate:rollback
*
* @param bool $prohibit
* @return void
*/
public static function prohibitDestructiveCommands(bool $prohibit = true)
{
FreshCommand::prohibit($prohibit);
RefreshCommand::prohibit($prohibit);
ResetCommand::prohibit($prohibit);
RollbackCommand::prohibit($prohibit);
WipeCommand::prohibit($prohibit);
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'db';
}
}

View File

@@ -0,0 +1,141 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Support\DateFactory;
/**
* @see https://carbon.nesbot.com/docs/
* @see https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Factory.php
*
* @method static mixed use(mixed $handler)
* @method static void useDefault()
* @method static void useCallable(callable $callable)
* @method static void useClass(string $dateClass)
* @method static void useFactory(object $factory)
* @method static bool canBeCreatedFromFormat(?string $date, string $format)
* @method static \Illuminate\Support\Carbon|null create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null)
* @method static \Illuminate\Support\Carbon createFromDate($year = null, $month = null, $day = null, $timezone = null)
* @method static \Illuminate\Support\Carbon|null createFromFormat($format, $time, $timezone = null)
* @method static \Illuminate\Support\Carbon|null createFromIsoFormat(string $format, string $time, $timezone = null, ?string $locale = 'en', ?\Symfony\Contracts\Translation\TranslatorInterface $translator = null)
* @method static \Illuminate\Support\Carbon|null createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null)
* @method static \Illuminate\Support\Carbon|null createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null)
* @method static \Illuminate\Support\Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null)
* @method static \Illuminate\Support\Carbon createFromTimeString(string $time, \DateTimeZone|string|int|null $timezone = null)
* @method static \Illuminate\Support\Carbon createFromTimestamp(string|int|float $timestamp, \DateTimeZone|string|int|null $timezone = null)
* @method static \Illuminate\Support\Carbon createFromTimestampMs(string|int|float $timestamp, \DateTimeZone|string|int|null $timezone = null)
* @method static \Illuminate\Support\Carbon createFromTimestampMsUTC($timestamp)
* @method static \Illuminate\Support\Carbon createFromTimestampUTC(string|int|float $timestamp)
* @method static \Illuminate\Support\Carbon createMidnightDate($year = null, $month = null, $day = null, $timezone = null)
* @method static \Illuminate\Support\Carbon|null createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null)
* @method static \Illuminate\Support\Carbon createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null)
* @method static void disableHumanDiffOption($humanDiffOption)
* @method static void enableHumanDiffOption($humanDiffOption)
* @method static mixed executeWithLocale(string $locale, callable $func)
* @method static \Illuminate\Support\Carbon fromSerialized($value)
* @method static array getAvailableLocales()
* @method static array getAvailableLocalesInfo()
* @method static array getDays()
* @method static ?string getFallbackLocale()
* @method static array getFormatsToIsoReplacements()
* @method static int getHumanDiffOptions()
* @method static array getIsoUnits()
* @method static array|false getLastErrors()
* @method static string getLocale()
* @method static int getMidDayAt()
* @method static string getTimeFormatByPrecision(string $unitPrecision)
* @method static string|\Closure|null getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null)
* @method static \Illuminate\Support\Carbon|null getTestNow()
* @method static \Symfony\Contracts\Translation\TranslatorInterface getTranslator()
* @method static int getWeekEndsAt(?string $locale = null)
* @method static int getWeekStartsAt(?string $locale = null)
* @method static array getWeekendDays()
* @method static bool hasFormat(string $date, string $format)
* @method static bool hasFormatWithModifiers(string $date, string $format)
* @method static bool hasMacro($name)
* @method static bool hasRelativeKeywords(?string $time)
* @method static bool hasTestNow()
* @method static \Illuminate\Support\Carbon instance(\DateTimeInterface $date)
* @method static bool isImmutable()
* @method static bool isModifiableUnit($unit)
* @method static bool isMutable()
* @method static bool isStrictModeEnabled()
* @method static bool localeHasDiffOneDayWords(string $locale)
* @method static bool localeHasDiffSyntax(string $locale)
* @method static bool localeHasDiffTwoDayWords(string $locale)
* @method static bool localeHasPeriodSyntax($locale)
* @method static bool localeHasShortUnits(string $locale)
* @method static void macro(string $name, ?callable $macro)
* @method static \Illuminate\Support\Carbon|null make($var, \DateTimeZone|string|null $timezone = null)
* @method static void mixin(object|string $mixin)
* @method static \Illuminate\Support\Carbon now(\DateTimeZone|string|int|null $timezone = null)
* @method static \Illuminate\Support\Carbon parse(\DateTimeInterface|\Carbon\WeekDay|\Carbon\Month|string|int|float|null $time, \DateTimeZone|string|int|null $timezone = null)
* @method static \Illuminate\Support\Carbon parseFromLocale(string $time, ?string $locale = null, \DateTimeZone|string|int|null $timezone = null)
* @method static string pluralUnit(string $unit)
* @method static \Illuminate\Support\Carbon|null rawCreateFromFormat(string $format, string $time, $timezone = null)
* @method static \Illuminate\Support\Carbon rawParse(\DateTimeInterface|\Carbon\WeekDay|\Carbon\Month|string|int|float|null $time, \DateTimeZone|string|int|null $timezone = null)
* @method static void resetMonthsOverflow()
* @method static void resetToStringFormat()
* @method static void resetYearsOverflow()
* @method static void serializeUsing($callback)
* @method static void setFallbackLocale(string $locale)
* @method static void setHumanDiffOptions($humanDiffOptions)
* @method static void setLocale(string $locale)
* @method static void setMidDayAt($hour)
* @method static void setTestNow(mixed $testNow = null)
* @method static void setTestNowAndTimezone(mixed $testNow = null, $timezone = null)
* @method static void setToStringFormat(string|\Closure|null $format)
* @method static void setTranslator(\Symfony\Contracts\Translation\TranslatorInterface $translator)
* @method static void setWeekEndsAt($day)
* @method static void setWeekStartsAt($day)
* @method static void setWeekendDays($days)
* @method static bool shouldOverflowMonths()
* @method static bool shouldOverflowYears()
* @method static string singularUnit(string $unit)
* @method static void sleep(int|float $seconds)
* @method static \Illuminate\Support\Carbon today(\DateTimeZone|string|int|null $timezone = null)
* @method static \Illuminate\Support\Carbon tomorrow(\DateTimeZone|string|int|null $timezone = null)
* @method static string translateTimeString(string $timeString, ?string $from = null, ?string $to = null, int $mode = \Carbon\CarbonInterface::TRANSLATE_ALL)
* @method static string translateWith(\Symfony\Contracts\Translation\TranslatorInterface $translator, string $key, array $parameters = [], $number = null)
* @method static void useMonthsOverflow($monthsOverflow = true)
* @method static void useStrictMode($strictModeEnabled = true)
* @method static void useYearsOverflow($yearsOverflow = true)
* @method static mixed withTestNow(mixed $testNow, callable $callback)
* @method static static withTimeZone(\DateTimeZone|string|int|null $timezone)
* @method static \Illuminate\Support\Carbon yesterday(\DateTimeZone|string|int|null $timezone = null)
*
* @see \Illuminate\Support\DateFactory
*/
class Date extends Facade
{
const DEFAULT_FACADE = DateFactory::class;
/**
* Get the registered name of the component.
*
* @return string
*
* @throws \RuntimeException
*/
protected static function getFacadeAccessor()
{
return 'date';
}
/**
* Resolve the facade root instance from the container.
*
* @param string $name
* @return mixed
*/
protected static function resolveFacadeInstance($name)
{
if (! isset(static::$resolvedInstance[$name]) && ! isset(static::$app, static::$app[$name])) {
$class = static::DEFAULT_FACADE;
static::swap(new $class);
}
return parent::resolveFacadeInstance($name);
}
}

View File

@@ -0,0 +1,136 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Testing\Fakes\EventFake;
/**
* @method static void listen(\Illuminate\Events\QueuedClosure|callable|array|string $events, \Illuminate\Events\QueuedClosure|callable|array|string|null $listener = null)
* @method static bool hasListeners(string $eventName)
* @method static bool hasWildcardListeners(string $eventName)
* @method static void push(string $event, object|array $payload = [])
* @method static void flush(string $event)
* @method static void subscribe(object|string $subscriber)
* @method static mixed until(string|object $event, mixed $payload = [])
* @method static array|null dispatch(string|object $event, mixed $payload = [], bool $halt = false)
* @method static array getListeners(string $eventName)
* @method static \Closure makeListener(\Closure|string|array $listener, bool $wildcard = false)
* @method static \Closure createClassListener(string $listener, bool $wildcard = false)
* @method static void forget(string $event)
* @method static void forgetPushed()
* @method static \Illuminate\Events\Dispatcher setQueueResolver(callable $resolver)
* @method static \Illuminate\Events\Dispatcher setTransactionManagerResolver(callable $resolver)
* @method static mixed defer(callable $callback, array|null $events = null)
* @method static array getRawListeners()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static \Illuminate\Support\Testing\Fakes\EventFake except(array|string $eventsToDispatch)
* @method static void assertListening(string $expectedEvent, string|array $expectedListener)
* @method static void assertDispatched(string|\Closure $event, callable|int|null $callback = null)
* @method static void assertDispatchedOnce(string $event, int $times = null)
* @method static void assertDispatchedTimes(string $event, int $times = 1)
* @method static void assertNotDispatched(string|\Closure $event, callable|null $callback = null)
* @method static void assertNothingDispatched()
* @method static \Illuminate\Support\Collection dispatched(string $event, callable|null $callback = null)
* @method static bool hasDispatched(string $event)
* @method static array dispatchedEvents()
*
* @see \Illuminate\Events\Dispatcher
* @see \Illuminate\Support\Testing\Fakes\EventFake
*/
class Event extends Facade
{
/**
* Replace the bound instance with a fake.
*
* @param array|string $eventsToFake
* @return \Illuminate\Support\Testing\Fakes\EventFake
*/
public static function fake($eventsToFake = [])
{
$actualDispatcher = static::isFake()
? static::getFacadeRoot()->dispatcher
: static::getFacadeRoot();
return tap(new EventFake($actualDispatcher, $eventsToFake), function ($fake) {
static::swap($fake);
Model::setEventDispatcher($fake);
Cache::refreshEventDispatcher();
});
}
/**
* Replace the bound instance with a fake that fakes all events except the given events.
*
* @param string[]|string $eventsToAllow
* @return \Illuminate\Support\Testing\Fakes\EventFake
*/
public static function fakeExcept($eventsToAllow)
{
return static::fake([
function ($eventName) use ($eventsToAllow) {
return ! in_array($eventName, (array) $eventsToAllow);
},
]);
}
/**
* Replace the bound instance with a fake during the given callable's execution.
*
* @param callable $callable
* @param array $eventsToFake
* @return mixed
*/
public static function fakeFor(callable $callable, array $eventsToFake = [])
{
$originalDispatcher = static::getFacadeRoot();
static::fake($eventsToFake);
try {
return $callable();
} finally {
static::swap($originalDispatcher);
Model::setEventDispatcher($originalDispatcher);
Cache::refreshEventDispatcher();
}
}
/**
* Replace the bound instance with a fake during the given callable's execution.
*
* @param callable $callable
* @param array $eventsToAllow
* @return mixed
*/
public static function fakeExceptFor(callable $callable, array $eventsToAllow = [])
{
$originalDispatcher = static::getFacadeRoot();
static::fakeExcept($eventsToAllow);
try {
return $callable();
} finally {
static::swap($originalDispatcher);
Model::setEventDispatcher($originalDispatcher);
Cache::refreshEventDispatcher();
}
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'events';
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Arr;
use Illuminate\Support\Testing\Fakes\ExceptionHandlerFake;
/**
* @method static void register()
* @method static \Illuminate\Foundation\Exceptions\ReportableHandler reportable(callable $reportUsing)
* @method static \Illuminate\Foundation\Exceptions\Handler renderable(callable $renderUsing)
* @method static \Illuminate\Foundation\Exceptions\Handler map(\Closure|string $from, \Closure|string|null $to = null)
* @method static \Illuminate\Foundation\Exceptions\Handler dontReport(array|string $exceptions)
* @method static \Illuminate\Foundation\Exceptions\Handler dontReportWhen(callable $dontReportWhen)
* @method static \Illuminate\Foundation\Exceptions\Handler ignore(array|string $exceptions)
* @method static \Illuminate\Foundation\Exceptions\Handler dontFlash(array|string $attributes)
* @method static \Illuminate\Foundation\Exceptions\Handler level(string $type, string $level)
* @method static void report(\Throwable $e)
* @method static bool shouldReport(\Throwable $e)
* @method static \Illuminate\Foundation\Exceptions\Handler throttleUsing(callable $throttleUsing)
* @method static \Illuminate\Foundation\Exceptions\Handler stopIgnoring(array|string $exceptions)
* @method static \Illuminate\Foundation\Exceptions\Handler buildContextUsing(\Closure $contextCallback)
* @method static \Symfony\Component\HttpFoundation\Response render(\Illuminate\Http\Request $request, \Throwable $e)
* @method static \Illuminate\Foundation\Exceptions\Handler respondUsing(callable $callback)
* @method static \Illuminate\Foundation\Exceptions\Handler shouldRenderJsonWhen(callable $callback)
* @method static \Illuminate\Foundation\Exceptions\Handler dontReportDuplicates()
* @method static \Illuminate\Contracts\Debug\ExceptionHandler handler()
* @method static void assertReported(\Closure|string $exception)
* @method static void assertReportedCount(int $count)
* @method static void assertNotReported(\Closure|string $exception)
* @method static void assertNothingReported()
* @method static void renderForConsole(\Symfony\Component\Console\Output\OutputInterface $output, \Throwable $e)
* @method static \Illuminate\Support\Testing\Fakes\ExceptionHandlerFake throwOnReport()
* @method static \Illuminate\Support\Testing\Fakes\ExceptionHandlerFake throwFirstReported()
* @method static array reported()
* @method static \Illuminate\Support\Testing\Fakes\ExceptionHandlerFake setHandler(\Illuminate\Contracts\Debug\ExceptionHandler $handler)
*
* @see \Illuminate\Foundation\Exceptions\Handler
* @see \Illuminate\Support\Testing\Fakes\ExceptionHandlerFake
*/
class Exceptions extends Facade
{
/**
* Replace the bound instance with a fake.
*
* @param array<int, class-string<\Throwable>>|class-string<\Throwable> $exceptions
* @return \Illuminate\Support\Testing\Fakes\ExceptionHandlerFake
*/
public static function fake(array|string $exceptions = [])
{
$exceptionHandler = static::isFake()
? static::getFacadeRoot()->handler()
: static::getFacadeRoot();
return tap(new ExceptionHandlerFake($exceptionHandler, Arr::wrap($exceptions)), function ($fake) {
static::swap($fake);
});
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return ExceptionHandler::class;
}
}

View File

@@ -0,0 +1,365 @@
<?php
namespace Illuminate\Support\Facades;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Benchmark;
use Illuminate\Support\Collection;
use Illuminate\Support\Js;
use Illuminate\Support\Number;
use Illuminate\Support\Str;
use Illuminate\Support\Testing\Fakes\Fake;
use Illuminate\Support\Uri;
use Mockery;
use Mockery\LegacyMockInterface;
use RuntimeException;
abstract class Facade
{
/**
* The application instance being facaded.
*
* @var \Illuminate\Contracts\Foundation\Application|null
*/
protected static $app;
/**
* The resolved object instances.
*
* @var array
*/
protected static $resolvedInstance;
/**
* Indicates if the resolved instance should be cached.
*
* @var bool
*/
protected static $cached = true;
/**
* Run a Closure when the facade has been resolved.
*
* @param \Closure $callback
* @return void
*/
public static function resolved(Closure $callback)
{
$accessor = static::getFacadeAccessor();
if (static::$app->resolved($accessor) === true) {
$callback(static::getFacadeRoot(), static::$app);
}
static::$app->afterResolving($accessor, function ($service, $app) use ($callback) {
$callback($service, $app);
});
}
/**
* Convert the facade into a Mockery spy.
*
* @return \Mockery\MockInterface
*/
public static function spy()
{
if (! static::isMock()) {
$class = static::getMockableClass();
return tap($class ? Mockery::spy($class) : Mockery::spy(), function ($spy) {
static::swap($spy);
});
}
}
/**
* Initiate a partial mock on the facade.
*
* @return \Mockery\MockInterface
*/
public static function partialMock()
{
$name = static::getFacadeAccessor();
$mock = static::isMock()
? static::$resolvedInstance[$name]
: static::createFreshMockInstance();
return $mock->makePartial();
}
/**
* Initiate a mock expectation on the facade.
*
* @return \Mockery\Expectation
*/
public static function shouldReceive()
{
$name = static::getFacadeAccessor();
$mock = static::isMock()
? static::$resolvedInstance[$name]
: static::createFreshMockInstance();
return $mock->shouldReceive(...func_get_args());
}
/**
* Initiate a mock expectation on the facade.
*
* @return \Mockery\Expectation
*/
public static function expects()
{
$name = static::getFacadeAccessor();
$mock = static::isMock()
? static::$resolvedInstance[$name]
: static::createFreshMockInstance();
return $mock->expects(...func_get_args());
}
/**
* Create a fresh mock instance for the given class.
*
* @return \Mockery\MockInterface
*/
protected static function createFreshMockInstance()
{
return tap(static::createMock(), function ($mock) {
static::swap($mock);
$mock->shouldAllowMockingProtectedMethods();
});
}
/**
* Create a fresh mock instance for the given class.
*
* @return \Mockery\MockInterface
*/
protected static function createMock()
{
$class = static::getMockableClass();
return $class ? Mockery::mock($class) : Mockery::mock();
}
/**
* Determines whether a mock is set as the instance of the facade.
*
* @return bool
*/
protected static function isMock()
{
$name = static::getFacadeAccessor();
return isset(static::$resolvedInstance[$name]) &&
static::$resolvedInstance[$name] instanceof LegacyMockInterface;
}
/**
* Get the mockable class for the bound instance.
*
* @return string|null
*/
protected static function getMockableClass()
{
if ($root = static::getFacadeRoot()) {
return get_class($root);
}
}
/**
* Hotswap the underlying instance behind the facade.
*
* @param mixed $instance
* @return void
*/
public static function swap($instance)
{
static::$resolvedInstance[static::getFacadeAccessor()] = $instance;
if (isset(static::$app)) {
static::$app->instance(static::getFacadeAccessor(), $instance);
}
}
/**
* Determines whether a "fake" has been set as the facade instance.
*
* @return bool
*/
public static function isFake()
{
$name = static::getFacadeAccessor();
return isset(static::$resolvedInstance[$name]) &&
static::$resolvedInstance[$name] instanceof Fake;
}
/**
* Get the root object behind the facade.
*
* @return mixed
*/
public static function getFacadeRoot()
{
return static::resolveFacadeInstance(static::getFacadeAccessor());
}
/**
* Get the registered name of the component.
*
* @return string
*
* @throws \RuntimeException
*/
protected static function getFacadeAccessor()
{
throw new RuntimeException('Facade does not implement getFacadeAccessor method.');
}
/**
* Resolve the facade root instance from the container.
*
* @param string $name
* @return mixed
*/
protected static function resolveFacadeInstance($name)
{
if (isset(static::$resolvedInstance[$name])) {
return static::$resolvedInstance[$name];
}
if (static::$app) {
if (static::$cached) {
return static::$resolvedInstance[$name] = static::$app[$name];
}
return static::$app[$name];
}
}
/**
* Clear a resolved facade instance.
*
* @param string $name
* @return void
*/
public static function clearResolvedInstance($name)
{
unset(static::$resolvedInstance[$name]);
}
/**
* Clear all of the resolved instances.
*
* @return void
*/
public static function clearResolvedInstances()
{
static::$resolvedInstance = [];
}
/**
* Get the application default aliases.
*
* @return \Illuminate\Support\Collection
*/
public static function defaultAliases()
{
return new Collection([
'App' => App::class,
'Arr' => Arr::class,
'Artisan' => Artisan::class,
'Auth' => Auth::class,
'Benchmark' => Benchmark::class,
'Blade' => Blade::class,
'Broadcast' => Broadcast::class,
'Bus' => Bus::class,
'Cache' => Cache::class,
'Concurrency' => Concurrency::class,
'Config' => Config::class,
'Context' => Context::class,
'Cookie' => Cookie::class,
'Crypt' => Crypt::class,
'Date' => Date::class,
'DB' => DB::class,
'Eloquent' => Model::class,
'Event' => Event::class,
'File' => File::class,
'Gate' => Gate::class,
'Hash' => Hash::class,
'Http' => Http::class,
'Js' => Js::class,
'Lang' => Lang::class,
'Log' => Log::class,
'Mail' => Mail::class,
'Notification' => Notification::class,
'Number' => Number::class,
'Password' => Password::class,
'Process' => Process::class,
'Queue' => Queue::class,
'RateLimiter' => RateLimiter::class,
'Redirect' => Redirect::class,
'Request' => Request::class,
'Response' => Response::class,
'Route' => Route::class,
'Schedule' => Schedule::class,
'Schema' => Schema::class,
'Session' => Session::class,
'Storage' => Storage::class,
'Str' => Str::class,
'Uri' => Uri::class,
'URL' => URL::class,
'Validator' => Validator::class,
'View' => View::class,
'Vite' => Vite::class,
]);
}
/**
* Get the application instance behind the facade.
*
* @return \Illuminate\Contracts\Foundation\Application|null
*/
public static function getFacadeApplication()
{
return static::$app;
}
/**
* Set the application instance.
*
* @param \Illuminate\Contracts\Foundation\Application|null $app
* @return void
*/
public static function setFacadeApplication($app)
{
static::$app = $app;
}
/**
* Handle dynamic, static calls to the object.
*
* @param string $method
* @param array $args
* @return mixed
*
* @throws \RuntimeException
*/
public static function __callStatic($method, $args)
{
$instance = static::getFacadeRoot();
if (! $instance) {
throw new RuntimeException('A facade root has not been set.');
}
return $instance->$method(...$args);
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static bool exists(string $path)
* @method static bool missing(string $path)
* @method static string get(string $path, bool $lock = false)
* @method static array json(string $path, int $flags = 0, bool $lock = false)
* @method static string sharedGet(string $path)
* @method static mixed getRequire(string $path, array $data = [])
* @method static mixed requireOnce(string $path, array $data = [])
* @method static \Illuminate\Support\LazyCollection lines(string $path)
* @method static string|false hash(string $path, string $algorithm = 'md5')
* @method static int|bool put(string $path, string $contents, bool $lock = false)
* @method static void replace(string $path, string $content, int|null $mode = null)
* @method static void replaceInFile(array|string $search, array|string $replace, string $path)
* @method static int prepend(string $path, string $data)
* @method static int append(string $path, string $data, bool $lock = false)
* @method static mixed chmod(string $path, int|null $mode = null)
* @method static bool delete(string|array $paths)
* @method static bool move(string $path, string $target)
* @method static bool copy(string $path, string $target)
* @method static bool|null link(string $target, string $link)
* @method static void relativeLink(string $target, string $link)
* @method static string name(string $path)
* @method static string basename(string $path)
* @method static string dirname(string $path)
* @method static string extension(string $path)
* @method static string|null guessExtension(string $path)
* @method static string type(string $path)
* @method static string|false mimeType(string $path)
* @method static int size(string $path)
* @method static int lastModified(string $path)
* @method static bool isDirectory(string $directory)
* @method static bool isEmptyDirectory(string $directory, bool $ignoreDotFiles = false)
* @method static bool isReadable(string $path)
* @method static bool isWritable(string $path)
* @method static bool hasSameHash(string $firstFile, string $secondFile)
* @method static bool isFile(string $file)
* @method static array glob(string $pattern, int $flags = 0)
* @method static \Symfony\Component\Finder\SplFileInfo[] files(string $directory, bool $hidden = false)
* @method static \Symfony\Component\Finder\SplFileInfo[] allFiles(string $directory, bool $hidden = false)
* @method static array directories(string $directory)
* @method static void ensureDirectoryExists(string $path, int $mode = 0755, bool $recursive = true)
* @method static bool makeDirectory(string $path, int $mode = 0755, bool $recursive = false, bool $force = false)
* @method static bool moveDirectory(string $from, string $to, bool $overwrite = false)
* @method static bool copyDirectory(string $directory, string $destination, int|null $options = null)
* @method static bool deleteDirectory(string $directory, bool $preserve = false)
* @method static bool deleteDirectories(string $directory)
* @method static bool cleanDirectory(string $directory)
* @method static \Illuminate\Filesystem\Filesystem|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Filesystem\Filesystem|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Filesystem\Filesystem
*/
class File extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'files';
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
/**
* @method static bool has(string|array $ability)
* @method static \Illuminate\Auth\Access\Response allowIf(\Illuminate\Auth\Access\Response|\Closure|bool $condition, string|null $message = null, string|null $code = null)
* @method static \Illuminate\Auth\Access\Response denyIf(\Illuminate\Auth\Access\Response|\Closure|bool $condition, string|null $message = null, string|null $code = null)
* @method static \Illuminate\Auth\Access\Gate define(\UnitEnum|string $ability, callable|array|string $callback)
* @method static \Illuminate\Auth\Access\Gate resource(string $name, string $class, array|null $abilities = null)
* @method static \Illuminate\Auth\Access\Gate policy(string $class, string $policy)
* @method static \Illuminate\Auth\Access\Gate before(callable $callback)
* @method static \Illuminate\Auth\Access\Gate after(callable $callback)
* @method static bool allows(iterable|\UnitEnum|string $ability, mixed $arguments = [])
* @method static bool denies(iterable|\UnitEnum|string $ability, mixed $arguments = [])
* @method static bool check(iterable|\UnitEnum|string $abilities, mixed $arguments = [])
* @method static bool any(iterable|\UnitEnum|string $abilities, mixed $arguments = [])
* @method static bool none(iterable|\UnitEnum|string $abilities, mixed $arguments = [])
* @method static \Illuminate\Auth\Access\Response authorize(\UnitEnum|string $ability, mixed $arguments = [])
* @method static \Illuminate\Auth\Access\Response inspect(\UnitEnum|string $ability, mixed $arguments = [])
* @method static mixed raw(string $ability, mixed $arguments = [])
* @method static mixed getPolicyFor(object|string $class)
* @method static \Illuminate\Auth\Access\Gate guessPolicyNamesUsing(callable $callback)
* @method static mixed resolvePolicy(object|string $class)
* @method static \Illuminate\Auth\Access\Gate forUser(\Illuminate\Contracts\Auth\Authenticatable|mixed $user)
* @method static array abilities()
* @method static array policies()
* @method static \Illuminate\Auth\Access\Gate defaultDenialResponse(\Illuminate\Auth\Access\Response $response)
* @method static \Illuminate\Auth\Access\Gate setContainer(\Illuminate\Contracts\Container\Container $container)
* @method static \Illuminate\Auth\Access\Response denyWithStatus(int $status, string|null $message = null, int|null $code = null)
* @method static \Illuminate\Auth\Access\Response denyAsNotFound(string|null $message = null, int|null $code = null)
*
* @see \Illuminate\Auth\Access\Gate
*/
class Gate extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return GateContract::class;
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Hashing\BcryptHasher createBcryptDriver()
* @method static \Illuminate\Hashing\ArgonHasher createArgonDriver()
* @method static \Illuminate\Hashing\Argon2IdHasher createArgon2idDriver()
* @method static array info(string $hashedValue)
* @method static string make(string $value, array $options = [])
* @method static bool check(string $value, string $hashedValue, array $options = [])
* @method static bool needsRehash(string $hashedValue, array $options = [])
* @method static bool isHashed(string $value)
* @method static string getDefaultDriver()
* @method static mixed driver(string|null $driver = null)
* @method static \Illuminate\Hashing\HashManager extend(string $driver, \Closure $callback)
* @method static array getDrivers()
* @method static \Illuminate\Contracts\Container\Container getContainer()
* @method static \Illuminate\Hashing\HashManager setContainer(\Illuminate\Contracts\Container\Container $container)
* @method static \Illuminate\Hashing\HashManager forgetDrivers()
*
* @see \Illuminate\Hashing\HashManager
* @see \Illuminate\Hashing\AbstractHasher
*/
class Hash extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'hash';
}
}

View File

@@ -0,0 +1,171 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Http\Client\Factory;
/**
* @method static \Illuminate\Http\Client\Factory globalMiddleware(callable $middleware)
* @method static \Illuminate\Http\Client\Factory globalRequestMiddleware(callable $middleware)
* @method static \Illuminate\Http\Client\Factory globalResponseMiddleware(callable $middleware)
* @method static \Illuminate\Http\Client\Factory globalOptions(\Closure|array $options)
* @method static \GuzzleHttp\Promise\PromiseInterface response(array|string|null $body = null, int $status = 200, array $headers = [])
* @method static \GuzzleHttp\Psr7\Response psr7Response(array|string|null $body = null, int $status = 200, array $headers = [])
* @method static \Illuminate\Http\Client\RequestException failedRequest(array|string|null $body = null, int $status = 200, array $headers = [])
* @method static \Closure failedConnection(string|null $message = null)
* @method static \Illuminate\Http\Client\ResponseSequence sequence(array $responses = [])
* @method static bool preventingStrayRequests()
* @method static \Illuminate\Http\Client\Factory allowStrayRequests(array|null $only = null)
* @method static \Illuminate\Http\Client\Factory record()
* @method static void recordRequestResponsePair(\Illuminate\Http\Client\Request $request, \Illuminate\Http\Client\Response|null $response)
* @method static void assertSent(callable|\Closure $callback)
* @method static void assertSentInOrder(array $callbacks)
* @method static void assertNotSent(callable|\Closure $callback)
* @method static void assertNothingSent()
* @method static void assertSentCount(int $count)
* @method static void assertSequencesAreEmpty()
* @method static \Illuminate\Support\Collection recorded(\Closure|callable $callback = null)
* @method static \Illuminate\Http\Client\PendingRequest createPendingRequest()
* @method static \Illuminate\Contracts\Events\Dispatcher|null getDispatcher()
* @method static array getGlobalMiddleware()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
* @method static \Illuminate\Http\Client\PendingRequest baseUrl(string $url)
* @method static \Illuminate\Http\Client\PendingRequest withBody(\Psr\Http\Message\StreamInterface|string $content, string $contentType = 'application/json')
* @method static \Illuminate\Http\Client\PendingRequest asJson()
* @method static \Illuminate\Http\Client\PendingRequest asForm()
* @method static \Illuminate\Http\Client\PendingRequest attach(string|array $name, string|resource $contents = '', string|null $filename = null, array $headers = [])
* @method static \Illuminate\Http\Client\PendingRequest asMultipart()
* @method static \Illuminate\Http\Client\PendingRequest bodyFormat(string $format)
* @method static \Illuminate\Http\Client\PendingRequest withQueryParameters(array $parameters)
* @method static \Illuminate\Http\Client\PendingRequest contentType(string $contentType)
* @method static \Illuminate\Http\Client\PendingRequest acceptJson()
* @method static \Illuminate\Http\Client\PendingRequest accept(string $contentType)
* @method static \Illuminate\Http\Client\PendingRequest withHeaders(array $headers)
* @method static \Illuminate\Http\Client\PendingRequest withHeader(string $name, mixed $value)
* @method static \Illuminate\Http\Client\PendingRequest replaceHeaders(array $headers)
* @method static \Illuminate\Http\Client\PendingRequest withBasicAuth(string $username, string $password)
* @method static \Illuminate\Http\Client\PendingRequest withDigestAuth(string $username, string $password)
* @method static \Illuminate\Http\Client\PendingRequest withNtlmAuth(string $username, string $password)
* @method static \Illuminate\Http\Client\PendingRequest withToken(string $token, string $type = 'Bearer')
* @method static \Illuminate\Http\Client\PendingRequest withUserAgent(string|bool $userAgent)
* @method static \Illuminate\Http\Client\PendingRequest withUrlParameters(array $parameters = [])
* @method static \Illuminate\Http\Client\PendingRequest withCookies(array $cookies, string $domain)
* @method static \Illuminate\Http\Client\PendingRequest maxRedirects(int $max)
* @method static \Illuminate\Http\Client\PendingRequest withoutRedirecting()
* @method static \Illuminate\Http\Client\PendingRequest withoutVerifying()
* @method static \Illuminate\Http\Client\PendingRequest sink(string|resource $to)
* @method static \Illuminate\Http\Client\PendingRequest timeout(int|float $seconds)
* @method static \Illuminate\Http\Client\PendingRequest connectTimeout(int|float $seconds)
* @method static \Illuminate\Http\Client\PendingRequest retry(array|int $times, \Closure|int $sleepMilliseconds = 0, callable|null $when = null, bool $throw = true)
* @method static \Illuminate\Http\Client\PendingRequest withOptions(array $options)
* @method static \Illuminate\Http\Client\PendingRequest withMiddleware(callable $middleware)
* @method static \Illuminate\Http\Client\PendingRequest withRequestMiddleware(callable $middleware)
* @method static \Illuminate\Http\Client\PendingRequest withResponseMiddleware(callable $middleware)
* @method static \Illuminate\Http\Client\PendingRequest beforeSending(callable $callback)
* @method static \Illuminate\Http\Client\PendingRequest throw(callable|null $callback = null)
* @method static \Illuminate\Http\Client\PendingRequest throwIf(callable|bool $condition)
* @method static \Illuminate\Http\Client\PendingRequest throwUnless(callable|bool $condition)
* @method static \Illuminate\Http\Client\PendingRequest dump()
* @method static \Illuminate\Http\Client\PendingRequest dd()
* @method static \Illuminate\Http\Client\Response get(string $url, array|string|null $query = null)
* @method static \Illuminate\Http\Client\Response head(string $url, array|string|null $query = null)
* @method static \Illuminate\Http\Client\Response post(string $url, array|\JsonSerializable|\Illuminate\Contracts\Support\Arrayable $data = [])
* @method static \Illuminate\Http\Client\Response patch(string $url, array|\JsonSerializable|\Illuminate\Contracts\Support\Arrayable $data = [])
* @method static \Illuminate\Http\Client\Response put(string $url, array|\JsonSerializable|\Illuminate\Contracts\Support\Arrayable $data = [])
* @method static \Illuminate\Http\Client\Response delete(string $url, array|\JsonSerializable|\Illuminate\Contracts\Support\Arrayable $data = [])
* @method static array pool(callable $callback)
* @method static \Illuminate\Http\Client\Response send(string $method, string $url, array $options = [])
* @method static \GuzzleHttp\Client buildClient()
* @method static \GuzzleHttp\Client createClient(\GuzzleHttp\HandlerStack $handlerStack)
* @method static \GuzzleHttp\HandlerStack buildHandlerStack()
* @method static \GuzzleHttp\HandlerStack pushHandlers(\GuzzleHttp\HandlerStack $handlerStack)
* @method static \Closure buildBeforeSendingHandler()
* @method static \Closure buildRecorderHandler()
* @method static \Closure buildStubHandler()
* @method static \GuzzleHttp\Psr7\RequestInterface runBeforeSendingCallbacks(\GuzzleHttp\Psr7\RequestInterface $request, array $options)
* @method static array mergeOptions(array ...$options)
* @method static \Illuminate\Http\Client\PendingRequest stub(callable $callback)
* @method static bool isAllowedRequestUrl(string $url)
* @method static \Illuminate\Http\Client\PendingRequest async(bool $async = true)
* @method static \GuzzleHttp\Promise\PromiseInterface|null getPromise()
* @method static \Illuminate\Http\Client\PendingRequest truncateExceptionsAt(int $length)
* @method static \Illuminate\Http\Client\PendingRequest dontTruncateExceptions()
* @method static \Illuminate\Http\Client\PendingRequest setClient(\GuzzleHttp\Client $client)
* @method static \Illuminate\Http\Client\PendingRequest setHandler(callable $handler)
* @method static array getOptions()
* @method static \Illuminate\Http\Client\PendingRequest|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Http\Client\PendingRequest|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
*
* @see \Illuminate\Http\Client\Factory
*/
class Http extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return Factory::class;
}
/**
* Register a stub callable that will intercept requests and be able to return stub responses.
*
* @param \Closure|array $callback
* @return \Illuminate\Http\Client\Factory
*/
public static function fake($callback = null)
{
return tap(static::getFacadeRoot(), function ($fake) use ($callback) {
static::swap($fake->fake($callback));
});
}
/**
* Register a response sequence for the given URL pattern.
*
* @param string $urlPattern
* @return \Illuminate\Http\Client\ResponseSequence
*/
public static function fakeSequence(string $urlPattern = '*')
{
$fake = tap(static::getFacadeRoot(), function ($fake) {
static::swap($fake);
});
return $fake->fakeSequence($urlPattern);
}
/**
* Indicate that an exception should be thrown if any request is not faked.
*
* @param bool $prevent
* @return \Illuminate\Http\Client\Factory
*/
public static function preventStrayRequests($prevent = true)
{
return tap(static::getFacadeRoot(), function ($fake) use ($prevent) {
static::swap($fake->preventStrayRequests($prevent));
});
}
/**
* Stub the given URL using the given callback.
*
* @param string $url
* @param \Illuminate\Http\Client\Response|\GuzzleHttp\Promise\PromiseInterface|callable $callback
* @return \Illuminate\Http\Client\Factory
*/
public static function stubUrl($url, $callback)
{
return tap(static::getFacadeRoot(), function ($fake) use ($url, $callback) {
static::swap($fake->stubUrl($url, $callback));
});
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static bool hasForLocale(string $key, string|null $locale = null)
* @method static bool has(string $key, string|null $locale = null, bool $fallback = true)
* @method static string|array get(string $key, array $replace = [], string|null $locale = null, bool $fallback = true)
* @method static string choice(string $key, \Countable|int|float|array $number, array $replace = [], string|null $locale = null)
* @method static void addLines(array $lines, string $locale, string $namespace = '*')
* @method static void load(string $namespace, string $group, string $locale)
* @method static \Illuminate\Translation\Translator handleMissingKeysUsing(callable|null $callback)
* @method static void addNamespace(string $namespace, string $hint)
* @method static void addPath(string $path)
* @method static void addJsonPath(string $path)
* @method static array parseKey(string $key)
* @method static void determineLocalesUsing(callable $callback)
* @method static \Illuminate\Translation\MessageSelector getSelector()
* @method static void setSelector(\Illuminate\Translation\MessageSelector $selector)
* @method static \Illuminate\Contracts\Translation\Loader getLoader()
* @method static string locale()
* @method static string getLocale()
* @method static void setLocale(string $locale)
* @method static string getFallback()
* @method static void setFallback(string $fallback)
* @method static void setLoaded(array $loaded)
* @method static void stringable(callable|string $class, callable|null $handler = null)
* @method static void setParsedKey(string $key, array $parsed)
* @method static void flushParsedKeys()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Translation\Translator
*/
class Lang extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'translator';
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Psr\Log\LoggerInterface build(array $config)
* @method static \Psr\Log\LoggerInterface stack(array $channels, string|null $channel = null)
* @method static \Psr\Log\LoggerInterface channel(string|null $channel = null)
* @method static \Psr\Log\LoggerInterface driver(string|null $driver = null)
* @method static \Illuminate\Log\LogManager shareContext(array $context)
* @method static array sharedContext()
* @method static \Illuminate\Log\LogManager withoutContext(string[]|null $keys = null)
* @method static \Illuminate\Log\LogManager flushSharedContext()
* @method static string|null getDefaultDriver()
* @method static void setDefaultDriver(string $name)
* @method static \Illuminate\Log\LogManager extend(string $driver, \Closure $callback)
* @method static void forgetChannel(string|null $driver = null)
* @method static array getChannels()
* @method static void emergency(string|\Stringable $message, array $context = [])
* @method static void alert(string|\Stringable $message, array $context = [])
* @method static void critical(string|\Stringable $message, array $context = [])
* @method static void error(string|\Stringable $message, array $context = [])
* @method static void warning(string|\Stringable $message, array $context = [])
* @method static void notice(string|\Stringable $message, array $context = [])
* @method static void info(string|\Stringable $message, array $context = [])
* @method static void debug(string|\Stringable $message, array $context = [])
* @method static void log(mixed $level, string|\Stringable $message, array $context = [])
* @method static \Illuminate\Log\LogManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static void write(string $level, \Illuminate\Contracts\Support\Arrayable|\Illuminate\Contracts\Support\Jsonable|\Illuminate\Support\Stringable|array|string $message, array $context = [])
* @method static \Illuminate\Log\Logger withContext(array $context = [])
* @method static void listen(\Closure $callback)
* @method static \Psr\Log\LoggerInterface getLogger()
* @method static \Illuminate\Contracts\Events\Dispatcher getEventDispatcher()
* @method static void setEventDispatcher(\Illuminate\Contracts\Events\Dispatcher $dispatcher)
* @method static \Illuminate\Log\Logger|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Log\Logger|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
*
* @see \Illuminate\Log\LogManager
*/
class Log extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'log';
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Support\Testing\Fakes\MailFake;
/**
* @method static \Illuminate\Contracts\Mail\Mailer mailer(string|null $name = null)
* @method static \Illuminate\Mail\Mailer driver(string|null $driver = null)
* @method static \Illuminate\Mail\Mailer build(array $config)
* @method static \Symfony\Component\Mailer\Transport\TransportInterface createSymfonyTransport(array $config)
* @method static string getDefaultDriver()
* @method static void setDefaultDriver(string $name)
* @method static void purge(string|null $name = null)
* @method static \Illuminate\Mail\MailManager extend(string $driver, \Closure $callback)
* @method static \Illuminate\Contracts\Foundation\Application getApplication()
* @method static \Illuminate\Mail\MailManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static \Illuminate\Mail\MailManager forgetMailers()
* @method static void alwaysFrom(string $address, string|null $name = null)
* @method static void alwaysReplyTo(string $address, string|null $name = null)
* @method static void alwaysReturnPath(string $address)
* @method static void alwaysTo(string $address, string|null $name = null)
* @method static \Illuminate\Mail\PendingMail to(mixed $users, string|null $name = null)
* @method static \Illuminate\Mail\PendingMail cc(mixed $users, string|null $name = null)
* @method static \Illuminate\Mail\PendingMail bcc(mixed $users, string|null $name = null)
* @method static \Illuminate\Mail\SentMessage|null html(string $html, mixed $callback)
* @method static \Illuminate\Mail\SentMessage|null raw(string $text, mixed $callback)
* @method static \Illuminate\Mail\SentMessage|null plain(string $view, array $data, mixed $callback)
* @method static string render(string|array $view, array $data = [])
* @method static \Illuminate\Mail\SentMessage|null send(\Illuminate\Contracts\Mail\Mailable|string|array $view, array $data = [], \Closure|string|null $callback = null)
* @method static \Illuminate\Mail\SentMessage|null sendNow(\Illuminate\Contracts\Mail\Mailable|string|array $mailable, array $data = [], \Closure|string|null $callback = null)
* @method static mixed queue(\Illuminate\Contracts\Mail\Mailable|string|array $view, \BackedEnum|string|null $queue = null)
* @method static mixed onQueue(\BackedEnum|string|null $queue, \Illuminate\Contracts\Mail\Mailable $view)
* @method static mixed queueOn(string $queue, \Illuminate\Contracts\Mail\Mailable $view)
* @method static mixed later(\DateTimeInterface|\DateInterval|int $delay, \Illuminate\Contracts\Mail\Mailable $view, string|null $queue = null)
* @method static mixed laterOn(string $queue, \DateTimeInterface|\DateInterval|int $delay, \Illuminate\Contracts\Mail\Mailable $view)
* @method static \Symfony\Component\Mailer\Transport\TransportInterface getSymfonyTransport()
* @method static \Illuminate\Contracts\View\Factory getViewFactory()
* @method static void setSymfonyTransport(\Symfony\Component\Mailer\Transport\TransportInterface $transport)
* @method static \Illuminate\Mail\Mailer setQueue(\Illuminate\Contracts\Queue\Factory $queue)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static void assertSent(string|\Closure $mailable, callable|array|string|int|null $callback = null)
* @method static void assertNotOutgoing(string|\Closure $mailable, callable|null $callback = null)
* @method static void assertNotSent(string|\Closure $mailable, callable|array|string|null $callback = null)
* @method static void assertNothingOutgoing()
* @method static void assertNothingSent()
* @method static void assertQueued(string|\Closure $mailable, callable|array|string|int|null $callback = null)
* @method static void assertNotQueued(string|\Closure $mailable, callable|array|string|null $callback = null)
* @method static void assertNothingQueued()
* @method static void assertSentCount(int $count)
* @method static void assertQueuedCount(int $count)
* @method static void assertOutgoingCount(int $count)
* @method static \Illuminate\Support\Collection sent(string|\Closure $mailable, callable|null $callback = null)
* @method static bool hasSent(string $mailable)
* @method static \Illuminate\Support\Collection queued(string|\Closure $mailable, callable|null $callback = null)
* @method static bool hasQueued(string $mailable)
*
* @see \Illuminate\Mail\MailManager
* @see \Illuminate\Support\Testing\Fakes\MailFake
*/
class Mail extends Facade
{
/**
* Replace the bound instance with a fake.
*
* @return \Illuminate\Support\Testing\Fakes\MailFake
*/
public static function fake()
{
$actualMailManager = static::isFake()
? static::getFacadeRoot()->manager
: static::getFacadeRoot();
return tap(new MailFake($actualMailManager), function ($fake) {
static::swap($fake);
});
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'mail.manager';
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Foundation\MaintenanceModeManager;
class MaintenanceMode extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return MaintenanceModeManager::class;
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Notifications\AnonymousNotifiable;
use Illuminate\Notifications\ChannelManager;
use Illuminate\Support\Testing\Fakes\NotificationFake;
/**
* @method static void send(\Illuminate\Support\Collection|mixed $notifiables, mixed $notification)
* @method static void sendNow(\Illuminate\Support\Collection|mixed $notifiables, mixed $notification, array|null $channels = null)
* @method static mixed channel(string|null $name = null)
* @method static string getDefaultDriver()
* @method static string deliversVia()
* @method static void deliverVia(string $channel)
* @method static \Illuminate\Notifications\ChannelManager locale(string $locale)
* @method static mixed driver(string|null $driver = null)
* @method static \Illuminate\Notifications\ChannelManager extend(string $driver, \Closure $callback)
* @method static array getDrivers()
* @method static \Illuminate\Contracts\Container\Container getContainer()
* @method static \Illuminate\Notifications\ChannelManager setContainer(\Illuminate\Contracts\Container\Container $container)
* @method static \Illuminate\Notifications\ChannelManager forgetDrivers()
* @method static void assertSentOnDemand(string|\Closure $notification, callable|null $callback = null)
* @method static void assertSentTo(mixed $notifiable, string|\Closure $notification, callable|null $callback = null)
* @method static void assertSentOnDemandTimes(string $notification, int $times = 1)
* @method static void assertSentToTimes(mixed $notifiable, string $notification, int $times = 1)
* @method static void assertNotSentTo(mixed $notifiable, string|\Closure $notification, callable|null $callback = null)
* @method static void assertNothingSent()
* @method static void assertNothingSentTo(mixed $notifiable)
* @method static void assertSentTimes(string $notification, int $expectedCount)
* @method static void assertCount(int $expectedCount)
* @method static \Illuminate\Support\Collection sent(mixed $notifiable, string $notification, callable|null $callback = null)
* @method static bool hasSent(mixed $notifiable, string $notification)
* @method static \Illuminate\Support\Testing\Fakes\NotificationFake serializeAndRestore(bool $serializeAndRestore = true)
* @method static array sentNotifications()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Notifications\ChannelManager
* @see \Illuminate\Support\Testing\Fakes\NotificationFake
*/
class Notification extends Facade
{
/**
* Replace the bound instance with a fake.
*
* @return \Illuminate\Support\Testing\Fakes\NotificationFake
*/
public static function fake()
{
return tap(new NotificationFake, function ($fake) {
static::swap($fake);
});
}
/**
* Begin sending a notification to an anonymous notifiable on the given channels.
*
* @param array $channels
* @return \Illuminate\Notifications\AnonymousNotifiable
*/
public static function routes(array $channels)
{
$notifiable = new AnonymousNotifiable;
foreach ($channels as $channel => $route) {
$notifiable->route($channel, $route);
}
return $notifiable;
}
/**
* Begin sending a notification to an anonymous notifiable.
*
* @param string $channel
* @param mixed $route
* @return \Illuminate\Notifications\AnonymousNotifiable
*/
public static function route($channel, $route)
{
return (new AnonymousNotifiable)->route($channel, $route);
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return ChannelManager::class;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static void resolveOptionsUsing(\Closure|null $resolver)
* @method static void resolveTokenUsing(\Closure|null $resolver)
* @method static void setUpProcess(callable $callback)
* @method static void setUpTestCase(callable $callback)
* @method static void setUpTestDatabase(callable $callback)
* @method static void tearDownProcess(callable $callback)
* @method static void tearDownTestCase(callable $callback)
* @method static void callSetUpProcessCallbacks()
* @method static void callSetUpTestCaseCallbacks(\Illuminate\Foundation\Testing\TestCase $testCase)
* @method static void callSetUpTestDatabaseCallbacks(string $database)
* @method static void callTearDownProcessCallbacks()
* @method static void callTearDownTestCaseCallbacks(\Illuminate\Foundation\Testing\TestCase $testCase)
* @method static mixed option(string $option)
* @method static string|false token()
*
* @see \Illuminate\Testing\ParallelTesting
*/
class ParallelTesting extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return \Illuminate\Testing\ParallelTesting::class;
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Contracts\Auth\PasswordBroker;
/**
* @method static \Illuminate\Contracts\Auth\PasswordBroker broker(string|null $name = null)
* @method static string getDefaultDriver()
* @method static void setDefaultDriver(string $name)
* @method static string sendResetLink(array $credentials, \Closure|null $callback = null)
* @method static mixed reset(array $credentials, \Closure $callback)
* @method static \Illuminate\Contracts\Auth\CanResetPassword|null getUser(array $credentials)
* @method static string createToken(\Illuminate\Contracts\Auth\CanResetPassword $user)
* @method static void deleteToken(\Illuminate\Contracts\Auth\CanResetPassword $user)
* @method static bool tokenExists(\Illuminate\Contracts\Auth\CanResetPassword $user, string $token)
* @method static \Illuminate\Auth\Passwords\TokenRepositoryInterface getRepository()
* @method static \Illuminate\Support\Timebox getTimebox()
*
* @see \Illuminate\Auth\Passwords\PasswordBrokerManager
* @see \Illuminate\Auth\Passwords\PasswordBroker
*/
class Password extends Facade
{
/**
* Constant representing a successfully sent password reset email.
*
* @var string
*/
const ResetLinkSent = PasswordBroker::RESET_LINK_SENT;
/**
* Constant representing a successfully reset password.
*
* @var string
*/
const PasswordReset = PasswordBroker::PASSWORD_RESET;
/**
* Constant indicating the user could not be found when attempting a password reset.
*
* @var string
*/
const InvalidUser = PasswordBroker::INVALID_USER;
/**
* Constant representing an invalid password reset token.
*
* @var string
*/
const InvalidToken = PasswordBroker::INVALID_TOKEN;
/**
* Constant representing a throttled password reset attempt.
*
* @var string
*/
const ResetThrottled = PasswordBroker::RESET_THROTTLED;
const RESET_LINK_SENT = PasswordBroker::RESET_LINK_SENT;
const PASSWORD_RESET = PasswordBroker::PASSWORD_RESET;
const INVALID_USER = PasswordBroker::INVALID_USER;
const INVALID_TOKEN = PasswordBroker::INVALID_TOKEN;
const RESET_THROTTLED = PasswordBroker::RESET_THROTTLED;
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'auth.password';
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Pipeline\Pipeline send(mixed $passable)
* @method static \Illuminate\Pipeline\Pipeline through(mixed $pipes)
* @method static \Illuminate\Pipeline\Pipeline pipe(mixed $pipes)
* @method static \Illuminate\Pipeline\Pipeline via(string $method)
* @method static mixed then(\Closure $destination)
* @method static mixed thenReturn()
* @method static \Illuminate\Pipeline\Pipeline finally(\Closure $callback)
* @method static \Illuminate\Pipeline\Pipeline withinTransaction(string|null|\UnitEnum|false $withinTransaction = null)
* @method static \Illuminate\Pipeline\Pipeline setContainer(\Illuminate\Contracts\Container\Container $container)
* @method static \Illuminate\Pipeline\Pipeline|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Pipeline\Pipeline|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Pipeline\Pipeline
*/
class Pipeline extends Facade
{
/**
* Indicates if the resolved instance should be cached.
*
* @var bool
*/
protected static $cached = false;
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'pipeline';
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Illuminate\Support\Facades;
use Closure;
use Illuminate\Process\Factory;
/**
* @method static \Illuminate\Process\PendingProcess command(array|string $command)
* @method static \Illuminate\Process\PendingProcess path(string $path)
* @method static \Illuminate\Process\PendingProcess timeout(int $timeout)
* @method static \Illuminate\Process\PendingProcess idleTimeout(int $timeout)
* @method static \Illuminate\Process\PendingProcess forever()
* @method static \Illuminate\Process\PendingProcess env(array $environment)
* @method static \Illuminate\Process\PendingProcess input(\Traversable|resource|string|int|float|bool|null $input)
* @method static \Illuminate\Process\PendingProcess quietly()
* @method static \Illuminate\Process\PendingProcess tty(bool $tty = true)
* @method static \Illuminate\Process\PendingProcess options(array $options)
* @method static \Illuminate\Contracts\Process\ProcessResult run(array|string|null $command = null, callable|null $output = null)
* @method static \Illuminate\Process\InvokedProcess start(array|string|null $command = null, callable|null $output = null)
* @method static bool supportsTty()
* @method static \Illuminate\Process\PendingProcess withFakeHandlers(array $fakeHandlers)
* @method static \Illuminate\Process\PendingProcess|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Process\PendingProcess|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Process\FakeProcessResult result(array|string $output = '', array|string $errorOutput = '', int $exitCode = 0)
* @method static \Illuminate\Process\FakeProcessDescription describe()
* @method static \Illuminate\Process\FakeProcessSequence sequence(array $processes = [])
* @method static bool isRecording()
* @method static \Illuminate\Process\Factory recordIfRecording(\Illuminate\Process\PendingProcess $process, \Illuminate\Contracts\Process\ProcessResult $result)
* @method static \Illuminate\Process\Factory record(\Illuminate\Process\PendingProcess $process, \Illuminate\Contracts\Process\ProcessResult $result)
* @method static \Illuminate\Process\Factory preventStrayProcesses(bool $prevent = true)
* @method static bool preventingStrayProcesses()
* @method static \Illuminate\Process\Factory assertRan(\Closure|string $callback)
* @method static \Illuminate\Process\Factory assertRanTimes(\Closure|string $callback, int $times = 1)
* @method static \Illuminate\Process\Factory assertNotRan(\Closure|string $callback)
* @method static \Illuminate\Process\Factory assertDidntRun(\Closure|string $callback)
* @method static \Illuminate\Process\Factory assertNothingRan()
* @method static \Illuminate\Process\Pool pool(callable $callback)
* @method static \Illuminate\Contracts\Process\ProcessResult pipe(callable|array $callback, callable|null $output = null)
* @method static \Illuminate\Process\ProcessPoolResults concurrently(callable $callback, callable|null $output = null)
* @method static \Illuminate\Process\PendingProcess newPendingProcess()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
*
* @see \Illuminate\Process\PendingProcess
* @see \Illuminate\Process\Factory
*/
class Process extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return Factory::class;
}
/**
* Indicate that the process factory should fake processes.
*
* @param \Closure|array|null $callback
* @return \Illuminate\Process\Factory
*/
public static function fake(Closure|array|null $callback = null)
{
return tap(static::getFacadeRoot(), function ($fake) use ($callback) {
static::swap($fake->fake($callback));
});
}
}

View File

@@ -0,0 +1,159 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Queue\Worker;
use Illuminate\Support\Testing\Fakes\QueueFake;
/**
* @method static void before(mixed $callback)
* @method static void after(mixed $callback)
* @method static void exceptionOccurred(mixed $callback)
* @method static void looping(mixed $callback)
* @method static void failing(mixed $callback)
* @method static void starting(mixed $callback)
* @method static void stopping(mixed $callback)
* @method static bool connected(string|null $name = null)
* @method static \Illuminate\Contracts\Queue\Queue connection(string|null $name = null)
* @method static void extend(string $driver, \Closure $resolver)
* @method static void addConnector(string $driver, \Closure $resolver)
* @method static string getDefaultDriver()
* @method static void setDefaultDriver(string $name)
* @method static string getName(string|null $connection = null)
* @method static \Illuminate\Contracts\Foundation\Application getApplication()
* @method static \Illuminate\Queue\QueueManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static int size(string|null $queue = null)
* @method static mixed push(string|object $job, mixed $data = '', string|null $queue = null)
* @method static mixed pushOn(string $queue, string|object $job, mixed $data = '')
* @method static mixed pushRaw(string $payload, string|null $queue = null, array $options = [])
* @method static mixed later(\DateTimeInterface|\DateInterval|int $delay, string|object $job, mixed $data = '', string|null $queue = null)
* @method static mixed laterOn(string $queue, \DateTimeInterface|\DateInterval|int $delay, string|object $job, mixed $data = '')
* @method static mixed bulk(array $jobs, mixed $data = '', string|null $queue = null)
* @method static \Illuminate\Contracts\Queue\Job|null pop(string|null $queue = null)
* @method static string getConnectionName()
* @method static \Illuminate\Contracts\Queue\Queue setConnectionName(string $name)
* @method static int pendingSize(string|null $queue = null)
* @method static int delayedSize(string|null $queue = null)
* @method static int reservedSize(string|null $queue = null)
* @method static int|null creationTimeOfOldestPendingJob(string|null $queue = null)
* @method static mixed getJobTries(mixed $job)
* @method static mixed getJobBackoff(mixed $job)
* @method static mixed getJobExpiration(mixed $job)
* @method static void createPayloadUsing(callable|null $callback)
* @method static \Illuminate\Container\Container getContainer()
* @method static void setContainer(\Illuminate\Container\Container $container)
* @method static \Illuminate\Support\Testing\Fakes\QueueFake except(array|string $jobsToBeQueued)
* @method static void assertPushed(string|\Closure $job, callable|int|null $callback = null)
* @method static void assertPushedOn(string $queue, string|\Closure $job, callable|null $callback = null)
* @method static void assertPushedWithChain(string $job, array $expectedChain = [], callable|null $callback = null)
* @method static void assertPushedWithoutChain(string $job, callable|null $callback = null)
* @method static void assertClosurePushed(callable|int|null $callback = null)
* @method static void assertClosureNotPushed(callable|null $callback = null)
* @method static void assertNotPushed(string|\Closure $job, callable|null $callback = null)
* @method static void assertCount(int $expectedCount)
* @method static void assertNothingPushed()
* @method static \Illuminate\Support\Collection pushed(string $job, callable|null $callback = null)
* @method static \Illuminate\Support\Collection pushedRaw(null|\Closure $callback = null)
* @method static \Illuminate\Support\Collection listenersPushed(string $listenerClass, \Closure|null $callback = null)
* @method static bool hasPushed(string $job)
* @method static bool shouldFakeJob(object $job)
* @method static array pushedJobs()
* @method static array rawPushes()
* @method static \Illuminate\Support\Testing\Fakes\QueueFake serializeAndRestore(bool $serializeAndRestore = true)
*
* @see \Illuminate\Queue\QueueManager
* @see \Illuminate\Queue\Queue
* @see \Illuminate\Support\Testing\Fakes\QueueFake
*/
class Queue extends Facade
{
/**
* Register a callback to be executed to pick jobs.
*
* @param string $workerName
* @param callable $callback
* @return void
*/
public static function popUsing($workerName, $callback)
{
Worker::popUsing($workerName, $callback);
}
/**
* Replace the bound instance with a fake.
*
* @param array|string $jobsToFake
* @return \Illuminate\Support\Testing\Fakes\QueueFake
*/
public static function fake($jobsToFake = [])
{
$actualQueueManager = static::isFake()
? static::getFacadeRoot()->queue
: static::getFacadeRoot();
return tap(new QueueFake(static::getFacadeApplication(), $jobsToFake, $actualQueueManager), function ($fake) {
static::swap($fake);
});
}
/**
* Replace the bound instance with a fake that fakes all jobs except the given jobs.
*
* @param string[]|string $jobsToAllow
* @return \Illuminate\Support\Testing\Fakes\QueueFake
*/
public static function fakeExcept($jobsToAllow)
{
return static::fake()->except($jobsToAllow);
}
/**
* Replace the bound instance with a fake during the given callable's execution.
*
* @param callable $callable
* @param array $jobsToFake
* @return mixed
*/
public static function fakeFor(callable $callable, array $jobsToFake = [])
{
$originalQueueManager = static::getFacadeRoot();
static::fake($jobsToFake);
try {
return $callable();
} finally {
static::swap($originalQueueManager);
}
}
/**
* Replace the bound instance with a fake during the given callable's execution.
*
* @param callable $callable
* @param array $jobsToAllow
* @return mixed
*/
public static function fakeExceptFor(callable $callable, array $jobsToAllow = [])
{
$originalQueueManager = static::getFacadeRoot();
static::fakeExcept($jobsToAllow);
try {
return $callable();
} finally {
static::swap($originalQueueManager);
}
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'queue';
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Cache\RateLimiter for(\BackedEnum|\UnitEnum|string $name, \Closure $callback)
* @method static \Closure|null limiter(\BackedEnum|\UnitEnum|string $name)
* @method static mixed attempt(string $key, int $maxAttempts, \Closure $callback, \DateTimeInterface|\DateInterval|int $decaySeconds = 60)
* @method static bool tooManyAttempts(string $key, int $maxAttempts)
* @method static int hit(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60)
* @method static int increment(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60, int $amount = 1)
* @method static int decrement(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60, int $amount = 1)
* @method static mixed attempts(string $key)
* @method static bool resetAttempts(string $key)
* @method static int remaining(string $key, int $maxAttempts)
* @method static int retriesLeft(string $key, int $maxAttempts)
* @method static void clear(string $key)
* @method static int availableIn(string $key)
* @method static string cleanRateLimiterKey(string $key)
*
* @see \Illuminate\Cache\RateLimiter
*/
class RateLimiter extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return \Illuminate\Cache\RateLimiter::class;
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Http\RedirectResponse back(int $status = 302, array $headers = [], mixed $fallback = false)
* @method static \Illuminate\Http\RedirectResponse refresh(int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse guest(string $path, int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Illuminate\Http\RedirectResponse intended(mixed $default = '/', int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Illuminate\Http\RedirectResponse to(string $path, int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Illuminate\Http\RedirectResponse away(string $path, int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse secure(string $path, int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse route(\BackedEnum|string $route, mixed $parameters = [], int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse signedRoute(\BackedEnum|string $route, mixed $parameters = [], \DateTimeInterface|\DateInterval|int|null $expiration = null, int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse temporarySignedRoute(\BackedEnum|string $route, \DateTimeInterface|\DateInterval|int|null $expiration, mixed $parameters = [], int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse action(string|array $action, mixed $parameters = [], int $status = 302, array $headers = [])
* @method static \Illuminate\Routing\UrlGenerator getUrlGenerator()
* @method static void setSession(\Illuminate\Session\Store $session)
* @method static string|null getIntendedUrl()
* @method static \Illuminate\Routing\Redirector setIntendedUrl(string $url)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Routing\Redirector
*/
class Redirect extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'redirect';
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Redis\Connections\Connection connection(\UnitEnum|string|null $name = null)
* @method static \Illuminate\Redis\Connections\Connection resolve(string|null $name = null)
* @method static array connections()
* @method static void enableEvents()
* @method static void disableEvents()
* @method static void setDriver(string $driver)
* @method static void purge(string|null $name = null)
* @method static \Illuminate\Redis\RedisManager extend(string $driver, \Closure $callback)
* @method static void createSubscription(array|string $channels, \Closure $callback, string $method = 'subscribe')
* @method static \Illuminate\Redis\Limiters\ConcurrencyLimiterBuilder funnel(string $name)
* @method static \Illuminate\Redis\Limiters\DurationLimiterBuilder throttle(string $name)
* @method static mixed client()
* @method static void subscribe(array|string $channels, \Closure $callback)
* @method static void psubscribe(array|string $channels, \Closure $callback)
* @method static mixed command(string $method, array $parameters = [])
* @method static void listen(\Closure $callback)
* @method static string|null getName()
* @method static \Illuminate\Redis\Connections\Connection setName(string $name)
* @method static \Illuminate\Contracts\Events\Dispatcher getEventDispatcher()
* @method static void setEventDispatcher(\Illuminate\Contracts\Events\Dispatcher $events)
* @method static void unsetEventDispatcher()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
*
* @see \Illuminate\Redis\RedisManager
*/
class Redis extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'redis';
}
}

View File

@@ -0,0 +1,205 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Http\Request capture()
* @method static \Illuminate\Http\Request instance()
* @method static string method()
* @method static \Illuminate\Support\Uri uri()
* @method static string root()
* @method static string url()
* @method static string fullUrl()
* @method static string fullUrlWithQuery(array $query)
* @method static string fullUrlWithoutQuery(array|string $keys)
* @method static string path()
* @method static string decodedPath()
* @method static string|null segment(int $index, string|null $default = null)
* @method static array segments()
* @method static bool is(mixed ...$patterns)
* @method static bool routeIs(mixed ...$patterns)
* @method static bool fullUrlIs(mixed ...$patterns)
* @method static string host()
* @method static string httpHost()
* @method static string schemeAndHttpHost()
* @method static bool ajax()
* @method static bool pjax()
* @method static bool prefetch()
* @method static bool secure()
* @method static string|null ip()
* @method static array ips()
* @method static string|null userAgent()
* @method static \Illuminate\Http\Request merge(array $input)
* @method static \Illuminate\Http\Request mergeIfMissing(array $input)
* @method static \Illuminate\Http\Request replace(array $input)
* @method static mixed get(string $key, mixed $default = null)
* @method static \Symfony\Component\HttpFoundation\InputBag|mixed json(string|null $key = null, mixed $default = null)
* @method static \Illuminate\Http\Request createFrom(\Illuminate\Http\Request $from, \Illuminate\Http\Request|null $to = null)
* @method static \Illuminate\Http\Request createFromBase(\Symfony\Component\HttpFoundation\Request $request)
* @method static \Illuminate\Http\Request duplicate(array|null $query = null, array|null $request = null, array|null $attributes = null, array|null $cookies = null, array|null $files = null, array|null $server = null)
* @method static bool hasSession(bool $skipIfUninitialized = false)
* @method static \Symfony\Component\HttpFoundation\Session\SessionInterface getSession()
* @method static \Illuminate\Contracts\Session\Session session()
* @method static void setLaravelSession(\Illuminate\Contracts\Session\Session $session)
* @method static void setRequestLocale(string $locale)
* @method static void setDefaultRequestLocale(string $locale)
* @method static mixed user(string|null $guard = null)
* @method static \Illuminate\Routing\Route|object|string|null route(string|null $param = null, mixed $default = null)
* @method static string fingerprint()
* @method static \Illuminate\Http\Request setJson(\Symfony\Component\HttpFoundation\InputBag $json)
* @method static \Closure getUserResolver()
* @method static \Illuminate\Http\Request setUserResolver(\Closure $callback)
* @method static \Closure getRouteResolver()
* @method static \Illuminate\Http\Request setRouteResolver(\Closure $callback)
* @method static array toArray()
* @method static void initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], string|resource|null $content = null)
* @method static \Illuminate\Http\Request createFromGlobals()
* @method static \Illuminate\Http\Request create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], string|resource|null $content = null)
* @method static void setFactory(callable|null $callable)
* @method static void overrideGlobals()
* @method static void setTrustedProxies(array $proxies, int $trustedHeaderSet)
* @method static string[] getTrustedProxies()
* @method static int getTrustedHeaderSet()
* @method static void setTrustedHosts(array $hostPatterns)
* @method static string[] getTrustedHosts()
* @method static string normalizeQueryString(string|null $qs)
* @method static void enableHttpMethodParameterOverride()
* @method static bool getHttpMethodParameterOverride()
* @method static bool hasPreviousSession()
* @method static void setSession(\Symfony\Component\HttpFoundation\Session\SessionInterface $session)
* @method static array getClientIps()
* @method static string|null getClientIp()
* @method static string getScriptName()
* @method static string getPathInfo()
* @method static string getBasePath()
* @method static string getBaseUrl()
* @method static string getScheme()
* @method static int|string|null getPort()
* @method static string|null getUser()
* @method static string|null getPassword()
* @method static string|null getUserInfo()
* @method static string getHttpHost()
* @method static string getRequestUri()
* @method static string getSchemeAndHttpHost()
* @method static string getUri()
* @method static string getUriForPath(string $path)
* @method static string getRelativeUriForPath(string $path)
* @method static string|null getQueryString()
* @method static bool isSecure()
* @method static string getHost()
* @method static void setMethod(string $method)
* @method static string getMethod()
* @method static string getRealMethod()
* @method static string|null getMimeType(string $format)
* @method static string[] getMimeTypes(string $format)
* @method static string|null getFormat(string|null $mimeType)
* @method static void setFormat(string|null $format, string|string[] $mimeTypes)
* @method static string|null getRequestFormat(string|null $default = 'html')
* @method static void setRequestFormat(string|null $format)
* @method static string|null getContentTypeFormat()
* @method static void setDefaultLocale(string $locale)
* @method static string getDefaultLocale()
* @method static void setLocale(string $locale)
* @method static string getLocale()
* @method static bool isMethod(string $method)
* @method static bool isMethodSafe()
* @method static bool isMethodIdempotent()
* @method static bool isMethodCacheable()
* @method static string|null getProtocolVersion()
* @method static string|resource getContent(bool $asResource = false)
* @method static \Symfony\Component\HttpFoundation\InputBag getPayload()
* @method static array getETags()
* @method static bool isNoCache()
* @method static string|null getPreferredFormat(string|null $default = 'html')
* @method static string|null getPreferredLanguage(string[] $locales = null)
* @method static string[] getLanguages()
* @method static string[] getCharsets()
* @method static string[] getEncodings()
* @method static string[] getAcceptableContentTypes()
* @method static bool isXmlHttpRequest()
* @method static bool preferSafeContent()
* @method static bool isFromTrustedProxy()
* @method static array filterPrecognitiveRules(array $rules)
* @method static bool isAttemptingPrecognition()
* @method static bool isPrecognitive()
* @method static bool isJson()
* @method static bool expectsJson()
* @method static bool wantsJson()
* @method static bool accepts(string|array $contentTypes)
* @method static string|null prefers(string|array $contentTypes)
* @method static bool acceptsAnyContentType()
* @method static bool acceptsJson()
* @method static bool acceptsHtml()
* @method static bool matchesType(string $actual, string $type)
* @method static string format(string $default = 'html')
* @method static string|array|null old(string|null $key = null, \Illuminate\Database\Eloquent\Model|string|array|null $default = null)
* @method static void flash()
* @method static void flashOnly(mixed $keys)
* @method static void flashExcept(mixed $keys)
* @method static void flush()
* @method static string|array|null server(string|null $key = null, string|array|null $default = null)
* @method static bool hasHeader(string $key)
* @method static string|array|null header(string|null $key = null, string|array|null $default = null)
* @method static string|null bearerToken()
* @method static array keys()
* @method static array all(mixed $keys = null)
* @method static mixed input(string|null $key = null, mixed $default = null)
* @method static \Illuminate\Support\Fluent fluent(array|string|null $key = null)
* @method static string|array|null query(string|null $key = null, string|array|null $default = null)
* @method static string|array|null post(string|null $key = null, string|array|null $default = null)
* @method static bool hasCookie(string $key)
* @method static string|array|null cookie(string|null $key = null, string|array|null $default = null)
* @method static array allFiles()
* @method static bool hasFile(string $key)
* @method static array|\Illuminate\Http\UploadedFile|\Illuminate\Http\UploadedFile[]|null file(string|null $key = null, mixed $default = null)
* @method static \Illuminate\Http\Request dump(mixed $keys = [])
* @method static never dd(mixed ...$args)
* @method static bool exists(string|array $key)
* @method static bool has(string|array $key)
* @method static bool hasAny(string|array $keys)
* @method static \Illuminate\Http\Request|mixed whenHas(string $key, callable $callback, callable|null $default = null)
* @method static bool filled(string|array $key)
* @method static bool isNotFilled(string|array $key)
* @method static bool anyFilled(string|array $keys)
* @method static \Illuminate\Http\Request|mixed whenFilled(string $key, callable $callback, callable|null $default = null)
* @method static bool missing(string|array $key)
* @method static \Illuminate\Http\Request|mixed whenMissing(string $key, callable $callback, callable|null $default = null)
* @method static \Illuminate\Support\Stringable str(string $key, mixed $default = null)
* @method static \Illuminate\Support\Stringable string(string $key, mixed $default = null)
* @method static bool boolean(string|null $key = null, bool $default = false)
* @method static int integer(string $key, int $default = 0)
* @method static float float(string $key, float $default = 0)
* @method static \Illuminate\Support\Carbon|null date(string $key, string|null $format = null, \UnitEnum|string|null $tz = null)
* @method static \BackedEnum|null enum(string $key, string $enumClass, \BackedEnum|null $default = null)
* @method static \BackedEnum[] enums(string $key, string $enumClass)
* @method static array array(array|string|null $key = null)
* @method static \Illuminate\Support\Collection collect(array|string|null $key = null)
* @method static array only(mixed $keys)
* @method static array except(mixed $keys)
* @method static \Illuminate\Http\Request|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Http\Request|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static array validate(array $rules, ...$params)
* @method static array validateWithBag(string $errorBag, array $rules, ...$params)
* @method static bool hasValidSignature(bool $absolute = true)
* @method static bool hasValidRelativeSignature()
* @method static bool hasValidSignatureWhileIgnoring($ignoreQuery = [], $absolute = true)
* @method static bool hasValidRelativeSignatureWhileIgnoring($ignoreQuery = [])
*
* @see \Illuminate\Http\Request
*/
class Request extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'request';
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Contracts\Routing\ResponseFactory as ResponseFactoryContract;
/**
* @method static \Illuminate\Http\Response make(mixed $content = '', int $status = 200, array $headers = [])
* @method static \Illuminate\Http\Response noContent(int $status = 204, array $headers = [])
* @method static \Illuminate\Http\Response view(string|array $view, array $data = [], int $status = 200, array $headers = [])
* @method static \Illuminate\Http\JsonResponse json(mixed $data = [], int $status = 200, array $headers = [], int $options = 0)
* @method static \Illuminate\Http\JsonResponse jsonp(string $callback, mixed $data = [], int $status = 200, array $headers = [], int $options = 0)
* @method static \Symfony\Component\HttpFoundation\StreamedResponse eventStream(\Closure $callback, array $headers = [], \Illuminate\Http\StreamedEvent|string|null $endStreamWith = '</stream>')
* @method static \Symfony\Component\HttpFoundation\StreamedResponse stream(callable|null $callback, int $status = 200, array $headers = [])
* @method static \Symfony\Component\HttpFoundation\StreamedJsonResponse streamJson(array $data, int $status = 200, array $headers = [], int $encodingOptions = 15)
* @method static \Symfony\Component\HttpFoundation\StreamedResponse streamDownload(callable $callback, string|null $name = null, array $headers = [], string|null $disposition = 'attachment')
* @method static \Symfony\Component\HttpFoundation\BinaryFileResponse download(\SplFileInfo|string $file, string|null $name = null, array $headers = [], string|null $disposition = 'attachment')
* @method static \Symfony\Component\HttpFoundation\BinaryFileResponse file(\SplFileInfo|string $file, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse redirectTo(string $path, int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Illuminate\Http\RedirectResponse redirectToRoute(\BackedEnum|string $route, mixed $parameters = [], int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse redirectToAction(array|string $action, mixed $parameters = [], int $status = 302, array $headers = [])
* @method static \Illuminate\Http\RedirectResponse redirectGuest(string $path, int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Illuminate\Http\RedirectResponse redirectToIntended(string $default = '/', int $status = 302, array $headers = [], bool|null $secure = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Routing\ResponseFactory
*/
class Response extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return ResponseFactoryContract::class;
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Routing\Route get(string $uri, array|string|callable|null $action = null)
* @method static \Illuminate\Routing\Route post(string $uri, array|string|callable|null $action = null)
* @method static \Illuminate\Routing\Route put(string $uri, array|string|callable|null $action = null)
* @method static \Illuminate\Routing\Route patch(string $uri, array|string|callable|null $action = null)
* @method static \Illuminate\Routing\Route delete(string $uri, array|string|callable|null $action = null)
* @method static \Illuminate\Routing\Route options(string $uri, array|string|callable|null $action = null)
* @method static \Illuminate\Routing\Route any(string $uri, array|string|callable|null $action = null)
* @method static \Illuminate\Routing\Route fallback(array|string|callable|null $action)
* @method static \Illuminate\Routing\Route redirect(string $uri, string $destination, int $status = 302)
* @method static \Illuminate\Routing\Route permanentRedirect(string $uri, string $destination)
* @method static \Illuminate\Routing\Route view(string $uri, string $view, array $data = [], int|array $status = 200, array $headers = [])
* @method static \Illuminate\Routing\Route match(array|string $methods, string $uri, array|string|callable|null $action = null)
* @method static void resources(array $resources, array $options = [])
* @method static void softDeletableResources(array $resources, array $options = [])
* @method static \Illuminate\Routing\PendingResourceRegistration resource(string $name, string $controller, array $options = [])
* @method static void apiResources(array $resources, array $options = [])
* @method static \Illuminate\Routing\PendingResourceRegistration apiResource(string $name, string $controller, array $options = [])
* @method static void singletons(array $singletons, array $options = [])
* @method static \Illuminate\Routing\PendingSingletonResourceRegistration singleton(string $name, string $controller, array $options = [])
* @method static void apiSingletons(array $singletons, array $options = [])
* @method static \Illuminate\Routing\PendingSingletonResourceRegistration apiSingleton(string $name, string $controller, array $options = [])
* @method static \Illuminate\Routing\Router group(array $attributes, \Closure|array|string $routes)
* @method static array mergeWithLastGroup(array $new, bool $prependExistingPrefix = true)
* @method static string getLastGroupPrefix()
* @method static \Illuminate\Routing\Route addRoute(array|string $methods, string $uri, array|string|callable|null $action)
* @method static \Illuminate\Routing\Route newRoute(array|string $methods, string $uri, mixed $action)
* @method static \Symfony\Component\HttpFoundation\Response respondWithRoute(string $name)
* @method static \Symfony\Component\HttpFoundation\Response dispatch(\Illuminate\Http\Request $request)
* @method static \Symfony\Component\HttpFoundation\Response dispatchToRoute(\Illuminate\Http\Request $request)
* @method static array gatherRouteMiddleware(\Illuminate\Routing\Route $route)
* @method static array resolveMiddleware(array $middleware, array $excluded = [])
* @method static \Symfony\Component\HttpFoundation\Response prepareResponse(\Symfony\Component\HttpFoundation\Request $request, mixed $response)
* @method static \Symfony\Component\HttpFoundation\Response toResponse(\Symfony\Component\HttpFoundation\Request $request, mixed $response)
* @method static \Illuminate\Routing\Route substituteBindings(\Illuminate\Routing\Route $route)
* @method static void substituteImplicitBindings(\Illuminate\Routing\Route $route)
* @method static \Illuminate\Routing\Router substituteImplicitBindingsUsing(callable $callback)
* @method static void matched(string|callable $callback)
* @method static array getMiddleware()
* @method static \Illuminate\Routing\Router aliasMiddleware(string $name, string $class)
* @method static bool hasMiddlewareGroup(string $name)
* @method static array getMiddlewareGroups()
* @method static \Illuminate\Routing\Router middlewareGroup(string $name, array $middleware)
* @method static \Illuminate\Routing\Router prependMiddlewareToGroup(string $group, string $middleware)
* @method static \Illuminate\Routing\Router pushMiddlewareToGroup(string $group, string $middleware)
* @method static \Illuminate\Routing\Router removeMiddlewareFromGroup(string $group, string $middleware)
* @method static \Illuminate\Routing\Router flushMiddlewareGroups()
* @method static void bind(string $key, string|callable $binder)
* @method static void model(string $key, string $class, \Closure|null $callback = null)
* @method static \Closure|null getBindingCallback(string $key)
* @method static array getPatterns()
* @method static void pattern(string $key, string $pattern)
* @method static void patterns(array $patterns)
* @method static bool hasGroupStack()
* @method static array getGroupStack()
* @method static mixed input(string $key, string|null $default = null)
* @method static \Illuminate\Http\Request getCurrentRequest()
* @method static \Illuminate\Routing\Route|null getCurrentRoute()
* @method static \Illuminate\Routing\Route|null current()
* @method static bool has(string|array $name)
* @method static string|null currentRouteName()
* @method static bool is(mixed ...$patterns)
* @method static bool currentRouteNamed(mixed ...$patterns)
* @method static string|null currentRouteAction()
* @method static bool uses(array|string ...$patterns)
* @method static bool currentRouteUses(string $action)
* @method static void singularResourceParameters(bool $singular = true)
* @method static void resourceParameters(array $parameters = [])
* @method static array|null resourceVerbs(array $verbs = [])
* @method static \Illuminate\Routing\RouteCollectionInterface getRoutes()
* @method static void setRoutes(\Illuminate\Routing\RouteCollection $routes)
* @method static void setCompiledRoutes(array $routes)
* @method static array uniqueMiddleware(array $middleware)
* @method static \Illuminate\Routing\Router setContainer(\Illuminate\Container\Container $container)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
* @method static \Illuminate\Support\HigherOrderTapProxy|\Illuminate\Routing\Router tap(callable|null $callback = null)
* @method static \Illuminate\Routing\RouteRegistrar attribute(string $key, mixed $value)
* @method static \Illuminate\Routing\RouteRegistrar whereAlpha(array|string $parameters)
* @method static \Illuminate\Routing\RouteRegistrar whereAlphaNumeric(array|string $parameters)
* @method static \Illuminate\Routing\RouteRegistrar whereNumber(array|string $parameters)
* @method static \Illuminate\Routing\RouteRegistrar whereUlid(array|string $parameters)
* @method static \Illuminate\Routing\RouteRegistrar whereUuid(array|string $parameters)
* @method static \Illuminate\Routing\RouteRegistrar whereIn(array|string $parameters, array $values)
* @method static \Illuminate\Routing\RouteRegistrar as(string $value)
* @method static \Illuminate\Routing\RouteRegistrar can(\UnitEnum|string $ability, array|string $models = [])
* @method static \Illuminate\Routing\RouteRegistrar controller(string $controller)
* @method static \Illuminate\Routing\RouteRegistrar domain(\BackedEnum|string $value)
* @method static \Illuminate\Routing\RouteRegistrar middleware(array|string|null $middleware)
* @method static \Illuminate\Routing\RouteRegistrar missing(\Closure $missing)
* @method static \Illuminate\Routing\RouteRegistrar name(\BackedEnum|string $value)
* @method static \Illuminate\Routing\RouteRegistrar namespace(string|null $value)
* @method static \Illuminate\Routing\RouteRegistrar prefix(string $prefix)
* @method static \Illuminate\Routing\RouteRegistrar scopeBindings()
* @method static \Illuminate\Routing\RouteRegistrar where(array $where)
* @method static \Illuminate\Routing\RouteRegistrar withoutMiddleware(array|string $middleware)
* @method static \Illuminate\Routing\RouteRegistrar withoutScopedBindings()
*
* @see \Illuminate\Routing\Router
*/
class Route extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'router';
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Console\Scheduling\Schedule as ConsoleSchedule;
/**
* @method static \Illuminate\Console\Scheduling\CallbackEvent call(string|callable $callback, array $parameters = [])
* @method static \Illuminate\Console\Scheduling\Event command(\Symfony\Component\Console\Command\Command|string $command, array $parameters = [])
* @method static \Illuminate\Console\Scheduling\CallbackEvent job(object|string $job, \UnitEnum|string|null $queue = null, \UnitEnum|string|null $connection = null)
* @method static \Illuminate\Console\Scheduling\Event exec(string $command, array $parameters = [])
* @method static void group(\Closure $events)
* @method static string compileArrayInput(string|int $key, array $value)
* @method static bool serverShouldRun(\Illuminate\Console\Scheduling\Event $event, \DateTimeInterface $time)
* @method static \Illuminate\Support\Collection dueEvents(\Illuminate\Contracts\Foundation\Application $app)
* @method static \Illuminate\Console\Scheduling\Event[] events()
* @method static \Illuminate\Console\Scheduling\Schedule useCache(string $store)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes withoutOverlapping(int $expiresAt = 1440)
* @method static void mergeAttributes(\Illuminate\Console\Scheduling\Event $event)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes user(string $user)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes environments(mixed $environments)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes evenInMaintenanceMode()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes onOneServer()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes runInBackground()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes when(\Closure|bool $callback)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes skip(\Closure|bool $callback)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes name(string $description)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes description(string $description)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes cron(string $expression)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes between(string $startTime, string $endTime)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes unlessBetween(string $startTime, string $endTime)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everySecond()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyTwoSeconds()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyFiveSeconds()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyTenSeconds()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyFifteenSeconds()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyTwentySeconds()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyThirtySeconds()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyMinute()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyTwoMinutes()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyThreeMinutes()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyFourMinutes()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyFiveMinutes()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyTenMinutes()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyFifteenMinutes()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyThirtyMinutes()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes hourly()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes hourlyAt(array|string|int|int[] $offset)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyOddHour(array|string|int $offset = 0)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyTwoHours(array|string|int $offset = 0)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyThreeHours(array|string|int $offset = 0)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everyFourHours(array|string|int $offset = 0)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes everySixHours(array|string|int $offset = 0)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes daily()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes at(string $time)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes dailyAt(string $time)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes twiceDaily(int $first = 1, int $second = 13)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes twiceDailyAt(int $first = 1, int $second = 13, int $offset = 0)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes weekdays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes weekends()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes mondays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes tuesdays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes wednesdays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes thursdays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes fridays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes saturdays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes sundays()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes weekly()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes weeklyOn(mixed $dayOfWeek, string $time = '0:0')
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes monthly()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes monthlyOn(int $dayOfMonth = 1, string $time = '0:0')
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes twiceMonthly(int $first = 1, int $second = 16, string $time = '0:0')
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes lastDayOfMonth(string $time = '0:0')
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes quarterly()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes quarterlyOn(int $dayOfQuarter = 1, string $time = '0:0')
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes yearly()
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes yearlyOn(int $month = 1, int|string $dayOfMonth = 1, string $time = '0:0')
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes days(mixed $days)
* @method static \Illuminate\Console\Scheduling\PendingEventAttributes timezone(\UnitEnum|\DateTimeZone|string $timezone)
*
* @see \Illuminate\Console\Scheduling\Schedule
*/
class Schedule extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return ConsoleSchedule::class;
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static void defaultStringLength(int $length)
* @method static void defaultTimePrecision(int|null $precision)
* @method static void defaultMorphKeyType(string $type)
* @method static void morphUsingUuids()
* @method static void morphUsingUlids()
* @method static bool createDatabase(string $name)
* @method static bool dropDatabaseIfExists(string $name)
* @method static array getSchemas()
* @method static bool hasTable(string $table)
* @method static bool hasView(string $view)
* @method static array getTables(string|string[]|null $schema = null)
* @method static array getTableListing(string|string[]|null $schema = null, bool $schemaQualified = true)
* @method static array getViews(string|string[]|null $schema = null)
* @method static array getTypes(string|string[]|null $schema = null)
* @method static bool hasColumn(string $table, string $column)
* @method static bool hasColumns(string $table, array $columns)
* @method static void whenTableHasColumn(string $table, string $column, \Closure $callback)
* @method static void whenTableDoesntHaveColumn(string $table, string $column, \Closure $callback)
* @method static string getColumnType(string $table, string $column, bool $fullDefinition = false)
* @method static array getColumnListing(string $table)
* @method static array getColumns(string $table)
* @method static array getIndexes(string $table)
* @method static array getIndexListing(string $table)
* @method static bool hasIndex(string $table, string|array $index, string|null $type = null)
* @method static array getForeignKeys(string $table)
* @method static void table(string $table, \Closure $callback)
* @method static void create(string $table, \Closure $callback)
* @method static void drop(string $table)
* @method static void dropIfExists(string $table)
* @method static void dropColumns(string $table, string|array $columns)
* @method static void dropAllTables()
* @method static void dropAllViews()
* @method static void dropAllTypes()
* @method static void rename(string $from, string $to)
* @method static bool enableForeignKeyConstraints()
* @method static bool disableForeignKeyConstraints()
* @method static mixed withoutForeignKeyConstraints(\Closure $callback)
* @method static string[]|null getCurrentSchemaListing()
* @method static string|null getCurrentSchemaName()
* @method static array parseSchemaAndTable(string $reference, string|bool|null $withDefaultSchema = null)
* @method static \Illuminate\Database\Connection getConnection()
* @method static void blueprintResolver(\Closure $resolver)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Database\Schema\Builder
*/
class Schema extends Facade
{
/**
* Indicates if the resolved facade should be cached.
*
* @var bool
*/
protected static $cached = false;
/**
* Get a schema builder instance for a connection.
*
* @param string|null $name
* @return \Illuminate\Database\Schema\Builder
*/
public static function connection($name)
{
return static::$app['db']->connection($name)->getSchemaBuilder();
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'db.schema';
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static bool shouldBlock()
* @method static string|null blockDriver()
* @method static int defaultRouteBlockLockSeconds()
* @method static int defaultRouteBlockWaitSeconds()
* @method static array getSessionConfig()
* @method static string getDefaultDriver()
* @method static void setDefaultDriver(string $name)
* @method static mixed driver(string|null $driver = null)
* @method static \Illuminate\Session\SessionManager extend(string $driver, \Closure $callback)
* @method static array getDrivers()
* @method static \Illuminate\Contracts\Container\Container getContainer()
* @method static \Illuminate\Session\SessionManager setContainer(\Illuminate\Contracts\Container\Container $container)
* @method static \Illuminate\Session\SessionManager forgetDrivers()
* @method static bool start()
* @method static void save()
* @method static void ageFlashData()
* @method static array all()
* @method static array only(array $keys)
* @method static array except(array $keys)
* @method static bool exists(string|array $key)
* @method static bool missing(string|array $key)
* @method static bool has(string|array $key)
* @method static bool hasAny(string|array $key)
* @method static mixed get(string $key, mixed $default = null)
* @method static mixed pull(string $key, mixed $default = null)
* @method static bool hasOldInput(string|null $key = null)
* @method static mixed getOldInput(string|null $key = null, mixed $default = null)
* @method static void replace(array $attributes)
* @method static void put(string|array $key, mixed $value = null)
* @method static mixed remember(string $key, \Closure $callback)
* @method static void push(string $key, mixed $value)
* @method static mixed increment(string $key, int $amount = 1)
* @method static int decrement(string $key, int $amount = 1)
* @method static void flash(string $key, mixed $value = true)
* @method static void now(string $key, mixed $value)
* @method static void reflash()
* @method static void keep(mixed $keys = null)
* @method static void flashInput(array $value)
* @method static mixed remove(string $key)
* @method static void forget(string|array $keys)
* @method static void flush()
* @method static bool invalidate()
* @method static bool regenerate(bool $destroy = false)
* @method static bool migrate(bool $destroy = false)
* @method static bool isStarted()
* @method static string getName()
* @method static void setName(string $name)
* @method static string id()
* @method static string getId()
* @method static void setId(string|null $id)
* @method static bool isValidId(string|null $id)
* @method static void setExists(bool $value)
* @method static string token()
* @method static void regenerateToken()
* @method static bool hasPreviousUri()
* @method static \Illuminate\Support\Uri previousUri()
* @method static string|null previousUrl()
* @method static void setPreviousUrl(string $url)
* @method static void passwordConfirmed()
* @method static \SessionHandlerInterface getHandler()
* @method static \SessionHandlerInterface setHandler(\SessionHandlerInterface $handler)
* @method static bool handlerNeedsRequest()
* @method static void setRequestOnHandler(\Illuminate\Http\Request $request)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Session\SessionManager
*/
class Session extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'session';
}
}

View File

@@ -0,0 +1,173 @@
<?php
namespace Illuminate\Support\Facades;
use Illuminate\Filesystem\Filesystem;
/**
* @method static \Illuminate\Contracts\Filesystem\Filesystem drive(string|null $name = null)
* @method static \Illuminate\Contracts\Filesystem\Filesystem disk(\UnitEnum|string|null $name = null)
* @method static \Illuminate\Contracts\Filesystem\Cloud cloud()
* @method static \Illuminate\Contracts\Filesystem\Filesystem build(string|array $config)
* @method static \Illuminate\Contracts\Filesystem\Filesystem createLocalDriver(array $config, string $name = 'local')
* @method static \Illuminate\Contracts\Filesystem\Filesystem createFtpDriver(array $config)
* @method static \Illuminate\Contracts\Filesystem\Filesystem createSftpDriver(array $config)
* @method static \Illuminate\Contracts\Filesystem\Cloud createS3Driver(array $config)
* @method static \Illuminate\Contracts\Filesystem\Filesystem createScopedDriver(array $config)
* @method static \Illuminate\Filesystem\FilesystemManager set(string $name, mixed $disk)
* @method static string getDefaultDriver()
* @method static string getDefaultCloudDriver()
* @method static \Illuminate\Filesystem\FilesystemManager forgetDisk(array|string $disk)
* @method static void purge(string|null $name = null)
* @method static \Illuminate\Filesystem\FilesystemManager extend(string $driver, \Closure $callback)
* @method static \Illuminate\Filesystem\FilesystemManager setApplication(\Illuminate\Contracts\Foundation\Application $app)
* @method static string path(string $path)
* @method static bool exists(string $path)
* @method static string|null get(string $path)
* @method static resource|null readStream(string $path)
* @method static bool put(string $path, \Psr\Http\Message\StreamInterface|\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|resource $contents, mixed $options = [])
* @method static string|false putFile(\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $path, \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|array|null $file = null, mixed $options = [])
* @method static string|false putFileAs(\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $path, \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|array|null $file, string|array|null $name = null, mixed $options = [])
* @method static bool writeStream(string $path, resource $resource, array $options = [])
* @method static string getVisibility(string $path)
* @method static bool setVisibility(string $path, string $visibility)
* @method static bool prepend(string $path, string $data)
* @method static bool append(string $path, string $data)
* @method static bool delete(string|array $paths)
* @method static bool copy(string $from, string $to)
* @method static bool move(string $from, string $to)
* @method static int size(string $path)
* @method static int lastModified(string $path)
* @method static array files(string|null $directory = null, bool $recursive = false)
* @method static array allFiles(string|null $directory = null)
* @method static array directories(string|null $directory = null, bool $recursive = false)
* @method static array allDirectories(string|null $directory = null)
* @method static bool makeDirectory(string $path)
* @method static bool deleteDirectory(string $directory)
* @method static \Illuminate\Filesystem\FilesystemAdapter assertExists(string|array $path, string|null $content = null)
* @method static \Illuminate\Filesystem\FilesystemAdapter assertCount(string $path, int $count, bool $recursive = false)
* @method static \Illuminate\Filesystem\FilesystemAdapter assertMissing(string|array $path)
* @method static \Illuminate\Filesystem\FilesystemAdapter assertDirectoryEmpty(string $path)
* @method static bool missing(string $path)
* @method static bool fileExists(string $path)
* @method static bool fileMissing(string $path)
* @method static bool directoryExists(string $path)
* @method static bool directoryMissing(string $path)
* @method static array|null json(string $path, int $flags = 0)
* @method static \Symfony\Component\HttpFoundation\StreamedResponse response(string $path, string|null $name = null, array $headers = [], string|null $disposition = 'inline')
* @method static \Symfony\Component\HttpFoundation\StreamedResponse serve(\Illuminate\Http\Request $request, string $path, string|null $name = null, array $headers = [])
* @method static \Symfony\Component\HttpFoundation\StreamedResponse download(string $path, string|null $name = null, array $headers = [])
* @method static string|false checksum(string $path, array $options = [])
* @method static string|false mimeType(string $path)
* @method static string url(string $path)
* @method static bool providesTemporaryUrls()
* @method static string temporaryUrl(string $path, \DateTimeInterface $expiration, array $options = [])
* @method static array temporaryUploadUrl(string $path, \DateTimeInterface $expiration, array $options = [])
* @method static \League\Flysystem\FilesystemOperator getDriver()
* @method static \League\Flysystem\FilesystemAdapter getAdapter()
* @method static array getConfig()
* @method static void serveUsing(\Closure $callback)
* @method static void buildTemporaryUrlsUsing(\Closure $callback)
* @method static \Illuminate\Filesystem\FilesystemAdapter|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Illuminate\Filesystem\FilesystemAdapter|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static mixed macroCall(string $method, array $parameters)
* @method static bool has(string $location)
* @method static string read(string $location)
* @method static \League\Flysystem\DirectoryListing listContents(string $location, bool $deep = false)
* @method static int fileSize(string $path)
* @method static string visibility(string $path)
* @method static void write(string $location, string $contents, array $config = [])
* @method static void createDirectory(string $location, array $config = [])
*
* @see \Illuminate\Filesystem\FilesystemManager
*/
class Storage extends Facade
{
/**
* Replace the given disk with a local testing disk.
*
* @param string|null $disk
* @param array $config
* @return \Illuminate\Contracts\Filesystem\Filesystem
*/
public static function fake($disk = null, array $config = [])
{
$root = self::getRootPath($disk = $disk ?: static::$app['config']->get('filesystems.default'));
if ($token = ParallelTesting::token()) {
$root = "{$root}_test_{$token}";
}
(new Filesystem)->cleanDirectory($root);
static::set($disk, $fake = static::createLocalDriver(
self::buildDiskConfiguration($disk, $config, root: $root)
));
return tap($fake)->buildTemporaryUrlsUsing(function ($path, $expiration) {
return URL::to($path.'?expiration='.$expiration->getTimestamp());
});
}
/**
* Replace the given disk with a persistent local testing disk.
*
* @param string|null $disk
* @param array $config
* @return \Illuminate\Contracts\Filesystem\Filesystem
*/
public static function persistentFake($disk = null, array $config = [])
{
$disk = $disk ?: static::$app['config']->get('filesystems.default');
static::set($disk, $fake = static::createLocalDriver(
self::buildDiskConfiguration($disk, $config, root: self::getRootPath($disk))
));
return $fake;
}
/**
* Get the root path of the given disk.
*
* @param string $disk
* @return string
*/
protected static function getRootPath(string $disk): string
{
return storage_path('framework/testing/disks/'.$disk);
}
/**
* Assemble the configuration of the given disk.
*
* @param string $disk
* @param array $config
* @param string $root
* @return array
*/
protected static function buildDiskConfiguration(string $disk, array $config, string $root): array
{
$originalConfig = static::$app['config']["filesystems.disks.{$disk}"] ?? [];
return array_merge([
'throw' => $originalConfig['throw'] ?? false],
$config,
['root' => $root]
);
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'filesystem';
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static string full()
* @method static string current()
* @method static string previous(mixed $fallback = false)
* @method static string previousPath(mixed $fallback = false)
* @method static string to(string $path, mixed $extra = [], bool|null $secure = null)
* @method static string query(string $path, array $query = [], mixed $extra = [], bool|null $secure = null)
* @method static string secure(string $path, array $parameters = [])
* @method static string asset(string $path, bool|null $secure = null)
* @method static string secureAsset(string $path)
* @method static string assetFrom(string $root, string $path, bool|null $secure = null)
* @method static string formatScheme(bool|null $secure = null)
* @method static string signedRoute(\BackedEnum|string $name, mixed $parameters = [], \DateTimeInterface|\DateInterval|int|null $expiration = null, bool $absolute = true)
* @method static string temporarySignedRoute(\BackedEnum|string $name, \DateTimeInterface|\DateInterval|int $expiration, array $parameters = [], bool $absolute = true)
* @method static bool hasValidSignature(\Illuminate\Http\Request $request, bool $absolute = true, \Closure|array $ignoreQuery = [])
* @method static bool hasValidRelativeSignature(\Illuminate\Http\Request $request, \Closure|array $ignoreQuery = [])
* @method static bool hasCorrectSignature(\Illuminate\Http\Request $request, bool $absolute = true, \Closure|array $ignoreQuery = [])
* @method static bool signatureHasNotExpired(\Illuminate\Http\Request $request)
* @method static string route(\BackedEnum|string $name, mixed $parameters = [], bool $absolute = true)
* @method static string toRoute(\Illuminate\Routing\Route $route, mixed $parameters, bool $absolute)
* @method static string action(string|array $action, mixed $parameters = [], bool $absolute = true)
* @method static array formatParameters(mixed $parameters)
* @method static string formatRoot(string $scheme, string|null $root = null)
* @method static string format(string $root, string $path, \Illuminate\Routing\Route|null $route = null)
* @method static bool isValidUrl(string $path)
* @method static void defaults(array $defaults)
* @method static array getDefaultParameters()
* @method static void forceScheme(string|null $scheme)
* @method static void forceHttps(bool $force = true)
* @method static void useOrigin(string|null $root)
* @method static void useAssetOrigin(string|null $root)
* @method static \Illuminate\Routing\UrlGenerator formatHostUsing(\Closure $callback)
* @method static \Illuminate\Routing\UrlGenerator formatPathUsing(\Closure $callback)
* @method static \Closure pathFormatter()
* @method static \Illuminate\Http\Request getRequest()
* @method static void setRequest(\Illuminate\Http\Request $request)
* @method static \Illuminate\Routing\UrlGenerator setRoutes(\Illuminate\Routing\RouteCollectionInterface $routes)
* @method static \Illuminate\Routing\UrlGenerator setSessionResolver(callable $sessionResolver)
* @method static \Illuminate\Routing\UrlGenerator setKeyResolver(callable $keyResolver)
* @method static \Illuminate\Routing\UrlGenerator withKeyResolver(callable $keyResolver)
* @method static \Illuminate\Routing\UrlGenerator resolveMissingNamedRoutesUsing(callable $missingNamedRouteResolver)
* @method static string getRootControllerNamespace()
* @method static \Illuminate\Routing\UrlGenerator setRootControllerNamespace(string $rootNamespace)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Routing\UrlGenerator
*/
class URL extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'url';
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Validation\Validator make(array $data, array $rules, array $messages = [], array $attributes = [])
* @method static array validate(array $data, array $rules, array $messages = [], array $attributes = [])
* @method static void extend(string $rule, \Closure|string $extension, string|null $message = null)
* @method static void extendImplicit(string $rule, \Closure|string $extension, string|null $message = null)
* @method static void extendDependent(string $rule, \Closure|string $extension, string|null $message = null)
* @method static void replacer(string $rule, \Closure|string $replacer)
* @method static void includeUnvalidatedArrayKeys()
* @method static void excludeUnvalidatedArrayKeys()
* @method static void resolver(\Closure $resolver)
* @method static \Illuminate\Contracts\Translation\Translator getTranslator()
* @method static \Illuminate\Validation\PresenceVerifierInterface getPresenceVerifier()
* @method static void setPresenceVerifier(\Illuminate\Validation\PresenceVerifierInterface $presenceVerifier)
* @method static \Illuminate\Contracts\Container\Container|null getContainer()
* @method static \Illuminate\Validation\Factory setContainer(\Illuminate\Contracts\Container\Container $container)
*
* @see \Illuminate\Validation\Factory
*/
class Validator extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'validator';
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Contracts\View\View file(string $path, \Illuminate\Contracts\Support\Arrayable|array $data = [], array $mergeData = [])
* @method static \Illuminate\Contracts\View\View make(string $view, \Illuminate\Contracts\Support\Arrayable|array $data = [], array $mergeData = [])
* @method static \Illuminate\Contracts\View\View first(array $views, \Illuminate\Contracts\Support\Arrayable|array $data = [], array $mergeData = [])
* @method static string renderWhen(bool $condition, string $view, \Illuminate\Contracts\Support\Arrayable|array $data = [], array $mergeData = [])
* @method static string renderUnless(bool $condition, string $view, \Illuminate\Contracts\Support\Arrayable|array $data = [], array $mergeData = [])
* @method static string renderEach(string $view, array $data, string $iterator, string $empty = 'raw|')
* @method static bool exists(string $view)
* @method static \Illuminate\Contracts\View\Engine getEngineFromPath(string $path)
* @method static mixed share(array|string $key, mixed $value = null)
* @method static void incrementRender()
* @method static void decrementRender()
* @method static bool doneRendering()
* @method static bool hasRenderedOnce(string $id)
* @method static void markAsRenderedOnce(string $id)
* @method static void addLocation(string $location)
* @method static void prependLocation(string $location)
* @method static \Illuminate\View\Factory addNamespace(string $namespace, string|array $hints)
* @method static \Illuminate\View\Factory prependNamespace(string $namespace, string|array $hints)
* @method static \Illuminate\View\Factory replaceNamespace(string $namespace, string|array $hints)
* @method static void addExtension(string $extension, string $engine, \Closure|null $resolver = null)
* @method static void flushState()
* @method static void flushStateIfDoneRendering()
* @method static array getExtensions()
* @method static \Illuminate\View\Engines\EngineResolver getEngineResolver()
* @method static \Illuminate\View\ViewFinderInterface getFinder()
* @method static void setFinder(\Illuminate\View\ViewFinderInterface $finder)
* @method static void flushFinderCache()
* @method static \Illuminate\Contracts\Events\Dispatcher getDispatcher()
* @method static void setDispatcher(\Illuminate\Contracts\Events\Dispatcher $events)
* @method static \Illuminate\Contracts\Container\Container getContainer()
* @method static void setContainer(\Illuminate\Contracts\Container\Container $container)
* @method static mixed shared(string $key, mixed $default = null)
* @method static array getShared()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
* @method static void startComponent(\Illuminate\Contracts\View\View|\Illuminate\Contracts\Support\Htmlable|\Closure|string $view, array $data = [])
* @method static void startComponentFirst(array $names, array $data = [])
* @method static string renderComponent()
* @method static mixed getConsumableComponentData(string $key, mixed $default = null)
* @method static void slot(string $name, string|null $content = null, array $attributes = [])
* @method static void endSlot()
* @method static array creator(array|string $views, \Closure|string $callback)
* @method static array composers(array $composers)
* @method static array composer(array|string $views, \Closure|string $callback)
* @method static void callComposer(\Illuminate\Contracts\View\View $view)
* @method static void callCreator(\Illuminate\Contracts\View\View $view)
* @method static void startFragment(string $fragment)
* @method static string stopFragment()
* @method static mixed getFragment(string $name, string|null $default = null)
* @method static array getFragments()
* @method static void flushFragments()
* @method static void startSection(string $section, string|null $content = null)
* @method static void inject(string $section, string $content)
* @method static string yieldSection()
* @method static string stopSection(bool $overwrite = false)
* @method static string appendSection()
* @method static string yieldContent(string $section, string $default = '')
* @method static string parentPlaceholder(string $section = '')
* @method static bool hasSection(string $name)
* @method static bool sectionMissing(string $name)
* @method static mixed getSection(string $name, string|null $default = null)
* @method static array getSections()
* @method static void flushSections()
* @method static void addLoop(\Countable|array $data)
* @method static void incrementLoopIndices()
* @method static void popLoop()
* @method static \stdClass|null getLastLoop()
* @method static array getLoopStack()
* @method static void startPush(string $section, string $content = '')
* @method static string stopPush()
* @method static void startPrepend(string $section, string $content = '')
* @method static string stopPrepend()
* @method static string yieldPushContent(string $section, string $default = '')
* @method static void flushStacks()
* @method static void startTranslation(array $replacements = [])
* @method static string renderTranslation()
*
* @see \Illuminate\View\Factory
*/
class View extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'view';
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Illuminate\Support\Facades;
/**
* @method static array preloadedAssets()
* @method static string|null cspNonce()
* @method static string useCspNonce(string|null $nonce = null)
* @method static \Illuminate\Foundation\Vite useIntegrityKey(string|false $key)
* @method static \Illuminate\Foundation\Vite withEntryPoints(array $entryPoints)
* @method static \Illuminate\Foundation\Vite mergeEntryPoints(array $entryPoints)
* @method static \Illuminate\Foundation\Vite useManifestFilename(string $filename)
* @method static \Illuminate\Foundation\Vite createAssetPathsUsing(callable|null $resolver)
* @method static string hotFile()
* @method static \Illuminate\Foundation\Vite useHotFile(string $path)
* @method static \Illuminate\Foundation\Vite useBuildDirectory(string $path)
* @method static \Illuminate\Foundation\Vite useScriptTagAttributes(callable|array $attributes)
* @method static \Illuminate\Foundation\Vite useStyleTagAttributes(callable|array $attributes)
* @method static \Illuminate\Foundation\Vite usePreloadTagAttributes(callable|array|false $attributes)
* @method static \Illuminate\Foundation\Vite prefetch(int|null $concurrency = null, string $event = 'load')
* @method static \Illuminate\Foundation\Vite useWaterfallPrefetching(int|null $concurrency = null)
* @method static \Illuminate\Foundation\Vite useAggressivePrefetching()
* @method static \Illuminate\Foundation\Vite usePrefetchStrategy(string|null $strategy, array $config = [])
* @method static \Illuminate\Support\HtmlString|void reactRefresh()
* @method static string asset(string $asset, string|null $buildDirectory = null)
* @method static string content(string $asset, string|null $buildDirectory = null)
* @method static string|null manifestHash(string|null $buildDirectory = null)
* @method static bool isRunningHot()
* @method static string toHtml()
* @method static void flush()
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Illuminate\Foundation\Vite
*/
class Vite extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return \Illuminate\Foundation\Vite::class;
}
}

355
plugins/vendor/illuminate/support/Fluent.php vendored Executable file
View File

@@ -0,0 +1,355 @@
<?php
namespace Illuminate\Support;
use ArrayAccess;
use ArrayIterator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\InteractsWithData;
use Illuminate\Support\Traits\Macroable;
use IteratorAggregate;
use JsonSerializable;
use Traversable;
/**
* @template TKey of array-key
* @template TValue
*
* @implements \Illuminate\Contracts\Support\Arrayable<TKey, TValue>
* @implements \ArrayAccess<TKey, TValue>
*/
class Fluent implements Arrayable, ArrayAccess, IteratorAggregate, Jsonable, JsonSerializable
{
use Conditionable, InteractsWithData, Macroable {
__call as macroCall;
}
/**
* All of the attributes set on the fluent instance.
*
* @var array<TKey, TValue>
*/
protected $attributes = [];
/**
* Create a new fluent instance.
*
* @param iterable<TKey, TValue> $attributes
*/
public function __construct($attributes = [])
{
$this->fill($attributes);
}
/**
* Create a new fluent instance.
*
* @param iterable<TKey, TValue> $attributes
* @return static
*/
public static function make($attributes = [])
{
return new static($attributes);
}
/**
* Get an attribute from the fluent instance using "dot" notation.
*
* @template TGetDefault
*
* @param TKey $key
* @param TGetDefault|(\Closure(): TGetDefault) $default
* @return TValue|TGetDefault
*/
public function get($key, $default = null)
{
return data_get($this->attributes, $key, $default);
}
/**
* Set an attribute on the fluent instance using "dot" notation.
*
* @param TKey $key
* @param TValue $value
* @return $this
*/
public function set($key, $value)
{
data_set($this->attributes, $key, $value);
return $this;
}
/**
* Fill the fluent instance with an array of attributes.
*
* @param iterable<TKey, TValue> $attributes
* @return $this
*/
public function fill($attributes)
{
foreach ($attributes as $key => $value) {
$this->attributes[$key] = $value;
}
return $this;
}
/**
* Get an attribute from the fluent instance.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function value($key, $default = null)
{
if (array_key_exists($key, $this->attributes)) {
return $this->attributes[$key];
}
return value($default);
}
/**
* Get the value of the given key as a new Fluent instance.
*
* @param string $key
* @param mixed $default
* @return static
*/
public function scope($key, $default = null)
{
return new static(
(array) $this->get($key, $default)
);
}
/**
* Get all of the attributes from the fluent instance.
*
* @param mixed $keys
* @return array
*/
public function all($keys = null)
{
$data = $this->data();
if (! $keys) {
return $data;
}
$results = [];
foreach (is_array($keys) ? $keys : func_get_args() as $key) {
Arr::set($results, $key, Arr::get($data, $key));
}
return $results;
}
/**
* Get data from the fluent instance.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
protected function data($key = null, $default = null)
{
return $this->get($key, $default);
}
/**
* Get the attributes from the fluent instance.
*
* @return array<TKey, TValue>
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* Convert the fluent instance to an array.
*
* @return array<TKey, TValue>
*/
public function toArray()
{
return $this->attributes;
}
/**
* Convert the object into something JSON serializable.
*
* @return array<TKey, TValue>
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* Convert the fluent instance to JSON.
*
* @param int $options
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}
/**
* Convert the fluent instance to pretty print formatted JSON.
*
* @params int $options
*
* @return string
*/
public function toPrettyJson(int $options = 0)
{
return $this->toJson(JSON_PRETTY_PRINT | $options);
}
/**
* Determine if the fluent instance is empty.
*
* @return bool
*/
public function isEmpty(): bool
{
return empty($this->attributes);
}
/**
* Determine if the fluent instance is not empty.
*
* @return bool
*/
public function isNotEmpty(): bool
{
return ! $this->isEmpty();
}
/**
* Determine if the given offset exists.
*
* @param TKey $offset
* @return bool
*/
public function offsetExists($offset): bool
{
return isset($this->attributes[$offset]);
}
/**
* Get the value for a given offset.
*
* @param TKey $offset
* @return TValue|null
*/
public function offsetGet($offset): mixed
{
return $this->value($offset);
}
/**
* Set the value at the given offset.
*
* @param TKey $offset
* @param TValue $value
* @return void
*/
public function offsetSet($offset, $value): void
{
$this->attributes[$offset] = $value;
}
/**
* Unset the value at the given offset.
*
* @param TKey $offset
* @return void
*/
public function offsetUnset($offset): void
{
unset($this->attributes[$offset]);
}
/**
* Get an iterator for the attributes.
*
* @return ArrayIterator<TKey, TValue>
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->attributes);
}
/**
* Handle dynamic calls to the fluent instance to set attributes.
*
* @param TKey $method
* @param array{0: ?TValue} $parameters
* @return $this
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
$this->attributes[$method] = count($parameters) > 0 ? array_first($parameters) : true;
return $this;
}
/**
* Dynamically retrieve the value of an attribute.
*
* @param TKey $key
* @return TValue|null
*/
public function __get($key)
{
return $this->value($key);
}
/**
* Dynamically set the value of an attribute.
*
* @param TKey $key
* @param TValue $value
* @return void
*/
public function __set($key, $value)
{
$this->offsetSet($key, $value);
}
/**
* Dynamically check if an attribute is set.
*
* @param TKey $key
* @return bool
*/
public function __isset($key)
{
return $this->offsetExists($key);
}
/**
* Dynamically unset an attribute.
*
* @param TKey $key
* @return void
*/
public function __unset($key)
{
$this->offsetUnset($key);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Illuminate\Support;
class HigherOrderTapProxy
{
/**
* The target being tapped.
*
* @var mixed
*/
public $target;
/**
* Create a new tap proxy instance.
*
* @param mixed $target
*/
public function __construct($target)
{
$this->target = $target;
}
/**
* Dynamically pass method calls to the target.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
$this->target->{$method}(...$parameters);
return $this->target;
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace Illuminate\Support;
use Illuminate\Contracts\Support\Htmlable;
use Stringable;
class HtmlString implements Htmlable, Stringable
{
/**
* The HTML string.
*
* @var string
*/
protected $html;
/**
* Create a new HTML string instance.
*
* @param string $html
*/
public function __construct($html = '')
{
$this->html = $html;
}
/**
* Get the HTML string.
*
* @return string
*/
public function toHtml()
{
return $this->html;
}
/**
* Determine if the given HTML string is empty.
*
* @return bool
*/
public function isEmpty()
{
return ($this->html ?? '') === '';
}
/**
* Determine if the given HTML string is not empty.
*
* @return bool
*/
public function isNotEmpty()
{
return ! $this->isEmpty();
}
/**
* Get the HTML string.
*
* @return string
*/
public function __toString()
{
return $this->toHtml() ?? '';
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace Illuminate\Support;
use Carbon\CarbonInterval;
use DateInterval;
use DateTimeInterface;
trait InteractsWithTime
{
/**
* Get the number of seconds until the given DateTime.
*
* @param \DateTimeInterface|\DateInterval|int $delay
* @return int
*/
protected function secondsUntil($delay)
{
$delay = $this->parseDateInterval($delay);
return $delay instanceof DateTimeInterface
? max(0, $delay->getTimestamp() - $this->currentTime())
: (int) $delay;
}
/**
* Get the "available at" UNIX timestamp.
*
* @param \DateTimeInterface|\DateInterval|int $delay
* @return int
*/
protected function availableAt($delay = 0)
{
$delay = $this->parseDateInterval($delay);
return $delay instanceof DateTimeInterface
? $delay->getTimestamp()
: Carbon::now()->addSeconds($delay)->getTimestamp();
}
/**
* If the given value is an interval, convert it to a DateTime instance.
*
* @param \DateTimeInterface|\DateInterval|int $delay
* @return \DateTimeInterface|int
*/
protected function parseDateInterval($delay)
{
if ($delay instanceof DateInterval) {
$delay = Carbon::now()->add($delay);
}
return $delay;
}
/**
* Get the current system time as a UNIX timestamp.
*
* @return int
*/
protected function currentTime()
{
return Carbon::now()->getTimestamp();
}
/**
* Given a start time, format the total run time for human readability.
*
* @param float $startTime
* @param float $endTime
* @return string
*/
protected function runTimeForHumans($startTime, $endTime = null)
{
$endTime ??= microtime(true);
$runTime = ($endTime - $startTime) * 1000;
return $runTime > 1000
? CarbonInterval::milliseconds($runTime)->cascade()->forHumans(short: true)
: number_format($runTime, 2).'ms';
}
}

157
plugins/vendor/illuminate/support/Js.php vendored Normal file
View File

@@ -0,0 +1,157 @@
<?php
namespace Illuminate\Support;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\Support\Jsonable;
use JsonSerializable;
use Stringable;
use UnitEnum;
class Js implements Htmlable, Stringable
{
/**
* The JavaScript string.
*
* @var string
*/
protected $js;
/**
* Flags that should be used when encoding to JSON.
*
* @var int
*/
protected const REQUIRED_FLAGS = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_THROW_ON_ERROR;
/**
* Create a new class instance.
*
* @param mixed $data
* @param int|null $flags
* @param int $depth
*
* @throws \JsonException
*/
public function __construct($data, $flags = 0, $depth = 512)
{
$this->js = $this->convertDataToJavaScriptExpression($data, $flags, $depth);
}
/**
* Create a new JavaScript string from the given data.
*
* @param mixed $data
* @param int $flags
* @param int $depth
* @return static
*
* @throws \JsonException
*/
public static function from($data, $flags = 0, $depth = 512)
{
return new static($data, $flags, $depth);
}
/**
* Convert the given data to a JavaScript expression.
*
* @param mixed $data
* @param int $flags
* @param int $depth
* @return string
*
* @throws \JsonException
*/
protected function convertDataToJavaScriptExpression($data, $flags = 0, $depth = 512)
{
if ($data instanceof self) {
return $data->toHtml();
}
if ($data instanceof Htmlable &&
! $data instanceof Arrayable &&
! $data instanceof Jsonable &&
! $data instanceof JsonSerializable) {
$data = $data->toHtml();
}
if ($data instanceof UnitEnum) {
$data = enum_value($data);
}
$json = static::encode($data, $flags, $depth);
if (is_string($data)) {
return "'".substr($json, 1, -1)."'";
}
return $this->convertJsonToJavaScriptExpression($json, $flags);
}
/**
* Encode the given data as JSON.
*
* @param mixed $data
* @param int $flags
* @param int $depth
* @return string
*
* @throws \JsonException
*/
public static function encode($data, $flags = 0, $depth = 512)
{
if ($data instanceof Jsonable) {
return $data->toJson($flags | static::REQUIRED_FLAGS);
}
if ($data instanceof Arrayable && ! ($data instanceof JsonSerializable)) {
$data = $data->toArray();
}
return json_encode($data, $flags | static::REQUIRED_FLAGS, $depth);
}
/**
* Convert the given JSON to a JavaScript expression.
*
* @param string $json
* @param int $flags
* @return string
*
* @throws \JsonException
*/
protected function convertJsonToJavaScriptExpression($json, $flags = 0)
{
if ($json === '[]' || $json === '{}') {
return $json;
}
if (Str::startsWith($json, ['"', '{', '['])) {
return "JSON.parse('".substr(json_encode($json, $flags | static::REQUIRED_FLAGS), 1, -1)."')";
}
return $json;
}
/**
* Get the string representation of the data for use in HTML.
*
* @return string
*/
public function toHtml()
{
return $this->js;
}
/**
* Get the string representation of the data for use in HTML.
*
* @return string
*/
public function __toString()
{
return $this->toHtml();
}
}

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.

View File

@@ -0,0 +1,284 @@
<?php
namespace Illuminate\Support;
use RuntimeException;
class Lottery
{
/**
* The number of expected wins.
*
* @var int|float
*/
protected $chances;
/**
* The number of potential opportunities to win.
*
* @var int|null
*/
protected $outOf;
/**
* The winning callback.
*
* @var null|callable
*/
protected $winner;
/**
* The losing callback.
*
* @var null|callable
*/
protected $loser;
/**
* The factory that should be used to generate results.
*
* @var callable|null
*/
protected static $resultFactory;
/**
* Create a new Lottery instance.
*
* @param int|float $chances
* @param int<1, max>|null $outOf
*/
public function __construct($chances, $outOf = null)
{
if ($outOf === null && is_float($chances) && $chances > 1) {
throw new RuntimeException('Float must not be greater than 1.');
}
if ($outOf !== null && $outOf < 1) {
throw new RuntimeException('Lottery "out of" value must be greater than or equal to 1.');
}
$this->chances = $chances;
$this->outOf = $outOf;
}
/**
* Create a new Lottery instance.
*
* @param int|float $chances
* @param int|null $outOf
* @return static
*/
public static function odds($chances, $outOf = null)
{
return new static($chances, $outOf);
}
/**
* Set the winner callback.
*
* @param callable $callback
* @return $this
*/
public function winner($callback)
{
$this->winner = $callback;
return $this;
}
/**
* Set the loser callback.
*
* @param callable $callback
* @return $this
*/
public function loser($callback)
{
$this->loser = $callback;
return $this;
}
/**
* Run the lottery.
*
* @param mixed ...$args
* @return mixed
*/
public function __invoke(...$args)
{
return $this->runCallback(...$args);
}
/**
* Run the lottery.
*
* @param null|int $times
* @return mixed
*/
public function choose($times = null)
{
if ($times === null) {
return $this->runCallback();
}
$results = [];
for ($i = 0; $i < $times; $i++) {
$results[] = $this->runCallback();
}
return $results;
}
/**
* Run the winner or loser callback, randomly.
*
* @param mixed ...$args
* @return callable
*/
protected function runCallback(...$args)
{
return $this->wins()
? ($this->winner ?? fn () => true)(...$args)
: ($this->loser ?? fn () => false)(...$args);
}
/**
* Determine if the lottery "wins" or "loses".
*
* @return bool
*/
protected function wins()
{
return static::resultFactory()($this->chances, $this->outOf);
}
/**
* The factory that determines the lottery result.
*
* @return callable
*/
protected static function resultFactory()
{
return static::$resultFactory ?? fn ($chances, $outOf) => $outOf === null
? random_int(0, PHP_INT_MAX) / PHP_INT_MAX <= $chances
: random_int(1, $outOf) <= $chances;
}
/**
* Force the lottery to always result in a win.
*
* @param callable|null $callback
* @return void
*/
public static function alwaysWin($callback = null)
{
self::setResultFactory(fn () => true);
if ($callback === null) {
return;
}
$callback();
static::determineResultNormally();
}
/**
* Force the lottery to always result in a lose.
*
* @param callable|null $callback
* @return void
*/
public static function alwaysLose($callback = null)
{
self::setResultFactory(fn () => false);
if ($callback === null) {
return;
}
$callback();
static::determineResultNormally();
}
/**
* Set the sequence that will be used to determine lottery results.
*
* @param array $sequence
* @param callable|null $whenMissing
* @return void
*/
public static function fix($sequence, $whenMissing = null)
{
static::forceResultWithSequence($sequence, $whenMissing);
}
/**
* Set the sequence that will be used to determine lottery results.
*
* @param array $sequence
* @param callable|null $whenMissing
* @return void
*/
public static function forceResultWithSequence($sequence, $whenMissing = null)
{
$next = 0;
$whenMissing ??= function ($chances, $outOf) use (&$next) {
$factoryCache = static::$resultFactory;
static::$resultFactory = null;
$result = static::resultFactory()($chances, $outOf);
static::$resultFactory = $factoryCache;
$next++;
return $result;
};
static::setResultFactory(function ($chances, $outOf) use (&$next, $sequence, $whenMissing) {
if (array_key_exists($next, $sequence)) {
return $sequence[$next++];
}
return $whenMissing($chances, $outOf);
});
}
/**
* Indicate that the lottery results should be determined normally.
*
* @return void
*/
public static function determineResultsNormally()
{
static::determineResultNormally();
}
/**
* Indicate that the lottery results should be determined normally.
*
* @return void
*/
public static function determineResultNormally()
{
static::$resultFactory = null;
}
/**
* Set the factory that should be used to determine the lottery results.
*
* @param callable $factory
* @return void
*/
public static function setResultFactory($factory)
{
self::$resultFactory = $factory;
}
}

188
plugins/vendor/illuminate/support/Manager.php vendored Executable file
View File

@@ -0,0 +1,188 @@
<?php
namespace Illuminate\Support;
use Closure;
use Illuminate\Contracts\Container\Container;
use InvalidArgumentException;
abstract class Manager
{
/**
* The container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* The configuration repository instance.
*
* @var \Illuminate\Contracts\Config\Repository
*/
protected $config;
/**
* The registered custom driver creators.
*
* @var array
*/
protected $customCreators = [];
/**
* The array of created "drivers".
*
* @var array
*/
protected $drivers = [];
/**
* Create a new manager instance.
*
* @param \Illuminate\Contracts\Container\Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
$this->config = $container->make('config');
}
/**
* Get the default driver name.
*
* @return string
*/
abstract public function getDefaultDriver();
/**
* Get a driver instance.
*
* @param string|null $driver
* @return mixed
*
* @throws \InvalidArgumentException
*/
public function driver($driver = null)
{
$driver = $driver ?: $this->getDefaultDriver();
if (is_null($driver)) {
throw new InvalidArgumentException(sprintf(
'Unable to resolve NULL driver for [%s].', static::class
));
}
// If the given driver has not been created before, we will create the instances
// here and cache it so we can return it next time very quickly. If there is
// already a driver created by this name, we'll just return that instance.
return $this->drivers[$driver] ??= $this->createDriver($driver);
}
/**
* Create a new driver instance.
*
* @param string $driver
* @return mixed
*
* @throws \InvalidArgumentException
*/
protected function createDriver($driver)
{
// First, we will determine if a custom driver creator exists for the given driver and
// if it does not we will check for a creator method for the driver. Custom creator
// callbacks allow developers to build their own "drivers" easily using Closures.
if (isset($this->customCreators[$driver])) {
return $this->callCustomCreator($driver);
}
$method = 'create'.Str::studly($driver).'Driver';
if (method_exists($this, $method)) {
return $this->$method();
}
throw new InvalidArgumentException("Driver [$driver] not supported.");
}
/**
* Call a custom driver creator.
*
* @param string $driver
* @return mixed
*/
protected function callCustomCreator($driver)
{
return $this->customCreators[$driver]($this->container);
}
/**
* Register a custom driver creator Closure.
*
* @param string $driver
* @param \Closure $callback
* @return $this
*/
public function extend($driver, Closure $callback)
{
$this->customCreators[$driver] = $callback;
return $this;
}
/**
* Get all of the created "drivers".
*
* @return array
*/
public function getDrivers()
{
return $this->drivers;
}
/**
* Get the container instance used by the manager.
*
* @return \Illuminate\Contracts\Container\Container
*/
public function getContainer()
{
return $this->container;
}
/**
* Set the container instance used by the manager.
*
* @param \Illuminate\Contracts\Container\Container $container
* @return $this
*/
public function setContainer(Container $container)
{
$this->container = $container;
return $this;
}
/**
* Forget all of the resolved driver instances.
*
* @return $this
*/
public function forgetDrivers()
{
$this->drivers = [];
return $this;
}
/**
* Dynamically call the default driver instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->driver()->$method(...$parameters);
}
}

View File

@@ -0,0 +1,455 @@
<?php
namespace Illuminate\Support;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\MessageBag as MessageBagContract;
use Illuminate\Contracts\Support\MessageProvider;
use JsonSerializable;
use Stringable;
class MessageBag implements Jsonable, JsonSerializable, MessageBagContract, MessageProvider, Stringable
{
/**
* All of the registered messages.
*
* @var array<string, array<string>>
*/
protected $messages = [];
/**
* Default format for message output.
*
* @var string
*/
protected $format = ':message';
/**
* Create a new message bag instance.
*
* @param array<string, Arrayable|string|array<string>> $messages
*/
public function __construct(array $messages = [])
{
foreach ($messages as $key => $value) {
$value = $value instanceof Arrayable ? $value->toArray() : (array) $value;
$this->messages[$key] = array_unique($value);
}
}
/**
* Get the keys present in the message bag.
*
* @return array<string>
*/
public function keys()
{
return array_keys($this->messages);
}
/**
* Add a message to the message bag.
*
* @param string $key
* @param string $message
* @return $this
*/
public function add($key, $message)
{
if ($this->isUnique($key, $message)) {
$this->messages[$key][] = $message;
}
return $this;
}
/**
* Add a message to the message bag if the given conditional is "true".
*
* @param bool $boolean
* @param string $key
* @param string $message
* @return $this
*/
public function addIf($boolean, $key, $message)
{
return $boolean ? $this->add($key, $message) : $this;
}
/**
* Determine if a key and message combination already exists.
*
* @param string $key
* @param string $message
* @return bool
*/
protected function isUnique($key, $message)
{
$messages = (array) $this->messages;
return ! isset($messages[$key]) || ! in_array($message, $messages[$key]);
}
/**
* Merge a new array of messages into the message bag.
*
* @param \Illuminate\Contracts\Support\MessageProvider|array<string, array<string>> $messages
* @return $this
*/
public function merge($messages)
{
if ($messages instanceof MessageProvider) {
$messages = $messages->getMessageBag()->getMessages();
}
$this->messages = array_merge_recursive($this->messages, $messages);
return $this;
}
/**
* Determine if messages exist for all of the given keys.
*
* @param array|string|null $key
* @return bool
*/
public function has($key)
{
if ($this->isEmpty()) {
return false;
}
if (is_null($key)) {
return $this->any();
}
$keys = is_array($key) ? $key : func_get_args();
foreach ($keys as $key) {
if ($this->first($key) === '') {
return false;
}
}
return true;
}
/**
* Determine if messages exist for any of the given keys.
*
* @param array|string|null $keys
* @return bool
*/
public function hasAny($keys = [])
{
if ($this->isEmpty()) {
return false;
}
$keys = is_array($keys) ? $keys : func_get_args();
foreach ($keys as $key) {
if ($this->has($key)) {
return true;
}
}
return false;
}
/**
* Determine if messages don't exist for all of the given keys.
*
* @param array|string|null $key
* @return bool
*/
public function missing($key)
{
$keys = is_array($key) ? $key : func_get_args();
return ! $this->hasAny($keys);
}
/**
* Get the first message from the message bag for a given key.
*
* @param string|null $key
* @param string|null $format
* @return string
*/
public function first($key = null, $format = null)
{
$messages = is_null($key) ? $this->all($format) : $this->get($key, $format);
$firstMessage = Arr::first($messages, null, '');
return is_array($firstMessage) ? Arr::first($firstMessage) : $firstMessage;
}
/**
* Get all of the messages from the message bag for a given key.
*
* @param string $key
* @param string|null $format
* @return array<string>|array<string, array<string>>
*/
public function get($key, $format = null)
{
// If the message exists in the message bag, we will transform it and return
// the message. Otherwise, we will check if the key is implicit & collect
// all the messages that match the given key and output it as an array.
if (array_key_exists($key, $this->messages)) {
return $this->transform(
$this->messages[$key], $this->checkFormat($format), $key
);
}
if (str_contains($key, '*')) {
return $this->getMessagesForWildcardKey($key, $format);
}
return [];
}
/**
* Get the messages for a wildcard key.
*
* @param string $key
* @param string|null $format
* @return array<string, array<string>>
*/
protected function getMessagesForWildcardKey($key, $format)
{
return (new Collection($this->messages))
->filter(fn ($messages, $messageKey) => Str::is($key, $messageKey))
->map(function ($messages, $messageKey) use ($format) {
return $this->transform($messages, $this->checkFormat($format), $messageKey);
})
->all();
}
/**
* Get all of the messages for every key in the message bag.
*
* @param string|null $format
* @return array<string>
*/
public function all($format = null)
{
$format = $this->checkFormat($format);
$all = [];
foreach ($this->messages as $key => $messages) {
$all = array_merge($all, $this->transform($messages, $format, $key));
}
return $all;
}
/**
* Get all of the unique messages for every key in the message bag.
*
* @param string|null $format
* @return array
*/
public function unique($format = null)
{
return array_unique($this->all($format));
}
/**
* Remove a message from the message bag.
*
* @param string $key
* @return $this
*/
public function forget($key)
{
unset($this->messages[$key]);
return $this;
}
/**
* Format an array of messages.
*
* @param array<string> $messages
* @param string $format
* @param string $messageKey
* @return array<string>
*/
protected function transform($messages, $format, $messageKey)
{
if ($format == ':message') {
return (array) $messages;
}
return (new Collection((array) $messages))
->map(function ($message) use ($format, $messageKey) {
// We will simply spin through the given messages and transform each one
// replacing the :message place holder with the real message allowing
// the messages to be easily formatted to each developer's desires.
return str_replace([':message', ':key'], [$message, $messageKey], $format);
})->all();
}
/**
* Get the appropriate format based on the given format.
*
* @param string $format
* @return string
*/
protected function checkFormat($format)
{
return $format ?: $this->format;
}
/**
* Get the raw messages in the message bag.
*
* @return array<string, array<string>>
*/
public function messages()
{
return $this->messages;
}
/**
* Get the raw messages in the message bag.
*
* @return array<string, array<string>>
*/
public function getMessages()
{
return $this->messages();
}
/**
* Get the messages for the instance.
*
* @return \Illuminate\Support\MessageBag
*/
public function getMessageBag()
{
return $this;
}
/**
* Get the default message format.
*
* @return string
*/
public function getFormat()
{
return $this->format;
}
/**
* Set the default message format.
*
* @param string $format
* @return \Illuminate\Support\MessageBag
*/
public function setFormat($format = ':message')
{
$this->format = $format;
return $this;
}
/**
* Determine if the message bag has any messages.
*
* @return bool
*/
public function isEmpty()
{
return ! $this->any();
}
/**
* Determine if the message bag has any messages.
*
* @return bool
*/
public function isNotEmpty()
{
return $this->any();
}
/**
* Determine if the message bag has any messages.
*
* @return bool
*/
public function any()
{
return $this->count() > 0;
}
/**
* Get the number of messages in the message bag.
*
* @return int
*/
public function count(): int
{
return count($this->messages, COUNT_RECURSIVE) - count($this->messages);
}
/**
* Get the instance as an array.
*
* @return array
*/
public function toArray()
{
return $this->getMessages();
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* Convert the object to its JSON representation.
*
* @param int $options
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}
/**
* Convert the object to pretty print formatted JSON.
*
* @params int $options
*
* @return string
*/
public function toPrettyJson(int $options = 0)
{
return $this->toJson(JSON_PRETTY_PRINT | $options);
}
/**
* Convert the message bag to its string representation.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
}

View File

@@ -0,0 +1,230 @@
<?php
namespace Illuminate\Support;
use Closure;
use InvalidArgumentException;
use RuntimeException;
abstract class MultipleInstanceManager
{
/**
* The application instance.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* The configuration repository instance.
*
* @var \Illuminate\Contracts\Config\Repository
*/
protected $config;
/**
* The array of resolved instances.
*
* @var array
*/
protected $instances = [];
/**
* The registered custom instance creators.
*
* @var array
*/
protected $customCreators = [];
/**
* The key name of the "driver" equivalent configuration option.
*
* @var string
*/
protected $driverKey = 'driver';
/**
* Create a new manager instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
*/
public function __construct($app)
{
$this->app = $app;
$this->config = $app->make('config');
}
/**
* Get the default instance name.
*
* @return string
*/
abstract public function getDefaultInstance();
/**
* Set the default instance name.
*
* @param string $name
* @return void
*/
abstract public function setDefaultInstance($name);
/**
* Get the instance specific configuration.
*
* @param string $name
* @return array
*/
abstract public function getInstanceConfig($name);
/**
* Get an instance by name.
*
* @param string|null $name
* @return mixed
*/
public function instance($name = null)
{
$name = $name ?: $this->getDefaultInstance();
return $this->instances[$name] = $this->get($name);
}
/**
* Attempt to get an instance from the local cache.
*
* @param string $name
* @return mixed
*/
protected function get($name)
{
return $this->instances[$name] ?? $this->resolve($name);
}
/**
* Resolve the given instance.
*
* @param string $name
* @return mixed
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
protected function resolve($name)
{
$config = $this->getInstanceConfig($name);
if (is_null($config)) {
throw new InvalidArgumentException("Instance [{$name}] is not defined.");
}
if (! array_key_exists($this->driverKey, $config)) {
throw new RuntimeException("Instance [{$name}] does not specify a {$this->driverKey}.");
}
$driverName = $config[$this->driverKey];
if (isset($this->customCreators[$driverName])) {
return $this->callCustomCreator($config);
} else {
$createMethod = 'create'.ucfirst($driverName).ucfirst($this->driverKey);
if (method_exists($this, $createMethod)) {
return $this->{$createMethod}($config);
}
$createMethod = 'create'.Str::studly($driverName).ucfirst($this->driverKey);
if (method_exists($this, $createMethod)) {
return $this->{$createMethod}($config);
}
throw new InvalidArgumentException("Instance {$this->driverKey} [{$config[$this->driverKey]}] is not supported.");
}
}
/**
* Call a custom instance creator.
*
* @param array $config
* @return mixed
*/
protected function callCustomCreator(array $config)
{
return $this->customCreators[$config[$this->driverKey]]($this->app, $config);
}
/**
* Unset the given instances.
*
* @param array|string|null $name
* @return $this
*/
public function forgetInstance($name = null)
{
$name ??= $this->getDefaultInstance();
foreach ((array) $name as $instanceName) {
if (isset($this->instances[$instanceName])) {
unset($this->instances[$instanceName]);
}
}
return $this;
}
/**
* Disconnect the given instance and remove from local cache.
*
* @param string|null $name
* @return void
*/
public function purge($name = null)
{
$name ??= $this->getDefaultInstance();
unset($this->instances[$name]);
}
/**
* Register a custom instance creator Closure.
*
* @param string $name
* @param \Closure $callback
*
* @param-closure-this $this $callback
*
* @return $this
*/
public function extend($name, Closure $callback)
{
$this->customCreators[$name] = $callback->bindTo($this, $this);
return $this;
}
/**
* Set the application instance used by the manager.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return $this
*/
public function setApplication($app)
{
$this->app = $app;
return $this;
}
/**
* Dynamically call the default instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->instance()->$method(...$parameters);
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace Illuminate\Support;
class NamespacedItemResolver
{
/**
* A cache of the parsed items.
*
* @var array
*/
protected $parsed = [];
/**
* Parse a key into namespace, group, and item.
*
* @param string $key
* @return array
*/
public function parseKey($key)
{
// If we've already parsed the given key, we'll return the cached version we
// already have, as this will save us some processing. We cache off every
// key we parse so we can quickly return it on all subsequent requests.
if (isset($this->parsed[$key])) {
return $this->parsed[$key];
}
// If the key does not contain a double colon, it means the key is not in a
// namespace, and is just a regular configuration item. Namespaces are a
// tool for organizing configuration items for things such as modules.
if (! str_contains($key, '::')) {
$segments = explode('.', $key);
$parsed = $this->parseBasicSegments($segments);
} else {
$parsed = $this->parseNamespacedSegments($key);
}
// Once we have the parsed array of this key's elements, such as its groups
// and namespace, we will cache each array inside a simple list that has
// the key and the parsed array for quick look-ups for later requests.
return $this->parsed[$key] = $parsed;
}
/**
* Parse an array of basic segments.
*
* @param array $segments
* @return array
*/
protected function parseBasicSegments(array $segments)
{
// The first segment in a basic array will always be the group, so we can go
// ahead and grab that segment. If there is only one total segment we are
// just pulling an entire group out of the array and not a single item.
$group = $segments[0];
// If there is more than one segment in this group, it means we are pulling
// a specific item out of a group and will need to return this item name
// as well as the group so we know which item to pull from the arrays.
$item = count($segments) === 1
? null
: implode('.', array_slice($segments, 1));
return [null, $group, $item];
}
/**
* Parse an array of namespaced segments.
*
* @param string $key
* @return array
*/
protected function parseNamespacedSegments($key)
{
[$namespace, $item] = explode('::', $key);
// First we'll just explode the first segment to get the namespace and group
// since the item should be in the remaining segments. Once we have these
// two pieces of data we can proceed with parsing out the item's value.
$itemSegments = explode('.', $item);
$groupAndItem = array_slice(
$this->parseBasicSegments($itemSegments), 1
);
return array_merge([$namespace], $groupAndItem);
}
/**
* Set the parsed value of a key.
*
* @param string $key
* @param array $parsed
* @return void
*/
public function setParsedKey($key, $parsed)
{
$this->parsed[$key] = $parsed;
}
/**
* Flush the cache of parsed keys.
*
* @return void
*/
public function flushParsedKeys()
{
$this->parsed = [];
}
}

View File

@@ -0,0 +1,442 @@
<?php
namespace Illuminate\Support;
use Illuminate\Support\Traits\Macroable;
use NumberFormatter;
use RuntimeException;
class Number
{
use Macroable;
/**
* The current default locale.
*
* @var string
*/
protected static $locale = 'en';
/**
* The current default currency.
*
* @var string
*/
protected static $currency = 'USD';
/**
* Format the given number according to the current locale.
*
* @param int|float $number
* @param int|null $precision
* @param int|null $maxPrecision
* @param string|null $locale
* @return string|false
*/
public static function format(int|float $number, ?int $precision = null, ?int $maxPrecision = null, ?string $locale = null)
{
static::ensureIntlExtensionIsInstalled();
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::DECIMAL);
if (! is_null($maxPrecision)) {
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $maxPrecision);
} elseif (! is_null($precision)) {
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
}
return $formatter->format($number);
}
/**
* Parse the given string according to the specified format type.
*
* @param string $string
* @param int|null $type
* @param string|null $locale
* @return int|float|false
*/
public static function parse(string $string, ?int $type = NumberFormatter::TYPE_DOUBLE, ?string $locale = null): int|float
{
static::ensureIntlExtensionIsInstalled();
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::DECIMAL);
return $formatter->parse($string, $type);
}
/**
* Parse a string into an integer according to the specified locale.
*
* @param string $string
* @param string|null $locale
* @return int|false
*/
public static function parseInt(string $string, ?string $locale = null): int
{
return self::parse($string, NumberFormatter::TYPE_INT32, $locale);
}
/**
* Parse a string into a float according to the specified locale.
*
* @param string $string
* @param string|null $locale
* @return float|false
*/
public static function parseFloat(string $string, ?string $locale = null): float
{
return self::parse($string, NumberFormatter::TYPE_DOUBLE, $locale);
}
/**
* Spell out the given number in the given locale.
*
* @param int|float $number
* @param string|null $locale
* @param int|null $after
* @param int|null $until
* @return string
*/
public static function spell(int|float $number, ?string $locale = null, ?int $after = null, ?int $until = null)
{
static::ensureIntlExtensionIsInstalled();
if (! is_null($after) && $number <= $after) {
return static::format($number, locale: $locale);
}
if (! is_null($until) && $number >= $until) {
return static::format($number, locale: $locale);
}
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT);
return $formatter->format($number);
}
/**
* Convert the given number to ordinal form.
*
* @param int|float $number
* @param string|null $locale
* @return string
*/
public static function ordinal(int|float $number, ?string $locale = null)
{
static::ensureIntlExtensionIsInstalled();
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::ORDINAL);
return $formatter->format($number);
}
/**
* Spell out the given number in the given locale in ordinal form.
*
* @param int|float $number
* @param string|null $locale
* @return string
*/
public static function spellOrdinal(int|float $number, ?string $locale = null)
{
static::ensureIntlExtensionIsInstalled();
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT);
$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, '%spellout-ordinal');
return $formatter->format($number);
}
/**
* Convert the given number to its percentage equivalent.
*
* @param int|float $number
* @param int $precision
* @param int|null $maxPrecision
* @param string|null $locale
* @return string|false
*/
public static function percentage(int|float $number, int $precision = 0, ?int $maxPrecision = null, ?string $locale = null)
{
static::ensureIntlExtensionIsInstalled();
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::PERCENT);
if (! is_null($maxPrecision)) {
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $maxPrecision);
} else {
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
}
return $formatter->format($number / 100);
}
/**
* Convert the given number to its currency equivalent.
*
* @param int|float $number
* @param string $in
* @param string|null $locale
* @param int|null $precision
* @return string|false
*/
public static function currency(int|float $number, string $in = '', ?string $locale = null, ?int $precision = null)
{
static::ensureIntlExtensionIsInstalled();
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::CURRENCY);
if (! is_null($precision)) {
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
}
return $formatter->formatCurrency($number, ! empty($in) ? $in : static::$currency);
}
/**
* Convert the given number to its file size equivalent.
*
* @param int|float $bytes
* @param int $precision
* @param int|null $maxPrecision
* @return string
*/
public static function fileSize(int|float $bytes, int $precision = 0, ?int $maxPrecision = null)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$unitCount = count($units);
for ($i = 0; ($bytes / 1024) > 0.9 && ($i < $unitCount - 1); $i++) {
$bytes /= 1024;
}
return sprintf('%s %s', static::format($bytes, $precision, $maxPrecision), $units[$i]);
}
/**
* Convert the number to its human-readable equivalent.
*
* @param int|float $number
* @param int $precision
* @param int|null $maxPrecision
* @return bool|string
*/
public static function abbreviate(int|float $number, int $precision = 0, ?int $maxPrecision = null)
{
return static::forHumans($number, $precision, $maxPrecision, abbreviate: true);
}
/**
* Convert the number to its human-readable equivalent.
*
* @param int|float $number
* @param int $precision
* @param int|null $maxPrecision
* @param bool $abbreviate
* @return string|false
*/
public static function forHumans(int|float $number, int $precision = 0, ?int $maxPrecision = null, bool $abbreviate = false)
{
return static::summarize($number, $precision, $maxPrecision, $abbreviate ? [
3 => 'K',
6 => 'M',
9 => 'B',
12 => 'T',
15 => 'Q',
] : [
3 => ' thousand',
6 => ' million',
9 => ' billion',
12 => ' trillion',
15 => ' quadrillion',
]);
}
/**
* Convert the number to its human-readable equivalent.
*
* @param int|float $number
* @param int $precision
* @param int|null $maxPrecision
* @param array $units
* @return string|false
*/
protected static function summarize(int|float $number, int $precision = 0, ?int $maxPrecision = null, array $units = [])
{
if (empty($units)) {
$units = [
3 => 'K',
6 => 'M',
9 => 'B',
12 => 'T',
15 => 'Q',
];
}
switch (true) {
case floatval($number) === 0.0:
return $precision > 0 ? static::format(0, $precision, $maxPrecision) : '0';
case $number < 0:
return sprintf('-%s', static::summarize(abs($number), $precision, $maxPrecision, $units));
case $number >= 1e15:
return sprintf('%s'.end($units), static::summarize($number / 1e15, $precision, $maxPrecision, $units));
}
$numberExponent = floor(log10($number));
$displayExponent = $numberExponent - ($numberExponent % 3);
$number /= pow(10, $displayExponent);
return trim(sprintf('%s%s', static::format($number, $precision, $maxPrecision), $units[$displayExponent] ?? ''));
}
/**
* Clamp the given number between the given minimum and maximum.
*
* @param int|float $number
* @param int|float $min
* @param int|float $max
* @return int|float
*/
public static function clamp(int|float $number, int|float $min, int|float $max)
{
return min(max($number, $min), $max);
}
/**
* Split the given number into pairs of min/max values.
*
* @param int|float $to
* @param int|float $by
* @param int|float $start
* @param int|float $offset
* @return array
*/
public static function pairs(int|float $to, int|float $by, int|float $start = 0, int|float $offset = 1)
{
$output = [];
for ($lower = $start; $lower < $to; $lower += $by) {
$upper = $lower + $by - $offset;
if ($upper > $to) {
$upper = $to;
}
$output[] = [$lower, $upper];
}
return $output;
}
/**
* Remove any trailing zero digits after the decimal point of the given number.
*
* @param int|float $number
* @return int|float
*/
public static function trim(int|float $number)
{
return json_decode(json_encode($number));
}
/**
* Execute the given callback using the given locale.
*
* @param string $locale
* @param callable $callback
* @return mixed
*/
public static function withLocale(string $locale, callable $callback)
{
$previousLocale = static::$locale;
static::useLocale($locale);
try {
return $callback();
} finally {
static::useLocale($previousLocale);
}
}
/**
* Execute the given callback using the given currency.
*
* @param string $currency
* @param callable $callback
* @return mixed
*/
public static function withCurrency(string $currency, callable $callback)
{
$previousCurrency = static::$currency;
static::useCurrency($currency);
try {
return $callback();
} finally {
static::useCurrency($previousCurrency);
}
}
/**
* Set the default locale.
*
* @param string $locale
* @return void
*/
public static function useLocale(string $locale)
{
static::$locale = $locale;
}
/**
* Set the default currency.
*
* @param string $currency
* @return void
*/
public static function useCurrency(string $currency)
{
static::$currency = $currency;
}
/**
* Get the default locale.
*
* @return string
*/
public static function defaultLocale()
{
return static::$locale;
}
/**
* Get the default currency.
*
* @return string
*/
public static function defaultCurrency()
{
return static::$currency;
}
/**
* Ensure the "intl" PHP extension is installed.
*
* @return void
*
* @throws \RuntimeException
*/
protected static function ensureIntlExtensionIsInstalled()
{
if (! extension_loaded('intl')) {
$method = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];
throw new RuntimeException('The "intl" PHP extension is required to use the ['.$method.'] method.');
}
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Illuminate\Support;
use WeakMap;
class Once
{
/**
* The current globally used instance.
*
* @var static|null
*/
protected static ?self $instance = null;
/**
* Indicates if the once instance is enabled.
*
* @var bool
*/
protected static bool $enabled = true;
/**
* Create a new once instance.
*
* @param \WeakMap<object, array<string, mixed>> $values
*/
protected function __construct(protected WeakMap $values)
{
//
}
/**
* Create a new once instance.
*
* @return static
*/
public static function instance()
{
return static::$instance ??= new static(new WeakMap);
}
/**
* Get the value of the given onceable.
*
* @param Onceable $onceable
* @return mixed
*/
public function value(Onceable $onceable)
{
if (! static::$enabled) {
return call_user_func($onceable->callable);
}
$object = $onceable->object ?: $this;
$hash = $onceable->hash;
if (! isset($this->values[$object])) {
$this->values[$object] = [];
}
if (array_key_exists($hash, $this->values[$object])) {
return $this->values[$object][$hash];
}
return $this->values[$object][$hash] = call_user_func($onceable->callable);
}
/**
* Re-enable the once instance if it was disabled.
*
* @return void
*/
public static function enable()
{
static::$enabled = true;
}
/**
* Disable the once instance.
*
* @return void
*/
public static function disable()
{
static::$enabled = false;
}
/**
* Flush the once instance.
*
* @return void
*/
public static function flush()
{
static::$instance = null;
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace Illuminate\Support;
use Closure;
use Illuminate\Contracts\Support\HasOnceHash;
use Laravel\SerializableClosure\Support\ReflectionClosure;
class Onceable
{
/**
* Create a new onceable instance.
*
* @param string $hash
* @param object|null $object
* @param callable $callable
*/
public function __construct(
public string $hash,
public ?object $object,
public $callable,
) {
//
}
/**
* Tries to create a new onceable instance from the given trace.
*
* @param array<int, array<string, mixed>> $trace
* @return static|null
*/
public static function tryFromTrace(array $trace, callable $callable)
{
if (! is_null($hash = static::hashFromTrace($trace, $callable))) {
$object = static::objectFromTrace($trace);
return new static($hash, $object, $callable);
}
}
/**
* Computes the object of the onceable from the given trace, if any.
*
* @param array<int, array<string, mixed>> $trace
* @return object|null
*/
protected static function objectFromTrace(array $trace)
{
return $trace[1]['object'] ?? null;
}
/**
* Computes the hash of the onceable from the given trace.
*
* @param array<int, array<string, mixed>> $trace
* @return string|null
*/
protected static function hashFromTrace(array $trace, callable $callable)
{
if (str_contains($trace[0]['file'] ?? '', 'eval()\'d code')) {
return null;
}
$uses = array_map(
static function (mixed $argument) {
if ($argument instanceof HasOnceHash) {
return $argument->onceHash();
}
if (is_object($argument)) {
return spl_object_hash($argument);
}
return $argument;
},
$callable instanceof Closure ? (new ReflectionClosure($callable))->getClosureUsedVariables() : [],
);
$class = $callable instanceof Closure ? (new ReflectionClosure($callable))->getClosureCalledClass()?->getName() : null;
$class ??= isset($trace[1]['class']) ? $trace[1]['class'] : null;
return hash('xxh128', sprintf(
'%s@%s%s:%s (%s)',
$trace[0]['file'],
$class ? $class.'@' : '',
$trace[1]['function'],
$trace[0]['line'],
serialize($uses),
));
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Illuminate\Support;
use ArrayAccess;
use ArrayObject;
use Illuminate\Support\Traits\Macroable;
class Optional implements ArrayAccess
{
use Macroable {
__call as macroCall;
}
/**
* The underlying object.
*
* @var mixed
*/
protected $value;
/**
* Create a new optional instance.
*
* @param mixed $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* Dynamically access a property on the underlying object.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
if (is_object($this->value)) {
return $this->value->{$key} ?? null;
}
}
/**
* Dynamically check a property exists on the underlying object.
*
* @param mixed $name
* @return bool
*/
public function __isset($name)
{
if (is_object($this->value)) {
return isset($this->value->{$name});
}
if (is_array($this->value) || $this->value instanceof ArrayObject) {
return isset($this->value[$name]);
}
return false;
}
/**
* Determine if an item exists at an offset.
*
* @param mixed $key
* @return bool
*/
public function offsetExists($key): bool
{
return Arr::accessible($this->value) && Arr::exists($this->value, $key);
}
/**
* Get an item at a given offset.
*
* @param mixed $key
* @return mixed
*/
public function offsetGet($key): mixed
{
return Arr::get($this->value, $key);
}
/**
* Set the item at a given offset.
*
* @param mixed $key
* @param mixed $value
* @return void
*/
public function offsetSet($key, $value): void
{
if (Arr::accessible($this->value)) {
$this->value[$key] = $value;
}
}
/**
* Unset the item at a given offset.
*
* @param string $key
* @return void
*/
public function offsetUnset($key): void
{
if (Arr::accessible($this->value)) {
unset($this->value[$key]);
}
}
/**
* Dynamically pass a method to the underlying object.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if (is_object($this->value)) {
return $this->value->{$method}(...$parameters);
}
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace Illuminate\Support;
use Doctrine\Inflector\InflectorFactory;
class Pluralizer
{
/**
* The cached inflector instance.
*
* @var static
*/
protected static $inflector;
/**
* The language that should be used by the inflector.
*
* @var string
*/
protected static $language = 'english';
/**
* Uncountable non-nouns word forms.
*
* Contains words supported by Doctrine/Inflector/Rules/English/Uninflected.php
*
* @var string[]
*/
public static $uncountable = [
'recommended',
'related',
];
/**
* Get the plural form of an English word.
*
* @param string $value
* @param int|array|\Countable $count
* @return string
*/
public static function plural($value, $count = 2)
{
if (is_countable($count)) {
$count = count($count);
}
if ((int) abs($count) === 1 || static::uncountable($value) || preg_match('/^(.*)[A-Za-z0-9\x{0080}-\x{FFFF}]$/u', $value) == 0) {
return $value;
}
$plural = static::inflector()->pluralize($value);
return static::matchCase($plural, $value);
}
/**
* Get the singular form of an English word.
*
* @param string $value
* @return string
*/
public static function singular($value)
{
$singular = static::inflector()->singularize($value);
return static::matchCase($singular, $value);
}
/**
* Determine if the given value is uncountable.
*
* @param string $value
* @return bool
*/
protected static function uncountable($value)
{
return in_array(strtolower($value), static::$uncountable);
}
/**
* Attempt to match the case on two strings.
*
* @param string $value
* @param string $comparison
* @return string
*/
protected static function matchCase($value, $comparison)
{
$functions = ['mb_strtolower', 'mb_strtoupper', 'ucfirst', 'ucwords'];
foreach ($functions as $function) {
if ($function($comparison) === $comparison) {
return $function($value);
}
}
return $value;
}
/**
* Get the inflector instance.
*
* @return \Doctrine\Inflector\Inflector
*/
public static function inflector()
{
if (is_null(static::$inflector)) {
static::$inflector = InflectorFactory::createForLanguage(static::$language)->build();
}
return static::$inflector;
}
/**
* Specify the language that should be used by the inflector.
*
* @param string $language
* @return void
*/
public static function useLanguage(string $language)
{
static::$language = $language;
static::$inflector = null;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Illuminate\Support;
/**
* ProcessUtils is a bunch of utility methods.
*
* This class was originally copied from Symfony 3.
*/
class ProcessUtils
{
/**
* Escapes a string to be used as a shell argument.
*
* @param string $argument
* @return string
*/
public static function escapeArgument($argument)
{
// Fix for PHP bug #43784 escapeshellarg removes % from given string
// Fix for PHP bug #49446 escapeshellarg doesn't work on Windows
// @see https://bugs.php.net/bug.php?id=43784
// @see https://bugs.php.net/bug.php?id=49446
if ('\\' === DIRECTORY_SEPARATOR) {
if ($argument === '') {
return '""';
}
$escapedArgument = '';
$quote = false;
foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
if ($part === '"') {
$escapedArgument .= '\\"';
} elseif (self::isSurroundedBy($part, '%')) {
// Avoid environment variable expansion
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
} else {
// escape trailing backslash
if (str_ends_with($part, '\\')) {
$part .= '\\';
}
$quote = true;
$escapedArgument .= $part;
}
}
if ($quote) {
$escapedArgument = '"'.$escapedArgument.'"';
}
return $escapedArgument;
}
return "'".str_replace("'", "'\\''", $argument)."'";
}
/**
* Is the given string surrounded by the given character?
*
* @param string $arg
* @param string $char
* @return bool
*/
protected static function isSurroundedBy($arg, $char)
{
return strlen($arg) > 2 && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
}
}

View File

@@ -0,0 +1,211 @@
<?php
namespace Illuminate\Support;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionEnum;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionUnionType;
class Reflector
{
/**
* This is a PHP 7.4 compatible implementation of is_callable.
*
* @param mixed $var
* @param bool $syntaxOnly
* @return bool
*/
public static function isCallable($var, $syntaxOnly = false)
{
if (! is_array($var)) {
return is_callable($var, $syntaxOnly);
}
if (! isset($var[0], $var[1]) || ! is_string($var[1] ?? null)) {
return false;
}
if ($syntaxOnly &&
(is_string($var[0]) || is_object($var[0])) &&
is_string($var[1])) {
return true;
}
$class = is_object($var[0]) ? get_class($var[0]) : $var[0];
$method = $var[1];
if (! class_exists($class)) {
return false;
}
if (method_exists($class, $method)) {
return (new ReflectionMethod($class, $method))->isPublic();
}
if (is_object($var[0]) && method_exists($class, '__call')) {
return (new ReflectionMethod($class, '__call'))->isPublic();
}
if (! is_object($var[0]) && method_exists($class, '__callStatic')) {
return (new ReflectionMethod($class, '__callStatic'))->isPublic();
}
return false;
}
/**
* Get the specified class attribute, optionally following an inheritance chain.
*
* @template TAttribute of object
*
* @param object|class-string $objectOrClass
* @param class-string<TAttribute> $attribute
* @return TAttribute|null
*/
public static function getClassAttribute($objectOrClass, $attribute, $ascend = false)
{
return static::getClassAttributes($objectOrClass, $attribute, $ascend)->flatten()->first();
}
/**
* Get the specified class attribute(s), optionally following an inheritance chain.
*
* @template TTarget of object
* @template TAttribute of object
*
* @param TTarget|class-string<TTarget> $objectOrClass
* @param class-string<TAttribute> $attribute
* @return ($includeParents is true ? Collection<class-string<contravariant TTarget>, Collection<int, TAttribute>> : Collection<int, TAttribute>)
*/
public static function getClassAttributes($objectOrClass, $attribute, $includeParents = false)
{
$reflectionClass = new ReflectionClass($objectOrClass);
$attributes = [];
do {
$attributes[$reflectionClass->name] = new Collection(array_map(
fn (ReflectionAttribute $reflectionAttribute) => $reflectionAttribute->newInstance(),
$reflectionClass->getAttributes($attribute)
));
} while ($includeParents && false !== $reflectionClass = $reflectionClass->getParentClass());
return $includeParents ? new Collection($attributes) : array_first($attributes);
}
/**
* Get the class name of the given parameter's type, if possible.
*
* @param \ReflectionParameter $parameter
* @return string|null
*/
public static function getParameterClassName($parameter)
{
$type = $parameter->getType();
if (! $type instanceof ReflectionNamedType || $type->isBuiltin()) {
return;
}
return static::getTypeName($parameter, $type);
}
/**
* Get the class names of the given parameter's type, including union types.
*
* @param \ReflectionParameter $parameter
* @return array
*/
public static function getParameterClassNames($parameter)
{
$type = $parameter->getType();
if (! $type instanceof ReflectionUnionType) {
return array_filter([static::getParameterClassName($parameter)]);
}
$unionTypes = [];
foreach ($type->getTypes() as $listedType) {
if (! $listedType instanceof ReflectionNamedType || $listedType->isBuiltin()) {
continue;
}
$unionTypes[] = static::getTypeName($parameter, $listedType);
}
return array_filter($unionTypes);
}
/**
* Get the given type's class name.
*
* @param \ReflectionParameter $parameter
* @param \ReflectionNamedType $type
* @return string
*/
protected static function getTypeName($parameter, $type)
{
$name = $type->getName();
if (! is_null($class = $parameter->getDeclaringClass())) {
if ($name === 'self') {
return $class->getName();
}
if ($name === 'parent' && $parent = $class->getParentClass()) {
return $parent->getName();
}
}
return $name;
}
/**
* Determine if the parameter's type is a subclass of the given type.
*
* @param \ReflectionParameter $parameter
* @param string $className
* @return bool
*/
public static function isParameterSubclassOf($parameter, $className)
{
$paramClassName = static::getParameterClassName($parameter);
return $paramClassName
&& (class_exists($paramClassName) || interface_exists($paramClassName))
&& (new ReflectionClass($paramClassName))->isSubclassOf($className);
}
/**
* Determine if the parameter's type is a Backed Enum with a string backing type.
*
* @param \ReflectionParameter $parameter
* @return bool
*/
public static function isParameterBackedEnumWithStringBackingType($parameter)
{
if (! $parameter->getType() instanceof ReflectionNamedType) {
return false;
}
$backedEnumClass = $parameter->getType()?->getName();
if (is_null($backedEnumClass)) {
return false;
}
if (enum_exists($backedEnumClass)) {
$reflectionBackedEnum = new ReflectionEnum($backedEnumClass);
return $reflectionBackedEnum->isBacked()
&& $reflectionBackedEnum->getBackingType()->getName() == 'string';
}
return false;
}
}

View File

@@ -0,0 +1,583 @@
<?php
namespace Illuminate\Support;
use Closure;
use Illuminate\Console\Application as Artisan;
use Illuminate\Contracts\Foundation\CachesConfiguration;
use Illuminate\Contracts\Foundation\CachesRoutes;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Database\Eloquent\Factory as ModelFactory;
use Illuminate\View\Compilers\BladeCompiler;
/**
* @property array<string, string> $bindings All of the container bindings that should be registered.
* @property array<array-key, string> $singletons All of the singletons that should be registered.
*/
abstract class ServiceProvider
{
/**
* The application instance.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* All of the registered booting callbacks.
*
* @var array
*/
protected $bootingCallbacks = [];
/**
* All of the registered booted callbacks.
*
* @var array
*/
protected $bootedCallbacks = [];
/**
* The paths that should be published.
*
* @var array
*/
public static $publishes = [];
/**
* The paths that should be published by group.
*
* @var array
*/
public static $publishGroups = [];
/**
* The migration paths available for publishing.
*
* @var array
*/
protected static $publishableMigrationPaths = [];
/**
* Commands that should be run during the "optimize" command.
*
* @var array<string, string>
*/
public static array $optimizeCommands = [];
/**
* Commands that should be run during the "optimize:clear" command.
*
* @var array<string, string>
*/
public static array $optimizeClearCommands = [];
/**
* Create a new service provider instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
*/
public function __construct($app)
{
$this->app = $app;
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Register a booting callback to be run before the "boot" method is called.
*
* @param \Closure $callback
* @return void
*/
public function booting(Closure $callback)
{
$this->bootingCallbacks[] = $callback;
}
/**
* Register a booted callback to be run after the "boot" method is called.
*
* @param \Closure $callback
* @return void
*/
public function booted(Closure $callback)
{
$this->bootedCallbacks[] = $callback;
}
/**
* Call the registered booting callbacks.
*
* @return void
*/
public function callBootingCallbacks()
{
$index = 0;
while ($index < count($this->bootingCallbacks)) {
$this->app->call($this->bootingCallbacks[$index]);
$index++;
}
}
/**
* Call the registered booted callbacks.
*
* @return void
*/
public function callBootedCallbacks()
{
$index = 0;
while ($index < count($this->bootedCallbacks)) {
$this->app->call($this->bootedCallbacks[$index]);
$index++;
}
}
/**
* Merge the given configuration with the existing configuration.
*
* @param string $path
* @param string $key
* @return void
*/
protected function mergeConfigFrom($path, $key)
{
if (! ($this->app instanceof CachesConfiguration && $this->app->configurationIsCached())) {
$config = $this->app->make('config');
$config->set($key, array_merge(
require $path, $config->get($key, [])
));
}
}
/**
* Replace the given configuration with the existing configuration recursively.
*
* @param string $path
* @param string $key
* @return void
*/
protected function replaceConfigRecursivelyFrom($path, $key)
{
if (! ($this->app instanceof CachesConfiguration && $this->app->configurationIsCached())) {
$config = $this->app->make('config');
$config->set($key, array_replace_recursive(
require $path, $config->get($key, [])
));
}
}
/**
* Load the given routes file if routes are not already cached.
*
* @param string $path
* @return void
*/
protected function loadRoutesFrom($path)
{
if (! ($this->app instanceof CachesRoutes && $this->app->routesAreCached())) {
require $path;
}
}
/**
* Register a view file namespace.
*
* @param string|array $path
* @param string $namespace
* @return void
*/
protected function loadViewsFrom($path, $namespace)
{
$this->callAfterResolving('view', function ($view) use ($path, $namespace) {
if (isset($this->app->config['view']['paths']) &&
is_array($this->app->config['view']['paths'])) {
foreach ($this->app->config['view']['paths'] as $viewPath) {
if (is_dir($appPath = $viewPath.'/vendor/'.$namespace)) {
$view->addNamespace($namespace, $appPath);
}
}
}
$view->addNamespace($namespace, $path);
});
}
/**
* Register the given view components with a custom prefix.
*
* @param string $prefix
* @param array $components
* @return void
*/
protected function loadViewComponentsAs($prefix, array $components)
{
$this->callAfterResolving(BladeCompiler::class, function ($blade) use ($prefix, $components) {
foreach ($components as $alias => $component) {
$blade->component($component, is_string($alias) ? $alias : null, $prefix);
}
});
}
/**
* Register a translation file namespace or path.
*
* @param string $path
* @param string|null $namespace
* @return void
*/
protected function loadTranslationsFrom($path, $namespace = null)
{
$this->callAfterResolving('translator', fn ($translator) => is_null($namespace)
? $translator->addPath($path)
: $translator->addNamespace($namespace, $path));
}
/**
* Register a JSON translation file path.
*
* @param string $path
* @return void
*/
protected function loadJsonTranslationsFrom($path)
{
$this->callAfterResolving('translator', function ($translator) use ($path) {
$translator->addJsonPath($path);
});
}
/**
* Register database migration paths.
*
* @param array|string $paths
* @return void
*/
protected function loadMigrationsFrom($paths)
{
$this->callAfterResolving('migrator', function ($migrator) use ($paths) {
foreach ((array) $paths as $path) {
$migrator->path($path);
}
});
}
/**
* Register Eloquent model factory paths.
*
* @deprecated Will be removed in a future Laravel version.
*
* @param array|string $paths
* @return void
*/
protected function loadFactoriesFrom($paths)
{
$this->callAfterResolving(ModelFactory::class, function ($factory) use ($paths) {
foreach ((array) $paths as $path) {
$factory->load($path);
}
});
}
/**
* Setup an after resolving listener, or fire immediately if already resolved.
*
* @param string $name
* @param callable $callback
* @return void
*/
protected function callAfterResolving($name, $callback)
{
$this->app->afterResolving($name, $callback);
if ($this->app->resolved($name)) {
$callback($this->app->make($name), $this->app);
}
}
/**
* Register migration paths to be published by the publish command.
*
* @param array $paths
* @param mixed $groups
* @return void
*/
protected function publishesMigrations(array $paths, $groups = null)
{
$this->publishes($paths, $groups);
if ($this->app->config->get('database.migrations.update_date_on_publish', false)) {
static::$publishableMigrationPaths = array_unique(array_merge(static::$publishableMigrationPaths, array_keys($paths)));
}
}
/**
* Register paths to be published by the publish command.
*
* @param array $paths
* @param mixed $groups
* @return void
*/
protected function publishes(array $paths, $groups = null)
{
$this->ensurePublishArrayInitialized($class = static::class);
static::$publishes[$class] = array_merge(static::$publishes[$class], $paths);
foreach ((array) $groups as $group) {
$this->addPublishGroup($group, $paths);
}
}
/**
* Ensure the publish array for the service provider is initialized.
*
* @param string $class
* @return void
*/
protected function ensurePublishArrayInitialized($class)
{
if (! array_key_exists($class, static::$publishes)) {
static::$publishes[$class] = [];
}
}
/**
* Add a publish group / tag to the service provider.
*
* @param string $group
* @param array $paths
* @return void
*/
protected function addPublishGroup($group, $paths)
{
if (! array_key_exists($group, static::$publishGroups)) {
static::$publishGroups[$group] = [];
}
static::$publishGroups[$group] = array_merge(
static::$publishGroups[$group], $paths
);
}
/**
* Get the paths to publish.
*
* @param string|null $provider
* @param string|null $group
* @return array
*/
public static function pathsToPublish($provider = null, $group = null)
{
if (! is_null($paths = static::pathsForProviderOrGroup($provider, $group))) {
return $paths;
}
return (new Collection(static::$publishes))->reduce(function ($paths, $p) {
return array_merge($paths, $p);
}, []);
}
/**
* Get the paths for the provider or group (or both).
*
* @param string|null $provider
* @param string|null $group
* @return array
*/
protected static function pathsForProviderOrGroup($provider, $group)
{
if ($provider && $group) {
return static::pathsForProviderAndGroup($provider, $group);
} elseif ($group && array_key_exists($group, static::$publishGroups)) {
return static::$publishGroups[$group];
} elseif ($provider && array_key_exists($provider, static::$publishes)) {
return static::$publishes[$provider];
} elseif ($group || $provider) {
return [];
}
}
/**
* Get the paths for the provider and group.
*
* @param string $provider
* @param string $group
* @return array
*/
protected static function pathsForProviderAndGroup($provider, $group)
{
if (! empty(static::$publishes[$provider]) && ! empty(static::$publishGroups[$group])) {
return array_intersect_key(static::$publishes[$provider], static::$publishGroups[$group]);
}
return [];
}
/**
* Get the service providers available for publishing.
*
* @return array
*/
public static function publishableProviders()
{
return array_keys(static::$publishes);
}
/**
* Get the migration paths available for publishing.
*
* @return array
*/
public static function publishableMigrationPaths()
{
return static::$publishableMigrationPaths;
}
/**
* Get the groups available for publishing.
*
* @return array
*/
public static function publishableGroups()
{
return array_keys(static::$publishGroups);
}
/**
* Register the package's custom Artisan commands.
*
* @param mixed $commands
* @return void
*/
public function commands($commands)
{
$commands = is_array($commands) ? $commands : func_get_args();
Artisan::starting(function ($artisan) use ($commands) {
$artisan->resolveCommands($commands);
});
}
/**
* Register commands that should run on "optimize" or "optimize:clear".
*
* @param string|null $optimize
* @param string|null $clear
* @param string|null $key
* @return void
*/
protected function optimizes(?string $optimize = null, ?string $clear = null, ?string $key = null)
{
$key ??= (string) Str::of(get_class($this))
->classBasename()
->before('ServiceProvider')
->kebab()
->lower()
->trim();
if (empty($key)) {
$key = class_basename(get_class($this));
}
if ($optimize) {
static::$optimizeCommands[$key] = $optimize;
}
if ($clear) {
static::$optimizeClearCommands[$key] = $clear;
}
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [];
}
/**
* Get the events that trigger this service provider to register.
*
* @return array
*/
public function when()
{
return [];
}
/**
* Determine if the provider is deferred.
*
* @return bool
*/
public function isDeferred()
{
return $this instanceof DeferrableProvider;
}
/**
* Get the default providers for a Laravel application.
*
* @return \Illuminate\Support\DefaultProviders
*/
public static function defaultProviders()
{
return new DefaultProviders;
}
/**
* Add the given provider to the application's provider bootstrap file.
*
* @param string $provider
* @param string $path
* @return bool
*/
public static function addProviderToBootstrapFile(string $provider, ?string $path = null)
{
$path ??= app()->getBootstrapProvidersPath();
if (! file_exists($path)) {
return false;
}
if (function_exists('opcache_invalidate')) {
opcache_invalidate($path, true);
}
$providers = (new Collection(require $path))
->merge([$provider])
->unique()
->sort()
->values()
->map(fn ($p) => ' '.$p.'::class,')
->implode(PHP_EOL);
$content = '<?php
return [
'.$providers.'
];';
file_put_contents($path, $content.PHP_EOL);
return true;
}
}

View File

@@ -0,0 +1,551 @@
<?php
namespace Illuminate\Support;
use Carbon\CarbonInterval;
use Closure;
use DateInterval;
use Illuminate\Support\Traits\Macroable;
use PHPUnit\Framework\Assert as PHPUnit;
use RuntimeException;
class Sleep
{
use Macroable;
/**
* The fake sleep callbacks.
*
* @var array
*/
public static $fakeSleepCallbacks = [];
/**
* Keep Carbon's "now" in sync when sleeping.
*
* @var bool
*/
protected static $syncWithCarbon = false;
/**
* The total duration to sleep.
*
* @var \Carbon\CarbonInterval
*/
public $duration;
/**
* The callback that determines if sleeping should continue.
*
* @var \Closure
*/
public $while;
/**
* The pending duration to sleep.
*
* @var int|float|null
*/
protected $pending = null;
/**
* Indicates that all sleeping should be faked.
*
* @var bool
*/
protected static $fake = false;
/**
* The sequence of sleep durations encountered while faking.
*
* @var array<int, \Carbon\CarbonInterval>
*/
protected static $sequence = [];
/**
* Indicates if the instance should sleep.
*
* @var bool
*/
protected $shouldSleep = true;
/**
* Indicates if the instance already slept via `then()`.
*
* @var bool
*/
protected $alreadySlept = false;
/**
* Create a new class instance.
*
* @param int|float|\DateInterval $duration
*/
public function __construct($duration)
{
$this->duration($duration);
}
/**
* Sleep for the given duration.
*
* @param \DateInterval|int|float $duration
* @return static
*/
public static function for($duration)
{
return new static($duration);
}
/**
* Sleep until the given timestamp.
*
* @param \DateTimeInterface|int|float|numeric-string $timestamp
* @return static
*/
public static function until($timestamp)
{
if (is_numeric($timestamp)) {
$timestamp = Carbon::createFromTimestamp($timestamp, date_default_timezone_get());
}
return new static(Carbon::now()->diff($timestamp));
}
/**
* Sleep for the given number of microseconds.
*
* @param int $duration
* @return static
*/
public static function usleep($duration)
{
return (new static($duration))->microseconds();
}
/**
* Sleep for the given number of seconds.
*
* @param int|float $duration
* @return static
*/
public static function sleep($duration)
{
return (new static($duration))->seconds();
}
/**
* Sleep for the given duration. Replaces any previously defined duration.
*
* @param \DateInterval|int|float $duration
* @return $this
*/
protected function duration($duration)
{
if (! $duration instanceof DateInterval) {
$this->duration = CarbonInterval::microsecond(0);
$this->pending = $duration;
} else {
$duration = CarbonInterval::instance($duration);
if ($duration->totalMicroseconds < 0) {
$duration = CarbonInterval::seconds(0);
}
$this->duration = $duration;
$this->pending = null;
}
return $this;
}
/**
* Sleep for the given number of minutes.
*
* @return $this
*/
public function minutes()
{
$this->duration->add('minutes', $this->pullPending());
return $this;
}
/**
* Sleep for one minute.
*
* @return $this
*/
public function minute()
{
return $this->minutes();
}
/**
* Sleep for the given number of seconds.
*
* @return $this
*/
public function seconds()
{
$this->duration->add('seconds', $this->pullPending());
return $this;
}
/**
* Sleep for one second.
*
* @return $this
*/
public function second()
{
return $this->seconds();
}
/**
* Sleep for the given number of milliseconds.
*
* @return $this
*/
public function milliseconds()
{
$this->duration->add('milliseconds', $this->pullPending());
return $this;
}
/**
* Sleep for one millisecond.
*
* @return $this
*/
public function millisecond()
{
return $this->milliseconds();
}
/**
* Sleep for the given number of microseconds.
*
* @return $this
*/
public function microseconds()
{
$this->duration->add('microseconds', $this->pullPending());
return $this;
}
/**
* Sleep for on microsecond.
*
* @return $this
*/
public function microsecond()
{
return $this->microseconds();
}
/**
* Add additional time to sleep for.
*
* @param int|float $duration
* @return $this
*/
public function and($duration)
{
$this->pending = $duration;
return $this;
}
/**
* Sleep while a given callback returns "true".
*
* @param \Closure $callback
* @return $this
*/
public function while(Closure $callback)
{
$this->while = $callback;
return $this;
}
/**
* Specify a callback that should be executed after sleeping.
*
* @param callable $then
* @return mixed
*/
public function then(callable $then)
{
$this->goodnight();
$this->alreadySlept = true;
return $then();
}
/**
* Handle the object's destruction.
*
* @return void
*/
public function __destruct()
{
$this->goodnight();
}
/**
* Handle the object's destruction.
*
* @return void
*/
protected function goodnight()
{
if ($this->alreadySlept || ! $this->shouldSleep) {
return;
}
if ($this->pending !== null) {
throw new RuntimeException('Unknown duration unit.');
}
if (static::$fake) {
static::$sequence[] = $this->duration;
if (static::$syncWithCarbon) {
Carbon::setTestNow(Carbon::now()->add($this->duration));
}
foreach (static::$fakeSleepCallbacks as $callback) {
$callback($this->duration);
}
return;
}
$remaining = $this->duration->copy();
$seconds = (int) $remaining->totalSeconds;
$while = $this->while ?: function () {
static $return = [true, false];
return array_shift($return);
};
while ($while()) {
if ($seconds > 0) {
sleep($seconds);
$remaining = $remaining->subSeconds($seconds);
}
$microseconds = (int) $remaining->totalMicroseconds;
if ($microseconds > 0) {
usleep($microseconds);
}
}
}
/**
* Resolve the pending duration.
*
* @return int|float
*/
protected function pullPending()
{
if ($this->pending === null) {
$this->shouldNotSleep();
throw new RuntimeException('No duration specified.');
}
if ($this->pending < 0) {
$this->pending = 0;
}
return tap($this->pending, function () {
$this->pending = null;
});
}
/**
* Stay awake and capture any attempts to sleep.
*
* @param bool $value
* @param bool $syncWithCarbon
* @return void
*/
public static function fake($value = true, $syncWithCarbon = false)
{
static::$fake = $value;
static::$sequence = [];
static::$fakeSleepCallbacks = [];
static::$syncWithCarbon = $syncWithCarbon;
}
/**
* Assert a given amount of sleeping occurred a specific number of times.
*
* @param \Closure $expected
* @param int $times
* @return void
*/
public static function assertSlept($expected, $times = 1)
{
$count = (new Collection(static::$sequence))->filter($expected)->count();
PHPUnit::assertSame(
$times,
$count,
"The expected sleep was found [{$count}] times instead of [{$times}]."
);
}
/**
* Assert sleeping occurred a given number of times.
*
* @param int $expected
* @return void
*/
public static function assertSleptTimes($expected)
{
PHPUnit::assertSame($expected, $count = count(static::$sequence), "Expected [{$expected}] sleeps but found [{$count}].");
}
/**
* Assert the given sleep sequence was encountered.
*
* @param array $sequence
* @return void
*/
public static function assertSequence($sequence)
{
try {
static::assertSleptTimes(count($sequence));
(new Collection($sequence))
->zip(static::$sequence)
->eachSpread(function (?Sleep $expected, CarbonInterval $actual) {
if ($expected === null) {
return;
}
PHPUnit::assertTrue(
$expected->shouldNotSleep()->duration->equalTo($actual),
vsprintf('Expected sleep duration of [%s] but actually slept for [%s].', [
$expected->duration->cascade()->forHumans([
'options' => 0,
'minimumUnit' => 'microsecond',
]),
$actual->cascade()->forHumans([
'options' => 0,
'minimumUnit' => 'microsecond',
]),
])
);
});
} finally {
foreach ($sequence as $expected) {
if ($expected instanceof self) {
$expected->shouldNotSleep();
}
}
}
}
/**
* Assert that no sleeping occurred.
*
* @return void
*/
public static function assertNeverSlept()
{
static::assertSleptTimes(0);
}
/**
* Assert that no sleeping occurred.
*
* @return void
*/
public static function assertInsomniac()
{
if (static::$sequence === []) {
PHPUnit::assertTrue(true);
}
foreach (static::$sequence as $duration) {
PHPUnit::assertSame(0, (int) $duration->totalMicroseconds, vsprintf('Unexpected sleep duration of [%s] found.', [
$duration->cascade()->forHumans([
'options' => 0,
'minimumUnit' => 'microsecond',
]),
]));
}
}
/**
* Indicate that the instance should not sleep.
*
* @return $this
*/
protected function shouldNotSleep()
{
$this->shouldSleep = false;
return $this;
}
/**
* Only sleep when the given condition is true.
*
* @param (\Closure($this): bool)|bool $condition
* @return $this
*/
public function when($condition)
{
$this->shouldSleep = (bool) value($condition, $this);
return $this;
}
/**
* Don't sleep when the given condition is true.
*
* @param (\Closure($this): bool)|bool $condition
* @return $this
*/
public function unless($condition)
{
return $this->when(! value($condition, $this));
}
/**
* Specify a callback that should be invoked when faking sleep within a test.
*
* @param callable $callback
* @return void
*/
public static function whenFakingSleep($callback)
{
static::$fakeSleepCallbacks[] = $callback;
}
/**
* Indicate that Carbon's "now" should be kept in sync when sleeping.
*
* @return void
*/
public static function syncWithCarbon($value = true)
{
static::$syncWithCarbon = $value;
}
}

2091
plugins/vendor/illuminate/support/Str.php vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,168 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Carbon\CarbonImmutable;
use Illuminate\Bus\Batch;
use Illuminate\Bus\UpdatedBatchJobCounts;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class BatchFake extends Batch
{
/**
* The jobs that have been added to the batch.
*
* @var array
*/
public $added = [];
/**
* Indicates if the batch has been deleted.
*
* @var bool
*/
public $deleted = false;
/**
* Create a new batch instance.
*
* @param string $id
* @param string $name
* @param int $totalJobs
* @param int $pendingJobs
* @param int $failedJobs
* @param array $failedJobIds
* @param array $options
* @param \Carbon\CarbonImmutable $createdAt
* @param \Carbon\CarbonImmutable|null $cancelledAt
* @param \Carbon\CarbonImmutable|null $finishedAt
*/
public function __construct(
string $id,
string $name,
int $totalJobs,
int $pendingJobs,
int $failedJobs,
array $failedJobIds,
array $options,
CarbonImmutable $createdAt,
?CarbonImmutable $cancelledAt = null,
?CarbonImmutable $finishedAt = null,
) {
$this->id = $id;
$this->name = $name;
$this->totalJobs = $totalJobs;
$this->pendingJobs = $pendingJobs;
$this->failedJobs = $failedJobs;
$this->failedJobIds = $failedJobIds;
$this->options = $options;
$this->createdAt = $createdAt;
$this->cancelledAt = $cancelledAt;
$this->finishedAt = $finishedAt;
}
/**
* Get a fresh instance of the batch represented by this ID.
*
* @return self
*/
public function fresh()
{
return $this;
}
/**
* Add additional jobs to the batch.
*
* @param \Illuminate\Support\Enumerable|object|array $jobs
* @return self
*/
public function add($jobs)
{
$jobs = Collection::wrap($jobs);
foreach ($jobs as $job) {
$this->added[] = $job;
}
$this->totalJobs += $jobs->count();
return $this;
}
/**
* Record that a job within the batch finished successfully, executing any callbacks if necessary.
*
* @param string $jobId
* @return void
*/
public function recordSuccessfulJob(string $jobId)
{
//
}
/**
* Decrement the pending jobs for the batch.
*
* @param string $jobId
* @return void
*/
public function decrementPendingJobs(string $jobId)
{
//
}
/**
* Record that a job within the batch failed to finish successfully, executing any callbacks if necessary.
*
* @param string $jobId
* @param \Throwable $e
* @return void
*/
public function recordFailedJob(string $jobId, $e)
{
//
}
/**
* Increment the failed jobs for the batch.
*
* @param string $jobId
* @return \Illuminate\Bus\UpdatedBatchJobCounts
*/
public function incrementFailedJobs(string $jobId)
{
return new UpdatedBatchJobCounts;
}
/**
* Cancel the batch.
*
* @return void
*/
public function cancel()
{
$this->cancelledAt = Carbon::now();
}
/**
* Delete the batch from storage.
*
* @return void
*/
public function delete()
{
$this->deleted = true;
}
/**
* Determine if the batch has been deleted.
*
* @return bool
*/
public function deleted()
{
return $this->deleted;
}
}

View File

@@ -0,0 +1,163 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Carbon\CarbonImmutable;
use Closure;
use Illuminate\Bus\BatchRepository;
use Illuminate\Bus\PendingBatch;
use Illuminate\Bus\UpdatedBatchJobCounts;
use Illuminate\Support\Str;
class BatchRepositoryFake implements BatchRepository
{
/**
* The batches stored in the repository.
*
* @var \Illuminate\Bus\Batch[]
*/
protected $batches = [];
/**
* Retrieve a list of batches.
*
* @param int $limit
* @param mixed $before
* @return \Illuminate\Bus\Batch[]
*/
public function get($limit, $before)
{
return $this->batches;
}
/**
* Retrieve information about an existing batch.
*
* @param string $batchId
* @return \Illuminate\Bus\Batch|null
*/
public function find(string $batchId)
{
return $this->batches[$batchId] ?? null;
}
/**
* Store a new pending batch.
*
* @param \Illuminate\Bus\PendingBatch $batch
* @return \Illuminate\Bus\Batch
*/
public function store(PendingBatch $batch)
{
$id = (string) Str::orderedUuid();
$this->batches[$id] = new BatchFake(
$id,
$batch->name,
count($batch->jobs),
count($batch->jobs),
0,
[],
$batch->options,
CarbonImmutable::now(),
null,
null
);
return $this->batches[$id];
}
/**
* Increment the total number of jobs within the batch.
*
* @param string $batchId
* @param int $amount
* @return void
*/
public function incrementTotalJobs(string $batchId, int $amount)
{
//
}
/**
* Decrement the total number of pending jobs for the batch.
*
* @param string $batchId
* @param string $jobId
* @return \Illuminate\Bus\UpdatedBatchJobCounts
*/
public function decrementPendingJobs(string $batchId, string $jobId)
{
return new UpdatedBatchJobCounts;
}
/**
* Increment the total number of failed jobs for the batch.
*
* @param string $batchId
* @param string $jobId
* @return \Illuminate\Bus\UpdatedBatchJobCounts
*/
public function incrementFailedJobs(string $batchId, string $jobId)
{
return new UpdatedBatchJobCounts;
}
/**
* Mark the batch that has the given ID as finished.
*
* @param string $batchId
* @return void
*/
public function markAsFinished(string $batchId)
{
if (isset($this->batches[$batchId])) {
$this->batches[$batchId]->finishedAt = now();
}
}
/**
* Cancel the batch that has the given ID.
*
* @param string $batchId
* @return void
*/
public function cancel(string $batchId)
{
if (isset($this->batches[$batchId])) {
$this->batches[$batchId]->cancel();
}
}
/**
* Delete the batch that has the given ID.
*
* @param string $batchId
* @return void
*/
public function delete(string $batchId)
{
unset($this->batches[$batchId]);
}
/**
* Execute the given Closure within a storage specific transaction.
*
* @param \Closure $callback
* @return mixed
*/
public function transaction(Closure $callback)
{
return $callback();
}
/**
* Rollback the last database transaction for the connection.
*
* @return void
*/
public function rollBack()
{
//
}
}

View File

@@ -0,0 +1,925 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Closure;
use Illuminate\Bus\BatchRepository;
use Illuminate\Bus\ChainedBatch;
use Illuminate\Bus\PendingBatch;
use Illuminate\Contracts\Bus\QueueingDispatcher;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ReflectsClosures;
use PHPUnit\Framework\Assert as PHPUnit;
use RuntimeException;
class BusFake implements Fake, QueueingDispatcher
{
use ReflectsClosures;
/**
* The original Bus dispatcher implementation.
*
* @var \Illuminate\Contracts\Bus\QueueingDispatcher
*/
public $dispatcher;
/**
* The job types that should be intercepted instead of dispatched.
*
* @var array
*/
protected $jobsToFake = [];
/**
* The job types that should be dispatched instead of faked.
*
* @var array
*/
protected $jobsToDispatch = [];
/**
* The fake repository to track batched jobs.
*
* @var \Illuminate\Bus\BatchRepository
*/
protected $batchRepository;
/**
* The commands that have been dispatched.
*
* @var array
*/
protected $commands = [];
/**
* The commands that have been dispatched synchronously.
*
* @var array
*/
protected $commandsSync = [];
/**
* The commands that have been dispatched after the response has been sent.
*
* @var array
*/
protected $commandsAfterResponse = [];
/**
* The batches that have been dispatched.
*
* @var array
*/
protected $batches = [];
/**
* Indicates if commands should be serialized and restored when pushed to the Bus.
*
* @var bool
*/
protected bool $serializeAndRestore = false;
/**
* Create a new bus fake instance.
*
* @param \Illuminate\Contracts\Bus\QueueingDispatcher $dispatcher
* @param array|string $jobsToFake
* @param \Illuminate\Bus\BatchRepository|null $batchRepository
*/
public function __construct(QueueingDispatcher $dispatcher, $jobsToFake = [], ?BatchRepository $batchRepository = null)
{
$this->dispatcher = $dispatcher;
$this->jobsToFake = Arr::wrap($jobsToFake);
$this->batchRepository = $batchRepository ?: new BatchRepositoryFake;
}
/**
* Specify the jobs that should be dispatched instead of faked.
*
* @param array|string $jobsToDispatch
* @return $this
*/
public function except($jobsToDispatch)
{
$this->jobsToDispatch = array_merge($this->jobsToDispatch, Arr::wrap($jobsToDispatch));
return $this;
}
/**
* Assert if a job was dispatched based on a truth-test callback.
*
* @param string|\Closure $command
* @param callable|int|null $callback
* @return void
*/
public function assertDispatched($command, $callback = null)
{
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
if (is_numeric($callback)) {
return $this->assertDispatchedTimes($command, $callback);
}
PHPUnit::assertTrue(
$this->dispatched($command, $callback)->count() > 0 ||
$this->dispatchedAfterResponse($command, $callback)->count() > 0 ||
$this->dispatchedSync($command, $callback)->count() > 0,
"The expected [{$command}] job was not dispatched."
);
}
/**
* Assert if a job was pushed exactly once.
*
* @param string|\Closure $command
* @param int $times
* @return void
*/
public function assertDispatchedOnce($command)
{
$this->assertDispatchedTimes($command, 1);
}
/**
* Assert if a job was pushed a number of times.
*
* @param string|\Closure $command
* @param int $times
* @return void
*/
public function assertDispatchedTimes($command, $times = 1)
{
$callback = null;
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
$count = $this->dispatched($command, $callback)->count() +
$this->dispatchedAfterResponse($command, $callback)->count() +
$this->dispatchedSync($command, $callback)->count();
PHPUnit::assertSame(
$times, $count,
sprintf(
"The expected [{$command}] job was pushed {$count} %s instead of {$times} %s.",
Str::plural('time', $count),
Str::plural('time', $times)
)
);
}
/**
* Determine if a job was dispatched based on a truth-test callback.
*
* @param string|\Closure $command
* @param callable|null $callback
* @return void
*/
public function assertNotDispatched($command, $callback = null)
{
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
PHPUnit::assertTrue(
$this->dispatched($command, $callback)->count() === 0 &&
$this->dispatchedAfterResponse($command, $callback)->count() === 0 &&
$this->dispatchedSync($command, $callback)->count() === 0,
"The unexpected [{$command}] job was dispatched."
);
}
/**
* Assert that no jobs were dispatched.
*
* @return void
*/
public function assertNothingDispatched()
{
$commandNames = implode("\n- ", array_keys($this->commands));
PHPUnit::assertEmpty($this->commands, "The following jobs were dispatched unexpectedly:\n\n- $commandNames\n");
}
/**
* Assert if a job was explicitly dispatched synchronously based on a truth-test callback.
*
* @param string|\Closure $command
* @param callable|int|null $callback
* @return void
*/
public function assertDispatchedSync($command, $callback = null)
{
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
if (is_numeric($callback)) {
return $this->assertDispatchedSyncTimes($command, $callback);
}
PHPUnit::assertTrue(
$this->dispatchedSync($command, $callback)->count() > 0,
"The expected [{$command}] job was not dispatched synchronously."
);
}
/**
* Assert if a job was pushed synchronously a number of times.
*
* @param string|\Closure $command
* @param int $times
* @return void
*/
public function assertDispatchedSyncTimes($command, $times = 1)
{
$callback = null;
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
$count = $this->dispatchedSync($command, $callback)->count();
PHPUnit::assertSame(
$times, $count,
sprintf(
"The expected [{$command}] job was synchronously pushed {$count} %s instead of {$times} %s.",
Str::plural('time', $count),
Str::plural('time', $times)
)
);
}
/**
* Determine if a job was dispatched based on a truth-test callback.
*
* @param string|\Closure $command
* @param callable|null $callback
* @return void
*/
public function assertNotDispatchedSync($command, $callback = null)
{
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
PHPUnit::assertCount(
0, $this->dispatchedSync($command, $callback),
"The unexpected [{$command}] job was dispatched synchronously."
);
}
/**
* Assert if a job was dispatched after the response was sent based on a truth-test callback.
*
* @param string|\Closure $command
* @param callable|int|null $callback
* @return void
*/
public function assertDispatchedAfterResponse($command, $callback = null)
{
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
if (is_numeric($callback)) {
return $this->assertDispatchedAfterResponseTimes($command, $callback);
}
PHPUnit::assertTrue(
$this->dispatchedAfterResponse($command, $callback)->count() > 0,
"The expected [{$command}] job was not dispatched after sending the response."
);
}
/**
* Assert if a job was pushed after the response was sent a number of times.
*
* @param string|\Closure $command
* @param int $times
* @return void
*/
public function assertDispatchedAfterResponseTimes($command, $times = 1)
{
$callback = null;
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
$count = $this->dispatchedAfterResponse($command, $callback)->count();
PHPUnit::assertSame(
$times, $count,
sprintf(
"The expected [{$command}] job was pushed {$count} %s instead of {$times} %s.",
Str::plural('time', $count),
Str::plural('time', $times)
)
);
}
/**
* Determine if a job was dispatched based on a truth-test callback.
*
* @param string|\Closure $command
* @param callable|null $callback
* @return void
*/
public function assertNotDispatchedAfterResponse($command, $callback = null)
{
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
PHPUnit::assertCount(
0, $this->dispatchedAfterResponse($command, $callback),
"The unexpected [{$command}] job was dispatched after sending the response."
);
}
/**
* Assert if a chain of jobs was dispatched.
*
* @param array $expectedChain
* @return void
*/
public function assertChained(array $expectedChain)
{
$command = $expectedChain[0];
$expectedChain = array_slice($expectedChain, 1);
$callback = null;
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
} elseif ($command instanceof ChainedBatchTruthTest) {
$instance = $command;
$command = ChainedBatch::class;
$callback = fn ($job) => $instance($job->toPendingBatch());
} elseif (! is_string($command)) {
$instance = $command;
$command = get_class($instance);
$callback = function ($job) use ($instance) {
return serialize($this->resetChainPropertiesToDefaults($job)) === serialize($instance);
};
}
PHPUnit::assertTrue(
$this->dispatched($command, $callback)->isNotEmpty(),
"The expected [{$command}] job was not dispatched."
);
$this->assertDispatchedWithChainOfObjects($command, $expectedChain, $callback);
}
/**
* Assert no chained jobs was dispatched.
*
* @return void
*/
public function assertNothingChained()
{
$this->assertNothingDispatched();
}
/**
* Reset the chain properties to their default values on the job.
*
* @param mixed $job
* @return mixed
*/
protected function resetChainPropertiesToDefaults($job)
{
return tap(clone $job, function ($job) {
$job->chainConnection = null;
$job->chainQueue = null;
$job->chainCatchCallbacks = null;
$job->chained = [];
});
}
/**
* Assert if a job was dispatched with an empty chain based on a truth-test callback.
*
* @param string|\Closure $command
* @param callable|null $callback
* @return void
*/
public function assertDispatchedWithoutChain($command, $callback = null)
{
if ($command instanceof Closure) {
[$command, $callback] = [$this->firstClosureParameterType($command), $command];
}
PHPUnit::assertTrue(
$this->dispatched($command, $callback)->isNotEmpty(),
"The expected [{$command}] job was not dispatched."
);
$this->assertDispatchedWithChainOfObjects($command, [], $callback);
}
/**
* Assert if a job was dispatched with chained jobs based on a truth-test callback.
*
* @param string $command
* @param array $expectedChain
* @param callable|null $callback
* @return void
*/
protected function assertDispatchedWithChainOfObjects($command, $expectedChain, $callback)
{
$chain = $expectedChain;
PHPUnit::assertTrue(
$this->dispatched($command, $callback)->filter(function ($job) use ($chain) {
if (count($chain) !== count($job->chained)) {
return false;
}
foreach ($job->chained as $index => $serializedChainedJob) {
if ($chain[$index] instanceof ChainedBatchTruthTest) {
$chainedBatch = unserialize($serializedChainedJob);
if (! $chainedBatch instanceof ChainedBatch ||
! $chain[$index]($chainedBatch->toPendingBatch())) {
return false;
}
} elseif ($chain[$index] instanceof Closure) {
[$expectedType, $callback] = [$this->firstClosureParameterType($chain[$index]), $chain[$index]];
$chainedJob = unserialize($serializedChainedJob);
if (! $chainedJob instanceof $expectedType) {
throw new RuntimeException('The chained job was expected to be of type '.$expectedType.', '.$chainedJob::class.' chained.');
}
if (! $callback($chainedJob)) {
return false;
}
} elseif (is_string($chain[$index])) {
if ($chain[$index] != get_class(unserialize($serializedChainedJob))) {
return false;
}
} elseif (serialize($chain[$index]) != $serializedChainedJob) {
return false;
}
}
return true;
})->isNotEmpty(),
'The expected chain was not dispatched.'
);
}
/**
* Create a new assertion about a chained batch.
*
* @param \Closure $callback
* @return \Illuminate\Support\Testing\Fakes\ChainedBatchTruthTest
*/
public function chainedBatch(Closure $callback)
{
return new ChainedBatchTruthTest($callback);
}
/**
* Assert if a batch was dispatched based on a truth-test callback.
*
* @param callable $callback
* @return void
*/
public function assertBatched(callable $callback)
{
PHPUnit::assertTrue(
$this->batched($callback)->count() > 0,
'The expected batch was not dispatched.'
);
}
/**
* Assert the number of batches that have been dispatched.
*
* @param int $count
* @return void
*/
public function assertBatchCount($count)
{
PHPUnit::assertCount(
$count, $this->batches,
);
}
/**
* Assert that no batched jobs were dispatched.
*
* @return void
*/
public function assertNothingBatched()
{
$jobNames = (new Collection($this->batches))
->map(fn ($batch) => $batch->jobs->map(fn ($job) => get_class($job)))
->flatten()
->join("\n- ");
PHPUnit::assertEmpty($this->batches, "The following batched jobs were dispatched unexpectedly:\n\n- $jobNames\n");
}
/**
* Assert that no jobs were dispatched, chained, or batched.
*
* @return void
*/
public function assertNothingPlaced()
{
$this->assertNothingDispatched();
$this->assertNothingBatched();
}
/**
* Get all of the jobs matching a truth-test callback.
*
* @param string $command
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function dispatched($command, $callback = null)
{
if (! $this->hasDispatched($command)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
return (new Collection($this->commands[$command]))->filter(fn ($command) => $callback($command));
}
/**
* Get all of the jobs dispatched synchronously matching a truth-test callback.
*
* @param string $command
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function dispatchedSync(string $command, $callback = null)
{
if (! $this->hasDispatchedSync($command)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
return (new Collection($this->commandsSync[$command]))->filter(fn ($command) => $callback($command));
}
/**
* Get all of the jobs dispatched after the response was sent matching a truth-test callback.
*
* @param string $command
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function dispatchedAfterResponse(string $command, $callback = null)
{
if (! $this->hasDispatchedAfterResponse($command)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
return (new Collection($this->commandsAfterResponse[$command]))->filter(fn ($command) => $callback($command));
}
/**
* Get all of the pending batches matching a truth-test callback.
*
* @param callable $callback
* @return \Illuminate\Support\Collection
*/
public function batched(callable $callback)
{
if (empty($this->batches)) {
return new Collection;
}
return (new Collection($this->batches))->filter(fn ($batch) => $callback($batch));
}
/**
* Determine if there are any stored commands for a given class.
*
* @param string $command
* @return bool
*/
public function hasDispatched($command)
{
return isset($this->commands[$command]) && ! empty($this->commands[$command]);
}
/**
* Determine if there are any stored commands for a given class.
*
* @param string $command
* @return bool
*/
public function hasDispatchedSync($command)
{
return isset($this->commandsSync[$command]) && ! empty($this->commandsSync[$command]);
}
/**
* Determine if there are any stored commands for a given class.
*
* @param string $command
* @return bool
*/
public function hasDispatchedAfterResponse($command)
{
return isset($this->commandsAfterResponse[$command]) && ! empty($this->commandsAfterResponse[$command]);
}
/**
* Dispatch a command to its appropriate handler.
*
* @param mixed $command
* @return mixed
*/
public function dispatch($command)
{
if ($this->shouldFakeJob($command)) {
$this->commands[get_class($command)][] = $this->getCommandRepresentation($command);
} else {
return $this->dispatcher->dispatch($command);
}
}
/**
* Dispatch a command to its appropriate handler in the current process.
*
* Queueable jobs will be dispatched to the "sync" queue.
*
* @param mixed $command
* @param mixed $handler
* @return mixed
*/
public function dispatchSync($command, $handler = null)
{
if ($this->shouldFakeJob($command)) {
$this->commandsSync[get_class($command)][] = $this->getCommandRepresentation($command);
} else {
return $this->dispatcher->dispatchSync($command, $handler);
}
}
/**
* Dispatch a command to its appropriate handler in the current process.
*
* @param mixed $command
* @param mixed $handler
* @return mixed
*/
public function dispatchNow($command, $handler = null)
{
if ($this->shouldFakeJob($command)) {
$this->commands[get_class($command)][] = $this->getCommandRepresentation($command);
} else {
return $this->dispatcher->dispatchNow($command, $handler);
}
}
/**
* Dispatch a command to its appropriate handler behind a queue.
*
* @param mixed $command
* @return mixed
*/
public function dispatchToQueue($command)
{
if ($this->shouldFakeJob($command)) {
$this->commands[get_class($command)][] = $this->getCommandRepresentation($command);
} else {
return $this->dispatcher->dispatchToQueue($command);
}
}
/**
* Dispatch a command to its appropriate handler.
*
* @param mixed $command
* @return mixed
*/
public function dispatchAfterResponse($command)
{
if ($this->shouldFakeJob($command)) {
$this->commandsAfterResponse[get_class($command)][] = $this->getCommandRepresentation($command);
} else {
return $this->dispatcher->dispatch($command);
}
}
/**
* Create a new chain of queueable jobs.
*
* @param \Illuminate\Support\Collection|array|null $jobs
* @return \Illuminate\Foundation\Bus\PendingChain
*/
public function chain($jobs = null)
{
$jobs = Collection::wrap($jobs);
$jobs = ChainedBatch::prepareNestedBatches($jobs);
return new PendingChainFake($this, $jobs->shift(), $jobs->toArray());
}
/**
* Attempt to find the batch with the given ID.
*
* @param string $batchId
* @return \Illuminate\Bus\Batch|null
*/
public function findBatch(string $batchId)
{
return $this->batchRepository->find($batchId);
}
/**
* Create a new batch of queueable jobs.
*
* @param \Illuminate\Support\Collection|array $jobs
* @return \Illuminate\Bus\PendingBatch
*/
public function batch($jobs)
{
return new PendingBatchFake($this, Collection::wrap($jobs));
}
/**
* Dispatch an empty job batch for testing.
*
* @param string $name
* @return \Illuminate\Bus\Batch
*/
public function dispatchFakeBatch($name = '')
{
return $this->batch([])->name($name)->dispatch();
}
/**
* Record the fake pending batch dispatch.
*
* @param \Illuminate\Bus\PendingBatch $pendingBatch
* @return \Illuminate\Bus\Batch
*/
public function recordPendingBatch(PendingBatch $pendingBatch)
{
$this->batches[] = $pendingBatch;
return $this->batchRepository->store($pendingBatch);
}
/**
* Determine if a command should be faked or actually dispatched.
*
* @param mixed $command
* @return bool
*/
protected function shouldFakeJob($command)
{
if ($this->shouldDispatchCommand($command)) {
return false;
}
if (empty($this->jobsToFake)) {
return true;
}
return (new Collection($this->jobsToFake))
->filter(function ($job) use ($command) {
return $job instanceof Closure
? $job($command)
: $job === get_class($command);
})->isNotEmpty();
}
/**
* Determine if a command should be dispatched or not.
*
* @param mixed $command
* @return bool
*/
protected function shouldDispatchCommand($command)
{
return (new Collection($this->jobsToDispatch))
->filter(function ($job) use ($command) {
return $job instanceof Closure
? $job($command)
: $job === get_class($command);
})->isNotEmpty();
}
/**
* Specify if commands should be serialized and restored when being batched.
*
* @param bool $serializeAndRestore
* @return $this
*/
public function serializeAndRestore(bool $serializeAndRestore = true)
{
$this->serializeAndRestore = $serializeAndRestore;
return $this;
}
/**
* Serialize and unserialize the command to simulate the queueing process.
*
* @param mixed $command
* @return mixed
*/
protected function serializeAndRestoreCommand($command)
{
return unserialize(serialize($command));
}
/**
* Return the command representation that should be stored.
*
* @param mixed $command
* @return mixed
*/
protected function getCommandRepresentation($command)
{
return $this->serializeAndRestore ? $this->serializeAndRestoreCommand($command) : $command;
}
/**
* Set the pipes commands should be piped through before dispatching.
*
* @param array $pipes
* @return $this
*/
public function pipeThrough(array $pipes)
{
$this->dispatcher->pipeThrough($pipes);
return $this;
}
/**
* Determine if the given command has a handler.
*
* @param mixed $command
* @return bool
*/
public function hasCommandHandler($command)
{
return $this->dispatcher->hasCommandHandler($command);
}
/**
* Retrieve the handler for a command.
*
* @param mixed $command
* @return mixed
*/
public function getCommandHandler($command)
{
return $this->dispatcher->getCommandHandler($command);
}
/**
* Map a command to a handler.
*
* @param array $map
* @return $this
*/
public function map(array $map)
{
$this->dispatcher->map($map);
return $this;
}
/**
* Get the batches that have been dispatched.
*
* @return array
*/
public function dispatchedBatches()
{
return $this->batches;
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Closure;
class ChainedBatchTruthTest
{
/**
* The underlying truth test.
*
* @var \Closure
*/
protected $callback;
/**
* Create a new truth test instance.
*
* @param \Closure $callback
*/
public function __construct(Closure $callback)
{
$this->callback = $callback;
}
/**
* Invoke the truth test with the given pending batch.
*
* @param \Illuminate\Bus\PendingBatch $pendingBatch
* @return bool
*/
public function __invoke($pendingBatch)
{
return call_user_func($this->callback, $pendingBatch);
}
}

View File

@@ -0,0 +1,453 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Closure;
use Illuminate\Container\Container;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\ReflectsClosures;
use PHPUnit\Framework\Assert as PHPUnit;
use ReflectionFunction;
class EventFake implements Dispatcher, Fake
{
use ForwardsCalls, ReflectsClosures;
/**
* The original event dispatcher.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
public $dispatcher;
/**
* The event types that should be intercepted instead of dispatched.
*
* @var array
*/
protected $eventsToFake = [];
/**
* The event types that should be dispatched instead of intercepted.
*
* @var array
*/
protected $eventsToDispatch = [];
/**
* All of the events that have been intercepted keyed by type.
*
* @var array
*/
protected $events = [];
/**
* Create a new event fake instance.
*
* @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
* @param array|string $eventsToFake
*/
public function __construct(Dispatcher $dispatcher, $eventsToFake = [])
{
$this->dispatcher = $dispatcher;
$this->eventsToFake = Arr::wrap($eventsToFake);
}
/**
* Specify the events that should be dispatched instead of faked.
*
* @param array|string $eventsToDispatch
* @return $this
*/
public function except($eventsToDispatch)
{
$this->eventsToDispatch = array_merge(
$this->eventsToDispatch,
Arr::wrap($eventsToDispatch)
);
return $this;
}
/**
* Assert if an event has a listener attached to it.
*
* @param string $expectedEvent
* @param string|array $expectedListener
* @return void
*/
public function assertListening($expectedEvent, $expectedListener)
{
foreach ($this->dispatcher->getListeners($expectedEvent) as $listenerClosure) {
$actualListener = (new ReflectionFunction($listenerClosure))
->getStaticVariables()['listener'];
$normalizedListener = $expectedListener;
if (is_string($actualListener) && Str::contains($actualListener, '@')) {
$actualListener = Str::parseCallback($actualListener);
if (is_string($expectedListener)) {
if (Str::contains($expectedListener, '@')) {
$normalizedListener = Str::parseCallback($expectedListener);
} else {
$normalizedListener = [
$expectedListener,
method_exists($expectedListener, 'handle') ? 'handle' : '__invoke',
];
}
}
}
if ($actualListener === $normalizedListener ||
($actualListener instanceof Closure &&
$normalizedListener === Closure::class)) {
PHPUnit::assertTrue(true);
return;
}
}
PHPUnit::assertTrue(
false,
sprintf(
'Event [%s] does not have the [%s] listener attached to it',
$expectedEvent,
print_r($expectedListener, true)
)
);
}
/**
* Assert if an event was dispatched based on a truth-test callback.
*
* @param string|\Closure $event
* @param callable|int|null $callback
* @return void
*/
public function assertDispatched($event, $callback = null)
{
if ($event instanceof Closure) {
[$event, $callback] = [$this->firstClosureParameterType($event), $event];
}
if (is_int($callback)) {
return $this->assertDispatchedTimes($event, $callback);
}
PHPUnit::assertTrue(
$this->dispatched($event, $callback)->count() > 0,
"The expected [{$event}] event was not dispatched."
);
}
/**
* Assert if an event was dispatched exactly once.
*
* @param string $event
* @param int $times
* @return void
*/
public function assertDispatchedOnce($event)
{
$this->assertDispatchedTimes($event, 1);
}
/**
* Assert if an event was dispatched a number of times.
*
* @param string $event
* @param int $times
* @return void
*/
public function assertDispatchedTimes($event, $times = 1)
{
$count = $this->dispatched($event)->count();
PHPUnit::assertSame(
$times, $count,
sprintf(
"The expected [{$event}] event was dispatched {$count} %s instead of {$times} %s.",
Str::plural('time', $count),
Str::plural('time', $times)
)
);
}
/**
* Determine if an event was dispatched based on a truth-test callback.
*
* @param string|\Closure $event
* @param callable|null $callback
* @return void
*/
public function assertNotDispatched($event, $callback = null)
{
if ($event instanceof Closure) {
[$event, $callback] = [$this->firstClosureParameterType($event), $event];
}
PHPUnit::assertCount(
0, $this->dispatched($event, $callback),
"The unexpected [{$event}] event was dispatched."
);
}
/**
* Assert that no events were dispatched.
*
* @return void
*/
public function assertNothingDispatched()
{
$count = count(Arr::flatten($this->events));
$eventNames = (new Collection($this->events))
->map(fn ($events, $eventName) => sprintf(
'%s dispatched %s %s',
$eventName,
count($events),
Str::plural('time', count($events)),
))
->join("\n- ");
PHPUnit::assertSame(
0, $count,
"{$count} unexpected events were dispatched:\n\n- $eventNames\n"
);
}
/**
* Get all of the events matching a truth-test callback.
*
* @param string $event
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function dispatched($event, $callback = null)
{
if (! $this->hasDispatched($event)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
return (new Collection($this->events[$event]))->filter(
fn ($arguments) => $callback(...$arguments)
);
}
/**
* Determine if the given event has been dispatched.
*
* @param string $event
* @return bool
*/
public function hasDispatched($event)
{
return isset($this->events[$event]) && ! empty($this->events[$event]);
}
/**
* Register an event listener with the dispatcher.
*
* @param \Closure|string|array $events
* @param mixed $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 and payload to be dispatched later.
*
* @param string $event
* @param array $payload
* @return void
*/
public function push($event, $payload = [])
{
//
}
/**
* 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)
{
//
}
/**
* 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)
{
$name = is_object($event) ? get_class($event) : (string) $event;
if ($this->shouldFakeEvent($name, $payload)) {
$this->fakeEvent($event, $name, func_get_args());
} else {
return $this->dispatcher->dispatch($event, $payload, $halt);
}
}
/**
* Determine if an event should be faked or actually dispatched.
*
* @param string $eventName
* @param mixed $payload
* @return bool
*/
protected function shouldFakeEvent($eventName, $payload)
{
if ($this->shouldDispatchEvent($eventName, $payload)) {
return false;
}
if (empty($this->eventsToFake)) {
return true;
}
return (new Collection($this->eventsToFake))
->filter(function ($event) use ($eventName, $payload) {
return $event instanceof Closure
? $event($eventName, $payload)
: $event === $eventName;
})
->isNotEmpty();
}
/**
* Push the event onto the fake events array immediately or after the next database transaction.
*
* @param string|object $event
* @param string $name
* @param array $arguments
* @return void
*/
protected function fakeEvent($event, $name, $arguments)
{
if ($event instanceof ShouldDispatchAfterCommit && Container::getInstance()->bound('db.transactions')) {
return Container::getInstance()->make('db.transactions')
->addCallback(fn () => $this->events[$name][] = $arguments);
}
$this->events[$name][] = $arguments;
}
/**
* Determine whether an event should be dispatched or not.
*
* @param string $eventName
* @param mixed $payload
* @return bool
*/
protected function shouldDispatchEvent($eventName, $payload)
{
if (empty($this->eventsToDispatch)) {
return false;
}
return (new Collection($this->eventsToDispatch))
->filter(function ($event) use ($eventName, $payload) {
return $event instanceof Closure
? $event($eventName, $payload)
: $event === $eventName;
})
->isNotEmpty();
}
/**
* Remove a set of listeners from the dispatcher.
*
* @param string $event
* @return void
*/
public function forget($event)
{
//
}
/**
* Forget all of the queued listeners.
*
* @return void
*/
public function forgetPushed()
{
//
}
/**
* Dispatch an event and call the listeners.
*
* @param string|object $event
* @param mixed $payload
* @return mixed
*/
public function until($event, $payload = [])
{
return $this->dispatch($event, $payload, true);
}
/**
* Get the events that have been dispatched.
*
* @return array
*/
public function dispatchedEvents()
{
return $this->events;
}
/**
* Handle dynamic method calls to the dispatcher.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->forwardCallTo($this->dispatcher, $method, $parameters);
}
}

View File

@@ -0,0 +1,285 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Closure;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\Concerns\WithoutExceptionHandlingHandler;
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\ReflectsClosures;
use Illuminate\Testing\Assert;
use PHPUnit\Framework\Assert as PHPUnit;
use PHPUnit\Framework\ExpectationFailedException;
use Throwable;
/**
* @mixin \Illuminate\Foundation\Exceptions\Handler
*/
class ExceptionHandlerFake implements ExceptionHandler, Fake
{
use ForwardsCalls, ReflectsClosures;
/**
* All of the exceptions that have been reported.
*
* @var list<\Throwable>
*/
protected $reported = [];
/**
* If the fake should throw exceptions when they are reported.
*
* @var bool
*/
protected $throwOnReport = false;
/**
* Create a new exception handler fake.
*
* @param \Illuminate\Contracts\Debug\ExceptionHandler $handler
* @param list<class-string<\Throwable>> $exceptions
*/
public function __construct(
protected ExceptionHandler $handler,
protected array $exceptions = [],
) {
//
}
/**
* Get the underlying handler implementation.
*
* @return \Illuminate\Contracts\Debug\ExceptionHandler
*/
public function handler()
{
return $this->handler;
}
/**
* Assert if an exception of the given type has been reported.
*
* @param (\Closure(\Throwable): bool)|class-string<\Throwable> $exception
* @return void
*/
public function assertReported(Closure|string $exception)
{
$message = sprintf(
'The expected [%s] exception was not reported.',
is_string($exception) ? $exception : $this->firstClosureParameterType($exception)
);
if (is_string($exception)) {
Assert::assertTrue(
in_array($exception, array_map(get_class(...), $this->reported), true),
$message,
);
return;
}
Assert::assertTrue(
(new Collection($this->reported))->contains(
fn (Throwable $e) => $this->firstClosureParameterType($exception) === get_class($e)
&& $exception($e) === true,
), $message,
);
}
/**
* Assert the number of exceptions that have been reported.
*
* @param int $count
* @return void
*/
public function assertReportedCount(int $count)
{
$total = (new Collection($this->reported))->count();
PHPUnit::assertSame(
$count, $total,
"The total number of exceptions reported was {$total} instead of {$count}."
);
}
/**
* Assert if an exception of the given type has not been reported.
*
* @param (\Closure(\Throwable): bool)|class-string<\Throwable> $exception
* @return void
*/
public function assertNotReported(Closure|string $exception)
{
try {
$this->assertReported($exception);
} catch (ExpectationFailedException $e) {
return;
}
throw new ExpectationFailedException(sprintf(
'The expected [%s] exception was reported.',
is_string($exception) ? $exception : $this->firstClosureParameterType($exception)
));
}
/**
* Assert nothing has been reported.
*
* @return void
*/
public function assertNothingReported()
{
Assert::assertEmpty(
$this->reported,
sprintf(
'The following exceptions were reported: %s.',
implode(', ', array_map(get_class(...), $this->reported)),
),
);
}
/**
* Report or log an exception.
*
* @param \Throwable $e
* @return void
*/
public function report($e)
{
if (! $this->isFakedException($e)) {
$this->handler->report($e);
return;
}
if (! $this->shouldReport($e)) {
return;
}
$this->reported[] = $e;
if ($this->throwOnReport) {
throw $e;
}
}
/**
* Determine if the given exception is faked.
*
* @param \Throwable $e
* @return bool
*/
protected function isFakedException(Throwable $e)
{
return count($this->exceptions) === 0 || in_array(get_class($e), $this->exceptions, true);
}
/**
* Determine if the exception should be reported.
*
* @param \Throwable $e
* @return bool
*/
public function shouldReport($e)
{
return $this->runningWithoutExceptionHandling() || $this->handler->shouldReport($e);
}
/**
* Determine if the handler is running without exception handling.
*
* @return bool
*/
protected function runningWithoutExceptionHandling()
{
return $this->handler instanceof WithoutExceptionHandlingHandler;
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Symfony\Component\HttpFoundation\Response
*/
public function render($request, $e)
{
return $this->handler->render($request, $e);
}
/**
* Render an exception to the console.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Throwable $e
* @return void
*/
public function renderForConsole($output, Throwable $e)
{
$this->handler->renderForConsole($output, $e);
}
/**
* Throw exceptions when they are reported.
*
* @return $this
*/
public function throwOnReport()
{
$this->throwOnReport = true;
return $this;
}
/**
* Throw the first reported exception.
*
* @return $this
*
* @throws \Throwable
*/
public function throwFirstReported()
{
foreach ($this->reported as $e) {
throw $e;
}
return $this;
}
/**
* Get the exceptions that have been reported.
*
* @return list<\Throwable>
*/
public function reported()
{
return $this->reported;
}
/**
* Set the "original" handler that should be used by the fake.
*
* @param \Illuminate\Contracts\Debug\ExceptionHandler $handler
* @return $this
*/
public function setHandler(ExceptionHandler $handler)
{
$this->handler = $handler;
return $this;
}
/**
* Handle dynamic method calls to the handler.
*
* @param string $method
* @param array<string, mixed> $parameters
* @return mixed
*/
public function __call(string $method, array $parameters)
{
return $this->forwardCallTo($this->handler, $method, $parameters);
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
interface Fake
{
//
}

View File

@@ -0,0 +1,600 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Closure;
use Illuminate\Contracts\Mail\Factory;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Contracts\Mail\MailQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\ReflectsClosures;
use PHPUnit\Framework\Assert as PHPUnit;
class MailFake implements Factory, Fake, Mailer, MailQueue
{
use ForwardsCalls, ReflectsClosures;
/**
* The mailer instance.
*
* @var MailManager
*/
public $manager;
/**
* The mailer currently being used to send a message.
*
* @var string
*/
protected $currentMailer;
/**
* All of the mailables that have been sent.
*
* @var array
*/
protected $mailables = [];
/**
* All of the mailables that have been queued.
*
* @var array
*/
protected $queuedMailables = [];
/**
* Create a new mail fake.
*
* @param MailManager $manager
*/
public function __construct(MailManager $manager)
{
$this->manager = $manager;
$this->currentMailer = $manager->getDefaultDriver();
}
/**
* Assert if a mailable was sent based on a truth-test callback.
*
* @param string|\Closure $mailable
* @param callable|array|string|int|null $callback
* @return void
*/
public function assertSent($mailable, $callback = null)
{
[$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback);
if (is_numeric($callback)) {
return $this->assertSentTimes($mailable, $callback);
}
$suggestion = count($this->queuedMailables) ? ' Did you mean to use assertQueued() instead?' : '';
if (is_array($callback) || is_string($callback)) {
foreach (Arr::wrap($callback) as $address) {
$callback = fn ($mail) => $mail->hasTo($address);
PHPUnit::assertTrue(
$this->sent($mailable, $callback)->count() > 0,
"The expected [{$mailable}] mailable was not sent to address [{$address}].".$suggestion
);
}
return;
}
PHPUnit::assertTrue(
$this->sent($mailable, $callback)->count() > 0,
"The expected [{$mailable}] mailable was not sent.".$suggestion
);
}
/**
* Assert if a mailable was sent a number of times.
*
* @param string $mailable
* @param int $times
* @return void
*/
protected function assertSentTimes($mailable, $times = 1)
{
$count = $this->sent($mailable)->count();
PHPUnit::assertSame(
$times, $count,
sprintf(
"The expected [{$mailable}] mailable was sent {$count} %s instead of {$times} %s.",
Str::plural('time', $count),
Str::plural('time', $times)
)
);
}
/**
* Determine if a mailable was not sent or queued to be sent based on a truth-test callback.
*
* @param string|\Closure $mailable
* @param callable|null $callback
* @return void
*/
public function assertNotOutgoing($mailable, $callback = null)
{
$this->assertNotSent($mailable, $callback);
$this->assertNotQueued($mailable, $callback);
}
/**
* Determine if a mailable was not sent based on a truth-test callback.
*
* @param string|\Closure $mailable
* @param callable|array|string|null $callback
* @return void
*/
public function assertNotSent($mailable, $callback = null)
{
if (is_string($callback) || is_array($callback)) {
foreach (Arr::wrap($callback) as $address) {
$callback = fn ($mail) => $mail->hasTo($address);
PHPUnit::assertCount(
0, $this->sent($mailable, $callback),
"The unexpected [{$mailable}] mailable was sent to address [{$address}]."
);
}
return;
}
[$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback);
PHPUnit::assertCount(
0, $this->sent($mailable, $callback),
"The unexpected [{$mailable}] mailable was sent."
);
}
/**
* Assert that no mailables were sent or queued to be sent.
*
* @return void
*/
public function assertNothingOutgoing()
{
$this->assertNothingSent();
$this->assertNothingQueued();
}
/**
* Assert that no mailables were sent.
*
* @return void
*/
public function assertNothingSent()
{
$mailableNames = (new Collection($this->mailables))->map(
fn ($mailable) => get_class($mailable)
)->join("\n- ");
PHPUnit::assertEmpty($this->mailables, "The following mailables were sent unexpectedly:\n\n- $mailableNames\n");
}
/**
* Assert if a mailable was queued based on a truth-test callback.
*
* @param string|\Closure $mailable
* @param callable|array|string|int|null $callback
* @return void
*/
public function assertQueued($mailable, $callback = null)
{
[$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback);
if (is_numeric($callback)) {
return $this->assertQueuedTimes($mailable, $callback);
}
if (is_string($callback) || is_array($callback)) {
foreach (Arr::wrap($callback) as $address) {
$callback = fn ($mail) => $mail->hasTo($address);
PHPUnit::assertTrue(
$this->queued($mailable, $callback)->count() > 0,
"The expected [{$mailable}] mailable was not queued to address [{$address}]."
);
}
return;
}
PHPUnit::assertTrue(
$this->queued($mailable, $callback)->count() > 0,
"The expected [{$mailable}] mailable was not queued."
);
}
/**
* Assert if a mailable was queued a number of times.
*
* @param string $mailable
* @param int $times
* @return void
*/
protected function assertQueuedTimes($mailable, $times = 1)
{
$count = $this->queued($mailable)->count();
PHPUnit::assertSame(
$times, $count,
sprintf(
"The expected [{$mailable}] mailable was queued {$count} %s instead of {$times} %s.",
Str::plural('time', $count),
Str::plural('time', $times)
)
);
}
/**
* Determine if a mailable was not queued based on a truth-test callback.
*
* @param string|\Closure $mailable
* @param callable|array|string|null $callback
* @return void
*/
public function assertNotQueued($mailable, $callback = null)
{
if (is_string($callback) || is_array($callback)) {
foreach (Arr::wrap($callback) as $address) {
$callback = fn ($mail) => $mail->hasTo($address);
PHPUnit::assertCount(
0, $this->queued($mailable, $callback),
"The unexpected [{$mailable}] mailable was queued to address [{$address}]."
);
}
return;
}
[$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback);
PHPUnit::assertCount(
0, $this->queued($mailable, $callback),
"The unexpected [{$mailable}] mailable was queued."
);
}
/**
* Assert that no mailables were queued.
*
* @return void
*/
public function assertNothingQueued()
{
$mailableNames = (new Collection($this->queuedMailables))->map(
fn ($mailable) => get_class($mailable)
)->join("\n- ");
PHPUnit::assertEmpty($this->queuedMailables, "The following mailables were queued unexpectedly:\n\n- $mailableNames\n");
}
/**
* Assert the total number of mailables that were sent.
*
* @param int $count
* @return void
*/
public function assertSentCount($count)
{
$total = (new Collection($this->mailables))->count();
PHPUnit::assertSame(
$count, $total,
"The total number of mailables sent was {$total} instead of {$count}."
);
}
/**
* Assert the total number of mailables that were queued.
*
* @param int $count
* @return void
*/
public function assertQueuedCount($count)
{
$total = (new Collection($this->queuedMailables))->count();
PHPUnit::assertSame(
$count, $total,
"The total number of mailables queued was {$total} instead of {$count}."
);
}
/**
* Assert the total number of mailables that were sent or queued.
*
* @param int $count
* @return void
*/
public function assertOutgoingCount($count)
{
$total = (new Collection($this->mailables))
->concat($this->queuedMailables)
->count();
PHPUnit::assertSame(
$count, $total,
"The total number of outgoing mailables was {$total} instead of {$count}."
);
}
/**
* Get all of the mailables matching a truth-test callback.
*
* @param string|\Closure $mailable
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function sent($mailable, $callback = null)
{
[$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback);
if (! $this->hasSent($mailable)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
return $this->mailablesOf($mailable)->filter(fn ($mailable) => $callback($mailable));
}
/**
* Determine if the given mailable has been sent.
*
* @param string $mailable
* @return bool
*/
public function hasSent($mailable)
{
return $this->mailablesOf($mailable)->count() > 0;
}
/**
* Get all of the queued mailables matching a truth-test callback.
*
* @param string|\Closure $mailable
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function queued($mailable, $callback = null)
{
[$mailable, $callback] = $this->prepareMailableAndCallback($mailable, $callback);
if (! $this->hasQueued($mailable)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
return $this->queuedMailablesOf($mailable)->filter(fn ($mailable) => $callback($mailable));
}
/**
* Determine if the given mailable has been queued.
*
* @param string $mailable
* @return bool
*/
public function hasQueued($mailable)
{
return $this->queuedMailablesOf($mailable)->count() > 0;
}
/**
* Get all of the mailed mailables for a given type.
*
* @param string $type
* @return \Illuminate\Support\Collection
*/
protected function mailablesOf($type)
{
return (new Collection($this->mailables))->filter(fn ($mailable) => $mailable instanceof $type);
}
/**
* Get all of the mailed mailables for a given type.
*
* @param string $type
* @return \Illuminate\Support\Collection
*/
protected function queuedMailablesOf($type)
{
return (new Collection($this->queuedMailables))->filter(fn ($mailable) => $mailable instanceof $type);
}
/**
* Get a mailer instance by name.
*
* @param string|null $name
* @return \Illuminate\Contracts\Mail\Mailer
*/
public function mailer($name = null)
{
$this->currentMailer = $name;
return $this;
}
/**
* Begin the process of mailing a mailable class instance.
*
* @param mixed $users
* @return \Illuminate\Mail\PendingMail
*/
public function to($users)
{
return (new PendingMailFake($this))->to($users);
}
/**
* Begin the process of mailing a mailable class instance.
*
* @param mixed $users
* @return \Illuminate\Mail\PendingMail
*/
public function cc($users)
{
return (new PendingMailFake($this))->cc($users);
}
/**
* Begin the process of mailing a mailable class instance.
*
* @param mixed $users
* @return \Illuminate\Mail\PendingMail
*/
public function bcc($users)
{
return (new PendingMailFake($this))->bcc($users);
}
/**
* Send a new message with only a raw text part.
*
* @param string $text
* @param \Closure|string $callback
* @return void
*/
public function raw($text, $callback)
{
//
}
/**
* Send a new message using a view.
*
* @param \Illuminate\Contracts\Mail\Mailable|string|array $view
* @param array $data
* @param \Closure|string|null $callback
* @return mixed|void
*/
public function send($view, array $data = [], $callback = null)
{
return $this->sendMail($view, $view instanceof ShouldQueue);
}
/**
* Send a new message synchronously using a view.
*
* @param \Illuminate\Contracts\Mail\Mailable|string|array $mailable
* @param array $data
* @param \Closure|string|null $callback
* @return void
*/
public function sendNow($mailable, array $data = [], $callback = null)
{
$this->sendMail($mailable, shouldQueue: false);
}
/**
* Send a new message using a view.
*
* @param \Illuminate\Contracts\Mail\Mailable|string|array $view
* @param bool $shouldQueue
* @return mixed|void
*/
protected function sendMail($view, $shouldQueue = false)
{
if (! $view instanceof Mailable) {
return;
}
$view->mailer($this->currentMailer);
if ($shouldQueue) {
return $this->queue($view);
}
$this->currentMailer = null;
$this->mailables[] = $view;
}
/**
* Queue a new message for sending.
*
* @param \Illuminate\Contracts\Mail\Mailable|string|array $view
* @param string|null $queue
* @return mixed
*/
public function queue($view, $queue = null)
{
if (! $view instanceof Mailable) {
return;
}
$view->mailer($this->currentMailer);
$this->currentMailer = null;
$this->queuedMailables[] = $view;
}
/**
* Queue a new e-mail message for sending after (n) seconds.
*
* @param \DateTimeInterface|\DateInterval|int $delay
* @param \Illuminate\Contracts\Mail\Mailable|string|array $view
* @param string|null $queue
* @return mixed
*/
public function later($delay, $view, $queue = null)
{
$this->queue($view, $queue);
}
/**
* Infer mailable class using reflection if a typehinted closure is passed to assertion.
*
* @param string|\Closure $mailable
* @param callable|null $callback
* @return array
*/
protected function prepareMailableAndCallback($mailable, $callback)
{
if ($mailable instanceof Closure) {
return [$this->firstClosureParameterType($mailable), $mailable];
}
return [$mailable, $callback];
}
/**
* Forget all of the resolved mailer instances.
*
* @return $this
*/
public function forgetMailers()
{
$this->currentMailer = null;
return $this;
}
/**
* Handle dynamic method calls to the mailer.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->forwardCallTo($this->manager, $method, $parameters);
}
}

View File

@@ -0,0 +1,405 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Closure;
use Exception;
use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher;
use Illuminate\Contracts\Notifications\Factory as NotificationFactory;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Notifications\AnonymousNotifiable;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\ReflectsClosures;
use PHPUnit\Framework\Assert as PHPUnit;
class NotificationFake implements Fake, NotificationDispatcher, NotificationFactory
{
use Macroable, ReflectsClosures;
/**
* All of the notifications that have been sent.
*
* @var array
*/
protected $notifications = [];
/**
* Locale used when sending notifications.
*
* @var string|null
*/
public $locale;
/**
* Indicates if notifications should be serialized and restored when pushed to the queue.
*
* @var bool
*/
protected $serializeAndRestore = false;
/**
* Assert if a notification was sent on-demand based on a truth-test callback.
*
* @param string|\Closure $notification
* @param callable|null $callback
* @return void
*
* @throws \Exception
*/
public function assertSentOnDemand($notification, $callback = null)
{
$this->assertSentTo(new AnonymousNotifiable, $notification, $callback);
}
/**
* Assert if a notification was sent based on a truth-test callback.
*
* @param mixed $notifiable
* @param string|\Closure $notification
* @param callable|null $callback
* @return void
*
* @throws \Exception
*/
public function assertSentTo($notifiable, $notification, $callback = null)
{
if (is_array($notifiable) || $notifiable instanceof Collection) {
if (count($notifiable) === 0) {
throw new Exception('No notifiable given.');
}
foreach ($notifiable as $singleNotifiable) {
$this->assertSentTo($singleNotifiable, $notification, $callback);
}
return;
}
if ($notification instanceof Closure) {
[$notification, $callback] = [$this->firstClosureParameterType($notification), $notification];
}
if (is_numeric($callback)) {
return $this->assertSentToTimes($notifiable, $notification, $callback);
}
PHPUnit::assertTrue(
$this->sent($notifiable, $notification, $callback)->count() > 0,
"The expected [{$notification}] notification was not sent."
);
}
/**
* Assert if a notification was sent on-demand a number of times.
*
* @param string $notification
* @param int $times
* @return void
*/
public function assertSentOnDemandTimes($notification, $times = 1)
{
$this->assertSentToTimes(new AnonymousNotifiable, $notification, $times);
}
/**
* Assert if a notification was sent a number of times.
*
* @param mixed $notifiable
* @param string $notification
* @param int $times
* @return void
*/
public function assertSentToTimes($notifiable, $notification, $times = 1)
{
$count = $this->sent($notifiable, $notification)->count();
PHPUnit::assertSame(
$times, $count,
"Expected [{$notification}] to be sent {$times} times, but was sent {$count} times."
);
}
/**
* Determine if a notification was sent based on a truth-test callback.
*
* @param mixed $notifiable
* @param string|\Closure $notification
* @param callable|null $callback
* @return void
*
* @throws \Exception
*/
public function assertNotSentTo($notifiable, $notification, $callback = null)
{
if (is_array($notifiable) || $notifiable instanceof Collection) {
if (count($notifiable) === 0) {
throw new Exception('No notifiable given.');
}
foreach ($notifiable as $singleNotifiable) {
$this->assertNotSentTo($singleNotifiable, $notification, $callback);
}
return;
}
if ($notification instanceof Closure) {
[$notification, $callback] = [$this->firstClosureParameterType($notification), $notification];
}
PHPUnit::assertCount(
0, $this->sent($notifiable, $notification, $callback),
"The unexpected [{$notification}] notification was sent."
);
}
/**
* Assert that no notifications were sent.
*
* @return void
*/
public function assertNothingSent()
{
$notificationNames = (new Collection($this->notifications))
->map(fn ($notifiableModels) => (new Collection($notifiableModels))
->map(fn ($notifiables) => (new Collection($notifiables))->keys())
)
->flatten()->join("\n- ");
PHPUnit::assertEmpty($this->notifications, "The following notifications were sent unexpectedly:\n\n- $notificationNames\n");
}
/**
* Assert that no notifications were sent to the given notifiable.
*
* @param mixed $notifiable
* @return void
*
* @throws \Exception
*/
public function assertNothingSentTo($notifiable)
{
if (is_array($notifiable) || $notifiable instanceof Collection) {
if (count($notifiable) === 0) {
throw new Exception('No notifiable given.');
}
foreach ($notifiable as $singleNotifiable) {
$this->assertNothingSentTo($singleNotifiable);
}
return;
}
PHPUnit::assertEmpty(
$this->notifications[get_class($notifiable)][$notifiable->getKey()] ?? [],
'Notifications were sent unexpectedly.',
);
}
/**
* Assert the total amount of times a notification was sent.
*
* @param string $notification
* @param int $expectedCount
* @return void
*/
public function assertSentTimes($notification, $expectedCount)
{
$actualCount = (new Collection($this->notifications))
->flatten(1)
->reduce(fn ($count, $sent) => $count + count($sent[$notification] ?? []), 0);
PHPUnit::assertSame(
$expectedCount, $actualCount,
sprintf(
"Expected [{$notification}] to be sent {$expectedCount} %s, but was sent {$actualCount} %s.",
Str::plural('time', $expectedCount),
Str::plural('time', $actualCount)
)
);
}
/**
* Assert the total count of notification that were sent.
*
* @param int $expectedCount
* @return void
*/
public function assertCount($expectedCount)
{
$actualCount = (new Collection($this->notifications))->flatten(3)->count();
PHPUnit::assertSame(
$expectedCount, $actualCount,
"Expected {$expectedCount} notifications to be sent, but {$actualCount} were sent."
);
}
/**
* Get all of the notifications matching a truth-test callback.
*
* @param mixed $notifiable
* @param string $notification
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function sent($notifiable, $notification, $callback = null)
{
if (! $this->hasSent($notifiable, $notification)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
$notifications = new Collection($this->notificationsFor($notifiable, $notification));
return $notifications->filter(
fn ($arguments) => $callback(...array_values($arguments))
)->pluck('notification');
}
/**
* Determine if there are more notifications left to inspect.
*
* @param mixed $notifiable
* @param string $notification
* @return bool
*/
public function hasSent($notifiable, $notification)
{
return ! empty($this->notificationsFor($notifiable, $notification));
}
/**
* Get all of the notifications for a notifiable entity by type.
*
* @param mixed $notifiable
* @param string $notification
* @return array
*/
protected function notificationsFor($notifiable, $notification)
{
return $this->notifications[get_class($notifiable)][(string) $notifiable->getKey()][$notification] ?? [];
}
/**
* Send the given notification to the given notifiable entities.
*
* @param \Illuminate\Support\Collection|mixed $notifiables
* @param mixed $notification
* @return void
*/
public function send($notifiables, $notification)
{
$this->sendNow($notifiables, $notification);
}
/**
* Send the given notification immediately.
*
* @param \Illuminate\Support\Collection|mixed $notifiables
* @param mixed $notification
* @param array|null $channels
* @return void
*/
public function sendNow($notifiables, $notification, ?array $channels = null)
{
if (! $notifiables instanceof Collection && ! is_array($notifiables)) {
$notifiables = [$notifiables];
}
foreach ($notifiables as $notifiable) {
if (! $notification->id) {
$notification->id = Str::uuid()->toString();
}
$notifiableChannels = $channels ?: $notification->via($notifiable);
if (method_exists($notification, 'shouldSend')) {
$notifiableChannels = array_filter(
$notifiableChannels,
fn ($channel) => $notification->shouldSend($notifiable, $channel) !== false
);
}
if (empty($notifiableChannels)) {
continue;
}
$this->notifications[get_class($notifiable)][(string) $notifiable->getKey()][get_class($notification)][] = [
'notification' => $this->serializeAndRestore && $notification instanceof ShouldQueue
? $this->serializeAndRestoreNotification($notification)
: $notification,
'channels' => $notifiableChannels,
'notifiable' => $notifiable,
'locale' => $notification->locale ?? $this->locale ?? value(function () use ($notifiable) {
if ($notifiable instanceof HasLocalePreference) {
return $notifiable->preferredLocale();
}
}),
];
}
}
/**
* Get a channel instance by name.
*
* @param string|null $name
* @return mixed
*/
public function channel($name = null)
{
//
}
/**
* Set the locale of notifications.
*
* @param string $locale
* @return $this
*/
public function locale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* Specify if notification should be serialized and restored when being "pushed" to the queue.
*
* @param bool $serializeAndRestore
* @return $this
*/
public function serializeAndRestore(bool $serializeAndRestore = true)
{
$this->serializeAndRestore = $serializeAndRestore;
return $this;
}
/**
* Serialize and unserialize the notification to simulate the queueing process.
*
* @param mixed $notification
* @return mixed
*/
protected function serializeAndRestoreNotification($notification)
{
return unserialize(serialize($notification));
}
/**
* Get the notifications that have been sent.
*
* @return array
*/
public function sentNotifications()
{
return $this->notifications;
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Illuminate\Bus\PendingBatch;
use Illuminate\Support\Collection;
class PendingBatchFake extends PendingBatch
{
/**
* The fake bus instance.
*
* @var \Illuminate\Support\Testing\Fakes\BusFake
*/
protected $bus;
/**
* Create a new pending batch instance.
*
* @param \Illuminate\Support\Testing\Fakes\BusFake $bus
* @param \Illuminate\Support\Collection $jobs
*/
public function __construct(BusFake $bus, Collection $jobs)
{
$this->bus = $bus;
$this->jobs = $jobs;
}
/**
* Dispatch the batch.
*
* @return \Illuminate\Bus\Batch
*/
public function dispatch()
{
return $this->bus->recordPendingBatch($this);
}
/**
* Dispatch the batch after the response is sent to the browser.
*
* @return \Illuminate\Bus\Batch
*/
public function dispatchAfterResponse()
{
return $this->bus->recordPendingBatch($this);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Closure;
use Illuminate\Foundation\Bus\PendingChain;
use Illuminate\Queue\CallQueuedClosure;
class PendingChainFake extends PendingChain
{
/**
* The fake bus instance.
*
* @var \Illuminate\Support\Testing\Fakes\BusFake
*/
protected $bus;
/**
* Create a new pending chain instance.
*
* @param \Illuminate\Support\Testing\Fakes\BusFake $bus
* @param mixed $job
* @param array $chain
*/
public function __construct(BusFake $bus, $job, $chain)
{
$this->bus = $bus;
$this->job = $job;
$this->chain = $chain;
}
/**
* Dispatch the job with the given arguments.
*
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public function dispatch()
{
if (is_string($this->job)) {
$firstJob = new $this->job(...func_get_args());
} elseif ($this->job instanceof Closure) {
$firstJob = CallQueuedClosure::create($this->job);
} else {
$firstJob = $this->job;
}
$firstJob->allOnConnection($this->connection);
$firstJob->allOnQueue($this->queue);
$firstJob->chain($this->chain);
$firstJob->delay($this->delay);
$firstJob->chainCatchCallbacks = $this->catchCallbacks();
return $this->bus->dispatch($firstJob);
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Mail\PendingMail;
class PendingMailFake extends PendingMail
{
/**
* Create a new instance.
*
* @param \Illuminate\Support\Testing\Fakes\MailFake $mailer
*/
public function __construct($mailer)
{
$this->mailer = $mailer;
}
/**
* Send a new mailable message instance.
*
* @param \Illuminate\Contracts\Mail\Mailable $mailable
* @return void
*/
public function send(Mailable $mailable)
{
$this->mailer->send($this->fill($mailable));
}
/**
* Send a new mailable message instance synchronously.
*
* @param \Illuminate\Contracts\Mail\Mailable $mailable
* @return void
*/
public function sendNow(Mailable $mailable)
{
$this->mailer->sendNow($this->fill($mailable));
}
/**
* Push the given mailable onto the queue.
*
* @param \Illuminate\Contracts\Mail\Mailable $mailable
* @return mixed
*/
public function queue(Mailable $mailable)
{
return $this->mailer->queue($this->fill($mailable));
}
}

View File

@@ -0,0 +1,689 @@
<?php
namespace Illuminate\Support\Testing\Fakes;
use BadMethodCallException;
use Closure;
use Illuminate\Contracts\Queue\Queue;
use Illuminate\Events\CallQueuedListener;
use Illuminate\Queue\CallQueuedClosure;
use Illuminate\Queue\QueueManager;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ReflectsClosures;
use PHPUnit\Framework\Assert as PHPUnit;
/**
* @phpstan-type RawPushType array{"payload": string, "queue": string|null, "options": array<array-key, mixed>}
*/
class QueueFake extends QueueManager implements Fake, Queue
{
use ReflectsClosures;
/**
* The original queue manager.
*
* @var \Illuminate\Contracts\Queue\Queue
*/
public $queue;
/**
* The job types that should be intercepted instead of pushed to the queue.
*
* @var \Illuminate\Support\Collection
*/
protected $jobsToFake;
/**
* The job types that should be pushed to the queue and not intercepted.
*
* @var \Illuminate\Support\Collection
*/
protected $jobsToBeQueued;
/**
* All of the jobs that have been pushed.
*
* @var array
*/
protected $jobs = [];
/**
* All of the payloads that have been raw pushed.
*
* @var list<RawPushType>
*/
protected $rawPushes = [];
/**
* Indicates if items should be serialized and restored when pushed to the queue.
*
* @var bool
*/
protected bool $serializeAndRestore = false;
/**
* Create a new fake queue instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param array $jobsToFake
* @param \Illuminate\Queue\QueueManager|null $queue
*/
public function __construct($app, $jobsToFake = [], $queue = null)
{
parent::__construct($app);
$this->jobsToFake = Collection::wrap($jobsToFake);
$this->jobsToBeQueued = new Collection;
$this->queue = $queue;
}
/**
* Specify the jobs that should be queued instead of faked.
*
* @param array|string $jobsToBeQueued
* @return $this
*/
public function except($jobsToBeQueued)
{
$this->jobsToBeQueued = Collection::wrap($jobsToBeQueued)->merge($this->jobsToBeQueued);
return $this;
}
/**
* Assert if a job was pushed based on a truth-test callback.
*
* @param string|\Closure $job
* @param callable|int|null $callback
* @return void
*/
public function assertPushed($job, $callback = null)
{
if ($job instanceof Closure) {
[$job, $callback] = [$this->firstClosureParameterType($job), $job];
}
if (is_numeric($callback)) {
return $this->assertPushedTimes($job, $callback);
}
PHPUnit::assertTrue(
$this->pushed($job, $callback)->count() > 0,
"The expected [{$job}] job was not pushed."
);
}
/**
* Assert if a job was pushed a number of times.
*
* @param string $job
* @param int $times
* @return void
*/
protected function assertPushedTimes($job, $times = 1)
{
$count = $this->pushed($job)->count();
PHPUnit::assertSame(
$times, $count,
sprintf(
"The expected [{$job}] job was pushed {$count} %s instead of {$times} %s.",
Str::plural('time', $count),
Str::plural('time', $times)
)
);
}
/**
* Assert if a job was pushed based on a truth-test callback.
*
* @param string $queue
* @param string|\Closure $job
* @param callable|null $callback
* @return void
*/
public function assertPushedOn($queue, $job, $callback = null)
{
if ($job instanceof Closure) {
[$job, $callback] = [$this->firstClosureParameterType($job), $job];
}
$this->assertPushed($job, function ($job, $pushedQueue) use ($callback, $queue) {
if ($pushedQueue !== $queue) {
return false;
}
return $callback ? $callback(...func_get_args()) : true;
});
}
/**
* Assert if a job was pushed with chained jobs based on a truth-test callback.
*
* @param string $job
* @param array $expectedChain
* @param callable|null $callback
* @return void
*/
public function assertPushedWithChain($job, $expectedChain = [], $callback = null)
{
PHPUnit::assertTrue(
$this->pushed($job, $callback)->isNotEmpty(),
"The expected [{$job}] job was not pushed."
);
PHPUnit::assertTrue(
(new Collection($expectedChain))->isNotEmpty(),
'The expected chain can not be empty.'
);
$this->isChainOfObjects($expectedChain)
? $this->assertPushedWithChainOfObjects($job, $expectedChain, $callback)
: $this->assertPushedWithChainOfClasses($job, $expectedChain, $callback);
}
/**
* Assert if a job was pushed with an empty chain based on a truth-test callback.
*
* @param string $job
* @param callable|null $callback
* @return void
*/
public function assertPushedWithoutChain($job, $callback = null)
{
PHPUnit::assertTrue(
$this->pushed($job, $callback)->isNotEmpty(),
"The expected [{$job}] job was not pushed."
);
$this->assertPushedWithChainOfClasses($job, [], $callback);
}
/**
* Assert if a job was pushed with chained jobs based on a truth-test callback.
*
* @param string $job
* @param array $expectedChain
* @param callable|null $callback
* @return void
*/
protected function assertPushedWithChainOfObjects($job, $expectedChain, $callback)
{
$chain = (new Collection($expectedChain))->map(fn ($job) => serialize($job))->all();
PHPUnit::assertTrue(
$this->pushed($job, $callback)->filter(fn ($job) => $job->chained == $chain)->isNotEmpty(),
'The expected chain was not pushed.'
);
}
/**
* Assert if a job was pushed with chained jobs based on a truth-test callback.
*
* @param string $job
* @param array $expectedChain
* @param callable|null $callback
* @return void
*/
protected function assertPushedWithChainOfClasses($job, $expectedChain, $callback)
{
$matching = $this->pushed($job, $callback)->map->chained->map(function ($chain) {
return (new Collection($chain))->map(function ($job) {
return get_class(unserialize($job));
});
})->filter(function ($chain) use ($expectedChain) {
return $chain->all() === $expectedChain;
});
PHPUnit::assertTrue(
$matching->isNotEmpty(), 'The expected chain was not pushed.'
);
}
/**
* Assert if a closure was pushed based on a truth-test callback.
*
* @param callable|int|null $callback
* @return void
*/
public function assertClosurePushed($callback = null)
{
$this->assertPushed(CallQueuedClosure::class, $callback);
}
/**
* Assert that a closure was not pushed based on a truth-test callback.
*
* @param callable|null $callback
* @return void
*/
public function assertClosureNotPushed($callback = null)
{
$this->assertNotPushed(CallQueuedClosure::class, $callback);
}
/**
* Determine if the given chain is entirely composed of objects.
*
* @param array $chain
* @return bool
*/
protected function isChainOfObjects($chain)
{
return ! (new Collection($chain))->contains(fn ($job) => ! is_object($job));
}
/**
* Determine if a job was pushed based on a truth-test callback.
*
* @param string|\Closure $job
* @param callable|null $callback
* @return void
*/
public function assertNotPushed($job, $callback = null)
{
if ($job instanceof Closure) {
[$job, $callback] = [$this->firstClosureParameterType($job), $job];
}
PHPUnit::assertCount(
0, $this->pushed($job, $callback),
"The unexpected [{$job}] job was pushed."
);
}
/**
* Assert the total count of jobs that were pushed.
*
* @param int $expectedCount
* @return void
*/
public function assertCount($expectedCount)
{
$actualCount = (new Collection($this->jobs))->flatten(1)->count();
PHPUnit::assertSame(
$expectedCount, $actualCount,
"Expected {$expectedCount} jobs to be pushed, but found {$actualCount} instead."
);
}
/**
* Assert that no jobs were pushed.
*
* @return void
*/
public function assertNothingPushed()
{
$pushedJobs = implode("\n- ", array_keys($this->jobs));
PHPUnit::assertEmpty($this->jobs, "The following jobs were pushed unexpectedly:\n\n- $pushedJobs\n");
}
/**
* Get all of the jobs matching a truth-test callback.
*
* @param string $job
* @param callable|null $callback
* @return \Illuminate\Support\Collection
*/
public function pushed($job, $callback = null)
{
if (! $this->hasPushed($job)) {
return new Collection;
}
$callback = $callback ?: fn () => true;
return (new Collection($this->jobs[$job]))->filter(
fn ($data) => $callback($data['job'], $data['queue'], $data['data'])
)->pluck('job');
}
/**
* Get all of the raw pushes matching a truth-test callback.
*
* @param null|\Closure(string, ?string, array): bool $callback
* @return \Illuminate\Support\Collection<int, RawPushType>
*/
public function pushedRaw($callback = null)
{
$callback ??= static fn () => true;
return (new Collection($this->rawPushes))->filter(fn ($data) => $callback($data['payload'], $data['queue'], $data['options']));
}
/**
* Get all of the jobs by listener class, passing an optional truth-test callback.
*
* @param class-string $listenerClass
* @param (\Closure(mixed, \Illuminate\Events\CallQueuedListener, string|null, mixed): bool)|null $callback
* @return \Illuminate\Support\Collection<int, \Illuminate\Events\CallQueuedListener>
*/
public function listenersPushed($listenerClass, $callback = null)
{
if (! $this->hasPushed(CallQueuedListener::class)) {
return new Collection;
}
$collection = (new Collection($this->jobs[CallQueuedListener::class]))
->filter(fn ($data) => $data['job']->class === $listenerClass);
if ($callback) {
$collection = $collection->filter(fn ($data) => $callback($data['job']->data[0] ?? null, $data['job'], $data['queue'], $data['data']));
}
return $collection->pluck('job');
}
/**
* Determine if there are any stored jobs for a given class.
*
* @param string $job
* @return bool
*/
public function hasPushed($job)
{
return isset($this->jobs[$job]) && ! empty($this->jobs[$job]);
}
/**
* Resolve a queue connection instance.
*
* @param mixed $value
* @return \Illuminate\Contracts\Queue\Queue
*/
public function connection($value = null)
{
return $this;
}
/**
* Get the size of the queue.
*
* @param string|null $queue
* @return int
*/
public function size($queue = null)
{
return (new Collection($this->jobs))
->flatten(1)
->filter(fn ($job) => $job['queue'] === $queue)
->count();
}
/**
* Get the number of pending jobs.
*
* @param string|null $queue
* @return int
*/
public function pendingSize($queue = null)
{
return $this->size($queue);
}
/**
* Get the number of delayed jobs.
*
* @param string|null $queue
* @return int
*/
public function delayedSize($queue = null)
{
return 0;
}
/**
* Get the number of reserved jobs.
*
* @param string|null $queue
* @return int
*/
public function reservedSize($queue = null)
{
return 0;
}
/**
* Get the creation timestamp of the oldest pending job, excluding delayed jobs.
*
* @param string|null $queue
* @return int|null
*/
public function creationTimeOfOldestPendingJob($queue = null)
{
return null;
}
/**
* Push a new job onto the queue.
*
* @param string|object $job
* @param mixed $data
* @param string|null $queue
* @return mixed
*/
public function push($job, $data = '', $queue = null)
{
if ($this->shouldFakeJob($job)) {
if ($job instanceof Closure) {
$job = CallQueuedClosure::create($job);
}
$this->jobs[is_object($job) ? get_class($job) : $job][] = [
'job' => $this->serializeAndRestore ? $this->serializeAndRestoreJob($job) : $job,
'queue' => $queue,
'data' => $data,
];
} else {
is_object($job) && isset($job->connection)
? $this->queue->connection($job->connection)->push($job, $data, $queue)
: $this->queue->push($job, $data, $queue);
}
}
/**
* Determine if a job should be faked or actually dispatched.
*
* @param object $job
* @return bool
*/
public function shouldFakeJob($job)
{
if ($this->shouldDispatchJob($job)) {
return false;
}
if ($this->jobsToFake->isEmpty()) {
return true;
}
return $this->jobsToFake->contains(
fn ($jobToFake) => $job instanceof ((string) $jobToFake) || $job === (string) $jobToFake
);
}
/**
* Determine if a job should be pushed to the queue instead of faked.
*
* @param object $job
* @return bool
*/
protected function shouldDispatchJob($job)
{
if ($this->jobsToBeQueued->isEmpty()) {
return false;
}
return $this->jobsToBeQueued->contains(
fn ($jobToQueue) => $job instanceof ((string) $jobToQueue)
);
}
/**
* Push a raw payload onto the queue.
*
* @param string $payload
* @param string|null $queue
* @param array $options
* @return mixed
*/
public function pushRaw($payload, $queue = null, array $options = [])
{
$this->rawPushes[] = [
'payload' => $payload,
'queue' => $queue,
'options' => $options,
];
}
/**
* Push a new job onto the queue after (n) seconds.
*
* @param \DateTimeInterface|\DateInterval|int $delay
* @param string|object $job
* @param mixed $data
* @param string|null $queue
* @return mixed
*/
public function later($delay, $job, $data = '', $queue = null)
{
return $this->push($job, $data, $queue);
}
/**
* Push a new job onto the queue.
*
* @param string $queue
* @param string|object $job
* @param mixed $data
* @return mixed
*/
public function pushOn($queue, $job, $data = '')
{
return $this->push($job, $data, $queue);
}
/**
* Push a new job onto a specific queue after (n) seconds.
*
* @param string $queue
* @param \DateTimeInterface|\DateInterval|int $delay
* @param string|object $job
* @param mixed $data
* @return mixed
*/
public function laterOn($queue, $delay, $job, $data = '')
{
return $this->push($job, $data, $queue);
}
/**
* Pop the next job off of the queue.
*
* @param string|null $queue
* @return \Illuminate\Contracts\Queue\Job|null
*/
public function pop($queue = null)
{
//
}
/**
* Push an array of jobs onto the queue.
*
* @param array $jobs
* @param mixed $data
* @param string|null $queue
* @return mixed
*/
public function bulk($jobs, $data = '', $queue = null)
{
foreach ($jobs as $job) {
$this->push($job, $data, $queue);
}
}
/**
* Get the jobs that have been pushed.
*
* @return array
*/
public function pushedJobs()
{
return $this->jobs;
}
/**
* Get the payloads that were pushed raw.
*
* @return list<RawPushType>
*/
public function rawPushes()
{
return $this->rawPushes;
}
/**
* Specify if jobs should be serialized and restored when being "pushed" to the queue.
*
* @param bool $serializeAndRestore
* @return $this
*/
public function serializeAndRestore(bool $serializeAndRestore = true)
{
$this->serializeAndRestore = $serializeAndRestore;
return $this;
}
/**
* Serialize and unserialize the job to simulate the queueing process.
*
* @param mixed $job
* @return mixed
*/
protected function serializeAndRestoreJob($job)
{
return unserialize(serialize($job));
}
/**
* Get the connection name for the queue.
*
* @return string
*/
public function getConnectionName()
{
//
}
/**
* Set the connection name for the queue.
*
* @param string $name
* @return $this
*/
public function setConnectionName($name)
{
return $this;
}
/**
* Override the QueueManager to prevent circular dependency.
*
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
throw new BadMethodCallException(sprintf(
'Call to undefined method %s::%s()', static::class, $method
));
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Illuminate\Support;
use Throwable;
class Timebox
{
/**
* Indicates if the timebox is allowed to return early.
*
* @var bool
*/
public $earlyReturn = false;
/**
* Invoke the given callback within the specified timebox minimum.
*
* @template TCallReturnType
*
* @param (callable($this): TCallReturnType) $callback
* @param int $microseconds
* @return TCallReturnType
*
* @throws \Throwable
*/
public function call(callable $callback, int $microseconds)
{
$exception = null;
$start = microtime(true);
try {
$result = $callback($this);
} catch (Throwable $caught) {
$exception = $caught;
}
$remainder = intval($microseconds - ((microtime(true) - $start) * 1000000));
if (! $this->earlyReturn && $remainder > 0) {
$this->usleep($remainder);
}
if ($exception) {
throw $exception;
}
return $result;
}
/**
* Indicate that the timebox can return early.
*
* @return $this
*/
public function returnEarly()
{
$this->earlyReturn = true;
return $this;
}
/**
* Indicate that the timebox cannot return early.
*
* @return $this
*/
public function dontReturnEarly()
{
$this->earlyReturn = false;
return $this;
}
/**
* Sleep for the specified number of microseconds.
*
* @param int $microseconds
* @return void
*/
protected function usleep(int $microseconds)
{
Sleep::usleep($microseconds);
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Illuminate\Support\Traits;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\Fluent;
trait CapsuleManagerTrait
{
/**
* The current globally used instance.
*
* @var object
*/
protected static $instance;
/**
* The container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* Setup the IoC container instance.
*
* @param \Illuminate\Contracts\Container\Container $container
* @return void
*/
protected function setupContainer(Container $container)
{
$this->container = $container;
if (! $this->container->bound('config')) {
$this->container->instance('config', new Fluent);
}
}
/**
* Make this capsule instance available globally.
*
* @return void
*/
public function setAsGlobal()
{
static::$instance = $this;
}
/**
* Get the IoC container instance.
*
* @return \Illuminate\Contracts\Container\Container
*/
public function getContainer()
{
return $this->container;
}
/**
* Set the IoC container instance.
*
* @param \Illuminate\Contracts\Container\Container $container
* @return void
*/
public function setContainer(Container $container)
{
$this->container = $container;
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Illuminate\Support\Traits;
trait Dumpable
{
/**
* Dump the given arguments and terminate execution.
*
* @param mixed ...$args
* @return never
*/
public function dd(...$args)
{
dd($this, ...$args);
}
/**
* Dump the given arguments.
*
* @param mixed ...$args
* @return $this
*/
public function dump(...$args)
{
dump($this, ...$args);
return $this;
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Illuminate\Support\Traits;
use BadMethodCallException;
use Error;
trait ForwardsCalls
{
/**
* Forward a method call to the given object.
*
* @param mixed $object
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
protected function forwardCallTo($object, $method, $parameters)
{
try {
return $object->{$method}(...$parameters);
} catch (Error|BadMethodCallException $e) {
$pattern = '~^Call to undefined method (?P<class>[^:]+)::(?P<method>[^\(]+)\(\)$~';
if (! preg_match($pattern, $e->getMessage(), $matches)) {
throw $e;
}
if ($matches['class'] != get_class($object) ||
$matches['method'] != $method) {
throw $e;
}
static::throwBadMethodCallException($method);
}
}
/**
* Forward a method call to the given object, returning $this if the forwarded call returned itself.
*
* @param mixed $object
* @param string $method
* @param array $parameters
* @return mixed
*
* @throws \BadMethodCallException
*/
protected function forwardDecoratedCallTo($object, $method, $parameters)
{
$result = $this->forwardCallTo($object, $method, $parameters);
return $result === $object ? $this : $result;
}
/**
* Throw a bad method call exception for the given method.
*
* @param string $method
* @return never
*
* @throws \BadMethodCallException
*/
protected static function throwBadMethodCallException($method)
{
throw new BadMethodCallException(sprintf(
'Call to undefined method %s::%s()', static::class, $method
));
}
}

View File

@@ -0,0 +1,426 @@
<?php
namespace Illuminate\Support\Traits;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use stdClass;
use function Illuminate\Support\enum_value;
trait InteractsWithData
{
/**
* Retrieve all data from the instance.
*
* @param mixed $keys
* @return array
*/
abstract public function all($keys = null);
/**
* Retrieve data from the instance.
*
* @param string|null $key
* @param mixed $default
* @return mixed
*/
abstract protected function data($key = null, $default = null);
/**
* Determine if the data contains a given key.
*
* @param string|array $key
* @return bool
*/
public function exists($key)
{
return $this->has($key);
}
/**
* Determine if the data contains a given key.
*
* @param string|array $key
* @return bool
*/
public function has($key)
{
$keys = is_array($key) ? $key : func_get_args();
$data = $this->all();
foreach ($keys as $value) {
if (! Arr::has($data, $value)) {
return false;
}
}
return true;
}
/**
* Determine if the instance contains any of the given keys.
*
* @param string|array $keys
* @return bool
*/
public function hasAny($keys)
{
$keys = is_array($keys) ? $keys : func_get_args();
$data = $this->all();
return Arr::hasAny($data, $keys);
}
/**
* Apply the callback if the instance contains the given key.
*
* @param string $key
* @param callable $callback
* @param callable|null $default
* @return $this|mixed
*/
public function whenHas($key, callable $callback, ?callable $default = null)
{
if ($this->has($key)) {
return $callback(data_get($this->all(), $key)) ?: $this;
}
if ($default) {
return $default();
}
return $this;
}
/**
* Determine if the instance contains a non-empty value for the given key.
*
* @param string|array $key
* @return bool
*/
public function filled($key)
{
$keys = is_array($key) ? $key : func_get_args();
foreach ($keys as $value) {
if ($this->isEmptyString($value)) {
return false;
}
}
return true;
}
/**
* Determine if the instance contains an empty value for the given key.
*
* @param string|array $key
* @return bool
*/
public function isNotFilled($key)
{
$keys = is_array($key) ? $key : func_get_args();
foreach ($keys as $value) {
if (! $this->isEmptyString($value)) {
return false;
}
}
return true;
}
/**
* Determine if the instance contains a non-empty value for any of the given keys.
*
* @param string|array $keys
* @return bool
*/
public function anyFilled($keys)
{
$keys = is_array($keys) ? $keys : func_get_args();
foreach ($keys as $key) {
if ($this->filled($key)) {
return true;
}
}
return false;
}
/**
* Apply the callback if the instance contains a non-empty value for the given key.
*
* @param string $key
* @param callable $callback
* @param callable|null $default
* @return $this|mixed
*/
public function whenFilled($key, callable $callback, ?callable $default = null)
{
if ($this->filled($key)) {
return $callback(data_get($this->all(), $key)) ?: $this;
}
if ($default) {
return $default();
}
return $this;
}
/**
* Determine if the instance is missing a given key.
*
* @param string|array $key
* @return bool
*/
public function missing($key)
{
$keys = is_array($key) ? $key : func_get_args();
return ! $this->has($keys);
}
/**
* Apply the callback if the instance is missing the given key.
*
* @param string $key
* @param callable $callback
* @param callable|null $default
* @return $this|mixed
*/
public function whenMissing($key, callable $callback, ?callable $default = null)
{
if ($this->missing($key)) {
return $callback(data_get($this->all(), $key)) ?: $this;
}
if ($default) {
return $default();
}
return $this;
}
/**
* Determine if the given key is an empty string for "filled".
*
* @param string $key
* @return bool
*/
protected function isEmptyString($key)
{
$value = $this->data($key);
return ! is_bool($value) && ! is_array($value) && trim((string) $value) === '';
}
/**
* Retrieve data from the instance as a Stringable instance.
*
* @param string $key
* @param mixed $default
* @return \Illuminate\Support\Stringable
*/
public function str($key, $default = null)
{
return $this->string($key, $default);
}
/**
* Retrieve data from the instance as a Stringable instance.
*
* @param string $key
* @param mixed $default
* @return \Illuminate\Support\Stringable
*/
public function string($key, $default = null)
{
return Str::of($this->data($key, $default));
}
/**
* Retrieve data as a boolean value.
*
* Returns true when value is "1", "true", "on", and "yes". Otherwise, returns false.
*
* @param string|null $key
* @param bool $default
* @return bool
*/
public function boolean($key = null, $default = false)
{
return filter_var($this->data($key, $default), FILTER_VALIDATE_BOOLEAN);
}
/**
* Retrieve data as an integer value.
*
* @param string $key
* @param int $default
* @return int
*/
public function integer($key, $default = 0)
{
return intval($this->data($key, $default));
}
/**
* Retrieve data as a float value.
*
* @param string $key
* @param float $default
* @return float
*/
public function float($key, $default = 0.0)
{
return floatval($this->data($key, $default));
}
/**
* Retrieve data from the instance as a Carbon instance.
*
* @param string $key
* @param string|null $format
* @param \UnitEnum|string|null $tz
* @return \Illuminate\Support\Carbon|null
*
* @throws \Carbon\Exceptions\InvalidFormatException
*/
public function date($key, $format = null, $tz = null)
{
$tz = enum_value($tz);
if ($this->isNotFilled($key)) {
return null;
}
if (is_null($format)) {
return Date::parse($this->data($key), $tz);
}
return Date::createFromFormat($format, $this->data($key), $tz);
}
/**
* Retrieve data from the instance as an enum.
*
* @template TEnum of \BackedEnum
*
* @param string $key
* @param class-string<TEnum> $enumClass
* @param TEnum|null $default
* @return TEnum|null
*/
public function enum($key, $enumClass, $default = null)
{
if ($this->isNotFilled($key) || ! $this->isBackedEnum($enumClass)) {
return value($default);
}
return $enumClass::tryFrom($this->data($key)) ?: value($default);
}
/**
* Retrieve data from the instance as an array of enums.
*
* @template TEnum of \BackedEnum
*
* @param string $key
* @param class-string<TEnum> $enumClass
* @return TEnum[]
*/
public function enums($key, $enumClass)
{
if ($this->isNotFilled($key) || ! $this->isBackedEnum($enumClass)) {
return [];
}
return $this->collect($key)
->map(fn ($value) => $enumClass::tryFrom($value))
->filter()
->all();
}
/**
* Determine if the given enum class is backed.
*
* @param class-string $enumClass
* @return bool
*/
protected function isBackedEnum($enumClass)
{
return enum_exists($enumClass) && method_exists($enumClass, 'tryFrom');
}
/**
* Retrieve data from the instance as an array.
*
* @param array|string|null $key
* @return array
*/
public function array($key = null)
{
return (array) (is_array($key) ? $this->only($key) : $this->data($key));
}
/**
* Retrieve data from the instance as a collection.
*
* @param array|string|null $key
* @return \Illuminate\Support\Collection
*/
public function collect($key = null)
{
return new Collection(is_array($key) ? $this->only($key) : $this->data($key));
}
/**
* Get a subset containing the provided keys with values from the instance data.
*
* @param mixed $keys
* @return array
*/
public function only($keys)
{
$results = [];
$data = $this->all();
$placeholder = new stdClass;
foreach (is_array($keys) ? $keys : func_get_args() as $key) {
$value = data_get($data, $key, $placeholder);
if ($value !== $placeholder) {
Arr::set($results, $key, $value);
}
}
return $results;
}
/**
* Get all of the data except for a specified array of items.
*
* @param mixed $keys
* @return array
*/
public function except($keys)
{
$keys = is_array($keys) ? $keys : func_get_args();
$results = $this->all();
Arr::forget($results, $keys);
return $results;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Illuminate\Support\Traits;
use Illuminate\Container\Container;
trait Localizable
{
/**
* Run the callback with the given locale.
*
* @param string $locale
* @param \Closure $callback
* @return mixed
*/
public function withLocale($locale, $callback)
{
if (! $locale) {
return $callback();
}
$app = Container::getInstance();
$original = $app->getLocale();
try {
$app->setLocale($locale);
return $callback();
} finally {
$app->setLocale($original);
}
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace Illuminate\Support\Traits;
use Closure;
use Illuminate\Support\Collection;
use Illuminate\Support\Reflector;
use ReflectionFunction;
use RuntimeException;
trait ReflectsClosures
{
/**
* Get the class name of the first parameter of the given Closure.
*
* @param \Closure $closure
* @return string
*
* @throws \ReflectionException
* @throws \RuntimeException
*/
protected function firstClosureParameterType(Closure $closure)
{
$types = array_values($this->closureParameterTypes($closure));
if (! $types) {
throw new RuntimeException('The given Closure has no parameters.');
}
if ($types[0] === null) {
throw new RuntimeException('The first parameter of the given Closure is missing a type hint.');
}
return $types[0];
}
/**
* Get the class names of the first parameter of the given Closure, including union types.
*
* @param \Closure $closure
* @return array
*
* @throws \ReflectionException
* @throws \RuntimeException
*/
protected function firstClosureParameterTypes(Closure $closure)
{
$reflection = new ReflectionFunction($closure);
$types = (new Collection($reflection->getParameters()))
->mapWithKeys(function ($parameter) {
if ($parameter->isVariadic()) {
return [$parameter->getName() => null];
}
return [$parameter->getName() => Reflector::getParameterClassNames($parameter)];
})
->filter()
->values()
->all();
if (empty($types)) {
throw new RuntimeException('The given Closure has no parameters.');
}
if (isset($types[0]) && empty($types[0])) {
throw new RuntimeException('The first parameter of the given Closure is missing a type hint.');
}
return $types[0];
}
/**
* Get the class names / types of the parameters of the given Closure.
*
* @param \Closure $closure
* @return array
*
* @throws \ReflectionException
*/
protected function closureParameterTypes(Closure $closure)
{
$reflection = new ReflectionFunction($closure);
return (new Collection($reflection->getParameters()))
->mapWithKeys(function ($parameter) {
if ($parameter->isVariadic()) {
return [$parameter->getName() => null];
}
return [$parameter->getName() => Reflector::getParameterClassName($parameter)];
})
->all();
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Illuminate\Support\Traits;
trait Tappable
{
/**
* Call the given Closure with this instance then return the instance.
*
* @param (callable($this): mixed)|null $callback
* @return ($callback is null ? \Illuminate\Support\HigherOrderTapProxy : $this)
*/
public function tap($callback = null)
{
return tap($this, $callback);
}
}

Some files were not shown because too many files have changed in this diff Show More