AggregateServiceProvider.php000064400000001743147133772320012215 0ustar00instances = []; 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; } } Benchmark.php000064400000002764147133772320007171 0ustar00map(function ($callback) use ($iterations) { return collect(range(1, $iterations))->map(function () use ($callback) { gc_collect_cycles(); $start = hrtime(true); $callback(); return (hrtime(true) - $start) / 1000000; })->average(); })->when( $benchmarkables instanceof Closure, fn ($c) => $c->first(), fn ($c) => $c->all(), ); } /** * 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): void { $result = collect(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); } } Carbon.php000064400000000651147133772320006474 0ustar00files = $files; $this->workingPath = $workingPath; } /** * Regenerate the Composer autoloader files. * * @param string|array $extra * @return int */ public function dumpAutoloads($extra = '') { $extra = $extra ? (array) $extra : []; $command = array_merge($this->findComposer(), ['dump-autoload'], $extra); return $this->getProcess($command)->run(); } /** * Regenerate the optimized Composer autoloader files. * * @return int */ public function dumpOptimized() { return $this->dumpAutoloads('--optimize'); } /** * Get the composer command for the environment. * * @return array */ public function findComposer() { if ($this->files->exists($this->workingPath.'/composer.phar')) { return [$this->phpBinary(), 'composer.phar']; } return ['composer']; } /** * Get the PHP binary. * * @return string */ protected function phpBinary() { return ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)); } /** * Get a new Symfony process instance. * * @param array $command * @return \Symfony\Component\Process\Process */ protected function getProcess(array $command) { return (new Process($command, $this->workingPath))->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; } } ConfigurationUrlParser.php000064400000010403147133772320011733 0ustar00 '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; } } DateFactory.php000064400000017410147133772320007476 0ustar00$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()); } } Env.php000064400000004565147133772320006030 0ustar00addAdapter(PutenvAdapter::class); } static::$repository = $builder->immutable()->make(); } return static::$repository; } /** * Gets the value of an environment variable. * * @param string $key * @param mixed $default * @return mixed */ public static function get($key, $default = null) { 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; }) ->getOrCall(fn () => value($default)); } } Exceptions/MathException.php000064400000000200147133772320012147 0ustar00providerIsLoaded(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); } } Facades/Blade.php000075500000005436147133772320007636 0ustar00dispatcher : static::getFacadeRoot(); return tap(new BusFake($actualDispatcher, $jobsToFake, $batchRepository), function ($fake) { static::swap($fake); }); } /** * Dispatch the given chain of jobs. * * @param array|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; } } Facades/Cache.php000075500000007216147133772320007630 0ustar00cookie($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'; } } Facades/Crypt.php000075500000001316147133772320007721 0ustar00dispatcher : 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); return tap($callable(), function () use ($originalDispatcher) { 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); return tap($callable(), function () use ($originalDispatcher) { static::swap($originalDispatcher); Model::setEventDispatcher($originalDispatcher); Cache::refreshEventDispatcher(); }); } /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'events'; } } Facades/Facade.php000075500000021244147133772320007765 0ustar00resolved($accessor) === true) { $callback(static::getFacadeRoot()); } static::$app->afterResolving($accessor, function ($service) use ($callback) { $callback($service); }); } /** * 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 */ protected 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 collect([ 'App' => App::class, 'Arr' => Arr::class, 'Artisan' => Artisan::class, 'Auth' => Auth::class, 'Blade' => Blade::class, 'Broadcast' => Broadcast::class, 'Bus' => Bus::class, 'Cache' => Cache::class, 'Config' => Config::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, 'Password' => Password::class, 'Process' => Process::class, 'Queue' => Queue::class, 'RateLimiter' => RateLimiter::class, 'Redirect' => Redirect::class, 'Request' => Request::class, 'Response' => Response::class, 'Route' => Route::class, 'Schema' => Schema::class, 'Session' => Session::class, 'Storage' => Storage::class, 'Str' => Str::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 */ public static function getFacadeApplication() { return static::$app; } /** * Set the application instance. * * @param \Illuminate\Contracts\Foundation\Application $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); } } Facades/File.php000075500000007322147133772320007502 0ustar00fake($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. * * @return \Illuminate\Http\Client\Factory */ public static function preventStrayRequests() { return tap(static::getFacadeRoot(), function ($fake) { static::swap($fake->preventStrayRequests()); }); } /** * 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)); }); } } Facades/Lang.php000075500000003744147133772320007510 0ustar00manager : 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'; } } Facades/Notification.php000064400000006503147133772320011246 0ustar00route($channel, $route); } /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return ChannelManager::class; } } Facades/ParallelTesting.php000064400000002344147133772320011711 0ustar00fake($callback)); }); } } Facades/Queue.php000075500000010624147133772320007706 0ustar00queue : static::getFacadeRoot(); return tap(new QueueFake(static::getFacadeApplication(), $jobsToFake, $actualQueueManager), function ($fake) { static::swap($fake); }); } /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'queue'; } } Facades/RateLimiter.php000064400000002100147133772320011026 0ustar00connection($name)->getSchemaBuilder(); } /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'db.schema'; } } Facades/Session.php000075500000006600147133772320010244 0ustar00get('filesystems.default'); $root = storage_path('framework/testing/disks/'.$disk); if ($token = ParallelTesting::token()) { $root = "{$root}_test_{$token}"; } (new Filesystem)->cleanDirectory($root); static::set($disk, $fake = static::createLocalDriver(array_merge($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(array_merge($config, [ 'root' => storage_path('framework/testing/disks/'.$disk), ]))); return $fake; } /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'filesystem'; } } Facades/URL.php000075500000007003147133772320007261 0ustar00 * @implements \ArrayAccess */ class Fluent implements Arrayable, ArrayAccess, Jsonable, JsonSerializable { /** * All of the attributes set on the fluent instance. * * @var array */ protected $attributes = []; /** * Create a new fluent instance. * * @param iterable $attributes * @return void */ public function __construct($attributes = []) { foreach ($attributes as $key => $value) { $this->attributes[$key] = $value; } } /** * Get an attribute from the fluent instance. * * @template TGetDefault * * @param TKey $key * @param TGetDefault|(\Closure(): TGetDefault) $default * @return TValue|TGetDefault */ public function get($key, $default = null) { if (array_key_exists($key, $this->attributes)) { return $this->attributes[$key]; } return value($default); } /** * Get the attributes from the fluent instance. * * @return array */ public function getAttributes() { return $this->attributes; } /** * Convert the fluent instance to an array. * * @return array */ public function toArray() { return $this->attributes; } /** * Convert the object into something JSON serializable. * * @return array */ 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); } /** * 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->get($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]); } /** * 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) { $this->attributes[$method] = count($parameters) > 0 ? reset($parameters) : true; return $this; } /** * Dynamically retrieve the value of an attribute. * * @param TKey $key * @return TValue|null */ public function __get($key) { return $this->get($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); } } HigherOrderTapProxy.php000064400000001231147133772320011174 0ustar00target = $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; } } HtmlString.php000064400000002041147133772320007356 0ustar00html = $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(); } } InteractsWithTime.php000064400000003064147133772320010700 0ustar00parseDateInterval($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()->addRealSeconds($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(); } } Js.php000064400000006706147133772320005653 0ustar00js = $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 BackedEnum) { $data = $data->value; } $json = $this->jsonEncode($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 */ protected function jsonEncode($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(); } } LICENSE.md000064400000002063147133772320006162 0ustar00The 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. Lottery.php000064400000013237147133772320006736 0ustar00 1) { throw new RuntimeException('Float must not be greater than 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) { return 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 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; } } Manager.php000075500000010722147133772320006645 0ustar00container = $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. if (! isset($this->drivers[$driver])) { $this->drivers[$driver] = $this->createDriver($driver); } return $this->drivers[$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); } else { $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); } } MessageBag.php000075500000023470147133772320007275 0ustar00 $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 */ 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 $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; } /** * 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 */ 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 */ protected function getMessagesForWildcardKey($key, $format) { return collect($this->messages) ->filter(function ($messages, $messageKey) use ($key) { return 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 */ 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 $messages * @param string $format * @param string $messageKey * @return array */ protected function transform($messages, $format, $messageKey) { if ($format == ':message') { return (array) $messages; } return collect((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 */ public function messages() { return $this->messages; } /** * Get the raw messages in the message bag. * * @return array */ 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 message bag to its string representation. * * @return string */ public function __toString() { return $this->toJson(); } } MultipleInstanceManager.php000064400000010377147133772320012051 0ustar00app = $app; } /** * 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 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 */ protected function resolve($name) { $config = $this->getInstanceConfig($name); if (is_null($config)) { throw new InvalidArgumentException("Instance [{$name}] is not defined."); } if (! array_key_exists('driver', $config)) { throw new RuntimeException("Instance [{$name}] does not specify a driver."); } if (isset($this->customCreators[$config['driver']])) { return $this->callCustomCreator($config); } else { $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; if (method_exists($this, $driverMethod)) { return $this->{$driverMethod}($config); } else { throw new InvalidArgumentException("Instance driver [{$config['driver']}] is not supported."); } } } /** * Call a custom instance creator. * * @param array $config * @return mixed */ protected function callCustomCreator(array $config) { return $this->customCreators[$config['driver']]($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 * @return $this */ public function extend($name, Closure $callback) { $this->customCreators[$name] = $callback->bindTo($this, $this); 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); } } NamespacedItemResolver.php000075500000006544147133772320011703 0ustar00parsed[$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 = []; } } Optional.php000064400000005214147133772320007055 0ustar00value = $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); } } } Pluralizer.php000075500000005534147133772320007431 0ustar00pluralize($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; } } ProcessUtils.php000064400000004002147133772320007721 0ustar00 2 && $char === $arg[0] && $char === $arg[strlen($arg) - 1]; } } Reflector.php000064400000010503147133772320007212 0ustar00isPublic(); } 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 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) { $backedEnumClass = (string) $parameter->getType(); if (enum_exists($backedEnumClass)) { $reflectionBackedEnum = new ReflectionEnum($backedEnumClass); return $reflectionBackedEnum->isBacked() && $reflectionBackedEnum->getBackingType()->getName() == 'string'; } return false; } } ServiceProvider.php000075500000025414147133772320010412 0ustar00app = $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, []) )); } } /** * 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. * * @param string $path * @param string $namespace * @return void */ protected function loadTranslationsFrom($path, $namespace) { $this->callAfterResolving('translator', function ($translator) use ($path, $namespace) { $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 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 collect(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 groups available for publishing. * * @return array */ public static function publishableGroups() { return array_keys(static::$publishGroups); } /** * Register the package's custom Artisan commands. * * @param array|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); }); } /** * 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; } } Str.php000064400000111273147133772320006043 0ustar00 $length - 1) { return false; } return mb_substr($subject, $index, 1); } /** * Determine if a given string contains a given substring. * * @param string $haystack * @param string|iterable $needles * @param bool $ignoreCase * @return bool */ public static function contains($haystack, $needles, $ignoreCase = false) { if ($ignoreCase) { $haystack = mb_strtolower($haystack); } if (! is_iterable($needles)) { $needles = (array) $needles; } foreach ($needles as $needle) { if ($ignoreCase) { $needle = mb_strtolower($needle); } if ($needle !== '' && str_contains($haystack, $needle)) { return true; } } return false; } /** * Determine if a given string contains all array values. * * @param string $haystack * @param iterable $needles * @param bool $ignoreCase * @return bool */ public static function containsAll($haystack, $needles, $ignoreCase = false) { foreach ($needles as $needle) { if (! static::contains($haystack, $needle, $ignoreCase)) { return false; } } return true; } /** * Determine if a given string ends with a given substring. * * @param string $haystack * @param string|iterable $needles * @return bool */ public static function endsWith($haystack, $needles) { if (! is_iterable($needles)) { $needles = (array) $needles; } foreach ($needles as $needle) { if ((string) $needle !== '' && str_ends_with($haystack, $needle)) { return true; } } return false; } /** * Extracts an excerpt from text that matches the first instance of a phrase. * * @param string $text * @param string $phrase * @param array $options * @return string|null */ public static function excerpt($text, $phrase = '', $options = []) { $radius = $options['radius'] ?? 100; $omission = $options['omission'] ?? '...'; preg_match('/^(.*?)('.preg_quote((string) $phrase).')(.*)$/iu', (string) $text, $matches); if (empty($matches)) { return null; } $start = ltrim($matches[1]); $start = str(mb_substr($start, max(mb_strlen($start, 'UTF-8') - $radius, 0), $radius, 'UTF-8'))->ltrim()->unless( fn ($startWithRadius) => $startWithRadius->exactly($start), fn ($startWithRadius) => $startWithRadius->prepend($omission), ); $end = rtrim($matches[3]); $end = str(mb_substr($end, 0, $radius, 'UTF-8'))->rtrim()->unless( fn ($endWithRadius) => $endWithRadius->exactly($end), fn ($endWithRadius) => $endWithRadius->append($omission), ); return $start->append($matches[2], $end)->toString(); } /** * Cap a string with a single instance of a given value. * * @param string $value * @param string $cap * @return string */ public static function finish($value, $cap) { $quoted = preg_quote($cap, '/'); return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap; } /** * Wrap the string with the given strings. * * @param string $value * @param string $before * @param string|null $after * @return string */ public static function wrap($value, $before, $after = null) { return $before.$value.($after ??= $before); } /** * Determine if a given string matches a given pattern. * * @param string|iterable $pattern * @param string $value * @return bool */ public static function is($pattern, $value) { $value = (string) $value; if (! is_iterable($pattern)) { $pattern = [$pattern]; } foreach ($pattern as $pattern) { $pattern = (string) $pattern; // If the given value is an exact match we can of course return true right // from the beginning. Otherwise, we will translate asterisks and do an // actual pattern match against the two strings to see if they match. if ($pattern === $value) { return true; } $pattern = preg_quote($pattern, '#'); // Asterisks are translated into zero-or-more regular expression wildcards // to make it convenient to check if the strings starts with the given // pattern such as "library/*", making any string check convenient. $pattern = str_replace('\*', '.*', $pattern); if (preg_match('#^'.$pattern.'\z#u', $value) === 1) { return true; } } return false; } /** * Determine if a given string is 7 bit ASCII. * * @param string $value * @return bool */ public static function isAscii($value) { return ASCII::is_ascii((string) $value); } /** * Determine if a given string is valid JSON. * * @param string $value * @return bool */ public static function isJson($value) { if (! is_string($value)) { return false; } try { json_decode($value, true, 512, JSON_THROW_ON_ERROR); } catch (JsonException) { return false; } return true; } /** * Determine if a given string is a valid UUID. * * @param string $value * @return bool */ public static function isUuid($value) { if (! is_string($value)) { return false; } return preg_match('/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iD', $value) > 0; } /** * Determine if a given string is a valid ULID. * * @param string $value * @return bool */ public static function isUlid($value) { if (! is_string($value)) { return false; } return Ulid::isValid($value); } /** * Convert a string to kebab case. * * @param string $value * @return string */ public static function kebab($value) { return static::snake($value, '-'); } /** * Return the length of the given string. * * @param string $value * @param string|null $encoding * @return int */ public static function length($value, $encoding = null) { return mb_strlen($value, $encoding); } /** * Limit the number of characters in a string. * * @param string $value * @param int $limit * @param string $end * @return string */ public static function limit($value, $limit = 100, $end = '...') { if (mb_strwidth($value, 'UTF-8') <= $limit) { return $value; } return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end; } /** * Convert the given string to lower-case. * * @param string $value * @return string */ public static function lower($value) { return mb_strtolower($value, 'UTF-8'); } /** * Limit the number of words in a string. * * @param string $value * @param int $words * @param string $end * @return string */ public static function words($value, $words = 100, $end = '...') { preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches); if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) { return $value; } return rtrim($matches[0]).$end; } /** * Converts GitHub flavored Markdown into HTML. * * @param string $string * @param array $options * @return string */ public static function markdown($string, array $options = []) { $converter = new GithubFlavoredMarkdownConverter($options); return (string) $converter->convert($string); } /** * Converts inline Markdown into HTML. * * @param string $string * @param array $options * @return string */ public static function inlineMarkdown($string, array $options = []) { $environment = new Environment($options); $environment->addExtension(new GithubFlavoredMarkdownExtension()); $environment->addExtension(new InlinesOnlyExtension()); $converter = new MarkdownConverter($environment); return (string) $converter->convert($string); } /** * Masks a portion of a string with a repeated character. * * @param string $string * @param string $character * @param int $index * @param int|null $length * @param string $encoding * @return string */ public static function mask($string, $character, $index, $length = null, $encoding = 'UTF-8') { if ($character === '') { return $string; } $segment = mb_substr($string, $index, $length, $encoding); if ($segment === '') { return $string; } $strlen = mb_strlen($string, $encoding); $startIndex = $index; if ($index < 0) { $startIndex = $index < -$strlen ? 0 : $strlen + $index; } $start = mb_substr($string, 0, $startIndex, $encoding); $segmentLen = mb_strlen($segment, $encoding); $end = mb_substr($string, $startIndex + $segmentLen); return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end; } /** * Get the string matching the given pattern. * * @param string $pattern * @param string $subject * @return string */ public static function match($pattern, $subject) { preg_match($pattern, $subject, $matches); if (! $matches) { return ''; } return $matches[1] ?? $matches[0]; } /** * Determine if a given string matches a given pattern. * * @param string|iterable $pattern * @param string $value * @return bool */ public static function isMatch($pattern, $value) { $value = (string) $value; if (! is_iterable($pattern)) { $pattern = [$pattern]; } foreach ($pattern as $pattern) { $pattern = (string) $pattern; if (preg_match($pattern, $value) === 1) { return true; } } return false; } /** * Get the string matching the given pattern. * * @param string $pattern * @param string $subject * @return \Illuminate\Support\Collection */ public static function matchAll($pattern, $subject) { preg_match_all($pattern, $subject, $matches); if (empty($matches[0])) { return collect(); } return collect($matches[1] ?? $matches[0]); } /** * Pad both sides of a string with another. * * @param string $value * @param int $length * @param string $pad * @return string */ public static function padBoth($value, $length, $pad = ' ') { $short = max(0, $length - mb_strlen($value)); $shortLeft = floor($short / 2); $shortRight = ceil($short / 2); return mb_substr(str_repeat($pad, $shortLeft), 0, $shortLeft). $value. mb_substr(str_repeat($pad, $shortRight), 0, $shortRight); } /** * Pad the left side of a string with another. * * @param string $value * @param int $length * @param string $pad * @return string */ public static function padLeft($value, $length, $pad = ' ') { $short = max(0, $length - mb_strlen($value)); return mb_substr(str_repeat($pad, $short), 0, $short).$value; } /** * Pad the right side of a string with another. * * @param string $value * @param int $length * @param string $pad * @return string */ public static function padRight($value, $length, $pad = ' ') { $short = max(0, $length - mb_strlen($value)); return $value.mb_substr(str_repeat($pad, $short), 0, $short); } /** * Parse a Class[@]method style callback into class and method. * * @param string $callback * @param string|null $default * @return array */ public static function parseCallback($callback, $default = null) { return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default]; } /** * 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) { return Pluralizer::plural($value, $count); } /** * Pluralize the last word of an English, studly caps case string. * * @param string $value * @param int|array|\Countable $count * @return string */ public static function pluralStudly($value, $count = 2) { $parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE); $lastWord = array_pop($parts); return implode('', $parts).self::plural($lastWord, $count); } /** * Generate a random, secure password. * * @param int $length * @param bool $letters * @param bool $numbers * @param bool $symbols * @param bool $spaces * @return string */ public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false) { return (new Collection) ->when($letters, fn ($c) => $c->merge([ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ])) ->when($numbers, fn ($c) => $c->merge([ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ])) ->when($symbols, fn ($c) => $c->merge([ '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '.', ',', '<', '>', '?', '/', '\\', '{', '}', '[', ']', '|', ':', ';', ])) ->when($spaces, fn ($c) => $c->merge([' '])) ->pipe(fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)])) ->implode(''); } /** * Generate a more truly "random" alpha-numeric string. * * @param int $length * @return string */ public static function random($length = 16) { return (static::$randomStringFactory ?? function ($length) { $string = ''; while (($len = strlen($string)) < $length) { $size = $length - $len; $bytesSize = (int) ceil(($size) / 3) * 3; $bytes = random_bytes($bytesSize); $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size); } return $string; })($length); } /** * Set the callable that will be used to generate random strings. * * @param callable|null $factory * @return void */ public static function createRandomStringsUsing(callable $factory = null) { static::$randomStringFactory = $factory; } /** * Set the sequence that will be used to generate random strings. * * @param array $sequence * @param callable|null $whenMissing * @return void */ public static function createRandomStringsUsingSequence(array $sequence, $whenMissing = null) { $next = 0; $whenMissing ??= function ($length) use (&$next) { $factoryCache = static::$randomStringFactory; static::$randomStringFactory = null; $randomString = static::random($length); static::$randomStringFactory = $factoryCache; $next++; return $randomString; }; static::createRandomStringsUsing(function ($length) use (&$next, $sequence, $whenMissing) { if (array_key_exists($next, $sequence)) { return $sequence[$next++]; } return $whenMissing($length); }); } /** * Indicate that random strings should be created normally and not using a custom factory. * * @return void */ public static function createRandomStringsNormally() { static::$randomStringFactory = null; } /** * Repeat the given string. * * @param string $string * @param int $times * @return string */ public static function repeat(string $string, int $times) { return str_repeat($string, $times); } /** * Replace a given value in the string sequentially with an array. * * @param string $search * @param iterable $replace * @param string $subject * @return string */ public static function replaceArray($search, $replace, $subject) { if ($replace instanceof Traversable) { $replace = collect($replace)->all(); } $segments = explode($search, $subject); $result = array_shift($segments); foreach ($segments as $segment) { $result .= (array_shift($replace) ?? $search).$segment; } return $result; } /** * Replace the given value in the given string. * * @param string|iterable $search * @param string|iterable $replace * @param string|iterable $subject * @return string */ public static function replace($search, $replace, $subject) { if ($search instanceof Traversable) { $search = collect($search)->all(); } if ($replace instanceof Traversable) { $replace = collect($replace)->all(); } if ($subject instanceof Traversable) { $subject = collect($subject)->all(); } return str_replace($search, $replace, $subject); } /** * Replace the first occurrence of a given value in the string. * * @param string $search * @param string $replace * @param string $subject * @return string */ public static function replaceFirst($search, $replace, $subject) { $search = (string) $search; if ($search === '') { return $subject; } $position = strpos($subject, $search); if ($position !== false) { return substr_replace($subject, $replace, $position, strlen($search)); } return $subject; } /** * Replace the last occurrence of a given value in the string. * * @param string $search * @param string $replace * @param string $subject * @return string */ public static function replaceLast($search, $replace, $subject) { if ($search === '') { return $subject; } $position = strrpos($subject, $search); if ($position !== false) { return substr_replace($subject, $replace, $position, strlen($search)); } return $subject; } /** * Remove any occurrence of the given string in the subject. * * @param string|iterable $search * @param string $subject * @param bool $caseSensitive * @return string */ public static function remove($search, $subject, $caseSensitive = true) { if ($search instanceof Traversable) { $search = collect($search)->all(); } $subject = $caseSensitive ? str_replace($search, '', $subject) : str_ireplace($search, '', $subject); return $subject; } /** * Reverse the given string. * * @param string $value * @return string */ public static function reverse(string $value) { return implode(array_reverse(mb_str_split($value))); } /** * Begin a string with a single instance of a given value. * * @param string $value * @param string $prefix * @return string */ public static function start($value, $prefix) { $quoted = preg_quote($prefix, '/'); return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value); } /** * Convert the given string to upper-case. * * @param string $value * @return string */ public static function upper($value) { return mb_strtoupper($value, 'UTF-8'); } /** * Convert the given string to title case. * * @param string $value * @return string */ public static function title($value) { return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8'); } /** * Convert the given string to title case for each word. * * @param string $value * @return string */ public static function headline($value) { $parts = explode(' ', $value); $parts = count($parts) > 1 ? array_map([static::class, 'title'], $parts) : array_map([static::class, 'title'], static::ucsplit(implode('_', $parts))); $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts)); return implode(' ', array_filter(explode('_', $collapsed))); } /** * Get the singular form of an English word. * * @param string $value * @return string */ public static function singular($value) { return Pluralizer::singular($value); } /** * Generate a URL friendly "slug" from a given string. * * @param string $title * @param string $separator * @param string|null $language * @param array $dictionary * @return string */ public static function slug($title, $separator = '-', $language = 'en', $dictionary = ['@' => 'at']) { $title = $language ? static::ascii($title, $language) : $title; // Convert all dashes/underscores into separator $flip = $separator === '-' ? '_' : '-'; $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title); // Replace dictionary words foreach ($dictionary as $key => $value) { $dictionary[$key] = $separator.$value.$separator; } $title = str_replace(array_keys($dictionary), array_values($dictionary), $title); // Remove all characters that are not the separator, letters, numbers, or whitespace $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title)); // Replace all separator characters and whitespace by a single separator $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); return trim($title, $separator); } /** * Convert a string to snake case. * * @param string $value * @param string $delimiter * @return string */ public static function snake($value, $delimiter = '_') { $key = $value; if (isset(static::$snakeCache[$key][$delimiter])) { return static::$snakeCache[$key][$delimiter]; } if (! ctype_lower($value)) { $value = preg_replace('/\s+/u', '', ucwords($value)); $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value)); } return static::$snakeCache[$key][$delimiter] = $value; } /** * Remove all "extra" blank space from the given string. * * @param string $value * @return string */ public static function squish($value) { return preg_replace('~(\s|\x{3164})+~u', ' ', preg_replace('~^[\s\x{FEFF}]+|[\s\x{FEFF}]+$~u', '', $value)); } /** * Determine if a given string starts with a given substring. * * @param string $haystack * @param string|iterable $needles * @return bool */ public static function startsWith($haystack, $needles) { if (! is_iterable($needles)) { $needles = [$needles]; } foreach ($needles as $needle) { if ((string) $needle !== '' && str_starts_with($haystack, $needle)) { return true; } } return false; } /** * Convert a value to studly caps case. * * @param string $value * @return string */ public static function studly($value) { $key = $value; if (isset(static::$studlyCache[$key])) { return static::$studlyCache[$key]; } $words = explode(' ', static::replace(['-', '_'], ' ', $value)); $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words); return static::$studlyCache[$key] = implode($studlyWords); } /** * Returns the portion of the string specified by the start and length parameters. * * @param string $string * @param int $start * @param int|null $length * @param string $encoding * @return string */ public static function substr($string, $start, $length = null, $encoding = 'UTF-8') { return mb_substr($string, $start, $length, $encoding); } /** * Returns the number of substring occurrences. * * @param string $haystack * @param string $needle * @param int $offset * @param int|null $length * @return int */ public static function substrCount($haystack, $needle, $offset = 0, $length = null) { if (! is_null($length)) { return substr_count($haystack, $needle, $offset, $length); } return substr_count($haystack, $needle, $offset); } /** * Replace text within a portion of a string. * * @param string|string[] $string * @param string|string[] $replace * @param int|int[] $offset * @param int|int[]|null $length * @return string|string[] */ public static function substrReplace($string, $replace, $offset = 0, $length = null) { if ($length === null) { $length = strlen($string); } return substr_replace($string, $replace, $offset, $length); } /** * Swap multiple keywords in a string with other keywords. * * @param array $map * @param string $subject * @return string */ public static function swap(array $map, $subject) { return strtr($subject, $map); } /** * Make a string's first character lowercase. * * @param string $string * @return string */ public static function lcfirst($string) { return static::lower(static::substr($string, 0, 1)).static::substr($string, 1); } /** * Make a string's first character uppercase. * * @param string $string * @return string */ public static function ucfirst($string) { return static::upper(static::substr($string, 0, 1)).static::substr($string, 1); } /** * Split a string into pieces by uppercase characters. * * @param string $string * @return string[] */ public static function ucsplit($string) { return preg_split('/(?=\p{Lu})/u', $string, -1, PREG_SPLIT_NO_EMPTY); } /** * Get the number of words a string contains. * * @param string $string * @param string|null $characters * @return int */ public static function wordCount($string, $characters = null) { return str_word_count($string, 0, $characters); } /** * Generate a UUID (version 4). * * @return \Ramsey\Uuid\UuidInterface */ public static function uuid() { return static::$uuidFactory ? call_user_func(static::$uuidFactory) : Uuid::uuid4(); } /** * Generate a time-ordered UUID (version 4). * * @return \Ramsey\Uuid\UuidInterface */ public static function orderedUuid() { if (static::$uuidFactory) { return call_user_func(static::$uuidFactory); } $factory = new UuidFactory; $factory->setRandomGenerator(new CombGenerator( $factory->getRandomGenerator(), $factory->getNumberConverter() )); $factory->setCodec(new TimestampFirstCombCodec( $factory->getUuidBuilder() )); return $factory->uuid4(); } /** * Set the callable that will be used to generate UUIDs. * * @param callable|null $factory * @return void */ public static function createUuidsUsing(callable $factory = null) { static::$uuidFactory = $factory; } /** * Set the sequence that will be used to generate UUIDs. * * @param array $sequence * @param callable|null $whenMissing * @return void */ public static function createUuidsUsingSequence(array $sequence, $whenMissing = null) { $next = 0; $whenMissing ??= function () use (&$next) { $factoryCache = static::$uuidFactory; static::$uuidFactory = null; $uuid = static::uuid(); static::$uuidFactory = $factoryCache; $next++; return $uuid; }; static::createUuidsUsing(function () use (&$next, $sequence, $whenMissing) { if (array_key_exists($next, $sequence)) { return $sequence[$next++]; } return $whenMissing(); }); } /** * Always return the same UUID when generating new UUIDs. * * @param \Closure|null $callback * @return \Ramsey\Uuid\UuidInterface */ public static function freezeUuids(Closure $callback = null) { $uuid = Str::uuid(); Str::createUuidsUsing(fn () => $uuid); if ($callback !== null) { try { $callback($uuid); } finally { Str::createUuidsNormally(); } } return $uuid; } /** * Indicate that UUIDs should be created normally and not using a custom factory. * * @return void */ public static function createUuidsNormally() { static::$uuidFactory = null; } /** * Generate a ULID. * * @param \DateTimeInterface|null $time * @return \Symfony\Component\Uid\Ulid */ public static function ulid($time = null) { if ($time === null) { return new Ulid(); } return new Ulid(Ulid::generate($time)); } /** * Remove all strings from the casing caches. * * @return void */ public static function flushCache() { static::$snakeCache = []; static::$camelCache = []; static::$studlyCache = []; } } Stringable.php000064400000073405147133772320007371 0ustar00value = (string) $value; } /** * Return the remainder of a string after the first occurrence of a given value. * * @param string $search * @return static */ public function after($search) { return new static(Str::after($this->value, $search)); } /** * Return the remainder of a string after the last occurrence of a given value. * * @param string $search * @return static */ public function afterLast($search) { return new static(Str::afterLast($this->value, $search)); } /** * Append the given values to the string. * * @param array|string ...$values * @return static */ public function append(...$values) { return new static($this->value.implode('', $values)); } /** * Append a new line to the string. * * @param int $count * @return $this */ public function newLine($count = 1) { return $this->append(str_repeat(PHP_EOL, $count)); } /** * Transliterate a UTF-8 value to ASCII. * * @param string $language * @return static */ public function ascii($language = 'en') { return new static(Str::ascii($this->value, $language)); } /** * Get the trailing name component of the path. * * @param string $suffix * @return static */ public function basename($suffix = '') { return new static(basename($this->value, $suffix)); } /** * Get the character at the specified index. * * @param int $index * @return string|false */ public function charAt($index) { return Str::charAt($this->value, $index); } /** * Get the basename of the class path. * * @return static */ public function classBasename() { return new static(class_basename($this->value)); } /** * Get the portion of a string before the first occurrence of a given value. * * @param string $search * @return static */ public function before($search) { return new static(Str::before($this->value, $search)); } /** * Get the portion of a string before the last occurrence of a given value. * * @param string $search * @return static */ public function beforeLast($search) { return new static(Str::beforeLast($this->value, $search)); } /** * Get the portion of a string between two given values. * * @param string $from * @param string $to * @return static */ public function between($from, $to) { return new static(Str::between($this->value, $from, $to)); } /** * Get the smallest possible portion of a string between two given values. * * @param string $from * @param string $to * @return static */ public function betweenFirst($from, $to) { return new static(Str::betweenFirst($this->value, $from, $to)); } /** * Convert a value to camel case. * * @return static */ public function camel() { return new static(Str::camel($this->value)); } /** * Determine if a given string contains a given substring. * * @param string|iterable $needles * @param bool $ignoreCase * @return bool */ public function contains($needles, $ignoreCase = false) { return Str::contains($this->value, $needles, $ignoreCase); } /** * Determine if a given string contains all array values. * * @param iterable $needles * @param bool $ignoreCase * @return bool */ public function containsAll($needles, $ignoreCase = false) { return Str::containsAll($this->value, $needles, $ignoreCase); } /** * Get the parent directory's path. * * @param int $levels * @return static */ public function dirname($levels = 1) { return new static(dirname($this->value, $levels)); } /** * Determine if a given string ends with a given substring. * * @param string|iterable $needles * @return bool */ public function endsWith($needles) { return Str::endsWith($this->value, $needles); } /** * Determine if the string is an exact match with the given value. * * @param \Illuminate\Support\Stringable|string $value * @return bool */ public function exactly($value) { if ($value instanceof Stringable) { $value = $value->toString(); } return $this->value === $value; } /** * Extracts an excerpt from text that matches the first instance of a phrase. * * @param string $phrase * @param array $options * @return string|null */ public function excerpt($phrase = '', $options = []) { return Str::excerpt($this->value, $phrase, $options); } /** * Explode the string into an array. * * @param string $delimiter * @param int $limit * @return \Illuminate\Support\Collection */ public function explode($delimiter, $limit = PHP_INT_MAX) { return collect(explode($delimiter, $this->value, $limit)); } /** * Split a string using a regular expression or by length. * * @param string|int $pattern * @param int $limit * @param int $flags * @return \Illuminate\Support\Collection */ public function split($pattern, $limit = -1, $flags = 0) { if (filter_var($pattern, FILTER_VALIDATE_INT) !== false) { return collect(mb_str_split($this->value, $pattern)); } $segments = preg_split($pattern, $this->value, $limit, $flags); return ! empty($segments) ? collect($segments) : collect(); } /** * Cap a string with a single instance of a given value. * * @param string $cap * @return static */ public function finish($cap) { return new static(Str::finish($this->value, $cap)); } /** * Determine if a given string matches a given pattern. * * @param string|iterable $pattern * @return bool */ public function is($pattern) { return Str::is($pattern, $this->value); } /** * Determine if a given string is 7 bit ASCII. * * @return bool */ public function isAscii() { return Str::isAscii($this->value); } /** * Determine if a given string is valid JSON. * * @return bool */ public function isJson() { return Str::isJson($this->value); } /** * Determine if a given string is a valid UUID. * * @return bool */ public function isUuid() { return Str::isUuid($this->value); } /** * Determine if a given string is a valid ULID. * * @return bool */ public function isUlid() { return Str::isUlid($this->value); } /** * Determine if the given string is empty. * * @return bool */ public function isEmpty() { return $this->value === ''; } /** * Determine if the given string is not empty. * * @return bool */ public function isNotEmpty() { return ! $this->isEmpty(); } /** * Convert a string to kebab case. * * @return static */ public function kebab() { return new static(Str::kebab($this->value)); } /** * Return the length of the given string. * * @param string|null $encoding * @return int */ public function length($encoding = null) { return Str::length($this->value, $encoding); } /** * Limit the number of characters in a string. * * @param int $limit * @param string $end * @return static */ public function limit($limit = 100, $end = '...') { return new static(Str::limit($this->value, $limit, $end)); } /** * Convert the given string to lower-case. * * @return static */ public function lower() { return new static(Str::lower($this->value)); } /** * Convert GitHub flavored Markdown into HTML. * * @param array $options * @return static */ public function markdown(array $options = []) { return new static(Str::markdown($this->value, $options)); } /** * Convert inline Markdown into HTML. * * @param array $options * @return static */ public function inlineMarkdown(array $options = []) { return new static(Str::inlineMarkdown($this->value, $options)); } /** * Masks a portion of a string with a repeated character. * * @param string $character * @param int $index * @param int|null $length * @param string $encoding * @return static */ public function mask($character, $index, $length = null, $encoding = 'UTF-8') { return new static(Str::mask($this->value, $character, $index, $length, $encoding)); } /** * Get the string matching the given pattern. * * @param string $pattern * @return static */ public function match($pattern) { return new static(Str::match($pattern, $this->value)); } /** * Determine if a given string matches a given pattern. * * @param string|iterable $pattern * @return bool */ public function isMatch($pattern) { return Str::isMatch($pattern, $this->value); } /** * Get the string matching the given pattern. * * @param string $pattern * @return \Illuminate\Support\Collection */ public function matchAll($pattern) { return Str::matchAll($pattern, $this->value); } /** * Determine if the string matches the given pattern. * * @param string $pattern * @return bool */ public function test($pattern) { return $this->isMatch($pattern); } /** * Pad both sides of the string with another. * * @param int $length * @param string $pad * @return static */ public function padBoth($length, $pad = ' ') { return new static(Str::padBoth($this->value, $length, $pad)); } /** * Pad the left side of the string with another. * * @param int $length * @param string $pad * @return static */ public function padLeft($length, $pad = ' ') { return new static(Str::padLeft($this->value, $length, $pad)); } /** * Pad the right side of the string with another. * * @param int $length * @param string $pad * @return static */ public function padRight($length, $pad = ' ') { return new static(Str::padRight($this->value, $length, $pad)); } /** * Parse a Class@method style callback into class and method. * * @param string|null $default * @return array */ public function parseCallback($default = null) { return Str::parseCallback($this->value, $default); } /** * Call the given callback and return a new string. * * @param callable $callback * @return static */ public function pipe(callable $callback) { return new static($callback($this)); } /** * Get the plural form of an English word. * * @param int|array|\Countable $count * @return static */ public function plural($count = 2) { return new static(Str::plural($this->value, $count)); } /** * Pluralize the last word of an English, studly caps case string. * * @param int|array|\Countable $count * @return static */ public function pluralStudly($count = 2) { return new static(Str::pluralStudly($this->value, $count)); } /** * Prepend the given values to the string. * * @param string ...$values * @return static */ public function prepend(...$values) { return new static(implode('', $values).$this->value); } /** * Remove any occurrence of the given string in the subject. * * @param string|iterable $search * @param bool $caseSensitive * @return static */ public function remove($search, $caseSensitive = true) { return new static(Str::remove($search, $this->value, $caseSensitive)); } /** * Reverse the string. * * @return static */ public function reverse() { return new static(Str::reverse($this->value)); } /** * Repeat the string. * * @param int $times * @return static */ public function repeat(int $times) { return new static(str_repeat($this->value, $times)); } /** * Replace the given value in the given string. * * @param string|iterable $search * @param string|iterable $replace * @return static */ public function replace($search, $replace) { return new static(Str::replace($search, $replace, $this->value)); } /** * Replace a given value in the string sequentially with an array. * * @param string $search * @param iterable $replace * @return static */ public function replaceArray($search, $replace) { return new static(Str::replaceArray($search, $replace, $this->value)); } /** * Replace the first occurrence of a given value in the string. * * @param string $search * @param string $replace * @return static */ public function replaceFirst($search, $replace) { return new static(Str::replaceFirst($search, $replace, $this->value)); } /** * Replace the last occurrence of a given value in the string. * * @param string $search * @param string $replace * @return static */ public function replaceLast($search, $replace) { return new static(Str::replaceLast($search, $replace, $this->value)); } /** * Replace the patterns matching the given regular expression. * * @param string $pattern * @param \Closure|string $replace * @param int $limit * @return static */ public function replaceMatches($pattern, $replace, $limit = -1) { if ($replace instanceof Closure) { return new static(preg_replace_callback($pattern, $replace, $this->value, $limit)); } return new static(preg_replace($pattern, $replace, $this->value, $limit)); } /** * Parse input from a string to a collection, according to a format. * * @param string $format * @return \Illuminate\Support\Collection */ public function scan($format) { return collect(sscanf($this->value, $format)); } /** * Remove all "extra" blank space from the given string. * * @return static */ public function squish() { return new static(Str::squish($this->value)); } /** * Begin a string with a single instance of a given value. * * @param string $prefix * @return static */ public function start($prefix) { return new static(Str::start($this->value, $prefix)); } /** * Strip HTML and PHP tags from the given string. * * @param string $allowedTags * @return static */ public function stripTags($allowedTags = null) { return new static(strip_tags($this->value, $allowedTags)); } /** * Convert the given string to upper-case. * * @return static */ public function upper() { return new static(Str::upper($this->value)); } /** * Convert the given string to title case. * * @return static */ public function title() { return new static(Str::title($this->value)); } /** * Convert the given string to title case for each word. * * @return static */ public function headline() { return new static(Str::headline($this->value)); } /** * Get the singular form of an English word. * * @return static */ public function singular() { return new static(Str::singular($this->value)); } /** * Generate a URL friendly "slug" from a given string. * * @param string $separator * @param string|null $language * @param array $dictionary * @return static */ public function slug($separator = '-', $language = 'en', $dictionary = ['@' => 'at']) { return new static(Str::slug($this->value, $separator, $language, $dictionary)); } /** * Convert a string to snake case. * * @param string $delimiter * @return static */ public function snake($delimiter = '_') { return new static(Str::snake($this->value, $delimiter)); } /** * Determine if a given string starts with a given substring. * * @param string|iterable $needles * @return bool */ public function startsWith($needles) { return Str::startsWith($this->value, $needles); } /** * Convert a value to studly caps case. * * @return static */ public function studly() { return new static(Str::studly($this->value)); } /** * Returns the portion of the string specified by the start and length parameters. * * @param int $start * @param int|null $length * @param string $encoding * @return static */ public function substr($start, $length = null, $encoding = 'UTF-8') { return new static(Str::substr($this->value, $start, $length, $encoding)); } /** * Returns the number of substring occurrences. * * @param string $needle * @param int $offset * @param int|null $length * @return int */ public function substrCount($needle, $offset = 0, $length = null) { return Str::substrCount($this->value, $needle, $offset, $length); } /** * Replace text within a portion of a string. * * @param string|string[] $replace * @param int|int[] $offset * @param int|int[]|null $length * @return static */ public function substrReplace($replace, $offset = 0, $length = null) { return new static(Str::substrReplace($this->value, $replace, $offset, $length)); } /** * Swap multiple keywords in a string with other keywords. * * @param array $map * @return static */ public function swap(array $map) { return new static(strtr($this->value, $map)); } /** * Trim the string of the given characters. * * @param string $characters * @return static */ public function trim($characters = null) { return new static(trim(...array_merge([$this->value], func_get_args()))); } /** * Left trim the string of the given characters. * * @param string $characters * @return static */ public function ltrim($characters = null) { return new static(ltrim(...array_merge([$this->value], func_get_args()))); } /** * Right trim the string of the given characters. * * @param string $characters * @return static */ public function rtrim($characters = null) { return new static(rtrim(...array_merge([$this->value], func_get_args()))); } /** * Make a string's first character lowercase. * * @return static */ public function lcfirst() { return new static(Str::lcfirst($this->value)); } /** * Make a string's first character uppercase. * * @return static */ public function ucfirst() { return new static(Str::ucfirst($this->value)); } /** * Split a string by uppercase characters. * * @return \Illuminate\Support\Collection */ public function ucsplit() { return collect(Str::ucsplit($this->value)); } /** * Execute the given callback if the string contains a given substring. * * @param string|iterable $needles * @param callable $callback * @param callable|null $default * @return static */ public function whenContains($needles, $callback, $default = null) { return $this->when($this->contains($needles), $callback, $default); } /** * Execute the given callback if the string contains all array values. * * @param iterable $needles * @param callable $callback * @param callable|null $default * @return static */ public function whenContainsAll(array $needles, $callback, $default = null) { return $this->when($this->containsAll($needles), $callback, $default); } /** * Execute the given callback if the string is empty. * * @param callable $callback * @param callable|null $default * @return static */ public function whenEmpty($callback, $default = null) { return $this->when($this->isEmpty(), $callback, $default); } /** * Execute the given callback if the string is not empty. * * @param callable $callback * @param callable|null $default * @return static */ public function whenNotEmpty($callback, $default = null) { return $this->when($this->isNotEmpty(), $callback, $default); } /** * Execute the given callback if the string ends with a given substring. * * @param string|iterable $needles * @param callable $callback * @param callable|null $default * @return static */ public function whenEndsWith($needles, $callback, $default = null) { return $this->when($this->endsWith($needles), $callback, $default); } /** * Execute the given callback if the string is an exact match with the given value. * * @param string $value * @param callable $callback * @param callable|null $default * @return static */ public function whenExactly($value, $callback, $default = null) { return $this->when($this->exactly($value), $callback, $default); } /** * Execute the given callback if the string is not an exact match with the given value. * * @param string $value * @param callable $callback * @param callable|null $default * @return static */ public function whenNotExactly($value, $callback, $default = null) { return $this->when(! $this->exactly($value), $callback, $default); } /** * Execute the given callback if the string matches a given pattern. * * @param string|iterable $pattern * @param callable $callback * @param callable|null $default * @return static */ public function whenIs($pattern, $callback, $default = null) { return $this->when($this->is($pattern), $callback, $default); } /** * Execute the given callback if the string is 7 bit ASCII. * * @param callable $callback * @param callable|null $default * @return static */ public function whenIsAscii($callback, $default = null) { return $this->when($this->isAscii(), $callback, $default); } /** * Execute the given callback if the string is a valid UUID. * * @param callable $callback * @param callable|null $default * @return static */ public function whenIsUuid($callback, $default = null) { return $this->when($this->isUuid(), $callback, $default); } /** * Execute the given callback if the string is a valid ULID. * * @param callable $callback * @param callable|null $default * @return static */ public function whenIsUlid($callback, $default = null) { return $this->when($this->isUlid(), $callback, $default); } /** * Execute the given callback if the string starts with a given substring. * * @param string|iterable $needles * @param callable $callback * @param callable|null $default * @return static */ public function whenStartsWith($needles, $callback, $default = null) { return $this->when($this->startsWith($needles), $callback, $default); } /** * Execute the given callback if the string matches the given pattern. * * @param string $pattern * @param callable $callback * @param callable|null $default * @return static */ public function whenTest($pattern, $callback, $default = null) { return $this->when($this->test($pattern), $callback, $default); } /** * Limit the number of words in a string. * * @param int $words * @param string $end * @return static */ public function words($words = 100, $end = '...') { return new static(Str::words($this->value, $words, $end)); } /** * Get the number of words a string contains. * * @param string|null $characters * @return int */ public function wordCount($characters = null) { return Str::wordCount($this->value, $characters); } /** * Wrap the string with the given strings. * * @param string $before * @param string|null $after * @return static */ public function wrap($before, $after = null) { return new static(Str::wrap($this->value, $before, $after)); } /** * Convert the string into a `HtmlString` instance. * * @return \Illuminate\Support\HtmlString */ public function toHtmlString() { return new HtmlString($this->value); } /** * Dump the string. * * @return $this */ public function dump() { VarDumper::dump($this->value); return $this; } /** * Dump the string and end the script. * * @return never */ public function dd() { $this->dump(); exit(1); } /** * Get the underlying string value. * * @return string */ public function value() { return $this->toString(); } /** * Get the underlying string value. * * @return string */ public function toString() { return $this->value; } /** * Get the underlying string value as an integer. * * @return int */ public function toInteger() { return intval($this->value); } /** * Get the underlying string value as a float. * * @return float */ public function toFloat() { return floatval($this->value); } /** * Get the underlying string value as a boolean. * * Returns true when value is "1", "true", "on", and "yes". Otherwise, returns false. * * @return bool */ public function toBoolean() { return filter_var($this->value, FILTER_VALIDATE_BOOLEAN); } /** * Get the underlying string value as a Carbon instance. * * @param string|null $format * @param string|null $tz * @return \Illuminate\Support\Carbon * * @throws \Carbon\Exceptions\InvalidFormatException */ public function toDate($format = null, $tz = null) { if (is_null($format)) { return Date::parse($this->value, $tz); } return Date::createFromFormat($format, $this->value, $tz); } /** * Convert the object to a string when JSON encoded. * * @return string */ public function jsonSerialize(): string { return $this->__toString(); } /** * Determine if the given offset exists. * * @param mixed $offset * @return bool */ public function offsetExists(mixed $offset): bool { return isset($this->value[$offset]); } /** * Get the value at the given offset. * * @param mixed $offset * @return string */ public function offsetGet(mixed $offset): string { return $this->value[$offset]; } /** * Set the value at the given offset. * * @param mixed $offset * @return void */ public function offsetSet(mixed $offset, mixed $value): void { $this->value[$offset] = $value; } /** * Unset the value at the given offset. * * @param mixed $offset * @return void */ public function offsetUnset(mixed $offset): void { unset($this->value[$offset]); } /** * Proxy dynamic properties onto methods. * * @param string $key * @return mixed */ public function __get($key) { return $this->{$key}(); } /** * Get the raw string value. * * @return string */ public function __toString() { return (string) $this->value; } } Testing/Fakes/BatchFake.php000064400000007365147133772320011557 0ustar00id = $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) { foreach ($jobs as $job) { $this->added[] = $job; } 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 \Illuminate\Bus\UpdatedBatchJobCounts */ 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; } } Testing/Fakes/BatchRepositoryFake.php000064400000006622147133772320013652 0ustar00batches; } /** * 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(); } } Testing/Fakes/BusFake.php000064400000055020147133772320011256 0ustar00dispatcher = $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 void */ 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 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, "The expected [{$command}] job was pushed {$count} times instead of {$times} 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() { PHPUnit::assertEmpty($this->commands, 'Jobs were dispatched unexpectedly.'); } /** * 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, "The expected [{$command}] job was synchronously pushed {$count} times instead of {$times} 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, "The expected [{$command}] job was pushed {$count} times instead of {$times} 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 (! 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." ); PHPUnit::assertTrue( collect($expectedChain)->isNotEmpty(), 'The expected chain can not be empty.' ); $this->isChainOfObjects($expectedChain) ? $this->assertDispatchedWithChainOfObjects($command, $expectedChain, $callback) : $this->assertDispatchedWithChainOfClasses($command, $expectedChain, $callback); } /** * 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->assertDispatchedWithChainOfClasses($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 = collect($expectedChain)->map(fn ($job) => serialize($job))->all(); PHPUnit::assertTrue( $this->dispatched($command, $callback)->filter( fn ($job) => $job->chained == $chain )->isNotEmpty(), 'The expected chain was not dispatched.' ); } /** * 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 assertDispatchedWithChainOfClasses($command, $expectedChain, $callback) { $matching = $this->dispatched($command, $callback)->map->chained->map(function ($chain) { return collect($chain)->map( fn ($job) => get_class(unserialize($job)) ); })->filter( fn ($chain) => $chain->all() === $expectedChain ); PHPUnit::assertTrue( $matching->isNotEmpty(), 'The expected chain was not dispatched.' ); } /** * Determine if the given chain is entirely composed of objects. * * @param array $chain * @return bool */ protected function isChainOfObjects($chain) { return ! collect($chain)->contains(fn ($job) => ! is_object($job)); } /** * 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() { PHPUnit::assertEmpty($this->batches, 'Batched jobs were dispatched unexpectedly.'); } /** * 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 collect(); } $callback = $callback ?: fn () => true; return collect($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 collect(); } $callback = $callback ?: fn () => true; return collect($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 collect(); } $callback = $callback ?: fn () => true; return collect($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 collect(); } return collect($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)][] = $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)][] = $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)][] = $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)][] = $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)][] = $command; } else { return $this->dispatcher->dispatch($command); } } /** * Create a new chain of queueable jobs. * * @param \Illuminate\Support\Collection|array $jobs * @return \Illuminate\Foundation\Bus\PendingChain */ public function chain($jobs) { $jobs = Collection::wrap($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 collect($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 collect($this->jobsToDispatch) ->filter(function ($job) use ($command) { return $job instanceof Closure ? $job($command) : $job === get_class($command); })->isNotEmpty(); } /** * 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; } } Testing/Fakes/EventFake.php000064400000023752147133772320011615 0ustar00dispatcher = $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, 'handle']; } } } 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 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, "The expected [{$event}] event was dispatched {$count} times instead of {$times} 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)); PHPUnit::assertSame( 0, $count, "{$count} unexpected events were dispatched." ); } /** * 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 collect(); } $callback = $callback ?: fn () => true; return collect($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->events[$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 collect($this->eventsToFake) ->filter(function ($event) use ($eventName, $payload) { return $event instanceof Closure ? $event($eventName, $payload) : $event === $eventName; }) ->isNotEmpty(); } /** * 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 collect($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 array|null */ public function until($event, $payload = []) { return $this->dispatch($event, $payload, true); } /** * 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); } } Testing/Fakes/Fake.php000064400000000116147133772320010600 0ustar00manager = $manager; } /** * Assert if a mailable was sent based on a truth-test callback. * * @param string|\Closure $mailable * @param callable|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); } $message = "The expected [{$mailable}] mailable was not sent."; if (count($this->queuedMailables) > 0) { $message .= ' Did you mean to use assertQueued() instead?'; } PHPUnit::assertTrue( $this->sent($mailable, $callback)->count() > 0, $message ); } /** * 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, "The expected [{$mailable}] mailable was sent {$count} times instead of {$times} 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|null $callback * @return void */ public function assertNotSent($mailable, $callback = null) { [$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 = collect($this->mailables)->map( fn ($mailable) => get_class($mailable) )->join(', '); PHPUnit::assertEmpty($this->mailables, 'The following mailables were sent unexpectedly: '.$mailableNames); } /** * Assert if a mailable was queued based on a truth-test callback. * * @param string|\Closure $mailable * @param callable|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); } 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, "The expected [{$mailable}] mailable was queued {$count} times instead of {$times} times." ); } /** * Determine if a mailable was not queued based on a truth-test callback. * * @param string|\Closure $mailable * @param callable|null $callback * @return void */ public function assertNotQueued($mailable, $callback = null) { [$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 = collect($this->queuedMailables)->map( fn ($mailable) => get_class($mailable) )->join(', '); PHPUnit::assertEmpty($this->queuedMailables, 'The following mailables were queued unexpectedly: '.$mailableNames); } /** * 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 collect(); } $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 collect(); } $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 collect($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 collect($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 void */ public function send($view, array $data = [], $callback = null) { if (! $view instanceof Mailable) { return; } $view->mailer($this->currentMailer); if ($view instanceof ShouldQueue) { return $this->queue($view, $data); } $this->currentMailer = null; $this->mailables[] = $view; } /** * Queue a new e-mail 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); } } Testing/Fakes/NotificationFake.php000064400000024550147133772320013157 0ustar00assertSentTo(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) { return $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() { PHPUnit::assertEmpty($this->notifications, 'Notifications were sent unexpectedly.'); } /** * 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 = collect($this->notifications) ->flatten(1) ->reduce(fn ($count, $sent) => $count + count($sent[$notification] ?? []), 0); PHPUnit::assertSame( $expectedCount, $actualCount, "Expected [{$notification}] to be sent {$expectedCount} times, but was sent {$actualCount} times." ); } /** * Assert the total count of notification that were sent. * * @param int $expectedCount * @return void */ public function assertCount($expectedCount) { $actualCount = collect($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 collect(); } $callback = $callback ?: fn () => true; $notifications = collect($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)][$notifiable->getKey()][$notification] ?? []; } /** * Send the given notification to the given notifiable entities. * * @param \Illuminate\Support\Collection|array|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|array|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)][$notifiable->getKey()][get_class($notification)][] = [ '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; } /** * Get the notifications that have been sent. * * @return array */ public function sentNotifications() { return $this->notifications; } } Testing/Fakes/PendingBatchFake.php000064400000002041147133772320013046 0ustar00bus = $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); } } Testing/Fakes/PendingChainFake.php000064400000002632147133772320013055 0ustar00bus = $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); } } Testing/Fakes/PendingMailFake.php000064400000001644147133772320012717 0ustar00mailer = $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)); } /** * 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)); } } Testing/Fakes/QueueFake.php000064400000033050147133772320011610 0ustar00jobsToFake = Collection::wrap($jobsToFake); $this->jobsToBeQueued = Collection::make(); $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, "The expected [{$job}] job was pushed {$count} times instead of {$times} 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( collect($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 = collect($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 collect($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 ! collect($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 that no jobs were pushed. * * @return void */ public function assertNothingPushed() { PHPUnit::assertEmpty($this->jobs, 'Jobs were pushed unexpectedly.'); } /** * 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 collect(); } $callback = $callback ?: fn () => true; return collect($this->jobs[$job])->filter( fn ($data) => $callback($data['job'], $data['queue'], $data['data']) )->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 collect($this->jobs)->flatten(1)->filter( fn ($job) => $job['queue'] === $queue )->count(); } /** * 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' => $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) ); } /** * 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 = []) { // } /** * 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 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 )); } } Timebox.php000064400000003170147133772320006676 0ustar00earlyReturn && $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) { usleep($microseconds); } } Traits/CapsuleManagerTrait.php000064400000002627147133772320012436 0ustar00container = $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; } } Traits/ForwardsCalls.php000064400000003573147133772320011312 0ustar00{$method}(...$parameters); } catch (Error|BadMethodCallException $e) { $pattern = '~^Call to undefined method (?P[^:]+)::(?P[^\(]+)\(\)$~'; 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); if ($result === $object) { return $this; } return $result; } /** * Throw a bad method call exception for the given method. * * @param string $method * @return void * * @throws \BadMethodCallException */ protected static function throwBadMethodCallException($method) { throw new BadMethodCallException(sprintf( 'Call to undefined method %s::%s()', static::class, $method )); } } Traits/Localizable.php000064400000001165147133772320010760 0ustar00getLocale(); try { $app->setLocale($locale); return $callback(); } finally { $app->setLocale($original); } } } Traits/ReflectsClosures.php000064400000004736147133772320012035 0ustar00closureParameterTypes($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 = collect($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 collect($reflection->getParameters())->mapWithKeys(function ($parameter) { if ($parameter->isVariadic()) { return [$parameter->getName() => null]; } return [$parameter->getName() => Reflector::getParameterClassName($parameter)]; })->all(); } } Traits/Tappable.php000064400000000543147133772320010266 0ustar00input = $input; } /** * Determine if the validated input has one or more keys. * * @param mixed $keys * @return bool */ public function has($keys) { $keys = is_array($keys) ? $keys : func_get_args(); foreach ($keys as $key) { if (! Arr::has($this->input, $key)) { return false; } } return true; } /** * Determine if the validated input is missing one or more keys. * * @param mixed $keys * @return bool */ public function missing($keys) { return ! $this->has($keys); } /** * Get a subset containing the provided keys with values from the input data. * * @param mixed $keys * @return array */ public function only($keys) { $results = []; $input = $this->input; $placeholder = new stdClass; foreach (is_array($keys) ? $keys : func_get_args() as $key) { $value = data_get($input, $key, $placeholder); if ($value !== $placeholder) { Arr::set($results, $key, $value); } } return $results; } /** * Get all of the input 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->input; Arr::forget($results, $keys); return $results; } /** * Merge the validated input with the given array of additional data. * * @param array $items * @return static */ public function merge(array $items) { return new static(array_merge($this->input, $items)); } /** * Get the input as a collection. * * @return \Illuminate\Support\Collection */ public function collect() { return new Collection($this->input); } /** * Get the raw, underlying input array. * * @return array */ public function all() { return $this->input; } /** * Get the instance as an array. * * @return array */ public function toArray() { return $this->all(); } /** * Dynamically access input data. * * @param string $name * @return mixed */ public function __get($name) { return $this->input[$name]; } /** * Dynamically set input data. * * @param string $name * @param mixed $value * @return mixed */ public function __set($name, $value) { $this->input[$name] = $value; } /** * Determine if an input key is set. * * @return bool */ public function __isset($name) { return isset($this->input[$name]); } /** * Remove an input key. * * @param string $name * @return void */ public function __unset($name) { unset($this->input[$name]); } /** * Determine if an item exists at an offset. * * @param mixed $key * @return bool */ public function offsetExists($key): bool { return isset($this->input[$key]); } /** * Get an item at a given offset. * * @param mixed $key * @return mixed */ public function offsetGet($key): mixed { return $this->input[$key]; } /** * Set the item at a given offset. * * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value): void { if (is_null($key)) { $this->input[] = $value; } else { $this->input[$key] = $value; } } /** * Unset the item at a given offset. * * @param string $key * @return void */ public function offsetUnset($key): void { unset($this->input[$key]); } /** * Get an iterator for the input. * * @return \ArrayIterator */ public function getIterator(): Traversable { return new ArrayIterator($this->input); } } ViewErrorBag.php000064400000005103147133772320007623 0ustar00bags[$key]); } /** * Get a MessageBag instance from the bags. * * @param string $key * @return \Illuminate\Contracts\Support\MessageBag */ public function getBag($key) { return Arr::get($this->bags, $key) ?: new MessageBag; } /** * Get all the bags. * * @return array */ public function getBags() { return $this->bags; } /** * Add a new MessageBag instance to the bags. * * @param string $key * @param \Illuminate\Contracts\Support\MessageBag $bag * @return $this */ public function put($key, MessageBagContract $bag) { $this->bags[$key] = $bag; return $this; } /** * Determine if the default message bag has any messages. * * @return bool */ public function any() { return $this->count() > 0; } /** * Get the number of messages in the default bag. * * @return int */ public function count(): int { return $this->getBag('default')->count(); } /** * Dynamically call methods on the default bag. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { return $this->getBag('default')->$method(...$parameters); } /** * Dynamically access a view error bag. * * @param string $key * @return \Illuminate\Contracts\Support\MessageBag */ public function __get($key) { return $this->getBag($key); } /** * Dynamically set a view error bag. * * @param string $key * @param \Illuminate\Contracts\Support\MessageBag $value * @return void */ public function __set($key, $value) { $this->put($key, $value); } /** * Convert the default bag to its string representation. * * @return string */ public function __toString() { return (string) $this->getBag('default'); } } composer.json000064400000003372147133772320007304 0ustar00{ "name": "illuminate/support", "description": "The Illuminate Support package.", "license": "MIT", "homepage": "https://laravel.com", "support": { "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, "authors": [ { "name": "Taylor Otwell", "email": "taylor@laravel.com" } ], "require": { "php": "^8.1", "ext-ctype": "*", "ext-filter": "*", "ext-mbstring": "*", "doctrine/inflector": "^2.0", "illuminate/collections": "^10.0", "illuminate/conditionable": "^10.0", "illuminate/contracts": "^10.0", "illuminate/macroable": "^10.0", "nesbot/carbon": "^2.62.1", "voku/portable-ascii": "^2.0" }, "conflict": { "tightenco/collect": "<5.5.33" }, "autoload": { "psr-4": { "Illuminate\\Support\\": "" }, "files": [ "helpers.php" ] }, "extra": { "branch-alias": { "dev-master": "10.x-dev" } }, "suggest": { "illuminate/filesystem": "Required to use the composer class (^10.0).", "league/commonmark": "Required to use Str::markdown() and Stringable::markdown() (^2.0.2).", "ramsey/uuid": "Required to use Str::uuid() (^4.7).", "symfony/process": "Required to use the composer class (^6.2).", "symfony/uid": "Required to use Str::ulid() (^6.2).", "symfony/var-dumper": "Required to use the dd function (^6.2).", "vlucas/phpdotenv": "Required to use the Env class and env helper (^5.4.1)." }, "config": { "sort-packages": true }, "minimum-stability": "dev" } helpers.php000075500000024120147133772320006732 0ustar00 $value) { if (is_numeric($key)) { $start++; $array[$start] = Arr::pull($array, $key); } } return $array; } } if (! function_exists('blank')) { /** * Determine if the given value is "blank". * * @param mixed $value * @return bool */ function blank($value) { if (is_null($value)) { return true; } if (is_string($value)) { return trim($value) === ''; } if (is_numeric($value) || is_bool($value)) { return false; } if ($value instanceof Countable) { return count($value) === 0; } return empty($value); } } if (! function_exists('class_basename')) { /** * Get the class "basename" of the given object / class. * * @param string|object $class * @return string */ function class_basename($class) { $class = is_object($class) ? get_class($class) : $class; return basename(str_replace('\\', '/', $class)); } } if (! function_exists('class_uses_recursive')) { /** * Returns all traits used by a class, its parent classes and trait of their traits. * * @param object|string $class * @return array */ function class_uses_recursive($class) { if (is_object($class)) { $class = get_class($class); } $results = []; foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) { $results += trait_uses_recursive($class); } return array_unique($results); } } if (! function_exists('e')) { /** * Encode HTML special characters in a string. * * @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|null $value * @param bool $doubleEncode * @return string */ function e($value, $doubleEncode = true) { if ($value instanceof DeferringDisplayableValue) { $value = $value->resolveDisplayableValue(); } if ($value instanceof Htmlable) { return $value->toHtml(); } if ($value instanceof BackedEnum) { $value = $value->value; } return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8', $doubleEncode); } } if (! function_exists('env')) { /** * Gets the value of an environment variable. * * @param string $key * @param mixed $default * @return mixed */ function env($key, $default = null) { return Env::get($key, $default); } } if (! function_exists('filled')) { /** * Determine if a value is "filled". * * @param mixed $value * @return bool */ function filled($value) { return ! blank($value); } } if (! function_exists('object_get')) { /** * Get an item from an object using "dot" notation. * * @param object $object * @param string|null $key * @param mixed $default * @return mixed */ function object_get($object, $key, $default = null) { if (is_null($key) || trim($key) === '') { return $object; } foreach (explode('.', $key) as $segment) { if (! is_object($object) || ! isset($object->{$segment})) { return value($default); } $object = $object->{$segment}; } return $object; } } if (! function_exists('optional')) { /** * Provide access to optional objects. * * @param mixed $value * @param callable|null $callback * @return mixed */ function optional($value = null, callable $callback = null) { if (is_null($callback)) { return new Optional($value); } elseif (! is_null($value)) { return $callback($value); } } } if (! function_exists('preg_replace_array')) { /** * Replace a given pattern with each value in the array in sequentially. * * @param string $pattern * @param array $replacements * @param string $subject * @return string */ function preg_replace_array($pattern, array $replacements, $subject) { return preg_replace_callback($pattern, function () use (&$replacements) { foreach ($replacements as $value) { return array_shift($replacements); } }, $subject); } } if (! function_exists('retry')) { /** * Retry an operation a given number of times. * * @param int|array $times * @param callable $callback * @param int|\Closure $sleepMilliseconds * @param callable|null $when * @return mixed * * @throws \Exception */ function retry($times, callable $callback, $sleepMilliseconds = 0, $when = null) { $attempts = 0; $backoff = []; if (is_array($times)) { $backoff = $times; $times = count($times) + 1; } beginning: $attempts++; $times--; try { return $callback($attempts); } catch (Exception $e) { if ($times < 1 || ($when && ! $when($e))) { throw $e; } $sleepMilliseconds = $backoff[$attempts - 1] ?? $sleepMilliseconds; if ($sleepMilliseconds) { usleep(value($sleepMilliseconds, $attempts, $e) * 1000); } goto beginning; } } } if (! function_exists('str')) { /** * Get a new stringable object from the given string. * * @param string|null $string * @return \Illuminate\Support\Stringable|mixed */ function str($string = null) { if (func_num_args() === 0) { return new class { public function __call($method, $parameters) { return Str::$method(...$parameters); } public function __toString() { return ''; } }; } return Str::of($string); } } if (! function_exists('tap')) { /** * Call the given Closure with the given value then return the value. * * @param mixed $value * @param callable|null $callback * @return mixed */ function tap($value, $callback = null) { if (is_null($callback)) { return new HigherOrderTapProxy($value); } $callback($value); return $value; } } if (! function_exists('throw_if')) { /** * Throw the given exception if the given condition is true. * * @param mixed $condition * @param \Throwable|string $exception * @param mixed ...$parameters * @return mixed * * @throws \Throwable */ function throw_if($condition, $exception = 'RuntimeException', ...$parameters) { if ($condition) { if (is_string($exception) && class_exists($exception)) { $exception = new $exception(...$parameters); } throw is_string($exception) ? new RuntimeException($exception) : $exception; } return $condition; } } if (! function_exists('throw_unless')) { /** * Throw the given exception unless the given condition is true. * * @param mixed $condition * @param \Throwable|string $exception * @param mixed ...$parameters * @return mixed * * @throws \Throwable */ function throw_unless($condition, $exception = 'RuntimeException', ...$parameters) { throw_if(! $condition, $exception, ...$parameters); return $condition; } } if (! function_exists('trait_uses_recursive')) { /** * Returns all traits used by a trait and its traits. * * @param string $trait * @return array */ function trait_uses_recursive($trait) { $traits = class_uses($trait) ?: []; foreach ($traits as $trait) { $traits += trait_uses_recursive($trait); } return $traits; } } if (! function_exists('transform')) { /** * Transform the given value if it is present. * * @template TValue of mixed * @template TReturn of mixed * @template TDefault of mixed * * @param TValue $value * @param callable(TValue): TReturn $callback * @param TDefault|callable(TValue): TDefault|null $default * @return ($value is empty ? ($default is null ? null : TDefault) : TReturn) */ function transform($value, callable $callback, $default = null) { if (filled($value)) { return $callback($value); } if (is_callable($default)) { return $default($value); } return $default; } } if (! function_exists('windows_os')) { /** * Determine whether the current environment is Windows based. * * @return bool */ function windows_os() { return PHP_OS_FAMILY === 'Windows'; } } if (! function_exists('with')) { /** * Return the given value, optionally passed through the given callback. * * @template TValue * @template TReturn * * @param TValue $value * @param (callable(TValue): (TReturn))|null $callback * @return ($callback is null ? TValue : TReturn) */ function with($value, callable $callback = null) { return is_null($callback) ? $value : $callback($value); } }