id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
194553
<?php namespace Illuminate\Auth\Middleware; use Closure; use Illuminate\Auth\AuthenticationException; use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests; use Illuminate\Http\Request; class Authenticate implements AuthenticatesRequests { /** * The authentication factory instance. * * @var \Illuminate\Contracts\Auth\Factory */ protected $auth; /** * The callback that should be used to generate the authentication redirect path. * * @var callable */ protected static $redirectToCallback; /** * Create a new middleware instance. * * @param \Illuminate\Contracts\Auth\Factory $auth * @return void */ public function __construct(Auth $auth) { $this->auth = $auth; } /** * Specify the guards for the middleware. * * @param string $guard * @param string $others * @return string */ public static function using($guard, ...$others) { return static::class.':'.implode(',', [$guard, ...$others]); } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string ...$guards * @return mixed * * @throws \Illuminate\Auth\AuthenticationException */ public function handle($request, Closure $next, ...$guards) { $this->authenticate($request, $guards); return $next($request); } /** * Determine if the user is logged in to any of the given guards. * * @param \Illuminate\Http\Request $request * @param array $guards * @return void * * @throws \Illuminate\Auth\AuthenticationException */ protected function authenticate($request, array $guards) { if (empty($guards)) { $guards = [null]; } foreach ($guards as $guard) { if ($this->auth->guard($guard)->check()) { return $this->auth->shouldUse($guard); } } $this->unauthenticated($request, $guards); } /** * Handle an unauthenticated user. * * @param \Illuminate\Http\Request $request * @param array $guards * @return void * * @throws \Illuminate\Auth\AuthenticationException */ protected function unauthenticated($request, array $guards) { throw new AuthenticationException( 'Unauthenticated.', $guards, $request->expectsJson() ? null : $this->redirectTo($request), ); } /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ protected function redirectTo(Request $request) { if (static::$redirectToCallback) { return call_user_func(static::$redirectToCallback, $request); } } /** * Specify the callback that should be used to generate the redirect path. * * @param callable $redirectToCallback * @return void */ public static function redirectUsing(callable $redirectToCallback) { static::$redirectToCallback = $redirectToCallback; } }
194558
class Gate implements GateContract { use HandlesAuthorization; /** * The container instance. * * @var \Illuminate\Contracts\Container\Container */ protected $container; /** * The user resolver callable. * * @var callable */ protected $userResolver; /** * All of the defined abilities. * * @var array */ protected $abilities = []; /** * All of the defined policies. * * @var array */ protected $policies = []; /** * All of the registered before callbacks. * * @var array */ protected $beforeCallbacks = []; /** * All of the registered after callbacks. * * @var array */ protected $afterCallbacks = []; /** * All of the defined abilities using class@method notation. * * @var array */ protected $stringCallbacks = []; /** * The default denial response for gates and policies. * * @var \Illuminate\Auth\Access\Response|null */ protected $defaultDenialResponse; /** * The callback to be used to guess policy names. * * @var callable|null */ protected $guessPolicyNamesUsingCallback; /** * Create a new gate instance. * * @param \Illuminate\Contracts\Container\Container $container * @param callable $userResolver * @param array $abilities * @param array $policies * @param array $beforeCallbacks * @param array $afterCallbacks * @param callable|null $guessPolicyNamesUsingCallback * @return void */ public function __construct(Container $container, callable $userResolver, array $abilities = [], array $policies = [], array $beforeCallbacks = [], array $afterCallbacks = [], ?callable $guessPolicyNamesUsingCallback = null) { $this->policies = $policies; $this->container = $container; $this->abilities = $abilities; $this->userResolver = $userResolver; $this->afterCallbacks = $afterCallbacks; $this->beforeCallbacks = $beforeCallbacks; $this->guessPolicyNamesUsingCallback = $guessPolicyNamesUsingCallback; } /** * Determine if a given ability has been defined. * * @param string|array $ability * @return bool */ public function has($ability) { $abilities = is_array($ability) ? $ability : func_get_args(); foreach ($abilities as $ability) { if (! isset($this->abilities[$ability])) { return false; } } return true; } /** * Perform an on-demand authorization check. Throw an authorization exception if the condition or callback is false. * * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition * @param string|null $message * @param string|null $code * @return \Illuminate\Auth\Access\Response * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function allowIf($condition, $message = null, $code = null) { return $this->authorizeOnDemand($condition, $message, $code, true); } /** * Perform an on-demand authorization check. Throw an authorization exception if the condition or callback is true. * * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition * @param string|null $message * @param string|null $code * @return \Illuminate\Auth\Access\Response * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function denyIf($condition, $message = null, $code = null) { return $this->authorizeOnDemand($condition, $message, $code, false); } /** * Authorize a given condition or callback. * * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition * @param string|null $message * @param string|null $code * @param bool $allowWhenResponseIs * @return \Illuminate\Auth\Access\Response * * @throws \Illuminate\Auth\Access\AuthorizationException */ protected function authorizeOnDemand($condition, $message, $code, $allowWhenResponseIs) { $user = $this->resolveUser(); if ($condition instanceof Closure) { $response = $this->canBeCalledWithUser($user, $condition) ? $condition($user) : new Response(false, $message, $code); } else { $response = $condition; } return with($response instanceof Response ? $response : new Response( (bool) $response === $allowWhenResponseIs, $message, $code ))->authorize(); } /** * Define a new ability. * * @param \BackedEnum|string $ability * @param callable|array|string $callback * @return $this * * @throws \InvalidArgumentException */ public function define($ability, $callback) { $ability = enum_value($ability); if (is_array($callback) && isset($callback[0]) && is_string($callback[0])) { $callback = $callback[0].'@'.$callback[1]; } if (is_callable($callback)) { $this->abilities[$ability] = $callback; } elseif (is_string($callback)) { $this->stringCallbacks[$ability] = $callback; $this->abilities[$ability] = $this->buildAbilityCallback($ability, $callback); } else { throw new InvalidArgumentException("Callback must be a callable, callback array, or a 'Class@method' string."); } return $this; } /** * Define abilities for a resource. * * @param string $name * @param string $class * @param array|null $abilities * @return $this */ public function resource($name, $class, ?array $abilities = null) { $abilities = $abilities ?: [ 'viewAny' => 'viewAny', 'view' => 'view', 'create' => 'create', 'update' => 'update', 'delete' => 'delete', ]; foreach ($abilities as $ability => $method) { $this->define($name.'.'.$ability, $class.'@'.$method); } return $this; } /** * Create the ability callback for a callback string. * * @param string $ability * @param string $callback * @return \Closure */ protected function buildAbilityCallback($ability, $callback) { return function () use ($ability, $callback) { if (str_contains($callback, '@')) { [$class, $method] = Str::parseCallback($callback); } else { $class = $callback; } $policy = $this->resolvePolicy($class); $arguments = func_get_args(); $user = array_shift($arguments); $result = $this->callPolicyBefore( $policy, $user, $ability, $arguments ); if (! is_null($result)) { return $result; } return isset($method) ? $policy->{$method}(...func_get_args()) : $policy(...func_get_args()); }; } /** * Define a policy class for a given class type. * * @param string $class * @param string $policy * @return $this */ public function policy($class, $policy) { $this->policies[$class] = $policy; return $this; } /** * Register a callback to run before all Gate checks. * * @param callable $callback * @return $this */ public function before(callable $callback) { $this->beforeCallbacks[] = $callback; return $this; } /** * Register a callback to run after all Gate checks. * * @param callable $callback * @return $this */ public function after(callable $callback) { $this->afterCallbacks[] = $callback; return $this; } /** * Determine if all of the given abilities should be granted for the current user. * * @param iterable|\BackedEnum|string $ability * @param array|mixed $arguments * @return bool */
194588
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Scripts --> <script src="{{ asset('js/app.js') }}" defer></script> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <div id="app"> <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm"> <div class="container"> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.name', 'Laravel') }} </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!-- Left Side Of Navbar --> <ul class="navbar-nav mr-auto"> </ul> <!-- Right Side Of Navbar --> <ul class="navbar-nav ml-auto"> <!-- Authentication Links --> @guest <li class="nav-item"> <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a> </li> @if (Route::has('register')) <li class="nav-item"> <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a> </li> @endif @else <li class="nav-item dropdown"> <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> {{ Auth::user()->name }} <span class="caret"></span> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> </div> </li> @endguest </ul> </div> </div> </nav> <main class="py-4"> @yield('content') </main> </div> </body> </html>
194623
<x-mail::layout> {{-- Header --}} <x-slot:header> <x-mail::header :url="config('app.url')"> {{ config('app.name') }} </x-mail::header> </x-slot:header> {{-- Body --}} {{ $slot }} {{-- Subcopy --}} @isset($subcopy) <x-slot:subcopy> <x-mail::subcopy> {{ $subcopy }} </x-mail::subcopy> </x-slot:subcopy> @endisset {{-- Footer --}} <x-slot:footer> <x-mail::footer> © {{ date('Y') }} {{ config('app.name') }}. {{ __('All rights reserved.') }} </x-mail::footer> </x-slot:footer> </x-mail::layout>
194632
<x-mail::layout> {{-- Header --}} <x-slot:header> <x-mail::header :url="config('app.url')"> {{ config('app.name') }} </x-mail::header> </x-slot:header> {{-- Body --}} {{ $slot }} {{-- Subcopy --}} @isset($subcopy) <x-slot:subcopy> <x-mail::subcopy> {{ $subcopy }} </x-mail::subcopy> </x-slot:subcopy> @endisset {{-- Footer --}} <x-slot:footer> <x-mail::footer> © {{ date('Y') }} {{ config('app.name') }}. @lang('All rights reserved.') </x-mail::footer> </x-slot:footer> </x-mail::layout>
194646
<?php namespace Illuminate\Contracts\Encryption; interface StringEncrypter { /** * Encrypt a string without serialization. * * @param string $value * @return string * * @throws \Illuminate\Contracts\Encryption\EncryptException */ public function encryptString(#[\SensitiveParameter] $value); /** * Decrypt the given string without unserialization. * * @param string $payload * @return string * * @throws \Illuminate\Contracts\Encryption\DecryptException */ public function decryptString($payload); }
194691
<?php namespace Illuminate\Contracts\Auth; interface Guard { /** * Determine if the current user is authenticated. * * @return bool */ public function check(); /** * Determine if the current user is a guest. * * @return bool */ public function guest(); /** * Get the currently authenticated user. * * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function user(); /** * Get the ID for the currently authenticated user. * * @return int|string|null */ public function id(); /** * Validate a user's credentials. * * @param array $credentials * @return bool */ public function validate(array $credentials = []); /** * Determine if the guard has a user instance. * * @return bool */ public function hasUser(); /** * Set the current user. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @return $this */ public function setUser(Authenticatable $user); }
194717
<?php namespace Illuminate\Contracts\Container; interface ContextualBindingBuilder { /** * Define the abstract target that depends on the context. * * @param string $abstract * @return $this */ public function needs($abstract); /** * Define the implementation for the contextual binding. * * @param \Closure|string|array $implementation * @return void */ public function give($implementation); /** * Define tagged services to be used as the implementation for the contextual binding. * * @param string $tag * @return void */ public function giveTagged($tag); /** * Specify the configuration item to bind as a primitive. * * @param string $key * @param mixed $default * @return void */ public function giveConfig($key, $default = null); }
194737
<?php namespace Illuminate\Contracts\View; use Illuminate\Contracts\Support\Renderable; interface View extends Renderable { /** * Get the name of the view. * * @return string */ public function name(); /** * Add a piece of data to the view. * * @param string|array $key * @param mixed $value * @return $this */ public function with($key, $value = null); /** * Get the array of view data. * * @return array */ public function getData(); }
194787
/** * Get the path to the application "app" directory. * * @param string $path * @return string */ public function path($path = '') { return $this->joinPaths($this->appPath ?: $this->basePath('app'), $path); } /** * Set the application directory. * * @param string $path * @return $this */ public function useAppPath($path) { $this->appPath = $path; $this->instance('path', $path); return $this; } /** * Get the base path of the Laravel installation. * * @param string $path * @return string */ public function basePath($path = '') { return $this->joinPaths($this->basePath, $path); } /** * Get the path to the bootstrap directory. * * @param string $path * @return string */ public function bootstrapPath($path = '') { return $this->joinPaths($this->bootstrapPath, $path); } /** * Get the path to the service provider list in the bootstrap directory. * * @return string */ public function getBootstrapProvidersPath() { return $this->bootstrapPath('providers.php'); } /** * Set the bootstrap file directory. * * @param string $path * @return $this */ public function useBootstrapPath($path) { $this->bootstrapPath = $path; $this->instance('path.bootstrap', $path); return $this; } /** * Get the path to the application configuration files. * * @param string $path * @return string */ public function configPath($path = '') { return $this->joinPaths($this->configPath ?: $this->basePath('config'), $path); } /** * Set the configuration directory. * * @param string $path * @return $this */ public function useConfigPath($path) { $this->configPath = $path; $this->instance('path.config', $path); return $this; } /** * Get the path to the database directory. * * @param string $path * @return string */ public function databasePath($path = '') { return $this->joinPaths($this->databasePath ?: $this->basePath('database'), $path); } /** * Set the database directory. * * @param string $path * @return $this */ public function useDatabasePath($path) { $this->databasePath = $path; $this->instance('path.database', $path); return $this; } /** * Get the path to the language files. * * @param string $path * @return string */ public function langPath($path = '') { return $this->joinPaths($this->langPath, $path); } /** * Set the language file directory. * * @param string $path * @return $this */ public function useLangPath($path) { $this->langPath = $path; $this->instance('path.lang', $path); return $this; } /** * Get the path to the public / web directory. * * @param string $path * @return string */ public function publicPath($path = '') { return $this->joinPaths($this->publicPath ?: $this->basePath('public'), $path); } /** * Set the public / web directory. * * @param string $path * @return $this */ public function usePublicPath($path) { $this->publicPath = $path; $this->instance('path.public', $path); return $this; } /** * Get the path to the storage directory. * * @param string $path * @return string */ public function storagePath($path = '') { if (isset($_ENV['LARAVEL_STORAGE_PATH'])) { return $this->joinPaths($this->storagePath ?: $_ENV['LARAVEL_STORAGE_PATH'], $path); } if (isset($_SERVER['LARAVEL_STORAGE_PATH'])) { return $this->joinPaths($this->storagePath ?: $_SERVER['LARAVEL_STORAGE_PATH'], $path); } return $this->joinPaths($this->storagePath ?: $this->basePath('storage'), $path); } /** * Set the storage directory. * * @param string $path * @return $this */ public function useStoragePath($path) { $this->storagePath = $path; $this->instance('path.storage', $path); return $this; } /** * Get the path to the resources directory. * * @param string $path * @return string */ public function resourcePath($path = '') { return $this->joinPaths($this->basePath('resources'), $path); } /** * Get the path to the views directory. * * This method returns the first configured path in the array of view paths. * * @param string $path * @return string */ public function viewPath($path = '') { $viewPath = rtrim($this['config']->get('view.paths')[0], DIRECTORY_SEPARATOR); return $this->joinPaths($viewPath, $path); } /** * Join the given paths together. * * @param string $basePath * @param string $path * @return string */ public function joinPaths($basePath, $path = '') { return join_paths($basePath, $path); } /** * Get the path to the environment file directory. * * @return string */ public function environmentPath() { return $this->environmentPath ?: $this->basePath; } /** * Set the directory for the environment file. * * @param string $path * @return $this */ public function useEnvironmentPath($path) { $this->environmentPath = $path; return $this; } /** * Set the environment file to be loaded during bootstrapping. * * @param string $file * @return $this */ public function loadEnvironmentFrom($file) { $this->environmentFile = $file; return $this; } /** * Get the environment file the application is using. * * @return string */ public function environmentFile() { return $this->environmentFile ?: '.env'; } /** * Get the fully qualified path to the environment file. * * @return string */ public function environmentFilePath() { return $this->environmentPath().DIRECTORY_SEPARATOR.$this->environmentFile(); } /** * Get or check the current application environment. * * @param string|array ...$environments * @return string|bool */ public function environment(...$environments) { if (count($environments) > 0) { $patterns = is_array($environments[0]) ? $environments[0] : $environments; return Str::is($patterns, $this['env']); } return $this['env']; } /** * Determine if the application is in the local environment. * * @return bool */ public function isLocal() { return $this['env'] === 'local'; } /** * Determine if the application is in the production environment. * * @return bool */ public function isProduction() { return $this['env'] === 'production'; } /** * Detect the application's current environment. * * @param \Closure $callback * @return string */ public function detectEnvironment(Closure $callback) { $args = $_SERVER['argv'] ?? null; return $this['env'] = (new EnvironmentDetector)->detect($callback, $args); } /** * Determine if the application is running in the console. * * @return bool */
194788
public function runningInConsole() { if ($this->isRunningInConsole === null) { $this->isRunningInConsole = Env::get('APP_RUNNING_IN_CONSOLE') ?? (\PHP_SAPI === 'cli' || \PHP_SAPI === 'phpdbg'); } return $this->isRunningInConsole; } /** * Determine if the application is running any of the given console commands. * * @param string|array ...$commands * @return bool */ public function runningConsoleCommand(...$commands) { if (! $this->runningInConsole()) { return false; } return in_array( $_SERVER['argv'][1] ?? null, is_array($commands[0]) ? $commands[0] : $commands ); } /** * Determine if the application is running unit tests. * * @return bool */ public function runningUnitTests() { return $this->bound('env') && $this['env'] === 'testing'; } /** * Determine if the application is running with debug mode enabled. * * @return bool */ public function hasDebugModeEnabled() { return (bool) $this['config']->get('app.debug'); } /** * Register a new registered listener. * * @param callable $callback * @return void */ public function registered($callback) { $this->registeredCallbacks[] = $callback; } /** * Register all of the configured providers. * * @return void */ public function registerConfiguredProviders() { $providers = Collection::make($this->make('config')->get('app.providers')) ->partition(fn ($provider) => str_starts_with($provider, 'Illuminate\\')); $providers->splice(1, 0, [$this->make(PackageManifest::class)->providers()]); (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath())) ->load($providers->collapse()->toArray()); $this->fireAppCallbacks($this->registeredCallbacks); } /** * Register a service provider with the application. * * @param \Illuminate\Support\ServiceProvider|string $provider * @param bool $force * @return \Illuminate\Support\ServiceProvider */ public function register($provider, $force = false) { if (($registered = $this->getProvider($provider)) && ! $force) { return $registered; } // If the given "provider" is a string, we will resolve it, passing in the // application instance automatically for the developer. This is simply // a more convenient way of specifying your service provider classes. if (is_string($provider)) { $provider = $this->resolveProvider($provider); } $provider->register(); // If there are bindings / singletons set as properties on the provider we // will spin through them and register them with the application, which // serves as a convenience layer while registering a lot of bindings. if (property_exists($provider, 'bindings')) { foreach ($provider->bindings as $key => $value) { $this->bind($key, $value); } } if (property_exists($provider, 'singletons')) { foreach ($provider->singletons as $key => $value) { $key = is_int($key) ? $value : $key; $this->singleton($key, $value); } } $this->markAsRegistered($provider); // If the application has already booted, we will call this boot method on // the provider class so it has an opportunity to do its boot logic and // will be ready for any usage by this developer's application logic. if ($this->isBooted()) { $this->bootProvider($provider); } return $provider; } /** * Get the registered service provider instance if it exists. * * @param \Illuminate\Support\ServiceProvider|string $provider * @return \Illuminate\Support\ServiceProvider|null */ public function getProvider($provider) { $name = is_string($provider) ? $provider : get_class($provider); return $this->serviceProviders[$name] ?? null; } /** * Get the registered service provider instances if any exist. * * @param \Illuminate\Support\ServiceProvider|string $provider * @return array */ public function getProviders($provider) { $name = is_string($provider) ? $provider : get_class($provider); return Arr::where($this->serviceProviders, fn ($value) => $value instanceof $name); } /** * Resolve a service provider instance from the class name. * * @param string $provider * @return \Illuminate\Support\ServiceProvider */ public function resolveProvider($provider) { return new $provider($this); } /** * Mark the given provider as registered. * * @param \Illuminate\Support\ServiceProvider $provider * @return void */ protected function markAsRegistered($provider) { $class = get_class($provider); $this->serviceProviders[$class] = $provider; $this->loadedProviders[$class] = true; } /** * Load and boot all of the remaining deferred providers. * * @return void */ public function loadDeferredProviders() { // We will simply spin through each of the deferred providers and register each // one and boot them if the application has booted. This should make each of // the remaining services available to this application for immediate use. foreach ($this->deferredServices as $service => $provider) { $this->loadDeferredProvider($service); } $this->deferredServices = []; } /** * Load the provider for a deferred service. * * @param string $service * @return void */ public function loadDeferredProvider($service) { if (! $this->isDeferredService($service)) { return; } $provider = $this->deferredServices[$service]; // If the service provider has not already been loaded and registered we can // register it with the application and remove the service from this list // of deferred services, since it will already be loaded on subsequent. if (! isset($this->loadedProviders[$provider])) { $this->registerDeferredProvider($provider, $service); } } /** * Register a deferred provider and service. * * @param string $provider * @param string|null $service * @return void */ public function registerDeferredProvider($provider, $service = null) { // Once the provider that provides the deferred service has been registered we // will remove it from our local list of the deferred services with related // providers so that this container does not try to resolve it out again. if ($service) { unset($this->deferredServices[$service]); } $this->register($instance = new $provider($this)); if (! $this->isBooted()) { $this->booting(function () use ($instance) { $this->bootProvider($instance); }); } } /** * Resolve the given type from the container. * * @param string $abstract * @param array $parameters * @return mixed * * @throws \Illuminate\Contracts\Container\BindingResolutionException */ public function make($abstract, array $parameters = []) { $this->loadDeferredProviderIfNeeded($abstract = $this->getAlias($abstract)); return parent::make($abstract, $parameters); } /** * Resolve the given type from the container. * * @param string $abstract * @param array $parameters * @param bool $raiseEvents * @return mixed * * @throws \Illuminate\Contracts\Container\BindingResolutionException * @throws \Illuminate\Contracts\Container\CircularDependencyException */ protected function resolve($abstract, $parameters = [], $raiseEvents = true) { $this->loadDeferredProviderIfNeeded($abstract = $this->getAlias($abstract)); return parent::resolve($abstract, $parameters, $raiseEvents); } /** * Load the deferred provider if the given type is a deferred service and the instance has not been loaded. * * @param string $abstract * @return void */ protected function loadDeferredProviderIfNeeded($abstract) { if ($this->isDeferredService($abstract) && ! isset($this->instances[$abstract])) { $this->loadDeferredProvider($abstract); } }
194809
<?php use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Contracts\Auth\Factory as AuthFactory; use Illuminate\Contracts\Broadcasting\Factory as BroadcastFactory; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Contracts\Cookie\Factory as CookieFactory; use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Contracts\Routing\ResponseFactory; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Contracts\Support\Responsable; use Illuminate\Contracts\Validation\Factory as ValidationFactory; use Illuminate\Contracts\View\Factory as ViewFactory; use Illuminate\Foundation\Bus\PendingClosureDispatch; use Illuminate\Foundation\Bus\PendingDispatch; use Illuminate\Foundation\Mix; use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Log\Context\Repository as ContextRepository; use Illuminate\Queue\CallQueuedClosure; use Illuminate\Routing\Router; use Illuminate\Support\Facades\Date; use Illuminate\Support\HtmlString; use Symfony\Component\HttpFoundation\Response; if (! function_exists('abort')) { /** * Throw an HttpException with the given data. * * @param \Symfony\Component\HttpFoundation\Response|\Illuminate\Contracts\Support\Responsable|int $code * @param string $message * @param array $headers * @return never * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @throws \Illuminate\Http\Exceptions\HttpResponseException */ function abort($code, $message = '', array $headers = []) { if ($code instanceof Response) { throw new HttpResponseException($code); } elseif ($code instanceof Responsable) { throw new HttpResponseException($code->toResponse(request())); } app()->abort($code, $message, $headers); } } if (! function_exists('abort_if')) { /** * Throw an HttpException with the given data if the given condition is true. * * @param bool $boolean * @param \Symfony\Component\HttpFoundation\Response|\Illuminate\Contracts\Support\Responsable|int $code * @param string $message * @param array $headers * @return void * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ function abort_if($boolean, $code, $message = '', array $headers = []) { if ($boolean) { abort($code, $message, $headers); } } } if (! function_exists('abort_unless')) { /** * Throw an HttpException with the given data unless the given condition is true. * * @param bool $boolean * @param \Symfony\Component\HttpFoundation\Response|\Illuminate\Contracts\Support\Responsable|int $code * @param string $message * @param array $headers * @return void * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ function abort_unless($boolean, $code, $message = '', array $headers = []) { if (! $boolean) { abort($code, $message, $headers); } } } if (! function_exists('action')) { /** * Generate the URL to a controller action. * * @param string|array $name * @param mixed $parameters * @param bool $absolute * @return string */ function action($name, $parameters = [], $absolute = true) { return app('url')->action($name, $parameters, $absolute); } } if (! function_exists('app')) { /** * Get the available container instance. * * @template TClass * * @param string|class-string<TClass>|null $abstract * @param array $parameters * @return ($abstract is class-string<TClass> ? TClass : ($abstract is null ? \Illuminate\Foundation\Application : mixed)) */ function app($abstract = null, array $parameters = []) { if (is_null($abstract)) { return Container::getInstance(); } return Container::getInstance()->make($abstract, $parameters); } } if (! function_exists('app_path')) { /** * Get the path to the application folder. * * @param string $path * @return string */ function app_path($path = '') { return app()->path($path); } } if (! function_exists('asset')) { /** * Generate an asset path for the application. * * @param string $path * @param bool|null $secure * @return string */ function asset($path, $secure = null) { return app('url')->asset($path, $secure); } } if (! function_exists('auth')) { /** * Get the available auth instance. * * @param string|null $guard * @return ($guard is null ? \Illuminate\Contracts\Auth\Factory : \Illuminate\Contracts\Auth\StatefulGuard) */ function auth($guard = null) { if (is_null($guard)) { return app(AuthFactory::class); } return app(AuthFactory::class)->guard($guard); } } if (! function_exists('back')) { /** * Create a new redirect response to the previous location. * * @param int $status * @param array $headers * @param mixed $fallback * @return \Illuminate\Http\RedirectResponse */ function back($status = 302, $headers = [], $fallback = false) { return app('redirect')->back($status, $headers, $fallback); } } if (! function_exists('base_path')) { /** * Get the path to the base of the install. * * @param string $path * @return string */ function base_path($path = '') { return app()->basePath($path); } } if (! function_exists('bcrypt')) { /** * Hash the given value against the bcrypt algorithm. * * @param string $value * @param array $options * @return string */ function bcrypt($value, $options = []) { return app('hash')->driver('bcrypt')->make($value, $options); } } if (! function_exists('broadcast')) { /** * Begin broadcasting an event. * * @param mixed|null $event * @return \Illuminate\Broadcasting\PendingBroadcast */ function broadcast($event = null) { return app(BroadcastFactory::class)->event($event); } } if (! function_exists('cache')) { /** * Get / set the specified cache value. * * If an array is passed, we'll assume you want to put to the cache. * * @param string|array<string, mixed>|null $key key|data * @param mixed $default default|expiration|null * @return ($key is null ? \Illuminate\Cache\CacheManager : ($key is string ? mixed : bool)) * * @throws \InvalidArgumentException */ function cache($key = null, $default = null) { if (is_null($key)) { return app('cache'); } if (is_string($key)) { return app('cache')->get($key, $default); } if (! is_array($key)) { throw new InvalidArgumentException( 'When setting a value in the cache, you must pass an array of key / value pairs.' ); } return app('cache')->put(key($key), reset($key), ttl: $default); } } if (! function_exists('config')) { /** * Get / set the specified configuration value. * * If an array is passed as the key, we will assume you want to set an array of values. * * @param array<string, mixed>|string|null $key * @param mixed $default * @return ($key is null ? \Illuminate\Config\Repository : ($key is string ? mixed : null)) */ function config($key = null, $default = null) { if (is_null($key)) { return app('config'); } if (is_array($key)) { return app('config')->set($key); } return app('config')->get($key, $default); } } if (! function_exists('config_path')) { /** * Get the configuration path. * * @param string $path * @return string */ function config_path($path = '') { return app()->configPath($path); } }
194816
{ /** * The user defined global middleware stack. * * @var array */ protected $global = []; /** * The middleware that should be prepended to the global middleware stack. * * @var array */ protected $prepends = []; /** * The middleware that should be appended to the global middleware stack. * * @var array */ protected $appends = []; /** * The middleware that should be removed from the global middleware stack. * * @var array */ protected $removals = []; /** * The middleware that should be replaced in the global middleware stack. * * @var array */ protected $replacements = []; /** * The user defined middleware groups. * * @var array */ protected $groups = []; /** * The middleware that should be prepended to the specified groups. * * @var array */ protected $groupPrepends = []; /** * The middleware that should be appended to the specified groups. * * @var array */ protected $groupAppends = []; /** * The middleware that should be removed from the specified groups. * * @var array */ protected $groupRemovals = []; /** * The middleware that should be replaced in the specified groups. * * @var array */ protected $groupReplacements = []; /** * The Folio / page middleware for the application. * * @var array */ protected $pageMiddleware = []; /** * Indicates if the "trust hosts" middleware is enabled. * * @var bool */ protected $trustHosts = false; /** * Indicates if Sanctum's frontend state middleware is enabled. * * @var bool */ protected $statefulApi = false; /** * Indicates the API middleware group's rate limiter. * * @var string */ protected $apiLimiter; /** * Indicates if Redis throttling should be applied. * * @var bool */ protected $throttleWithRedis = false; /** * Indicates if sessions should be authenticated for the "web" middleware group. * * @var bool */ protected $authenticatedSessions = false; /** * The custom middleware aliases. * * @var array */ protected $customAliases = []; /** * The custom middleware priority definition. * * @var array */ protected $priority = []; /** * Prepend middleware to the application's global middleware stack. * * @param array|string $middleware * @return $this */ public function prepend(array|string $middleware) { $this->prepends = array_merge( Arr::wrap($middleware), $this->prepends ); return $this; } /** * Append middleware to the application's global middleware stack. * * @param array|string $middleware * @return $this */ public function append(array|string $middleware) { $this->appends = array_merge( $this->appends, Arr::wrap($middleware) ); return $this; } /** * Remove middleware from the application's global middleware stack. * * @param array|string $middleware * @return $this */ public function remove(array|string $middleware) { $this->removals = array_merge( $this->removals, Arr::wrap($middleware) ); return $this; } /** * Specify a middleware that should be replaced with another middleware. * * @param string $search * @param string $replace * @return $this */ public function replace(string $search, string $replace) { $this->replacements[$search] = $replace; return $this; } /** * Define the global middleware for the application. * * @param array $middleware * @return $this */ public function use(array $middleware) { $this->global = $middleware; return $this; } /** * Define a middleware group. * * @param string $group * @param array $middleware * @return $this */ public function group(string $group, array $middleware) { $this->groups[$group] = $middleware; return $this; } /** * Prepend the given middleware to the specified group. * * @param string $group * @param array|string $middleware * @return $this */ public function prependToGroup(string $group, array|string $middleware) { $this->groupPrepends[$group] = array_merge( Arr::wrap($middleware), $this->groupPrepends[$group] ?? [] ); return $this; } /** * Append the given middleware to the specified group. * * @param string $group * @param array|string $middleware * @return $this */ public function appendToGroup(string $group, array|string $middleware) { $this->groupAppends[$group] = array_merge( $this->groupAppends[$group] ?? [], Arr::wrap($middleware) ); return $this; } /** * Remove the given middleware from the specified group. * * @param string $group * @param array|string $middleware * @return $this */ public function removeFromGroup(string $group, array|string $middleware) { $this->groupRemovals[$group] = array_merge( Arr::wrap($middleware), $this->groupRemovals[$group] ?? [] ); return $this; } /** * Replace the given middleware in the specified group with another middleware. * * @param string $group * @param string $search * @param string $replace * @return $this */ public function replaceInGroup(string $group, string $search, string $replace) { $this->groupReplacements[$group][$search] = $replace; return $this; } /** * Modify the middleware in the "web" group. * * @param array|string $append * @param array|string $prepend * @param array|string $remove * @param array $replace * @return $this */ public function web(array|string $append = [], array|string $prepend = [], array|string $remove = [], array $replace = []) { return $this->modifyGroup('web', $append, $prepend, $remove, $replace); } /** * Modify the middleware in the "api" group. * * @param array|string $append * @param array|string $prepend * @param array|string $remove * @param array $replace * @return $this */ public function api(array|string $append = [], array|string $prepend = [], array|string $remove = [], array $replace = []) { return $this->modifyGroup('api', $append, $prepend, $remove, $replace); } /** * Modify the middleware in the given group. * * @param string $group * @param array|string $append * @param array|string $prepend * @param array|string $remove * @param array $replace * @return $this */ protected function modifyGroup(string $group, array|string $append, array|string $prepend, array|string $remove, array $replace) { if (! empty($append)) { $this->appendToGroup($group, $append); } if (! empty($prepend)) { $this->prependToGroup($group, $prepend); } if (! empty($remove)) { $this->removeFromGroup($group, $remove); } if (! empty($replace)) { foreach ($replace as $search => $replace) { $this->replaceInGroup($group, $search, $replace); } } return $this; } /** * Register the Folio / page middleware for the application. * * @param array $middleware * @return $this */ public function pages(array $middleware) { $this->pageMiddleware = $middleware; return $this; }
194817
/** * Register additional middleware aliases. * * @param array $aliases * @return $this */ public function alias(array $aliases) { $this->customAliases = $aliases; return $this; } /** * Define the middleware priority for the application. * * @param array $priority * @return $this */ public function priority(array $priority) { $this->priority = $priority; return $this; } /** * Get the global middleware. * * @return array */ public function getGlobalMiddleware() { $middleware = $this->global ?: array_values(array_filter([ \Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class, $this->trustHosts ? \Illuminate\Http\Middleware\TrustHosts::class : null, \Illuminate\Http\Middleware\TrustProxies::class, \Illuminate\Http\Middleware\HandleCors::class, \Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Http\Middleware\ValidatePostSize::class, \Illuminate\Foundation\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ])); $middleware = array_map(function ($middleware) { return $this->replacements[$middleware] ?? $middleware; }, $middleware); return array_values(array_filter( array_diff( array_unique(array_merge($this->prepends, $middleware, $this->appends)), $this->removals ) )); } /** * Get the middleware groups. * * @return array */ public function getMiddlewareGroups() { $middleware = [ 'web' => array_values(array_filter([ \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, $this->authenticatedSessions ? 'auth.session' : null, ])), 'api' => array_values(array_filter([ $this->statefulApi ? \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class : null, $this->apiLimiter ? 'throttle:'.$this->apiLimiter : null, \Illuminate\Routing\Middleware\SubstituteBindings::class, ])), ]; $middleware = array_merge($middleware, $this->groups); foreach ($middleware as $group => $groupedMiddleware) { foreach ($groupedMiddleware as $index => $groupMiddleware) { if (isset($this->groupReplacements[$group][$groupMiddleware])) { $middleware[$group][$index] = $this->groupReplacements[$group][$groupMiddleware]; } } } foreach ($this->groupRemovals as $group => $removals) { $middleware[$group] = array_values(array_filter( array_diff($middleware[$group] ?? [], $removals) )); } foreach ($this->groupPrepends as $group => $prepends) { $middleware[$group] = array_values(array_filter( array_unique(array_merge($prepends, $middleware[$group] ?? [])) )); } foreach ($this->groupAppends as $group => $appends) { $middleware[$group] = array_values(array_filter( array_unique(array_merge($middleware[$group] ?? [], $appends)) )); } return $middleware; } /** * Configure where guests are redirected by the "auth" middleware. * * @param callable|string $redirect * @return $this */ public function redirectGuestsTo(callable|string $redirect) { return $this->redirectTo(guests: $redirect); } /** * Configure where users are redirected by the "guest" middleware. * * @param callable|string $redirect * @return $this */ public function redirectUsersTo(callable|string $redirect) { return $this->redirectTo(users: $redirect); } /** * Configure where users are redirected by the authentication and guest middleware. * * @param callable|string $guests * @param callable|string $users * @return $this */ public function redirectTo(callable|string|null $guests = null, callable|string|null $users = null) { $guests = is_string($guests) ? fn () => $guests : $guests; $users = is_string($users) ? fn () => $users : $users; if ($guests) { Authenticate::redirectUsing($guests); AuthenticateSession::redirectUsing($guests); AuthenticationException::redirectUsing($guests); } if ($users) { RedirectIfAuthenticated::redirectUsing($users); } return $this; } /** * Configure the cookie encryption middleware. * * @param array<int, string> $except * @return $this */ public function encryptCookies(array $except = []) { EncryptCookies::except($except); return $this; } /** * Configure the CSRF token validation middleware. * * @param array $except * @return $this */ public function validateCsrfTokens(array $except = []) { ValidateCsrfToken::except($except); return $this; } /** * Configure the URL signature validation middleware. * * @param array $except * @return $this */ public function validateSignatures(array $except = []) { ValidateSignature::except($except); return $this; } /** * Configure the empty string conversion middleware. * * @param array<int, (\Closure(\Illuminate\Http\Request): bool)> $except * @return $this */ public function convertEmptyStringsToNull(array $except = []) { collect($except)->each(fn (Closure $callback) => ConvertEmptyStringsToNull::skipWhen($callback)); return $this; } /** * Configure the string trimming middleware. * * @param array<int, (\Closure(\Illuminate\Http\Request): bool)|string> $except * @return $this */ public function trimStrings(array $except = []) { [$skipWhen, $except] = collect($except)->partition(fn ($value) => $value instanceof Closure); $skipWhen->each(fn (Closure $callback) => TrimStrings::skipWhen($callback)); TrimStrings::except($except->all()); return $this; } /** * Indicate that the trusted host middleware should be enabled. * * @param array<int, string>|(callable(): array<int, string>)|null $at * @param bool $subdomains * @return $this */ public function trustHosts(array|callable|null $at = null, bool $subdomains = true) { $this->trustHosts = true; if (! is_null($at)) { TrustHosts::at($at, $subdomains); } return $this; } /** * Configure the trusted proxies for the application. * * @param array<int, string>|string|null $at * @param int|null $headers * @return $this */ public function trustProxies(array|string|null $at = null, ?int $headers = null) { if (! is_null($at)) { TrustProxies::at($at); } if (! is_null($headers)) { TrustProxies::withHeaders($headers); } return $this; } /** * Configure the middleware that prevents requests during maintenance mode. * * @param array<int, string> $except * @return $this */ public function preventRequestsDuringMaintenance(array $except = []) { PreventRequestsDuringMaintenance::except($except); return $this; } /** * Indicate that Sanctum's frontend state middleware should be enabled. * * @return $this */ public function statefulApi() { $this->statefulApi = true; return $this; } /** * Indicate that the API middleware group's throttling middleware should be enabled. * * @param string $limiter * @param bool $redis * @return $this */
194821
class ApplicationBuilder { /** * The service provider that are marked for registration. * * @var array */ protected array $pendingProviders = []; /** * Any additional routing callbacks that should be invoked while registering routes. * * @var array */ protected array $additionalRoutingCallbacks = []; /** * The Folio / page middleware that have been defined by the user. * * @var array */ protected array $pageMiddleware = []; /** * Create a new application builder instance. */ public function __construct(protected Application $app) { } /** * Register the standard kernel classes for the application. * * @return $this */ public function withKernels() { $this->app->singleton( \Illuminate\Contracts\Http\Kernel::class, \Illuminate\Foundation\Http\Kernel::class, ); $this->app->singleton( \Illuminate\Contracts\Console\Kernel::class, \Illuminate\Foundation\Console\Kernel::class, ); return $this; } /** * Register additional service providers. * * @param array $providers * @param bool $withBootstrapProviders * @return $this */ public function withProviders(array $providers = [], bool $withBootstrapProviders = true) { RegisterProviders::merge( $providers, $withBootstrapProviders ? $this->app->getBootstrapProvidersPath() : null ); return $this; } /** * Register the core event service provider for the application. * * @param array|bool $discover * @return $this */ public function withEvents(array|bool $discover = []) { if (is_array($discover) && count($discover) > 0) { AppEventServiceProvider::setEventDiscoveryPaths($discover); } if ($discover === false) { AppEventServiceProvider::disableEventDiscovery(); } if (! isset($this->pendingProviders[AppEventServiceProvider::class])) { $this->app->booting(function () { $this->app->register(AppEventServiceProvider::class); }); } $this->pendingProviders[AppEventServiceProvider::class] = true; return $this; } /** * Register the broadcasting services for the application. * * @param string $channels * @param array $attributes * @return $this */ public function withBroadcasting(string $channels, array $attributes = []) { $this->app->booted(function () use ($channels, $attributes) { Broadcast::routes(! empty($attributes) ? $attributes : null); if (file_exists($channels)) { require $channels; } }); return $this; } /** * Register the routing services for the application. * * @param \Closure|null $using * @param array|string|null $web * @param array|string|null $api * @param string|null $commands * @param string|null $channels * @param string|null $pages * @param string $apiPrefix * @param callable|null $then * @return $this */ public function withRouting(?Closure $using = null, array|string|null $web = null, array|string|null $api = null, ?string $commands = null, ?string $channels = null, ?string $pages = null, ?string $health = null, string $apiPrefix = 'api', ?callable $then = null) { if (is_null($using) && (is_string($web) || is_array($web) || is_string($api) || is_array($api) || is_string($pages) || is_string($health)) || is_callable($then)) { $using = $this->buildRoutingCallback($web, $api, $pages, $health, $apiPrefix, $then); } AppRouteServiceProvider::loadRoutesUsing($using); $this->app->booting(function () { $this->app->register(AppRouteServiceProvider::class, force: true); }); if (is_string($commands) && realpath($commands) !== false) { $this->withCommands([$commands]); } if (is_string($channels) && realpath($channels) !== false) { $this->withBroadcasting($channels); } return $this; } /** * Create the routing callback for the application. * * @param array|string|null $web * @param array|string|null $api * @param string|null $pages * @param string|null $health * @param string $apiPrefix * @param callable|null $then * @return \Closure */ protected function buildRoutingCallback(array|string|null $web, array|string|null $api, ?string $pages, ?string $health, string $apiPrefix, ?callable $then) { return function () use ($web, $api, $pages, $health, $apiPrefix, $then) { if (is_string($api) || is_array($api)) { if (is_array($api)) { foreach ($api as $apiRoute) { if (realpath($apiRoute) !== false) { Route::middleware('api')->prefix($apiPrefix)->group($apiRoute); } } } else { Route::middleware('api')->prefix($apiPrefix)->group($api); } } if (is_string($health)) { Route::get($health, function () { Event::dispatch(new DiagnosingHealth); return View::file(__DIR__.'/../resources/health-up.blade.php'); }); } if (is_string($web) || is_array($web)) { if (is_array($web)) { foreach ($web as $webRoute) { if (realpath($webRoute) !== false) { Route::middleware('web')->group($webRoute); } } } else { Route::middleware('web')->group($web); } } foreach ($this->additionalRoutingCallbacks as $callback) { $callback(); } if (is_string($pages) && realpath($pages) !== false && class_exists(Folio::class)) { Folio::route($pages, middleware: $this->pageMiddleware); } if (is_callable($then)) { $then($this->app); } }; } /** * Register the global middleware, middleware groups, and middleware aliases for the application. * * @param callable|null $callback * @return $this */ public function withMiddleware(?callable $callback = null) { $this->app->afterResolving(HttpKernel::class, function ($kernel) use ($callback) { $middleware = (new Middleware) ->redirectGuestsTo(fn () => route('login')); if (! is_null($callback)) { $callback($middleware); } $this->pageMiddleware = $middleware->getPageMiddleware(); $kernel->setGlobalMiddleware($middleware->getGlobalMiddleware()); $kernel->setMiddlewareGroups($middleware->getMiddlewareGroups()); $kernel->setMiddlewareAliases($middleware->getMiddlewareAliases()); if ($priorities = $middleware->getMiddlewarePriority()) { $kernel->setMiddlewarePriority($priorities); } }); return $this; } /** * Register additional Artisan commands with the application. * * @param array $commands * @return $this */ public function withCommands(array $commands = []) { if (empty($commands)) { $commands = [$this->app->path('Console/Commands')]; } $this->app->afterResolving(ConsoleKernel::class, function ($kernel) use ($commands) { [$commands, $paths] = collect($commands)->partition(fn ($command) => class_exists($command)); [$routes, $paths] = $paths->partition(fn ($path) => is_file($path)); $this->app->booted(static function () use ($kernel, $commands, $paths, $routes) { $kernel->addCommands($commands->all()); $kernel->addCommandPaths($paths->all()); $kernel->addCommandRoutePaths($routes->all()); }); }); return $this; } /** * Register additional Artisan route paths. * * @param array $paths * @return $this */
194824
<?php namespace Illuminate\Foundation\Bootstrap; use Dotenv\Dotenv; use Dotenv\Exception\InvalidFileException; use Illuminate\Contracts\Foundation\Application; use Illuminate\Support\Env; use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Output\ConsoleOutput; class LoadEnvironmentVariables { /** * Bootstrap the given application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function bootstrap(Application $app) { if ($app->configurationIsCached()) { return; } $this->checkForSpecificEnvironmentFile($app); try { $this->createDotenv($app)->safeLoad(); } catch (InvalidFileException $e) { $this->writeErrorAndDie($e); } } /** * Detect if a custom environment file matching the APP_ENV exists. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ protected function checkForSpecificEnvironmentFile($app) { if ($app->runningInConsole() && ($input = new ArgvInput)->hasParameterOption('--env') && $this->setEnvironmentFilePath($app, $app->environmentFile().'.'.$input->getParameterOption('--env'))) { return; } $environment = Env::get('APP_ENV'); if (! $environment) { return; } $this->setEnvironmentFilePath( $app, $app->environmentFile().'.'.$environment ); } /** * Load a custom environment file. * * @param \Illuminate\Contracts\Foundation\Application $app * @param string $file * @return bool */ protected function setEnvironmentFilePath($app, $file) { if (is_file($app->environmentPath().'/'.$file)) { $app->loadEnvironmentFrom($file); return true; } return false; } /** * Create a Dotenv instance. * * @param \Illuminate\Contracts\Foundation\Application $app * @return \Dotenv\Dotenv */ protected function createDotenv($app) { return Dotenv::create( Env::getRepository(), $app->environmentPath(), $app->environmentFile() ); } /** * Write the error information to the screen and exit. * * @param \Dotenv\Exception\InvalidFileException $e * @return never */ protected function writeErrorAndDie(InvalidFileException $e) { $output = (new ConsoleOutput)->getErrorOutput(); $output->writeln('The environment file is invalid!'); $output->writeln($e->getMessage()); http_response_code(500); exit(1); } }
194825
<?php namespace Illuminate\Foundation\Bootstrap; use Illuminate\Config\Repository; use Illuminate\Contracts\Config\Repository as RepositoryContract; use Illuminate\Contracts\Foundation\Application; use SplFileInfo; use Symfony\Component\Finder\Finder; class LoadConfiguration { /** * Bootstrap the given application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function bootstrap(Application $app) { $items = []; // First we will see if we have a cache configuration file. If we do, we'll load // the configuration items from that file so that it is very quick. Otherwise // we will need to spin through every configuration file and load them all. if (file_exists($cached = $app->getCachedConfigPath())) { $items = require $cached; $app->instance('config_loaded_from_cache', $loadedFromCache = true); } // Next we will spin through all of the configuration files in the configuration // directory and load each one into the repository. This will make all of the // options available to the developer for use in various parts of this app. $app->instance('config', $config = new Repository($items)); if (! isset($loadedFromCache)) { $this->loadConfigurationFiles($app, $config); } // Finally, we will set the application's environment based on the configuration // values that were loaded. We will pass a callback which will be used to get // the environment in a web context where an "--env" switch is not present. $app->detectEnvironment(fn () => $config->get('app.env', 'production')); date_default_timezone_set($config->get('app.timezone', 'UTC')); mb_internal_encoding('UTF-8'); } /** * Load the configuration items from all of the files. * * @param \Illuminate\Contracts\Foundation\Application $app * @param \Illuminate\Contracts\Config\Repository $repository * @return void * * @throws \Exception */ protected function loadConfigurationFiles(Application $app, RepositoryContract $repository) { $files = $this->getConfigurationFiles($app); $shouldMerge = method_exists($app, 'shouldMergeFrameworkConfiguration') ? $app->shouldMergeFrameworkConfiguration() : true; $base = $shouldMerge ? $this->getBaseConfiguration() : []; foreach (array_diff(array_keys($base), array_keys($files)) as $name => $config) { $repository->set($name, $config); } foreach ($files as $name => $path) { $base = $this->loadConfigurationFile($repository, $name, $path, $base); } foreach ($base as $name => $config) { $repository->set($name, $config); } } /** * Load the given configuration file. * * @param \Illuminate\Contracts\Config\Repository $repository * @param string $name * @param string $path * @param array $base * @return array */ protected function loadConfigurationFile(RepositoryContract $repository, $name, $path, array $base) { $config = (fn () => require $path)(); if (isset($base[$name])) { $config = array_merge($base[$name], $config); foreach ($this->mergeableOptions($name) as $option) { if (isset($config[$option])) { $config[$option] = array_merge($base[$name][$option], $config[$option]); } } unset($base[$name]); } $repository->set($name, $config); return $base; } /** * Get the options within the configuration file that should be merged again. * * @param string $name * @return array */ protected function mergeableOptions($name) { return [ 'auth' => ['guards', 'providers', 'passwords'], 'broadcasting' => ['connections'], 'cache' => ['stores'], 'database' => ['connections'], 'filesystems' => ['disks'], 'logging' => ['channels'], 'mail' => ['mailers'], 'queue' => ['connections'], ][$name] ?? []; } /** * Get all of the configuration files for the application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return array */ protected function getConfigurationFiles(Application $app) { $files = []; $configPath = realpath($app->configPath()); if (! $configPath) { return []; } foreach (Finder::create()->files()->name('*.php')->in($configPath) as $file) { $directory = $this->getNestedDirectory($file, $configPath); $files[$directory.basename($file->getRealPath(), '.php')] = $file->getRealPath(); } ksort($files, SORT_NATURAL); return $files; } /** * Get the configuration file nesting path. * * @param \SplFileInfo $file * @param string $configPath * @return string */ protected function getNestedDirectory(SplFileInfo $file, $configPath) { $directory = $file->getPath(); if ($nested = trim(str_replace($configPath, '', $directory), DIRECTORY_SEPARATOR)) { $nested = str_replace(DIRECTORY_SEPARATOR, '.', $nested).'.'; } return $nested; } /** * Get the base configuration files. * * @return array */ protected function getBaseConfiguration() { $config = []; foreach (Finder::create()->files()->name('*.php')->in(__DIR__.'/../../../../config') as $file) { $config[basename($file->getRealPath(), '.php')] = require $file->getRealPath(); } return $config; } }
194828
<?php namespace Illuminate\Foundation\Bootstrap; use Illuminate\Contracts\Foundation\Application; use Illuminate\Foundation\AliasLoader; use Illuminate\Foundation\PackageManifest; use Illuminate\Support\Facades\Facade; class RegisterFacades { /** * Bootstrap the given application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function bootstrap(Application $app) { Facade::clearResolvedInstances(); Facade::setFacadeApplication($app); AliasLoader::getInstance(array_merge( $app->make('config')->get('app.aliases', []), $app->make(PackageManifest::class)->aliases() ))->register(); } }
194832
<?php namespace Illuminate\Foundation\Auth; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\MustVerifyEmail; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\Access\Authorizable; class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail; }
194833
<?php namespace Illuminate\Foundation\Auth; use Illuminate\Auth\Events\Verified; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Validator; class EmailVerificationRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { if (! hash_equals((string) $this->user()->getKey(), (string) $this->route('id'))) { return false; } if (! hash_equals(sha1($this->user()->getEmailForVerification()), (string) $this->route('hash'))) { return false; } return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // ]; } /** * Fulfill the email verification request. * * @return void */ public function fulfill() { if (! $this->user()->hasVerifiedEmail()) { $this->user()->markEmailAsVerified(); event(new Verified($this->user())); } } /** * Configure the validator instance. * * @param \Illuminate\Validation\Validator $validator * @return \Illuminate\Validation\Validator */ public function withValidator(Validator $validator) { return $validator; } }
194835
<?php namespace Illuminate\Foundation\Auth\Access; use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Support\Str; trait AuthorizesRequests { /** * Authorize a given action for the current user. * * @param mixed $ability * @param mixed|array $arguments * @return \Illuminate\Auth\Access\Response * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function authorize($ability, $arguments = []) { [$ability, $arguments] = $this->parseAbilityAndArguments($ability, $arguments); return app(Gate::class)->authorize($ability, $arguments); } /** * Authorize a given action for a user. * * @param \Illuminate\Contracts\Auth\Authenticatable|mixed $user * @param mixed $ability * @param mixed|array $arguments * @return \Illuminate\Auth\Access\Response * * @throws \Illuminate\Auth\Access\AuthorizationException */ public function authorizeForUser($user, $ability, $arguments = []) { [$ability, $arguments] = $this->parseAbilityAndArguments($ability, $arguments); return app(Gate::class)->forUser($user)->authorize($ability, $arguments); } /** * Guesses the ability's name if it wasn't provided. * * @param mixed $ability * @param mixed|array $arguments * @return array */ protected function parseAbilityAndArguments($ability, $arguments) { if (is_string($ability) && ! str_contains($ability, '\\')) { return [$ability, $arguments]; } $method = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function']; return [$this->normalizeGuessedAbilityName($method), $ability]; } /** * Normalize the ability name that has been guessed from the method name. * * @param string $ability * @return string */ protected function normalizeGuessedAbilityName($ability) { $map = $this->resourceAbilityMap(); return $map[$ability] ?? $ability; } /** * Authorize a resource action based on the incoming request. * * @param string|array $model * @param string|array|null $parameter * @param array $options * @param \Illuminate\Http\Request|null $request * @return void */ public function authorizeResource($model, $parameter = null, array $options = [], $request = null) { $model = is_array($model) ? implode(',', $model) : $model; $parameter = is_array($parameter) ? implode(',', $parameter) : $parameter; $parameter = $parameter ?: Str::snake(class_basename($model)); $middleware = []; foreach ($this->resourceAbilityMap() as $method => $ability) { $modelName = in_array($method, $this->resourceMethodsWithoutModels()) ? $model : $parameter; $middleware["can:{$ability},{$modelName}"][] = $method; } foreach ($middleware as $middlewareName => $methods) { $this->middleware($middlewareName, $options)->only($methods); } } /** * Get the map of resource methods to ability names. * * @return array */ protected function resourceAbilityMap() { return [ 'index' => 'viewAny', 'show' => 'view', 'create' => 'create', 'store' => 'create', 'edit' => 'update', 'update' => 'update', 'destroy' => 'delete', ]; } /** * Get the list of resource methods which do not have model parameters. * * @return array */ protected function resourceMethodsWithoutModels() { return ['index', 'create', 'store']; } }
194846
const defaultTheme = require('tailwindcss/defaultTheme'); /** @type {import('tailwindcss').Config} */ module.exports = { content: ['./**/*.blade.php'], darkMode: 'class', theme: { extend: { fontFamily: { sans: ['Figtree', ...defaultTheme.fontFamily.sans], }, }, }, plugins: [], };
194847
@import 'tippy.js/dist/tippy.css'; @import 'tippy.js/themes/material.css'; @import 'tippy.js/animations/scale.css'; @tailwind base; @tailwind components; @tailwind utilities; [x-cloak] { display: none; } html { tab-size: 4; } table.hljs-ln { color: inherit; font-size: inherit; border-spacing: 2px; } pre code.hljs { background: none; padding: 0em; padding-top: 0.5em; width: 100%; } .hljs-ln-line { white-space-collapse: preserve; text-wrap: nowrap; } .trace { -webkit-mask-image: linear-gradient(180deg, #000 calc(100% - 4rem), transparent); } .scrollbar-hidden { -ms-overflow-style: none; scrollbar-width: none; overflow-x: scroll; } .scrollbar-hidden::-webkit-scrollbar { -webkit-appearance: none; width: 0; height: 0; } .hljs-ln .hljs-ln-numbers { padding: 5px; border-right-color: transparent; margin-right: 5px; } .hljs-ln-n { width: 50px; } .hljs-ln-numbers { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; text-align: center; border-right: 1px solid #ccc; vertical-align: top; padding-right: 5px; } .hljs-ln-code { width: 100%; padding-left: 10px; padding-right: 10px; } .hljs-ln-code:hover { background-color: rgba(239, 68, 68, 0.2); }
194856
.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.shadow-xl{--tw-shadow:0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-gray-900\/5{--tw-ring-color:rgb(17 24 39 / .05)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}[x-cloak]{display:none}html{-moz-tab-size:4;-o-tab-size:4;tab-size:4}table.hljs-ln{color:inherit;font-size:inherit;border-spacing:2px}pre code.hljs{background:none;padding:.5em 0 0;width:100%}.hljs-ln-line{white-space-collapse:preserve;text-wrap:nowrap}.trace{-webkit-mask-image:linear-gradient(180deg,#000 calc(100% - 4rem),transparent)}.scrollbar-hidden{-ms-overflow-style:none;scrollbar-width:none;overflow-x:scroll}.scrollbar-hidden::-webkit-scrollbar{-webkit-appearance:none;width:0;height:0}.hljs-ln .hljs-ln-numbers{padding:5px;border-right-color:transparent;margin-right:5px}.hljs-ln-n{width:50px}.hljs-ln-numbers{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;text-align:center;border-right:1px solid #ccc;vertical-align:top;padding-right:5px}.hljs-ln-code{width:100%;padding-left:10px;padding-right:10px}.hljs-ln-code:hover{background-color:#ef444433}.default\:col-span-full:default{grid-column:1 / -1}.default\:row-span-1:default{grid-row:span 1 / span 1}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.hover\:bg-gray-100\/75:hover{background-color:#f3f4f6bf}.hover\:text-gray-500:hover{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.hover\:underline:hover{text-decoration-line:underline}.focus\:text-gray-500:focus{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border:is(.dark *){border-width:1px}.dark\:border-gray-700:is(.dark *){--tw-border-opacity:1;border-color:rgb(55 65 81 / var(--tw-border-opacity))}.dark\:border-gray-800:is(.dark *){--tw-border-opacity:1;border-color:rgb(31 41 55 / var(--tw-border-opacity))}.dark\:border-gray-900:is(.dark *){--tw-border-opacity:1;border-color:rgb(17 24 39 / var(--tw-border-opacity))}.dark\:border-l-red-500:is(.dark *){--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:bg-gray-900\/80:is(.dark *){background-color:#111827cc}.dark\:bg-gray-950\/95:is(.dark *){background-color:#030712f2}.dark\:bg-red-500\/20:is(.dark *){background-color:#ef444433}.dark\:text-gray-100:is(.dark *){--tw-text-opacity:1;color:rgb(243 244 246 / var(--tw-text-opacity))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity:1;color:rgb(209 213 219 / var(--tw-text-opacity))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity:1;color:rgb(75 85 99 / var(--tw-text-opacity))}.dark\:text-gray-950:is(.dark *){--tw-text-opacity:1;color:rgb(3 7 18 / var(--tw-text-opacity))}.dark\:text-white:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255 / var(--tw-text-opacity))}.dark\:ring-1:is(.dark *){--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.dark\:ring-gray-800:is(.dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(31 41 55 / var(--tw-ring-opacity))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800\/75:hover:is(.dark *){background-color:#1f2937bf}.dark\:hover\:text-gray-500:hover:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:focus\:text-gray-500:focus:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:col-span-1{grid-column:span 1 / span 1}.sm\:col-span-2{grid-column:span 2 / span 2}.sm\:mt-10{margin-top:2.5rem}.sm\:gap-6{gap:1.5rem}.sm\:p-12{padding:3rem}.sm\:py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media (min-width: 768px){.md\:block{display:block}.md\:inline{display:inline}.md\:flex{display:flex}.md\:hidden{display:none}.md\:min-w-64{min-width:16rem}.md\:max-w-80{max-width:20rem}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:gap-2{gap:.5rem}}@media (min-width: 1024px){.lg\:block{display:block}.lg\:inline-block{display:inline-block}.lg\:w-\[12rem\]{width:12rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}.lg\:text-2xl{font-size:1.5rem;line-height:2rem}.lg\:text-base{font-size:1rem;line-height:1.5rem}.lg\:text-sm{font-size:.875rem;line-height:1.25rem}.default\:lg\:col-span-6:default{grid-column:span 6 / span 6}}
194871
Q("for",(e,{expression:t},{effect:n,cleanup:r})=>{let i=Hu(t),o=ae(e,i.items),a=ae(e,e._x_keyExpression||"index");e._x_prevKeys=[],e._x_lookup={},n(()=>ju(e,i,o,a)),r(()=>{Object.values(e._x_lookup).forEach(s=>s.remove()),delete e._x_prevKeys,delete e._x_lookup})});function ju(e,t,n,r){let i=a=>typeof a=="object"&&!Array.isArray(a),o=e;n(a=>{Fu(a)&&a>=0&&(a=Array.from(Array(a).keys(),h=>h+1)),a===void 0&&(a=[]);let s=e._x_lookup,c=e._x_prevKeys,f=[],l=[];if(i(a))a=Object.entries(a).map(([h,E])=>{let O=di(t,E,h,a);r(M=>{l.includes(M)&&ve("Duplicate key on x-for",e),l.push(M)},{scope:{index:h,...O}}),f.push(O)});else for(let h=0;h<a.length;h++){let E=di(t,a[h],h,a);r(O=>{l.includes(O)&&ve("Duplicate key on x-for",e),l.push(O)},{scope:{index:h,...E}}),f.push(E)}let v=[],b=[],_=[],A=[];for(let h=0;h<c.length;h++){let E=c[h];l.indexOf(E)===-1&&_.push(E)}c=c.filter(h=>!_.includes(h));let S="template";for(let h=0;h<l.length;h++){let E=l[h],O=c.indexOf(E);if(O===-1)c.splice(h,0,E),v.push([S,h]);else if(O!==h){let M=c.splice(h,1)[0],u=c.splice(O-1,1)[0];c.splice(h,0,u),c.splice(O,0,M),b.push([M,u])}else A.push(E);S=E}for(let h=0;h<_.length;h++){let E=_[h];s[E]._x_effects&&s[E]._x_effects.forEach($i),s[E].remove(),s[E]=null,delete s[E]}for(let h=0;h<b.length;h++){let[E,O]=b[h],M=s[E],u=s[O],I=document.createElement("div");ee(()=>{u||ve('x-for ":key" is undefined or invalid',o,O,s),u.after(I),M.after(u),u._x_currentIfEl&&u.after(u._x_currentIfEl),I.before(M),M._x_currentIfEl&&M.after(M._x_currentIfEl),I.remove()}),u._x_refreshXForScope(f[l.indexOf(O)])}for(let h=0;h<v.length;h++){let[E,O]=v[h],M=E==="template"?o:s[E];M._x_currentIfEl&&(M=M._x_currentIfEl);let u=f[O],I=l[O],m=document.importNode(o.content,!0).firstElementChild,L=yt(u);Ht(m,L,o),m._x_refreshXForScope=K=>{Object.entries(K).forEach(([P,H])=>{L[P]=H})},ee(()=>{M.after(m),Ke(()=>Ne(m))()}),typeof I=="object"&&ve("x-for key cannot be an object, it must be a string or an integer",o),s[I]=m}for(let h=0;h<A.length;h++)s[A[h]]._x_refreshXForScope(f[l.indexOf(A[h])]);o._x_prevKeys=l})}function Hu(e){let t=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,n=/^\s*\(|\)\s*$/g,r=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/,i=e.match(r);if(!i)return;let o={};o.items=i[2].trim();let a=i[1].replace(n,"").trim(),s=a.match(t);return s?(o.item=a.replace(t,"").trim(),o.index=s[1].trim(),s[2]&&(o.collection=s[2].trim())):o.item=a,o}function di(e,t,n,r){let i={};return/^\[.*\]$/.test(e.item)&&Array.isArray(t)?e.item.replace("[","").replace("]","").split(",").map(a=>a.trim()).forEach((a,s)=>{i[a]=t[s]}):/^\{.*\}$/.test(e.item)&&!Array.isArray(t)&&typeof t=="object"?e.item.replace("{","").replace("}","").split(",").map(a=>a.trim()).forEach(a=>{i[a]=t[a]}):i[e.item]=t,e.index&&(i[e.index]=n),e.collection&&(i[e.collection]=r),i}function Fu(e){return!Array.isArray(e)&&!isNaN(e)}function Xo(){}Xo.inline=(e,{expression:t},{cleanup:n})=>{let r=pn(e);r._x_refs||(r._x_refs={}),r._x_refs[t]=e,n(()=>delete r._x_refs[t])};Q("ref",Xo);Q("if",(e,{expression:t},{effect:n,cleanup:r})=>{e.tagName.toLowerCase()!=="template"&&ve("x-if can only be used on a <template> tag",e);let i=ae(e,t),o=()=>{if(e._x_currentIfEl)return e._x_currentIfEl;let s=e.content.cloneNode(!0).firstElementChild;return Ht(s,{},e),ee(()=>{e.after(s),Ke(()=>Ne(s))()}),e._x_currentIfEl=s,e._x_undoIf=()=>{He(s,c=>{c._x_effects&&c._x_effects.forEach($i)}),s.remove(),delete e._x_currentIfEl},s},a=()=>{e._x_undoIf&&(e._x_undoIf(),delete e._x_undoIf)};n(()=>i(s=>{s?o():a()})),r(()=>e._x_undoIf&&e._x_undoIf())});Q("id",(e,{expression:t},{evaluate:n})=>{n(t).forEach(i=>Tu(e,i))});gn((e,t)=>{e._x_ids&&(t._x_ids=e._x_ids)});br(io("@",oo(xt("on:"))));Q("on",Ke((e,{value:t,modifiers:n,expression:r},{cleanup:i})=>{let o=r?ae(e,r):()=>{};e.tagName.toLowerCase()==="template"&&(e._x_forwardEvents||(e._x_forwardEvents=[]),e._x_forwardEvents.includes(t)||e._x_forwardEvents.push(t));let a=tr(e,t,n,s=>{o(()=>{},{scope:{$event:s},params:[s]})});i(()=>a())}));yn("Collapse","collapse","collapse");yn("Intersect","intersect","intersect");yn("Focus","trap","focus");yn("Mask","mask","mask");function yn(e,t,n){Q(t,r=>ve(`You can't use [x-${t}] without first installing the "${e}" plugin here: https://alpinejs.dev/plugins/${n}`,r))}Wt.setEvaluator(eo);Wt.setReactivityEngine({reactive:Cr,effect:Qc,release:eu,raw:X});var Uu=Wt,Wu=Uu;function Ku(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Yo(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw new Error("map is read-only")}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw new Error("set is read-only")}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{const n=e[t],r=typeof n;(r==="object"||r==="function")&&!Object.isFrozen(n)&&Yo(n)}),e}class pi{constructor(t){t.data===void 0&&(t.data={}),this.data=t.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function Jo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function je(e,...t){const n=Object.create(null);for(const r in e)n[r]=e[r];return t.forEach(function(r){for(const i in r)n[i]=r[i]}),n}const zu="</span>",hi=e=>!!e.scope,Vu=(e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return[`${t}${n.shift()}`,...n.map((r,i)=>`${r}${"_".repeat(i+1)}`)].join(" ")}return`${t}${e}`};
194887
<script> (function () { const darkStyles = document.querySelector('style[data-theme="dark"]')?.textContent const lightStyles = document.querySelector('style[data-theme="light"]')?.textContent const removeStyles = () => { document.querySelector('style[data-theme="dark"]')?.remove() document.querySelector('style[data-theme="light"]')?.remove() } removeStyles() setDarkClass = () => { removeStyles() const isDark = localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) isDark ? document.documentElement.classList.add('dark') : document.documentElement.classList.remove('dark') if (isDark) { document.head.insertAdjacentHTML('beforeend', `<style data-theme="dark">${darkStyles}</style>`) } else { document.head.insertAdjacentHTML('beforeend', `<style data-theme="light">${lightStyles}</style>`) } } setDarkClass() window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', setDarkClass) })(); </script> <div class="relative" x-data="{ menu: false, theme: localStorage.theme, darkMode() { this.theme = 'dark' localStorage.theme = 'dark' setDarkClass() }, lightMode() { this.theme = 'light' localStorage.theme = 'light' setDarkClass() }, systemMode() { this.theme = undefined localStorage.removeItem('theme') setDarkClass() }, }" @click.outside="menu = false" > <button x-cloak class="block rounded p-1 hover:bg-gray-100 dark:hover:bg-gray-800" :class="theme ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600 hover:text-gray-500 focus:text-gray-500 dark:hover:text-gray-500 dark:focus:text-gray-500'" @click="menu = ! menu" > <x-laravel-exceptions-renderer::icons.sun class="block h-5 w-5 dark:hidden" /> <x-laravel-exceptions-renderer::icons.moon class="hidden h-5 w-5 dark:block" /> </button> <div x-show="menu" class="absolute right-0 z-10 flex origin-top-right flex-col rounded-md bg-white shadow-xl ring-1 ring-gray-900/5 dark:bg-gray-800" style="display: none" @click="menu = false" > <button class="flex items-center gap-3 px-4 py-2 hover:rounded-t-md hover:bg-gray-100 dark:hover:bg-gray-700" :class="theme === 'light' ? 'text-gray-900 dark:text-gray-100' : 'text-gray-500 dark:text-gray-400'" @click="lightMode()" > <x-laravel-exceptions-renderer::icons.sun class="h-5 w-5" /> Light </button> <button class="flex items-center gap-3 px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-700" :class="theme === 'dark' ? 'text-gray-900 dark:text-gray-100' : 'text-gray-500 dark:text-gray-400'" @click="darkMode()" > <x-laravel-exceptions-renderer::icons.moon class="h-5 w-5" /> Dark </button> <button class="flex items-center gap-3 px-4 py-2 hover:rounded-b-md hover:bg-gray-100 dark:hover:bg-gray-700" :class="theme === undefined ? 'text-gray-900 dark:text-gray-100' : 'text-gray-500 dark:text-gray-400'" @click="systemMode()" > <x-laravel-exceptions-renderer::icons.computer-desktop class="h-5 w-5" /> System </button> </div> </div>
194888
<div class="hidden overflow-x-auto sm:col-span-1 lg:block"> <div class="h-[35.5rem] scrollbar-hidden trace text-sm text-gray-400 dark:text-gray-300" > <div class="mb-2 inline-block rounded-full bg-red-500/20 px-3 py-2 dark:bg-red-500/20 sm:col-span-1"> <button @click="includeVendorFrames = !includeVendorFrames" class="inline-flex items-center font-bold leading-5 text-red-500" > <span x-show="includeVendorFrames">Collapse</span> <span x-cloak x-show="!includeVendorFrames" >Expand</span > <span class="ml-1">vendor frames</span> <div class="flex flex-col ml-1 -mt-2" x-cloak x-show="includeVendorFrames"> <x-laravel-exceptions-renderer::icons.chevron-down /> <x-laravel-exceptions-renderer::icons.chevron-up /> </div> <div class="flex flex-col ml-1 -mt-2" x-cloak x-show="! includeVendorFrames"> <x-laravel-exceptions-renderer::icons.chevron-up /> <x-laravel-exceptions-renderer::icons.chevron-down /> </div> </button> </div> <div class="mb-12 space-y-2"> @foreach ($exception->frames() as $frame) @if (! $frame->isFromVendor()) @php $vendorFramesCollapsed = $exception->frames()->take($loop->index)->reverse()->takeUntil(fn ($frame) => ! $frame->isFromVendor()); @endphp <div x-show="! includeVendorFrames"> @if ($vendorFramesCollapsed->isNotEmpty()) <div class="text-gray-500"> {{ $vendorFramesCollapsed->count() }} vendor frame{{ $vendorFramesCollapsed->count() > 1 ? 's' : '' }} collapsed </div> @endif </div> @endif <button class="w-full text-left dark:border-gray-900" x-show="{{ $frame->isFromVendor() ? 'includeVendorFrames' : 'true' }}" @click="index = {{ $loop->index }}" > <div x-bind:class=" index === {{ $loop->index }} ? 'rounded-r-md bg-gray-100 dark:bg-gray-800 border-l dark:border dark:border-gray-700 border-l-red-500 dark:border-l-red-500' : 'hover:bg-gray-100/75 dark:hover:bg-gray-800/75' " > <div class="scrollbar-hidden overflow-x-auto border-l-2 border-transparent p-2"> <div class="nowrap text-gray-900 dark:text-gray-300"> <span class="inline-flex items-baseline"> <span class="text-gray-900 dark:text-gray-300">{{ $frame->source() }}</span> <span class="font-mono text-xs">:{{ $frame->line() }}</span> </span> </div> <div class="text-gray-500 dark:text-gray-400"> {{ $exception->frames()->get($loop->index + 1)?->callable() }} </div> </div> </div> </button> @if (! $frame->isFromVendor() && $exception->frames()->slice($loop->index + 1)->filter(fn ($frame) => ! $frame->isFromVendor())->isEmpty()) @if ($exception->frames()->slice($loop->index + 1)->count()) <div x-show="! includeVendorFrames"> <div class="text-gray-500"> {{ $exception->frames()->slice($loop->index + 1)->count() }} vendor frame{{ $exception->frames()->slice($loop->index + 1)->count() > 1 ? 's' : '' }} collapsed </div> </div> @endif @endif @endforeach </div> </div> </div>
194904
protected function renderViaCallbacks($request, Throwable $e) { foreach ($this->renderCallbacks as $renderCallback) { foreach ($this->firstClosureParameterTypes($renderCallback) as $type) { if (is_a($e, $type)) { $response = $renderCallback($e, $request); if (! is_null($response)) { return $response; } } } } } /** * Render a default exception response if any. * * @param \Illuminate\Http\Request $request * @param \Throwable $e * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse */ protected function renderExceptionResponse($request, Throwable $e) { return $this->shouldReturnJson($request, $e) ? $this->prepareJsonResponse($request, $e) : $this->prepareResponse($request, $e); } /** * Convert an authentication exception into a response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse */ protected function unauthenticated($request, AuthenticationException $exception) { return $this->shouldReturnJson($request, $exception) ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest($exception->redirectTo($request) ?? route('login')); } /** * Create a response object from the given validation exception. * * @param \Illuminate\Validation\ValidationException $e * @param \Illuminate\Http\Request $request * @return \Symfony\Component\HttpFoundation\Response */ protected function convertValidationExceptionToResponse(ValidationException $e, $request) { if ($e->response) { return $e->response; } return $this->shouldReturnJson($request, $e) ? $this->invalidJson($request, $e) : $this->invalid($request, $e); } /** * Convert a validation exception into a response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Validation\ValidationException $exception * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse */ protected function invalid($request, ValidationException $exception) { return redirect($exception->redirectTo ?? url()->previous()) ->withInput(Arr::except($request->input(), $this->dontFlash)) ->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag)); } /** * Convert a validation exception into a JSON response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Validation\ValidationException $exception * @return \Illuminate\Http\JsonResponse */ protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'message' => $exception->getMessage(), 'errors' => $exception->errors(), ], $exception->status); } /** * Determine if the exception handler response should be JSON. * * @param \Illuminate\Http\Request $request * @param \Throwable $e * @return bool */ protected function shouldReturnJson($request, Throwable $e) { return $this->shouldRenderJsonWhenCallback ? call_user_func($this->shouldRenderJsonWhenCallback, $request, $e) : $request->expectsJson(); } /** * Register the callable that determines if the exception handler response should be JSON. * * @param callable(\Illuminate\Http\Request $request, \Throwable): bool $callback * @return $this */ public function shouldRenderJsonWhen($callback) { $this->shouldRenderJsonWhenCallback = $callback; return $this; } /** * Prepare a response for the given exception. * * @param \Illuminate\Http\Request $request * @param \Throwable $e * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse */ protected function prepareResponse($request, Throwable $e) { if (! $this->isHttpException($e) && config('app.debug')) { return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e)->prepare($request); } if (! $this->isHttpException($e)) { $e = new HttpException(500, $e->getMessage(), $e); } return $this->toIlluminateResponse( $this->renderHttpException($e), $e )->prepare($request); } /** * Create a Symfony response for the given exception. * * @param \Throwable $e * @return \Symfony\Component\HttpFoundation\Response */ protected function convertExceptionToResponse(Throwable $e) { return new SymfonyResponse( $this->renderExceptionContent($e), $this->isHttpException($e) ? $e->getStatusCode() : 500, $this->isHttpException($e) ? $e->getHeaders() : [] ); } /** * Get the response content for the given exception. * * @param \Throwable $e * @return string */ protected function renderExceptionContent(Throwable $e) { try { if (config('app.debug')) { if (app()->has(ExceptionRenderer::class)) { return $this->renderExceptionWithCustomRenderer($e); } elseif ($this->container->bound(Renderer::class)) { return $this->container->make(Renderer::class)->render(request(), $e); } } return $this->renderExceptionWithSymfony($e, config('app.debug')); } catch (Throwable $e) { return $this->renderExceptionWithSymfony($e, config('app.debug')); } } /** * Render an exception to a string using the registered `ExceptionRenderer`. * * @param \Throwable $e * @return string */ protected function renderExceptionWithCustomRenderer(Throwable $e) { return app(ExceptionRenderer::class)->render($e); } /** * Render an exception to a string using Symfony. * * @param \Throwable $e * @param bool $debug * @return string */ protected function renderExceptionWithSymfony(Throwable $e, $debug) { $renderer = new HtmlErrorRenderer($debug); return $renderer->render($e)->getAsString(); } /** * Render the given HttpException. * * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e * @return \Symfony\Component\HttpFoundation\Response */ protected function renderHttpException(HttpExceptionInterface $e) { $this->registerErrorViewPaths(); if ($view = $this->getHttpExceptionView($e)) { try { return response()->view($view, [ 'errors' => new ViewErrorBag, 'exception' => $e, ], $e->getStatusCode(), $e->getHeaders()); } catch (Throwable $t) { config('app.debug') && throw $t; $this->report($t); } } return $this->convertExceptionToResponse($e); } /** * Register the error template hint paths. * * @return void */ protected function registerErrorViewPaths() { (new RegisterErrorViewPaths)(); } /** * Get the view used to render HTTP exceptions. * * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e * @return string|null */ protected function getHttpExceptionView(HttpExceptionInterface $e) { $view = 'errors::'.$e->getStatusCode(); if (view()->exists($view)) { return $view; } $view = substr($view, 0, -2).'xx'; if (view()->exists($view)) { return $view; } return null; } /** * Map the given exception into an Illuminate response. * * @param \Symfony\Component\HttpFoundation\Response $response * @param \Throwable $e * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */
194917
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@yield('title')</title> <style> /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}code{font-family:monospace,monospace;font-size:1em}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}code{font-family:Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-gray-400{--border-opacity:1;border-color:#cbd5e0;border-color:rgba(203,213,224,var(--border-opacity))}.border-t{border-top-width:1px}.border-r{border-right-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-xl{max-width:36rem}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.uppercase{text-transform:uppercase}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.tracking-wider{letter-spacing:.05em}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@-webkit-keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@-webkit-keyframes ping{0%{transform:scale(1);opacity:1}75%,to{transform:scale(2);opacity:0}}@keyframes ping{0%{transform:scale(1);opacity:1}75%,to{transform:scale(2);opacity:0}}@-webkit-keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}@-webkit-keyframes bounce{0%,to{transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(.8,0,1,1);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:translateY(0);-webkit-animation-timing-function:cubic-bezier(0,0,.2,1);animation-timing-function:cubic-bezier(0,0,.2,1)}}@keyframes bounce{0%,to{transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(.8,0,1,1);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:translateY(0);-webkit-animation-timing-function:cubic-bezier(0,0,.2,1);animation-timing-function:cubic-bezier(0,0,.2,1)}}@media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}@media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}} </style>
194933
<?php namespace Illuminate\Foundation\Testing; use Illuminate\Contracts\Console\Kernel; use Illuminate\Foundation\Application; use PHPUnit\Framework\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use Concerns\InteractsWithContainer, Concerns\MakesHttpRequests, Concerns\InteractsWithAuthentication, Concerns\InteractsWithConsole, Concerns\InteractsWithDatabase, Concerns\InteractsWithDeprecationHandling, Concerns\InteractsWithExceptionHandling, Concerns\InteractsWithSession, Concerns\InteractsWithTime, Concerns\InteractsWithTestCaseLifecycle, Concerns\InteractsWithViews; /** * Creates the application. * * @return \Illuminate\Foundation\Application */ public function createApplication() { $app = require Application::inferBasePath().'/bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); return $app; } /** * Setup the test environment. * * @return void */ protected function setUp(): void { $this->setUpTheTestEnvironment(); } /** * Refresh the application instance. * * @return void */ protected function refreshApplication() { $this->app = $this->createApplication(); } /** * Clean up the testing environment before the next test. * * @return void * * @throws \Mockery\Exception\InvalidCountException */ protected function tearDown(): void { $this->tearDownTheTestEnvironment(); } /** * Clean up the testing environment before the next test case. * * @return void */ public static function tearDownAfterClass(): void { static::tearDownAfterClassUsingTestCase(); } }
194947
trait MakesHttpRequests { /** * Additional headers for the request. * * @var array */ protected $defaultHeaders = []; /** * Additional cookies for the request. * * @var array */ protected $defaultCookies = []; /** * Additional cookies will not be encrypted for the request. * * @var array */ protected $unencryptedCookies = []; /** * Additional server variables for the request. * * @var array */ protected $serverVariables = []; /** * Indicates whether redirects should be followed. * * @var bool */ protected $followRedirects = false; /** * Indicates whether cookies should be encrypted. * * @var bool */ protected $encryptCookies = true; /** * Indicated whether JSON requests should be performed "with credentials" (cookies). * * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials * * @var bool */ protected $withCredentials = false; /** * Define additional headers to be sent with the request. * * @param array $headers * @return $this */ public function withHeaders(array $headers) { $this->defaultHeaders = array_merge($this->defaultHeaders, $headers); return $this; } /** * Add a header to be sent with the request. * * @param string $name * @param string $value * @return $this */ public function withHeader(string $name, string $value) { $this->defaultHeaders[$name] = $value; return $this; } /** * Remove a header from the request. * * @param string $name * @return $this */ public function withoutHeader(string $name) { unset($this->defaultHeaders[$name]); return $this; } /** * Remove headers from the request. * * @param array $headers * @return $this */ public function withoutHeaders(array $headers) { foreach ($headers as $name) { $this->withoutHeader($name); } return $this; } /** * Add an authorization token for the request. * * @param string $token * @param string $type * @return $this */ public function withToken(string $token, string $type = 'Bearer') { return $this->withHeader('Authorization', $type.' '.$token); } /** * Add a basic authentication header to the request with the given credentials. * * @param string $username * @param string $password * @return $this */ public function withBasicAuth(string $username, string $password) { return $this->withToken(base64_encode("$username:$password"), 'Basic'); } /** * Remove the authorization token from the request. * * @return $this */ public function withoutToken() { return $this->withoutHeader('Authorization'); } /** * Flush all the configured headers. * * @return $this */ public function flushHeaders() { $this->defaultHeaders = []; return $this; } /** * Define a set of server variables to be sent with the requests. * * @param array $server * @return $this */ public function withServerVariables(array $server) { $this->serverVariables = $server; return $this; } /** * Disable middleware for the test. * * @param string|array|null $middleware * @return $this */ public function withoutMiddleware($middleware = null) { if (is_null($middleware)) { $this->app->instance('middleware.disable', true); return $this; } foreach ((array) $middleware as $abstract) { $this->app->instance($abstract, new class { public function handle($request, $next) { return $next($request); } }); } return $this; } /** * Enable the given middleware for the test. * * @param string|array|null $middleware * @return $this */ public function withMiddleware($middleware = null) { if (is_null($middleware)) { unset($this->app['middleware.disable']); return $this; } foreach ((array) $middleware as $abstract) { unset($this->app[$abstract]); } return $this; } /** * Define additional cookies to be sent with the request. * * @param array $cookies * @return $this */ public function withCookies(array $cookies) { $this->defaultCookies = array_merge($this->defaultCookies, $cookies); return $this; } /** * Add a cookie to be sent with the request. * * @param string $name * @param string $value * @return $this */ public function withCookie(string $name, string $value) { $this->defaultCookies[$name] = $value; return $this; } /** * Define additional cookies will not be encrypted before sending with the request. * * @param array $cookies * @return $this */ public function withUnencryptedCookies(array $cookies) { $this->unencryptedCookies = array_merge($this->unencryptedCookies, $cookies); return $this; } /** * Add a cookie will not be encrypted before sending with the request. * * @param string $name * @param string $value * @return $this */ public function withUnencryptedCookie(string $name, string $value) { $this->unencryptedCookies[$name] = $value; return $this; } /** * Automatically follow any redirects returned from the response. * * @return $this */ public function followingRedirects() { $this->followRedirects = true; return $this; } /** * Include cookies and authorization headers for JSON requests. * * @return $this */ public function withCredentials() { $this->withCredentials = true; return $this; } /** * Disable automatic encryption of cookie values. * * @return $this */ public function disableCookieEncryption() { $this->encryptCookies = false; return $this; } /** * Set the referer header and previous URL session value from a given URL in order to simulate a previous request. * * @param string $url * @return $this */ public function from(string $url) { $this->app['session']->setPreviousUrl($url); return $this->withHeader('referer', $url); } /** * Set the referer header and previous URL session value from a given route in order to simulate a previous request. * * @param string $name * @param mixed $parameters * @return $this */ public function fromRoute(string $name, $parameters = []) { return $this->from($this->app['url']->route($name, $parameters)); } /** * Set the Precognition header to "true". * * @return $this */ public function withPrecognition() { return $this->withHeader('Precognition', 'true'); } /** * Visit the given URI with a GET request. * * @param string $uri * @param array $headers * @return \Illuminate\Testing\TestResponse */ public function get($uri, array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $cookies = $this->prepareCookiesForRequest(); return $this->call('GET', $uri, [], $cookies, [], $server); } /** * Visit the given URI with a GET request, expecting a JSON response. * * @param string $uri * @param array $headers * @param int $options * @return \Illuminate\Testing\TestResponse */
194948
public function getJson($uri, array $headers = [], $options = 0) { return $this->json('GET', $uri, [], $headers, $options); } /** * Visit the given URI with a POST request. * * @param string $uri * @param array $data * @param array $headers * @return \Illuminate\Testing\TestResponse */ public function post($uri, array $data = [], array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $cookies = $this->prepareCookiesForRequest(); return $this->call('POST', $uri, $data, $cookies, [], $server); } /** * Visit the given URI with a POST request, expecting a JSON response. * * @param string $uri * @param array $data * @param array $headers * @param int $options * @return \Illuminate\Testing\TestResponse */ public function postJson($uri, array $data = [], array $headers = [], $options = 0) { return $this->json('POST', $uri, $data, $headers, $options); } /** * Visit the given URI with a PUT request. * * @param string $uri * @param array $data * @param array $headers * @return \Illuminate\Testing\TestResponse */ public function put($uri, array $data = [], array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $cookies = $this->prepareCookiesForRequest(); return $this->call('PUT', $uri, $data, $cookies, [], $server); } /** * Visit the given URI with a PUT request, expecting a JSON response. * * @param string $uri * @param array $data * @param array $headers * @param int $options * @return \Illuminate\Testing\TestResponse */ public function putJson($uri, array $data = [], array $headers = [], $options = 0) { return $this->json('PUT', $uri, $data, $headers, $options); } /** * Visit the given URI with a PATCH request. * * @param string $uri * @param array $data * @param array $headers * @return \Illuminate\Testing\TestResponse */ public function patch($uri, array $data = [], array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $cookies = $this->prepareCookiesForRequest(); return $this->call('PATCH', $uri, $data, $cookies, [], $server); } /** * Visit the given URI with a PATCH request, expecting a JSON response. * * @param string $uri * @param array $data * @param array $headers * @param int $options * @return \Illuminate\Testing\TestResponse */ public function patchJson($uri, array $data = [], array $headers = [], $options = 0) { return $this->json('PATCH', $uri, $data, $headers, $options); } /** * Visit the given URI with a DELETE request. * * @param string $uri * @param array $data * @param array $headers * @return \Illuminate\Testing\TestResponse */ public function delete($uri, array $data = [], array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $cookies = $this->prepareCookiesForRequest(); return $this->call('DELETE', $uri, $data, $cookies, [], $server); } /** * Visit the given URI with a DELETE request, expecting a JSON response. * * @param string $uri * @param array $data * @param array $headers * @param int $options * @return \Illuminate\Testing\TestResponse */ public function deleteJson($uri, array $data = [], array $headers = [], $options = 0) { return $this->json('DELETE', $uri, $data, $headers, $options); } /** * Visit the given URI with an OPTIONS request. * * @param string $uri * @param array $data * @param array $headers * @return \Illuminate\Testing\TestResponse */ public function options($uri, array $data = [], array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $cookies = $this->prepareCookiesForRequest(); return $this->call('OPTIONS', $uri, $data, $cookies, [], $server); } /** * Visit the given URI with an OPTIONS request, expecting a JSON response. * * @param string $uri * @param array $data * @param array $headers * @param int $options * @return \Illuminate\Testing\TestResponse */ public function optionsJson($uri, array $data = [], array $headers = [], $options = 0) { return $this->json('OPTIONS', $uri, $data, $headers, $options); } /** * Visit the given URI with a HEAD request. * * @param string $uri * @param array $headers * @return \Illuminate\Testing\TestResponse */ public function head($uri, array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $cookies = $this->prepareCookiesForRequest(); return $this->call('HEAD', $uri, [], $cookies, [], $server); } /** * Call the given URI with a JSON request. * * @param string $method * @param string $uri * @param array $data * @param array $headers * @param int $options * @return \Illuminate\Testing\TestResponse */ public function json($method, $uri, array $data = [], array $headers = [], $options = 0) { $files = $this->extractFilesFromDataArray($data); $content = json_encode($data, $options); $headers = array_merge([ 'CONTENT_LENGTH' => mb_strlen($content, '8bit'), 'CONTENT_TYPE' => 'application/json', 'Accept' => 'application/json', ], $headers); return $this->call( $method, $uri, [], $this->prepareCookiesForJsonRequest(), $files, $this->transformHeadersToServerVars($headers), $content ); } /** * Call the given URI and return the Response. * * @param string $method * @param string $uri * @param array $parameters * @param array $cookies * @param array $files * @param array $server * @param string|null $content * @return \Illuminate\Testing\TestResponse */ public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null) { $kernel = $this->app->make(HttpKernel::class); $files = array_merge($files, $this->extractFilesFromDataArray($parameters)); $symfonyRequest = SymfonyRequest::create( $this->prepareUrlForRequest($uri), $method, $parameters, $cookies, $files, array_replace($this->serverVariables, $server), $content ); $response = $kernel->handle( $request = $this->createTestRequest($symfonyRequest) ); $kernel->terminate($request, $response); if ($this->followRedirects) { $response = $this->followRedirects($response); } return $this->createTestResponse($response, $request); } /** * Turn the given URI into a fully qualified URL. * * @param string $uri * @return string */
194961
<?php namespace Illuminate\Foundation\Http; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\Response; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Validation\Factory as ValidationFactory; use Illuminate\Contracts\Validation\ValidatesWhenResolved; use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\Validation\ValidatesWhenResolvedTrait; class FormRequest extends Request implements ValidatesWhenResolved { use ValidatesWhenResolvedTrait; /** * The container instance. * * @var \Illuminate\Contracts\Container\Container */ protected $container; /** * The redirector instance. * * @var \Illuminate\Routing\Redirector */ protected $redirector; /** * The URI to redirect to if validation fails. * * @var string */ protected $redirect; /** * The route to redirect to if validation fails. * * @var string */ protected $redirectRoute; /** * The controller action to redirect to if validation fails. * * @var string */ protected $redirectAction; /** * The key to be used for the view error bag. * * @var string */ protected $errorBag = 'default'; /** * Indicates whether validation should stop after the first rule failure. * * @var bool */ protected $stopOnFirstFailure = false; /** * The validator instance. * * @var \Illuminate\Contracts\Validation\Validator */ protected $validator; /** * Get the validator instance for the request. * * @return \Illuminate\Contracts\Validation\Validator */ protected function getValidatorInstance() { if ($this->validator) { return $this->validator; } $factory = $this->container->make(ValidationFactory::class); if (method_exists($this, 'validator')) { $validator = $this->container->call([$this, 'validator'], compact('factory')); } else { $validator = $this->createDefaultValidator($factory); } if (method_exists($this, 'withValidator')) { $this->withValidator($validator); } if (method_exists($this, 'after')) { $validator->after($this->container->call( $this->after(...), ['validator' => $validator] )); } $this->setValidator($validator); return $this->validator; } /** * Create the default validator instance. * * @param \Illuminate\Contracts\Validation\Factory $factory * @return \Illuminate\Contracts\Validation\Validator */ protected function createDefaultValidator(ValidationFactory $factory) { $rules = $this->validationRules(); $validator = $factory->make( $this->validationData(), $rules, $this->messages(), $this->attributes(), )->stopOnFirstFailure($this->stopOnFirstFailure); if ($this->isPrecognitive()) { $validator->setRules( $this->filterPrecognitiveRules($validator->getRulesWithoutPlaceholders()) ); } return $validator; } /** * Get data to be validated from the request. * * @return array */ public function validationData() { return $this->all(); } /** * Get the validation rules for this form request. * * @return array */ protected function validationRules() { return method_exists($this, 'rules') ? $this->container->call([$this, 'rules']) : []; } /** * Handle a failed validation attempt. * * @param \Illuminate\Contracts\Validation\Validator $validator * @return void * * @throws \Illuminate\Validation\ValidationException */ protected function failedValidation(Validator $validator) { $exception = $validator->getException(); throw (new $exception($validator)) ->errorBag($this->errorBag) ->redirectTo($this->getRedirectUrl()); } /** * Get the URL to redirect to on a validation error. * * @return string */ protected function getRedirectUrl() { $url = $this->redirector->getUrlGenerator(); if ($this->redirect) { return $url->to($this->redirect); } elseif ($this->redirectRoute) { return $url->route($this->redirectRoute); } elseif ($this->redirectAction) { return $url->action($this->redirectAction); } return $url->previous(); } /** * Determine if the request passes the authorization check. * * @return bool * * @throws \Illuminate\Auth\Access\AuthorizationException */ protected function passesAuthorization() { if (method_exists($this, 'authorize')) { $result = $this->container->call([$this, 'authorize']); return $result instanceof Response ? $result->authorize() : $result; } return true; } /** * Handle a failed authorization attempt. * * @return void * * @throws \Illuminate\Auth\Access\AuthorizationException */ protected function failedAuthorization() { throw new AuthorizationException; } /** * Get a validated input container for the validated input. * * @param array|null $keys * @return \Illuminate\Support\ValidatedInput|array */ public function safe(?array $keys = null) { return is_array($keys) ? $this->validator->safe()->only($keys) : $this->validator->safe(); } /** * Get the validated data from the request. * * @param array|int|string|null $key * @param mixed $default * @return mixed */ public function validated($key = null, $default = null) { return data_get($this->validator->validated(), $key, $default); } /** * Get custom messages for validator errors. * * @return array */ public function messages() { return []; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return []; } /** * Set the Validator instance. * * @param \Illuminate\Contracts\Validation\Validator $validator * @return $this */ public function setValidator(Validator $validator) { $this->validator = $validator; return $this; } /** * Set the Redirector instance. * * @param \Illuminate\Routing\Redirector $redirector * @return $this */ public function setRedirector(Redirector $redirector) { $this->redirector = $redirector; return $this; } /** * Set the container implementation. * * @param \Illuminate\Contracts\Container\Container $container * @return $this */ public function setContainer(Container $container) { $this->container = $container; return $this; } }
194965
class Kernel implements KernelContract { use InteractsWithTime; /** * The application implementation. * * @var \Illuminate\Contracts\Foundation\Application */ protected $app; /** * The router instance. * * @var \Illuminate\Routing\Router */ protected $router; /** * The bootstrap classes for the application. * * @var string[] */ protected $bootstrappers = [ \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class, \Illuminate\Foundation\Bootstrap\LoadConfiguration::class, \Illuminate\Foundation\Bootstrap\HandleExceptions::class, \Illuminate\Foundation\Bootstrap\RegisterFacades::class, \Illuminate\Foundation\Bootstrap\RegisterProviders::class, \Illuminate\Foundation\Bootstrap\BootProviders::class, ]; /** * The application's middleware stack. * * @var array<int, class-string|string> */ protected $middleware = []; /** * The application's route middleware groups. * * @var array<string, array<int, class-string|string>> */ protected $middlewareGroups = []; /** * The application's route middleware. * * @var array<string, class-string|string> * * @deprecated */ protected $routeMiddleware = []; /** * The application's middleware aliases. * * @var array<string, class-string|string> */ protected $middlewareAliases = []; /** * All of the registered request duration handlers. * * @var array */ protected $requestLifecycleDurationHandlers = []; /** * When the kernel starting handling the current request. * * @var \Illuminate\Support\Carbon|null */ protected $requestStartedAt; /** * The priority-sorted list of middleware. * * Forces non-global middleware to always be in the given order. * * @var string[] */ protected $middlewarePriority = [ \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class, \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class, \Illuminate\Routing\Middleware\ThrottleRequests::class, \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class, \Illuminate\Contracts\Session\Middleware\AuthenticatesSessions::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Auth\Middleware\Authorize::class, ]; /** * Create a new HTTP kernel instance. * * @param \Illuminate\Contracts\Foundation\Application $app * @param \Illuminate\Routing\Router $router * @return void */ public function __construct(Application $app, Router $router) { $this->app = $app; $this->router = $router; $this->syncMiddlewareToRouter(); } /** * Handle an incoming HTTP request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function handle($request) { $this->requestStartedAt = Carbon::now(); try { $request->enableHttpMethodParameterOverride(); $response = $this->sendRequestThroughRouter($request); } catch (Throwable $e) { $this->reportException($e); $response = $this->renderException($request, $e); } $this->app['events']->dispatch( new RequestHandled($request, $response) ); return $response; } /** * Send the given request through the middleware / router. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ protected function sendRequestThroughRouter($request) { $this->app->instance('request', $request); Facade::clearResolvedInstance('request'); $this->bootstrap(); return (new Pipeline($this->app)) ->send($request) ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware) ->then($this->dispatchToRouter()); } /** * Bootstrap the application for HTTP requests. * * @return void */ public function bootstrap() { if (! $this->app->hasBeenBootstrapped()) { $this->app->bootstrapWith($this->bootstrappers()); } } /** * Get the route dispatcher callback. * * @return \Closure */ protected function dispatchToRouter() { return function ($request) { $this->app->instance('request', $request); return $this->router->dispatch($request); }; } /** * Call the terminate method on any terminable middleware. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response $response * @return void */ public function terminate($request, $response) { $this->app['events']->dispatch(new Terminating); $this->terminateMiddleware($request, $response); $this->app->terminate(); if ($this->requestStartedAt === null) { return; } $this->requestStartedAt->setTimezone($this->app['config']->get('app.timezone') ?? 'UTC'); foreach ($this->requestLifecycleDurationHandlers as ['threshold' => $threshold, 'handler' => $handler]) { $end ??= Carbon::now(); if ($this->requestStartedAt->diffInMilliseconds($end) > $threshold) { $handler($this->requestStartedAt, $request, $response); } } $this->requestStartedAt = null; } /** * Call the terminate method on any terminable middleware. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response $response * @return void */ protected function terminateMiddleware($request, $response) { $middlewares = $this->app->shouldSkipMiddleware() ? [] : array_merge( $this->gatherRouteMiddleware($request), $this->middleware ); foreach ($middlewares as $middleware) { if (! is_string($middleware)) { continue; } [$name] = $this->parseMiddleware($middleware); $instance = $this->app->make($name); if (method_exists($instance, 'terminate')) { $instance->terminate($request, $response); } } } /** * Register a callback to be invoked when the requests lifecycle duration exceeds a given amount of time. * * @param \DateTimeInterface|\Carbon\CarbonInterval|float|int $threshold * @param callable $handler * @return void */ public function whenRequestLifecycleIsLongerThan($threshold, $handler) { $threshold = $threshold instanceof DateTimeInterface ? $this->secondsUntil($threshold) * 1000 : $threshold; $threshold = $threshold instanceof CarbonInterval ? $threshold->totalMilliseconds : $threshold; $this->requestLifecycleDurationHandlers[] = [ 'threshold' => $threshold, 'handler' => $handler, ]; } /** * When the request being handled started. * * @return \Illuminate\Support\Carbon|null */ public function requestStartedAt() { return $this->requestStartedAt; } /** * Gather the route middleware for the given request. * * @param \Illuminate\Http\Request $request * @return array */ protected function gatherRouteMiddleware($request) { if ($route = $request->route()) { return $this->router->gatherRouteMiddleware($route); } return []; } /** * Parse a middleware string to get the name and parameters. * * @param string $middleware * @return array */ protected function parseMiddleware($middleware) { [$name, $parameters] = array_pad(explode(':', $middleware, 2), 2, []); if (is_string($parameters)) { $parameters = explode(',', $parameters); } return [$name, $parameters]; } /** * Determine if the kernel has a given middleware. * * @param string $middleware * @return bool */ public function hasMiddleware($middleware) { return in_array($middleware, $this->middleware); } /** * Add a new middleware to the beginning of the stack if it does not already exist. * * @param string $middleware * @return $this */
194966
public function prependMiddleware($middleware) { if (array_search($middleware, $this->middleware) === false) { array_unshift($this->middleware, $middleware); } return $this; } /** * Add a new middleware to end of the stack if it does not already exist. * * @param string $middleware * @return $this */ public function pushMiddleware($middleware) { if (array_search($middleware, $this->middleware) === false) { $this->middleware[] = $middleware; } return $this; } /** * Prepend the given middleware to the given middleware group. * * @param string $group * @param string $middleware * @return $this * * @throws \InvalidArgumentException */ public function prependMiddlewareToGroup($group, $middleware) { if (! isset($this->middlewareGroups[$group])) { throw new InvalidArgumentException("The [{$group}] middleware group has not been defined."); } if (array_search($middleware, $this->middlewareGroups[$group]) === false) { array_unshift($this->middlewareGroups[$group], $middleware); } $this->syncMiddlewareToRouter(); return $this; } /** * Append the given middleware to the given middleware group. * * @param string $group * @param string $middleware * @return $this * * @throws \InvalidArgumentException */ public function appendMiddlewareToGroup($group, $middleware) { if (! isset($this->middlewareGroups[$group])) { throw new InvalidArgumentException("The [{$group}] middleware group has not been defined."); } if (array_search($middleware, $this->middlewareGroups[$group]) === false) { $this->middlewareGroups[$group][] = $middleware; } $this->syncMiddlewareToRouter(); return $this; } /** * Prepend the given middleware to the middleware priority list. * * @param string $middleware * @return $this */ public function prependToMiddlewarePriority($middleware) { if (! in_array($middleware, $this->middlewarePriority)) { array_unshift($this->middlewarePriority, $middleware); } $this->syncMiddlewareToRouter(); return $this; } /** * Append the given middleware to the middleware priority list. * * @param string $middleware * @return $this */ public function appendToMiddlewarePriority($middleware) { if (! in_array($middleware, $this->middlewarePriority)) { $this->middlewarePriority[] = $middleware; } $this->syncMiddlewareToRouter(); return $this; } /** * Add the given middleware to the middleware priority list before other middleware. * * @param array|string $before * @param string $middleware * @return $this */ public function addToMiddlewarePriorityBefore($before, $middleware) { return $this->addToMiddlewarePriorityRelative($before, $middleware, after: false); } /** * Add the given middleware to the middleware priority list after other middleware. * * @param array|string $after * @param string $middleware * @return $this */ public function addToMiddlewarePriorityAfter($after, $middleware) { return $this->addToMiddlewarePriorityRelative($after, $middleware); } /** * Add the given middleware to the middleware priority list relative to other middleware. * * @param string|array $existing * @param string $middleware * @param bool $after * @return $this */ protected function addToMiddlewarePriorityRelative($existing, $middleware, $after = true) { if (! in_array($middleware, $this->middlewarePriority)) { $index = $after ? 0 : count($this->middlewarePriority); foreach ((array) $existing as $existingMiddleware) { if (in_array($existingMiddleware, $this->middlewarePriority)) { $middlewareIndex = array_search($existingMiddleware, $this->middlewarePriority); if ($after && $middlewareIndex > $index) { $index = $middlewareIndex + 1; } elseif ($after === false && $middlewareIndex < $index) { $index = $middlewareIndex; } } } if ($index === 0 && $after === false) { array_unshift($this->middlewarePriority, $middleware); } elseif (($after && $index === 0) || $index === count($this->middlewarePriority)) { $this->middlewarePriority[] = $middleware; } else { array_splice($this->middlewarePriority, $index, 0, $middleware); } } $this->syncMiddlewareToRouter(); return $this; } /** * Sync the current state of the middleware to the router. * * @return void */ protected function syncMiddlewareToRouter() { $this->router->middlewarePriority = $this->middlewarePriority; foreach ($this->middlewareGroups as $key => $middleware) { $this->router->middlewareGroup($key, $middleware); } foreach (array_merge($this->routeMiddleware, $this->middlewareAliases) as $key => $middleware) { $this->router->aliasMiddleware($key, $middleware); } } /** * Get the priority-sorted list of middleware. * * @return array */ public function getMiddlewarePriority() { return $this->middlewarePriority; } /** * Get the bootstrap classes for the application. * * @return array */ protected function bootstrappers() { return $this->bootstrappers; } /** * Report the exception to the exception handler. * * @param \Throwable $e * @return void */ protected function reportException(Throwable $e) { $this->app[ExceptionHandler::class]->report($e); } /** * Render the exception to a response. * * @param \Illuminate\Http\Request $request * @param \Throwable $e * @return \Symfony\Component\HttpFoundation\Response */ protected function renderException($request, Throwable $e) { return $this->app[ExceptionHandler::class]->render($request, $e); } /** * Get the application's global middleware. * * @return array */ public function getGlobalMiddleware() { return $this->middleware; } /** * Set the application's global middleware. * * @param array $middleware * @return $this */ public function setGlobalMiddleware(array $middleware) { $this->middleware = $middleware; $this->syncMiddlewareToRouter(); return $this; } /** * Get the application's route middleware groups. * * @return array */ public function getMiddlewareGroups() { return $this->middlewareGroups; } /** * Set the application's middleware groups. * * @param array $groups * @return $this */ public function setMiddlewareGroups(array $groups) { $this->middlewareGroups = $groups; $this->syncMiddlewareToRouter(); return $this; } /** * Get the application's route middleware aliases. * * @return array * * @deprecated */ public function getRouteMiddleware() { return $this->getMiddlewareAliases(); } /** * Get the application's route middleware aliases. * * @return array */ public function getMiddlewareAliases() { return array_merge($this->routeMiddleware, $this->middlewareAliases); } /** * Set the application's route middleware aliases. * * @param array $aliases * @return $this */ public function setMiddlewareAliases(array $aliases) { $this->middlewareAliases = $aliases; $this->syncMiddlewareToRouter(); return $this; } /** * Set the application's middleware priority. * * @param array $priority * @return $this */ public function setMiddlewarePriority(array $priority) { $this->middlewarePriority = $priority; $this->syncMiddlewareToRouter(); return $this; } /** * Get the Laravel application instance. * * @return \Illuminate\Contracts\Foundation\Application */ public function getApplication() { return $this->app; }
194970
<?php namespace Illuminate\Foundation\Http\Middleware; use Closure; use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Support\Responsable; use Illuminate\Cookie\CookieValuePrefix; use Illuminate\Cookie\Middleware\EncryptCookies; use Illuminate\Foundation\Http\Middleware\Concerns\ExcludesPaths; use Illuminate\Session\TokenMismatchException; use Illuminate\Support\Arr; use Illuminate\Support\InteractsWithTime; use Symfony\Component\HttpFoundation\Cookie; class VerifyCsrfToken { use InteractsWithTime, ExcludesPaths; /** * The application instance. * * @var \Illuminate\Contracts\Foundation\Application */ protected $app; /** * The encrypter implementation. * * @var \Illuminate\Contracts\Encryption\Encrypter */ protected $encrypter; /** * The URIs that should be excluded. * * @var array<int, string> */ protected $except = []; /** * The globally ignored URIs that should be excluded from CSRF verification. * * @var array */ protected static $neverVerify = []; /** * Indicates whether the XSRF-TOKEN cookie should be set on the response. * * @var bool */ protected $addHttpCookie = true; /** * Create a new middleware instance. * * @param \Illuminate\Contracts\Foundation\Application $app * @param \Illuminate\Contracts\Encryption\Encrypter $encrypter * @return void */ public function __construct(Application $app, Encrypter $encrypter) { $this->app = $app; $this->encrypter = $encrypter; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed * * @throws \Illuminate\Session\TokenMismatchException */ public function handle($request, Closure $next) { if ( $this->isReading($request) || $this->runningUnitTests() || $this->inExceptArray($request) || $this->tokensMatch($request) ) { return tap($next($request), function ($response) use ($request) { if ($this->shouldAddXsrfTokenCookie()) { $this->addCookieToResponse($request, $response); } }); } throw new TokenMismatchException('CSRF token mismatch.'); } /** * Determine if the HTTP request uses a ‘read’ verb. * * @param \Illuminate\Http\Request $request * @return bool */ protected function isReading($request) { return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']); } /** * Determine if the application is running unit tests. * * @return bool */ protected function runningUnitTests() { return $this->app->runningInConsole() && $this->app->runningUnitTests(); } /** * Get the URIs that should be excluded. * * @return array */ public function getExcludedPaths() { return array_merge($this->except, static::$neverVerify); } /** * Determine if the session and input CSRF tokens match. * * @param \Illuminate\Http\Request $request * @return bool */ protected function tokensMatch($request) { $token = $this->getTokenFromRequest($request); return is_string($request->session()->token()) && is_string($token) && hash_equals($request->session()->token(), $token); } /** * Get the CSRF token from the request. * * @param \Illuminate\Http\Request $request * @return string|null */ protected function getTokenFromRequest($request) { $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN'); if (! $token && $header = $request->header('X-XSRF-TOKEN')) { try { $token = CookieValuePrefix::remove($this->encrypter->decrypt($header, static::serialized())); } catch (DecryptException) { $token = ''; } } return $token; } /** * Determine if the cookie should be added to the response. * * @return bool */ public function shouldAddXsrfTokenCookie() { return $this->addHttpCookie; } /** * Add the CSRF token to the response cookies. * * @param \Illuminate\Http\Request $request * @param \Symfony\Component\HttpFoundation\Response $response * @return \Symfony\Component\HttpFoundation\Response */ protected function addCookieToResponse($request, $response) { $config = config('session'); if ($response instanceof Responsable) { $response = $response->toResponse($request); } $response->headers->setCookie($this->newCookie($request, $config)); return $response; } /** * Create a new "XSRF-TOKEN" cookie that contains the CSRF token. * * @param \Illuminate\Http\Request $request * @param array $config * @return \Symfony\Component\HttpFoundation\Cookie */ protected function newCookie($request, $config) { return new Cookie( 'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']), $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null, $config['partitioned'] ?? false ); } /** * Indicate that the given URIs should be excluded from CSRF verification. * * @param array|string $uris * @return void */ public static function except($uris) { static::$neverVerify = array_values(array_unique( array_merge(static::$neverVerify, Arr::wrap($uris)) )); } /** * Determine if the cookie contents should be serialized. * * @return bool */ public static function serialized() { return EncryptCookies::serialized('XSRF-TOKEN'); } /** * Flush the state of the middleware. * * @return void */ public static function flushState() { static::$neverVerify = []; } }
194986
<?php namespace Illuminate\Foundation\Events; class LocaleUpdated { /** * The new locale. * * @var string */ public $locale; /** * Create a new event instance. * * @param string $locale * @return void */ public function __construct($locale) { $this->locale = $locale; } }
195004
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\GeneratorCommand; use Illuminate\Support\ServiceProvider; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputOption; #[AsCommand(name: 'make:provider')] class ProviderMakeCommand extends GeneratorCommand { /** * The console command name. * * @var string */ protected $name = 'make:provider'; /** * The console command description. * * @var string */ protected $description = 'Create a new service provider class'; /** * The type of class being generated. * * @var string */ protected $type = 'Provider'; /** * Execute the console command. * * @return bool|null * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function handle() { $result = parent::handle(); if ($result === false) { return $result; } ServiceProvider::addProviderToBootstrapFile( $this->qualifyClass($this->getNameInput()), $this->laravel->getBootstrapProvidersPath(), ); return $result; } /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return $this->resolveStubPath('/stubs/provider.stub'); } /** * Resolve the fully-qualified path to the stub. * * @param string $stub * @return string */ protected function resolveStubPath($stub) { return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath : __DIR__.$stub; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Providers'; } /** * Get the console command arguments. * * @return array */ protected function getOptions() { return [ ['force', 'f', InputOption::VALUE_NONE, 'Create the class even if the provider already exists'], ]; } }
195023
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'storage:link')] class StorageLinkCommand extends Command { /** * The console command signature. * * @var string */ protected $signature = 'storage:link {--relative : Create the symbolic link using relative paths} {--force : Recreate existing symbolic links}'; /** * The console command description. * * @var string */ protected $description = 'Create the symbolic links configured for the application'; /** * Execute the console command. * * @return void */ public function handle() { $relative = $this->option('relative'); foreach ($this->links() as $link => $target) { if (file_exists($link) && ! $this->isRemovableSymlink($link, $this->option('force'))) { $this->components->error("The [$link] link already exists."); continue; } if (is_link($link)) { $this->laravel->make('files')->delete($link); } if ($relative) { $this->laravel->make('files')->relativeLink($target, $link); } else { $this->laravel->make('files')->link($target, $link); } $this->components->info("The [$link] link has been connected to [$target]."); } } /** * Get the symbolic links that are configured for the application. * * @return array */ protected function links() { return $this->laravel['config']['filesystems.links'] ?? [public_path('storage') => storage_path('app/public')]; } /** * Determine if the provided path is a symlink that can be removed. * * @param string $link * @param bool $force * @return bool */ protected function isRemovableSymlink(string $link, bool $force): bool { return is_link($link) && $force; } }
195028
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\Process; use Symfony\Component\Console\Attribute\AsCommand; use function Illuminate\Support\php_binary; #[AsCommand(name: 'install:api')] class ApiInstallCommand extends Command { use InteractsWithComposerPackages; /** * The name and signature of the console command. * * @var string */ protected $signature = 'install:api {--composer=global : Absolute path to the Composer binary which should be used to install packages} {--force : Overwrite any existing API routes file} {--passport : Install Laravel Passport instead of Laravel Sanctum} {--without-migration-prompt : Do not prompt to run pending migrations}'; /** * The console command description. * * @var string */ protected $description = 'Create an API routes file and install Laravel Sanctum or Laravel Passport'; /** * Execute the console command. * * @return int */ public function handle() { if ($this->option('passport')) { $this->installPassport(); } else { $this->installSanctum(); } if (file_exists($apiRoutesPath = $this->laravel->basePath('routes/api.php')) && ! $this->option('force')) { $this->components->error('API routes file already exists.'); } else { $this->components->info('Published API routes file.'); copy(__DIR__.'/stubs/api-routes.stub', $apiRoutesPath); if ($this->option('passport')) { (new Filesystem)->replaceInFile( 'auth:sanctum', 'auth:api', $apiRoutesPath, ); } $this->uncommentApiRoutesFile(); } if ($this->option('passport')) { Process::run(array_filter([ php_binary(), defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan', 'passport:install', $this->confirm('Would you like to use UUIDs for all client IDs?') ? '--uuids' : null, ])); $this->components->info('API scaffolding installed. Please add the [Laravel\Passport\HasApiTokens] trait to your User model.'); } else { if (! $this->option('without-migration-prompt')) { if ($this->confirm('One new database migration has been published. Would you like to run all pending database migrations?', true)) { $this->call('migrate'); } } $this->components->info('API scaffolding installed. Please add the [Laravel\Sanctum\HasApiTokens] trait to your User model.'); } } /** * Uncomment the API routes file in the application bootstrap file. * * @return void */ protected function uncommentApiRoutesFile() { $appBootstrapPath = $this->laravel->bootstrapPath('app.php'); $content = file_get_contents($appBootstrapPath); if (str_contains($content, '// api: ')) { (new Filesystem)->replaceInFile( '// api: ', 'api: ', $appBootstrapPath, ); } elseif (str_contains($content, 'web: __DIR__.\'/../routes/web.php\',')) { (new Filesystem)->replaceInFile( 'web: __DIR__.\'/../routes/web.php\',', 'web: __DIR__.\'/../routes/web.php\','.PHP_EOL.' api: __DIR__.\'/../routes/api.php\',', $appBootstrapPath, ); } else { $this->components->warn('Unable to automatically add API route definition to bootstrap file. API route file should be registered manually.'); return; } } /** * Install Laravel Sanctum into the application. * * @return void */ protected function installSanctum() { $this->requireComposerPackages($this->option('composer'), [ 'laravel/sanctum:^4.0', ]); $migrationPublished = collect(scandir($this->laravel->databasePath('migrations')))->contains(function ($migration) { return preg_match('/\d{4}_\d{2}_\d{2}_\d{6}_create_personal_access_tokens_table.php/', $migration); }); if (! $migrationPublished) { Process::run([ php_binary(), defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan', 'vendor:publish', '--provider', 'Laravel\\Sanctum\\SanctumServiceProvider', ]); } } /** * Install Laravel Passport into the application. * * @return void */ protected function installPassport() { $this->requireComposerPackages($this->option('composer'), [ 'laravel/passport:^12.0', ]); } }
195029
<?php namespace Illuminate\Foundation\Console; use Composer\InstalledVersions; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\Process; use Symfony\Component\Console\Attribute\AsCommand; use function Illuminate\Support\php_binary; use function Laravel\Prompts\confirm; #[AsCommand(name: 'install:broadcasting')] class BroadcastingInstallCommand extends Command { use InteractsWithComposerPackages; /** * The name and signature of the console command. * * @var string */ protected $signature = 'install:broadcasting {--composer=global : Absolute path to the Composer binary which should be used to install packages} {--force : Overwrite any existing broadcasting routes file} {--without-reverb : Do not prompt to install Laravel Reverb} {--without-node : Do not prompt to install Node dependencies}'; /** * The console command description. * * @var string */ protected $description = 'Create a broadcasting channel routes file'; /** * Execute the console command. * * @return int */ public function handle() { $this->call('config:publish', ['name' => 'broadcasting']); // Install channel routes file... if (! file_exists($broadcastingRoutesPath = $this->laravel->basePath('routes/channels.php')) || $this->option('force')) { $this->components->info("Published 'channels' route file."); copy(__DIR__.'/stubs/broadcasting-routes.stub', $broadcastingRoutesPath); } $this->uncommentChannelsRoutesFile(); $this->enableBroadcastServiceProvider(); // Install bootstrapping... if (! file_exists($echoScriptPath = $this->laravel->resourcePath('js/echo.js'))) { if (! is_dir($directory = $this->laravel->resourcePath('js'))) { mkdir($directory, 0755, true); } copy(__DIR__.'/stubs/echo-js.stub', $echoScriptPath); } if (file_exists($bootstrapScriptPath = $this->laravel->resourcePath('js/bootstrap.js'))) { $bootstrapScript = file_get_contents( $bootstrapScriptPath ); if (! str_contains($bootstrapScript, './echo')) { file_put_contents( $bootstrapScriptPath, trim($bootstrapScript.PHP_EOL.file_get_contents(__DIR__.'/stubs/echo-bootstrap-js.stub')).PHP_EOL, ); } } $this->installReverb(); $this->installNodeDependencies(); } /** * Uncomment the "channels" routes file in the application bootstrap file. * * @return void */ protected function uncommentChannelsRoutesFile() { $appBootstrapPath = $this->laravel->bootstrapPath('app.php'); $content = file_get_contents($appBootstrapPath); if (str_contains($content, '// channels: ')) { (new Filesystem)->replaceInFile( '// channels: ', 'channels: ', $appBootstrapPath, ); } elseif (str_contains($content, 'channels: ')) { return; } elseif (str_contains($content, 'commands: __DIR__.\'/../routes/console.php\',')) { (new Filesystem)->replaceInFile( 'commands: __DIR__.\'/../routes/console.php\',', 'commands: __DIR__.\'/../routes/console.php\','.PHP_EOL.' channels: __DIR__.\'/../routes/channels.php\',', $appBootstrapPath, ); } } /** * Uncomment the "BroadcastServiceProvider" in the application configuration. * * @return void */ protected function enableBroadcastServiceProvider() { $filesystem = new Filesystem; if (! $filesystem->exists(app()->configPath('app.php')) || ! $filesystem->exists('app/Providers/BroadcastServiceProvider.php')) { return; } $config = $filesystem->get(app()->configPath('app.php')); if (str_contains($config, '// App\Providers\BroadcastServiceProvider::class')) { $filesystem->replaceInFile( '// App\Providers\BroadcastServiceProvider::class', 'App\Providers\BroadcastServiceProvider::class', app()->configPath('app.php'), ); } } /** * Install Laravel Reverb into the application if desired. * * @return void */ protected function installReverb() { if ($this->option('without-reverb') || InstalledVersions::isInstalled('laravel/reverb')) { return; } $install = confirm('Would you like to install Laravel Reverb?', default: true); if (! $install) { return; } $this->requireComposerPackages($this->option('composer'), [ 'laravel/reverb:^1.0', ]); Process::run([ php_binary(), defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan', 'reverb:install', ]); $this->components->info('Reverb installed successfully.'); } /** * Install and build Node dependencies. * * @return void */ protected function installNodeDependencies() { if ($this->option('without-node') || ! confirm('Would you like to install and build the Node dependencies required for broadcasting?', default: true)) { return; } $this->components->info('Installing and building Node dependencies.'); if (file_exists(base_path('pnpm-lock.yaml'))) { $commands = [ 'pnpm add --save-dev laravel-echo pusher-js', 'pnpm run build', ]; } elseif (file_exists(base_path('yarn.lock'))) { $commands = [ 'yarn add --dev laravel-echo pusher-js', 'yarn run build', ]; } elseif (file_exists(base_path('bun.lockb'))) { $commands = [ 'bun add --dev laravel-echo pusher-js', 'bun run build', ]; } else { $commands = [ 'npm install --save-dev laravel-echo pusher-js', 'npm run build', ]; } $command = Process::command(implode(' && ', $commands)) ->path(base_path()); if (! windows_os()) { $command->tty(true); } if ($command->run()->failed()) { $this->components->warn("Node dependency installation failed. Please run the following commands manually: \n\n".implode(' && ', $commands)); } else { $this->components->info('Node dependencies installed successfully.'); } } }
195046
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'config:clear')] class ConfigClearCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'config:clear'; /** * The console command description. * * @var string */ protected $description = 'Remove the configuration cache file'; /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * Create a new config clear command instance. * * @param \Illuminate\Filesystem\Filesystem $files * @return void */ public function __construct(Filesystem $files) { parent::__construct(); $this->files = $files; } /** * Execute the console command. * * @return void */ public function handle() { $this->files->delete($this->laravel->getCachedConfigPath()); $this->components->info('Configuration cache cleared successfully.'); } }
195054
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\Command; use Illuminate\Support\ServiceProvider; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'optimize:clear')] class OptimizeClearCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'optimize:clear'; /** * The console command description. * * @var string */ protected $description = 'Remove the cached bootstrap files'; /** * Execute the console command. * * @return void */ public function handle() { $this->components->info('Clearing cached bootstrap files.'); foreach ($this->getOptimizeClearTasks() as $description => $command) { $this->components->task($description, fn () => $this->callSilently($command) == 0); } $this->newLine(); } /** * Get the commands that should be run to clear the "optimization" files. * * @return array */ public function getOptimizeClearTasks() { return [ 'cache' => 'cache:clear', 'compiled' => 'clear-compiled', 'config' => 'config:clear', 'events' => 'event:clear', 'routes' => 'route:clear', 'views' => 'view:clear', ...ServiceProvider::$optimizeClearCommands, ]; } }
195074
<?php namespace {{ namespace }}; use Illuminate\Foundation\Http\FormRequest; class {{ class }} extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return false; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ // ]; } }
195076
<?php namespace {{ namespace }}; use Illuminate\Auth\Access\Response; use {{ namespacedModel }}; use {{ namespacedUserModel }}; class {{ class }} { /** * Determine whether the user can view any models. */ public function viewAny({{ user }} $user): bool { // } /** * Determine whether the user can view the model. */ public function view({{ user }} $user, {{ model }} ${{ modelVariable }}): bool { // } /** * Determine whether the user can create models. */ public function create({{ user }} $user): bool { // } /** * Determine whether the user can update the model. */ public function update({{ user }} $user, {{ model }} ${{ modelVariable }}): bool { // } /** * Determine whether the user can delete the model. */ public function delete({{ user }} $user, {{ model }} ${{ modelVariable }}): bool { // } /** * Determine whether the user can restore the model. */ public function restore({{ user }} $user, {{ model }} ${{ modelVariable }}): bool { // } /** * Determine whether the user can permanently delete the model. */ public function forceDelete({{ user }} $user, {{ model }} ${{ modelVariable }}): bool { // } }
195116
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:sanctum');
195156
class Filesystem { use Conditionable, Macroable; /** * Determine if a file or directory exists. * * @param string $path * @return bool */ public function exists($path) { return file_exists($path); } /** * Determine if a file or directory is missing. * * @param string $path * @return bool */ public function missing($path) { return ! $this->exists($path); } /** * Get the contents of a file. * * @param string $path * @param bool $lock * @return string * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function get($path, $lock = false) { if ($this->isFile($path)) { return $lock ? $this->sharedGet($path) : file_get_contents($path); } throw new FileNotFoundException("File does not exist at path {$path}."); } /** * Get the contents of a file as decoded JSON. * * @param string $path * @param int $flags * @param bool $lock * @return array * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function json($path, $flags = 0, $lock = false) { return json_decode($this->get($path, $lock), true, 512, $flags); } /** * Get contents of a file with shared access. * * @param string $path * @return string */ public function sharedGet($path) { $contents = ''; $handle = fopen($path, 'rb'); if ($handle) { try { if (flock($handle, LOCK_SH)) { clearstatcache(true, $path); $contents = fread($handle, $this->size($path) ?: 1); flock($handle, LOCK_UN); } } finally { fclose($handle); } } return $contents; } /** * Get the returned value of a file. * * @param string $path * @param array $data * @return mixed * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function getRequire($path, array $data = []) { if ($this->isFile($path)) { $__path = $path; $__data = $data; return (static function () use ($__path, $__data) { extract($__data, EXTR_SKIP); return require $__path; })(); } throw new FileNotFoundException("File does not exist at path {$path}."); } /** * Require the given file once. * * @param string $path * @param array $data * @return mixed * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function requireOnce($path, array $data = []) { if ($this->isFile($path)) { $__path = $path; $__data = $data; return (static function () use ($__path, $__data) { extract($__data, EXTR_SKIP); return require_once $__path; })(); } throw new FileNotFoundException("File does not exist at path {$path}."); } /** * Get the contents of a file one line at a time. * * @param string $path * @return \Illuminate\Support\LazyCollection * * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function lines($path) { if (! $this->isFile($path)) { throw new FileNotFoundException( "File does not exist at path {$path}." ); } return LazyCollection::make(function () use ($path) { $file = new SplFileObject($path); $file->setFlags(SplFileObject::DROP_NEW_LINE); while (! $file->eof()) { yield $file->fgets(); } }); } /** * Get the hash of the file at the given path. * * @param string $path * @param string $algorithm * @return string|false */ public function hash($path, $algorithm = 'md5') { return hash_file($algorithm, $path); } /** * Write the contents of a file. * * @param string $path * @param string $contents * @param bool $lock * @return int|bool */ public function put($path, $contents, $lock = false) { return file_put_contents($path, $contents, $lock ? LOCK_EX : 0); } /** * Write the contents of a file, replacing it atomically if it already exists. * * @param string $path * @param string $content * @param int|null $mode * @return void */ public function replace($path, $content, $mode = null) { // If the path already exists and is a symlink, get the real path... clearstatcache(true, $path); $path = realpath($path) ?: $path; $tempPath = tempnam(dirname($path), basename($path)); // Fix permissions of tempPath because `tempnam()` creates it with permissions set to 0600... if (! is_null($mode)) { chmod($tempPath, $mode); } else { chmod($tempPath, 0777 - umask()); } file_put_contents($tempPath, $content); rename($tempPath, $path); } /** * Replace a given string within a given file. * * @param array|string $search * @param array|string $replace * @param string $path * @return void */ public function replaceInFile($search, $replace, $path) { file_put_contents($path, str_replace($search, $replace, file_get_contents($path))); } /** * Prepend to a file. * * @param string $path * @param string $data * @return int */ public function prepend($path, $data) { if ($this->exists($path)) { return $this->put($path, $data.$this->get($path)); } return $this->put($path, $data); } /** * Append to a file. * * @param string $path * @param string $data * @param bool $lock * @return int */ public function append($path, $data, $lock = false) { return file_put_contents($path, $data, FILE_APPEND | ($lock ? LOCK_EX : 0)); } /** * Get or set UNIX mode of a file or directory. * * @param string $path * @param int|null $mode * @return mixed */ public function chmod($path, $mode = null) { if ($mode) { return chmod($path, $mode); } return substr(sprintf('%o', fileperms($path)), -4); } /** * Delete the file at a given path. * * @param string|array $paths * @return bool */ public function delete($paths) { $paths = is_array($paths) ? $paths : func_get_args(); $success = true; foreach ($paths as $path) { try { if (@unlink($path)) { clearstatcache(false, $path); } else { $success = false; } } catch (ErrorException) { $success = false; } } return $success; } /** * Move a file to a new location. * * @param string $path * @param string $target * @return bool */ public function move($path, $target) { return rename($path, $target); } /** * Copy a file to a new location. * * @param string $path * @param string $target * @return bool */ public function copy($path, $target) { return copy($path, $target); }
195157
/** * Create a symlink to the target file or directory. On Windows, a hard link is created if the target is a file. * * @param string $target * @param string $link * @return bool|null */ public function link($target, $link) { if (! windows_os()) { return symlink($target, $link); } $mode = $this->isDirectory($target) ? 'J' : 'H'; exec("mklink /{$mode} ".escapeshellarg($link).' '.escapeshellarg($target)); } /** * Create a relative symlink to the target file or directory. * * @param string $target * @param string $link * @return void * * @throws \RuntimeException */ public function relativeLink($target, $link) { if (! class_exists(SymfonyFilesystem::class)) { throw new RuntimeException( 'To enable support for relative links, please install the symfony/filesystem package.' ); } $relativeTarget = (new SymfonyFilesystem)->makePathRelative($target, dirname($link)); $this->link($this->isFile($target) ? rtrim($relativeTarget, '/') : $relativeTarget, $link); } /** * Extract the file name from a file path. * * @param string $path * @return string */ public function name($path) { return pathinfo($path, PATHINFO_FILENAME); } /** * Extract the trailing name component from a file path. * * @param string $path * @return string */ public function basename($path) { return pathinfo($path, PATHINFO_BASENAME); } /** * Extract the parent directory from a file path. * * @param string $path * @return string */ public function dirname($path) { return pathinfo($path, PATHINFO_DIRNAME); } /** * Extract the file extension from a file path. * * @param string $path * @return string */ public function extension($path) { return pathinfo($path, PATHINFO_EXTENSION); } /** * Guess the file extension from the mime-type of a given file. * * @param string $path * @return string|null * * @throws \RuntimeException */ public function guessExtension($path) { if (! class_exists(MimeTypes::class)) { throw new RuntimeException( 'To enable support for guessing extensions, please install the symfony/mime package.' ); } return (new MimeTypes)->getExtensions($this->mimeType($path))[0] ?? null; } /** * Get the file type of a given file. * * @param string $path * @return string */ public function type($path) { return filetype($path); } /** * Get the mime-type of a given file. * * @param string $path * @return string|false */ public function mimeType($path) { return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path); } /** * Get the file size of a given file. * * @param string $path * @return int */ public function size($path) { return filesize($path); } /** * Get the file's last modification time. * * @param string $path * @return int */ public function lastModified($path) { return filemtime($path); } /** * Determine if the given path is a directory. * * @param string $directory * @return bool */ public function isDirectory($directory) { return is_dir($directory); } /** * Determine if the given path is a directory that does not contain any other files or directories. * * @param string $directory * @param bool $ignoreDotFiles * @return bool */ public function isEmptyDirectory($directory, $ignoreDotFiles = false) { return ! Finder::create()->ignoreDotFiles($ignoreDotFiles)->in($directory)->depth(0)->hasResults(); } /** * Determine if the given path is readable. * * @param string $path * @return bool */ public function isReadable($path) { return is_readable($path); } /** * Determine if the given path is writable. * * @param string $path * @return bool */ public function isWritable($path) { return is_writable($path); } /** * Determine if two files are the same by comparing their hashes. * * @param string $firstFile * @param string $secondFile * @return bool */ public function hasSameHash($firstFile, $secondFile) { $hash = @md5_file($firstFile); return $hash && hash_equals($hash, (string) @md5_file($secondFile)); } /** * Determine if the given path is a file. * * @param string $file * @return bool */ public function isFile($file) { return is_file($file); } /** * Find path names matching a given pattern. * * @param string $pattern * @param int $flags * @return array */ public function glob($pattern, $flags = 0) { return glob($pattern, $flags); } /** * Get an array of all files in a directory. * * @param string $directory * @param bool $hidden * @return \Symfony\Component\Finder\SplFileInfo[] */ public function files($directory, $hidden = false) { return iterator_to_array( Finder::create()->files()->ignoreDotFiles(! $hidden)->in($directory)->depth(0)->sortByName(), false ); } /** * Get all of the files from the given directory (recursive). * * @param string $directory * @param bool $hidden * @return \Symfony\Component\Finder\SplFileInfo[] */ public function allFiles($directory, $hidden = false) { return iterator_to_array( Finder::create()->files()->ignoreDotFiles(! $hidden)->in($directory)->sortByName(), false ); } /** * Get all of the directories within a given directory. * * @param string $directory * @return array */ public function directories($directory) { $directories = []; foreach (Finder::create()->in($directory)->directories()->depth(0)->sortByName() as $dir) { $directories[] = $dir->getPathname(); } return $directories; } /** * Ensure a directory exists. * * @param string $path * @param int $mode * @param bool $recursive * @return void */ public function ensureDirectoryExists($path, $mode = 0755, $recursive = true) { if (! $this->isDirectory($path)) { $this->makeDirectory($path, $mode, $recursive); } } /** * Create a directory. * * @param string $path * @param int $mode * @param bool $recursive * @param bool $force * @return bool */ public function makeDirectory($path, $mode = 0755, $recursive = false, $force = false) { if ($force) { return @mkdir($path, $mode, $recursive); } return mkdir($path, $mode, $recursive); } /** * Move a directory. * * @param string $from * @param string $to * @param bool $overwrite * @return bool */ public function moveDirectory($from, $to, $overwrite = false) { if ($overwrite && $this->isDirectory($to) && ! $this->deleteDirectory($to)) { return false; } return @rename($from, $to) === true; }
195159
<?php namespace Illuminate\Filesystem; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use League\Flysystem\PathTraversalDetected; class ServeFile { /** * Create a new invokable controller to serve files. */ public function __construct(protected string $disk, protected array $config, protected bool $isProduction) { // } /** * Handle the incoming request. */ public function __invoke(Request $request, string $path) { abort_unless( $this->hasValidSignature($request), $this->isProduction ? 404 : 403 ); try { abort_unless(Storage::disk($this->disk)->exists($path), 404); $headers = [ 'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0', 'Content-Security-Policy' => "default-src 'none'; style-src 'unsafe-inline'; sandbox", ]; return tap( Storage::disk($this->disk)->serve($request, $path, headers: $headers), function ($response) use ($headers) { if (! $response->headers->has('Content-Security-Policy')) { $response->headers->replace($headers); } } ); } catch (PathTraversalDetected $e) { abort(404); } } /** * Determine if the request has a valid signature if applicable. */ protected function hasValidSignature(Request $request): bool { return ($this->config['visibility'] ?? 'private') === 'public' || $request->hasValidRelativeSignature(); } }
195165
/** * Write the contents of a file. * * @param string $path * @param \Psr\Http\Message\StreamInterface|\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|resource $contents * @param mixed $options * @return string|bool */ public function put($path, $contents, $options = []) { $options = is_string($options) ? ['visibility' => $options] : (array) $options; // If the given contents is actually a file or uploaded file instance than we will // automatically store the file using a stream. This provides a convenient path // for the developer to store streams without managing them manually in code. if ($contents instanceof File || $contents instanceof UploadedFile) { return $this->putFile($path, $contents, $options); } try { if ($contents instanceof StreamInterface) { $this->driver->writeStream($path, $contents->detach(), $options); return true; } is_resource($contents) ? $this->driver->writeStream($path, $contents, $options) : $this->driver->write($path, $contents, $options); } catch (UnableToWriteFile|UnableToSetVisibility $e) { throw_if($this->throwsExceptions(), $e); return false; } return true; } /** * Store the uploaded file on the disk. * * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $path * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|array|null $file * @param mixed $options * @return string|false */ public function putFile($path, $file = null, $options = []) { if (is_null($file) || is_array($file)) { [$path, $file, $options] = ['', $path, $file ?? []]; } $file = is_string($file) ? new File($file) : $file; return $this->putFileAs($path, $file, $file->hashName(), $options); } /** * Store the uploaded file on the disk with a given name. * * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $path * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|array|null $file * @param string|array|null $name * @param mixed $options * @return string|false */ public function putFileAs($path, $file, $name = null, $options = []) { if (is_null($name) || is_array($name)) { [$path, $file, $name, $options] = ['', $path, $file, $name ?? []]; } $stream = fopen(is_string($file) ? $file : $file->getRealPath(), 'r'); // Next, we will format the path of the file and store the file using a stream since // they provide better performance than alternatives. Once we write the file this // stream will get closed automatically by us so the developer doesn't have to. $result = $this->put( $path = trim($path.'/'.$name, '/'), $stream, $options ); if (is_resource($stream)) { fclose($stream); } return $result ? $path : false; } /** * Get the visibility for the given path. * * @param string $path * @return string */ public function getVisibility($path) { if ($this->driver->visibility($path) == Visibility::PUBLIC) { return FilesystemContract::VISIBILITY_PUBLIC; } return FilesystemContract::VISIBILITY_PRIVATE; } /** * Set the visibility for the given path. * * @param string $path * @param string $visibility * @return bool */ public function setVisibility($path, $visibility) { try { $this->driver->setVisibility($path, $this->parseVisibility($visibility)); } catch (UnableToSetVisibility $e) { throw_if($this->throwsExceptions(), $e); return false; } return true; } /** * Prepend to a file. * * @param string $path * @param string $data * @param string $separator * @return bool */ public function prepend($path, $data, $separator = PHP_EOL) { if ($this->fileExists($path)) { return $this->put($path, $data.$separator.$this->get($path)); } return $this->put($path, $data); } /** * Append to a file. * * @param string $path * @param string $data * @param string $separator * @return bool */ public function append($path, $data, $separator = PHP_EOL) { if ($this->fileExists($path)) { return $this->put($path, $this->get($path).$separator.$data); } return $this->put($path, $data); } /** * Delete the file at a given path. * * @param string|array $paths * @return bool */ public function delete($paths) { $paths = is_array($paths) ? $paths : func_get_args(); $success = true; foreach ($paths as $path) { try { $this->driver->delete($path); } catch (UnableToDeleteFile $e) { throw_if($this->throwsExceptions(), $e); $success = false; } } return $success; } /** * Copy a file to a new location. * * @param string $from * @param string $to * @return bool */ public function copy($from, $to) { try { $this->driver->copy($from, $to); } catch (UnableToCopyFile $e) { throw_if($this->throwsExceptions(), $e); return false; } return true; } /** * Move a file to a new location. * * @param string $from * @param string $to * @return bool */ public function move($from, $to) { try { $this->driver->move($from, $to); } catch (UnableToMoveFile $e) { throw_if($this->throwsExceptions(), $e); return false; } return true; } /** * Get the file size of a given file. * * @param string $path * @return int */ public function size($path) { return $this->driver->fileSize($path); } /** * Get the checksum for a file. * * @return string|false * * @throws UnableToProvideChecksum */ public function checksum(string $path, array $options = []) { try { return $this->driver->checksum($path, $options); } catch (UnableToProvideChecksum $e) { throw_if($this->throwsExceptions(), $e); return false; } } /** * Get the mime-type of a given file. * * @param string $path * @return string|false */ public function mimeType($path) { try { return $this->driver->mimeType($path); } catch (UnableToRetrieveMetadata $e) { throw_if($this->throwsExceptions(), $e); } return false; } /** * Get the file's last modification time. * * @param string $path * @return int */ public function lastModified($path) { return $this->driver->lastModified($path); } /** * {@inheritdoc} */ public function readStream($path) { try { return $this->driver->readStream($path); } catch (UnableToReadFile $e) { throw_if($this->throwsExceptions(), $e); } } /** * {@inheritdoc} */
195166
public function writeStream($path, $resource, array $options = []) { try { $this->driver->writeStream($path, $resource, $options); } catch (UnableToWriteFile|UnableToSetVisibility $e) { throw_if($this->throwsExceptions(), $e); return false; } return true; } /** * Get the URL for the file at the given path. * * @param string $path * @return string * * @throws \RuntimeException */ public function url($path) { if (isset($this->config['prefix'])) { $path = $this->concatPathToUrl($this->config['prefix'], $path); } $adapter = $this->adapter; if (method_exists($adapter, 'getUrl')) { return $adapter->getUrl($path); } elseif (method_exists($this->driver, 'getUrl')) { return $this->driver->getUrl($path); } elseif ($adapter instanceof FtpAdapter || $adapter instanceof SftpAdapter) { return $this->getFtpUrl($path); } elseif ($adapter instanceof LocalAdapter) { return $this->getLocalUrl($path); } else { throw new RuntimeException('This driver does not support retrieving URLs.'); } } /** * Get the URL for the file at the given path. * * @param string $path * @return string */ protected function getFtpUrl($path) { return isset($this->config['url']) ? $this->concatPathToUrl($this->config['url'], $path) : $path; } /** * Get the URL for the file at the given path. * * @param string $path * @return string */ protected function getLocalUrl($path) { // If an explicit base URL has been set on the disk configuration then we will use // it as the base URL instead of the default path. This allows the developer to // have full control over the base path for this filesystem's generated URLs. if (isset($this->config['url'])) { return $this->concatPathToUrl($this->config['url'], $path); } $path = '/storage/'.$path; // If the path contains "storage/public", it probably means the developer is using // the default disk to generate the path instead of the "public" disk like they // are really supposed to use. We will remove the public from this path here. if (str_contains($path, '/storage/public/')) { return Str::replaceFirst('/public/', '/', $path); } return $path; } /** * Determine if temporary URLs can be generated. * * @return bool */ public function providesTemporaryUrls() { return method_exists($this->adapter, 'getTemporaryUrl') || isset($this->temporaryUrlCallback); } /** * Get a temporary URL for the file at the given path. * * @param string $path * @param \DateTimeInterface $expiration * @param array $options * @return string * * @throws \RuntimeException */ public function temporaryUrl($path, $expiration, array $options = []) { if (method_exists($this->adapter, 'getTemporaryUrl')) { return $this->adapter->getTemporaryUrl($path, $expiration, $options); } if ($this->temporaryUrlCallback) { return $this->temporaryUrlCallback->bindTo($this, static::class)( $path, $expiration, $options ); } throw new RuntimeException('This driver does not support creating temporary URLs.'); } /** * Get a temporary upload URL for the file at the given path. * * @param string $path * @param \DateTimeInterface $expiration * @param array $options * @return array * * @throws \RuntimeException */ public function temporaryUploadUrl($path, $expiration, array $options = []) { if (method_exists($this->adapter, 'temporaryUploadUrl')) { return $this->adapter->temporaryUploadUrl($path, $expiration, $options); } throw new RuntimeException('This driver does not support creating temporary upload URLs.'); } /** * Concatenate a path to a URL. * * @param string $url * @param string $path * @return string */ protected function concatPathToUrl($url, $path) { return rtrim($url, '/').'/'.ltrim($path, '/'); } /** * Replace the scheme, host and port of the given UriInterface with values from the given URL. * * @param \Psr\Http\Message\UriInterface $uri * @param string $url * @return \Psr\Http\Message\UriInterface */ protected function replaceBaseUrl($uri, $url) { $parsed = parse_url($url); return $uri ->withScheme($parsed['scheme']) ->withHost($parsed['host']) ->withPort($parsed['port'] ?? null); } /** * Get an array of all files in a directory. * * @param string|null $directory * @param bool $recursive * @return array */ public function files($directory = null, $recursive = false) { return $this->driver->listContents($directory ?? '', $recursive) ->filter(function (StorageAttributes $attributes) { return $attributes->isFile(); }) ->sortByPath() ->map(function (StorageAttributes $attributes) { return $attributes->path(); }) ->toArray(); } /** * Get all of the files from the given directory (recursive). * * @param string|null $directory * @return array */ public function allFiles($directory = null) { return $this->files($directory, true); } /** * Get all of the directories within a given directory. * * @param string|null $directory * @param bool $recursive * @return array */ public function directories($directory = null, $recursive = false) { return $this->driver->listContents($directory ?? '', $recursive) ->filter(function (StorageAttributes $attributes) { return $attributes->isDir(); }) ->map(function (StorageAttributes $attributes) { return $attributes->path(); }) ->toArray(); } /** * Get all the directories within a given directory (recursive). * * @param string|null $directory * @return array */ public function allDirectories($directory = null) { return $this->directories($directory, true); } /** * Create a directory. * * @param string $path * @return bool */ public function makeDirectory($path) { try { $this->driver->createDirectory($path); } catch (UnableToCreateDirectory|UnableToSetVisibility $e) { throw_if($this->throwsExceptions(), $e); return false; } return true; } /** * Recursively delete a directory. * * @param string $directory * @return bool */ public function deleteDirectory($directory) { try { $this->driver->deleteDirectory($directory); } catch (UnableToDeleteDirectory $e) { throw_if($this->throwsExceptions(), $e); return false; } return true; } /** * Get the Flysystem driver. * * @return \League\Flysystem\FilesystemOperator */ public function getDriver() { return $this->driver; } /** * Get the Flysystem adapter. * * @return \League\Flysystem\FilesystemAdapter */ public function getAdapter() { return $this->adapter; } /** * Get the configuration values. * * @return array */ public function getConfig() { return $this->config; } /** * Parse the given visibility value. * * @param string|null $visibility * @return string|null * * @throws \InvalidArgumentException */
195186
class AssertableJsonString implements ArrayAccess, Countable { /** * The original encoded json. * * @var \Illuminate\Contracts\Support\Jsonable|\JsonSerializable|array|string */ public $json; /** * The decoded json contents. * * @var array|null */ protected $decoded; /** * Create a new assertable JSON string instance. * * @param \Illuminate\Contracts\Support\Jsonable|\JsonSerializable|array|string $jsonable * @return void */ public function __construct($jsonable) { $this->json = $jsonable; if ($jsonable instanceof JsonSerializable) { $this->decoded = $jsonable->jsonSerialize(); } elseif ($jsonable instanceof Jsonable) { $this->decoded = json_decode($jsonable->toJson(), true); } elseif (is_array($jsonable)) { $this->decoded = $jsonable; } else { $this->decoded = json_decode($jsonable, true); } } /** * Validate and return the decoded response JSON. * * @param string|null $key * @return mixed */ public function json($key = null) { return data_get($this->decoded, $key); } /** * Assert that the response JSON has the expected count of items at the given key. * * @param int $count * @param string|null $key * @return $this */ public function assertCount(int $count, $key = null) { if (! is_null($key)) { PHPUnit::assertCount( $count, data_get($this->decoded, $key), "Failed to assert that the response count matched the expected {$count}" ); return $this; } PHPUnit::assertCount($count, $this->decoded, "Failed to assert that the response count matched the expected {$count}" ); return $this; } /** * Assert that the response has the exact given JSON. * * @param array $data * @return $this */ public function assertExact(array $data) { $actual = $this->reorderAssocKeys((array) $this->decoded); $expected = $this->reorderAssocKeys($data); PHPUnit::assertEquals( json_encode($expected, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), json_encode($actual, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ); return $this; } /** * Assert that the response has the similar JSON as given. * * @param array $data * @return $this */ public function assertSimilar(array $data) { $actual = json_encode( Arr::sortRecursive((array) $this->decoded), JSON_UNESCAPED_UNICODE ); PHPUnit::assertEquals(json_encode(Arr::sortRecursive($data), JSON_UNESCAPED_UNICODE), $actual); return $this; } /** * Assert that the response contains the given JSON fragment. * * @param array $data * @return $this */ public function assertFragment(array $data) { $actual = json_encode( Arr::sortRecursive((array) $this->decoded), JSON_UNESCAPED_UNICODE ); foreach (Arr::sortRecursive($data) as $key => $value) { $expected = $this->jsonSearchStrings($key, $value); PHPUnit::assertTrue( Str::contains($actual, $expected), 'Unable to find JSON fragment: '.PHP_EOL.PHP_EOL. '['.json_encode([$key => $value], JSON_UNESCAPED_UNICODE).']'.PHP_EOL.PHP_EOL. 'within'.PHP_EOL.PHP_EOL. "[{$actual}]." ); } return $this; } /** * Assert that the response does not contain the given JSON fragment. * * @param array $data * @param bool $exact * @return $this */ public function assertMissing(array $data, $exact = false) { if ($exact) { return $this->assertMissingExact($data); } $actual = json_encode( Arr::sortRecursive((array) $this->decoded), JSON_UNESCAPED_UNICODE ); foreach (Arr::sortRecursive($data) as $key => $value) { $unexpected = $this->jsonSearchStrings($key, $value); PHPUnit::assertFalse( Str::contains($actual, $unexpected), 'Found unexpected JSON fragment: '.PHP_EOL.PHP_EOL. '['.json_encode([$key => $value], JSON_UNESCAPED_UNICODE).']'.PHP_EOL.PHP_EOL. 'within'.PHP_EOL.PHP_EOL. "[{$actual}]." ); } return $this; } /** * Assert that the response does not contain the exact JSON fragment. * * @param array $data * @return $this */ public function assertMissingExact(array $data) { $actual = json_encode( Arr::sortRecursive((array) $this->decoded), JSON_UNESCAPED_UNICODE ); foreach (Arr::sortRecursive($data) as $key => $value) { $unexpected = $this->jsonSearchStrings($key, $value); if (! Str::contains($actual, $unexpected)) { return $this; } } PHPUnit::fail( 'Found unexpected JSON fragment: '.PHP_EOL.PHP_EOL. '['.json_encode($data, JSON_UNESCAPED_UNICODE).']'.PHP_EOL.PHP_EOL. 'within'.PHP_EOL.PHP_EOL. "[{$actual}]." ); } /** * Assert that the response does not contain the given path. * * @param string $path * @return $this */ public function assertMissingPath($path) { PHPUnit::assertFalse(Arr::has($this->json(), $path)); return $this; } /** * Assert that the expected value and type exists at the given path in the response. * * @param string $path * @param mixed $expect * @return $this */ public function assertPath($path, $expect) { if ($expect instanceof Closure) { PHPUnit::assertTrue($expect($this->json($path))); } else { PHPUnit::assertSame($expect, $this->json($path)); } return $this; } /** * Assert that the given path in the response contains all of the expected values without looking at the order. * * @param string $path * @param array $expect * @return $this */ public function assertPathCanonicalizing($path, $expect) { PHPUnit::assertEqualsCanonicalizing($expect, $this->json($path)); return $this; } /** * Assert that the response has a given JSON structure. * * @param array|null $structure * @param array|null $responseData * @param bool $exact * @return $this */ public function assertStructure(?array $structure = null, $responseData = null, bool $exact = false) { if (is_null($structure)) { return $this->assertSimilar($this->decoded); } if (! is_null($responseData)) { return (new static($responseData))->assertStructure($structure, null, $exact); } if ($exact) { PHPUnit::assertIsArray($this->decoded); $keys = collect($structure)->map(fn ($value, $key) => is_array($value) ? $key : $value)->values(); if ($keys->all() !== ['*']) { PHPUnit::assertEquals($keys->sort()->values()->all(), collect($this->decoded)->keys()->sort()->values()->all()); } } foreach ($structure as $key => $value) { if (is_array($value) && $key === '*') { PHPUnit::assertIsArray($this->decoded); foreach ($this->decoded as $responseDataItem) { $this->assertStructure($structure['*'], $responseDataItem, $exact); } } elseif (is_array($value)) { PHPUnit::assertArrayHasKey($key, $this->decoded); $this->assertStructure($structure[$key], $this->decoded[$key], $exact); } else { PHPUnit::assertArrayHasKey($value, $this->decoded); } } return $this; }
195219
public function build($concrete) { // If the concrete type is actually a Closure, we will just execute it and // hand back the results of the functions, which allows functions to be // used as resolvers for more fine-tuned resolution of these objects. if ($concrete instanceof Closure) { $this->buildStack[] = spl_object_hash($concrete); try { return $concrete($this, $this->getLastParameterOverride()); } finally { array_pop($this->buildStack); } } try { $reflector = new ReflectionClass($concrete); } catch (ReflectionException $e) { throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e); } // If the type is not instantiable, the developer is attempting to resolve // an abstract type such as an Interface or Abstract Class and there is // no binding registered for the abstractions so we need to bail out. if (! $reflector->isInstantiable()) { return $this->notInstantiable($concrete); } $this->buildStack[] = $concrete; $constructor = $reflector->getConstructor(); // If there are no constructors, that means there are no dependencies then // we can just resolve the instances of the objects right away, without // resolving any other types or dependencies out of these containers. if (is_null($constructor)) { array_pop($this->buildStack); $this->fireAfterResolvingAttributeCallbacks( $reflector->getAttributes(), $instance = new $concrete ); return $instance; } $dependencies = $constructor->getParameters(); // Once we have all the constructor's parameters we can create each of the // dependency instances and then use the reflection instances to make a // new instance of this class, injecting the created dependencies in. try { $instances = $this->resolveDependencies($dependencies); } catch (BindingResolutionException $e) { array_pop($this->buildStack); throw $e; } array_pop($this->buildStack); $this->fireAfterResolvingAttributeCallbacks( $reflector->getAttributes(), $instance = $reflector->newInstanceArgs($instances) ); return $instance; } /** * Resolve all of the dependencies from the ReflectionParameters. * * @param \ReflectionParameter[] $dependencies * @return array * * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function resolveDependencies(array $dependencies) { $results = []; foreach ($dependencies as $dependency) { // If the dependency has an override for this particular build we will use // that instead as the value. Otherwise, we will continue with this run // of resolutions and let reflection attempt to determine the result. if ($this->hasParameterOverride($dependency)) { $results[] = $this->getParameterOverride($dependency); continue; } $result = null; if (! is_null($attribute = Util::getContextualAttributeFromDependency($dependency))) { $result = $this->resolveFromAttribute($attribute); } // If the class is null, it means the dependency is a string or some other // primitive type which we can not resolve since it is not a class and // we will just bomb out with an error since we have no-where to go. $result ??= is_null(Util::getParameterClassName($dependency)) ? $this->resolvePrimitive($dependency) : $this->resolveClass($dependency); $this->fireAfterResolvingAttributeCallbacks($dependency->getAttributes(), $result); if ($dependency->isVariadic()) { $results = array_merge($results, $result); } else { $results[] = $result; } } return $results; } /** * Determine if the given dependency has a parameter override. * * @param \ReflectionParameter $dependency * @return bool */ protected function hasParameterOverride($dependency) { return array_key_exists( $dependency->name, $this->getLastParameterOverride() ); } /** * Get a parameter override for a dependency. * * @param \ReflectionParameter $dependency * @return mixed */ protected function getParameterOverride($dependency) { return $this->getLastParameterOverride()[$dependency->name]; } /** * Get the last parameter override. * * @return array */ protected function getLastParameterOverride() { return count($this->with) ? end($this->with) : []; } /** * Resolve a non-class hinted primitive dependency. * * @param \ReflectionParameter $parameter * @return mixed * * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function resolvePrimitive(ReflectionParameter $parameter) { if (! is_null($concrete = $this->getContextualConcrete('$'.$parameter->getName()))) { return Util::unwrapIfClosure($concrete, $this); } if ($parameter->isDefaultValueAvailable()) { return $parameter->getDefaultValue(); } if ($parameter->isVariadic()) { return []; } if ($parameter->hasType() && $parameter->allowsNull()) { return null; } $this->unresolvablePrimitive($parameter); } /** * Resolve a class based dependency from the container. * * @param \ReflectionParameter $parameter * @return mixed * * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function resolveClass(ReflectionParameter $parameter) { try { return $parameter->isVariadic() ? $this->resolveVariadicClass($parameter) : $this->make(Util::getParameterClassName($parameter)); } // If we can not resolve the class instance, we will check to see if the value // is optional, and if it is we will return the optional parameter value as // the value of the dependency, similarly to how we do this with scalars. catch (BindingResolutionException $e) { if ($parameter->isDefaultValueAvailable()) { array_pop($this->with); return $parameter->getDefaultValue(); } if ($parameter->isVariadic()) { array_pop($this->with); return []; } throw $e; } } /** * Resolve a class based variadic dependency from the container. * * @param \ReflectionParameter $parameter * @return mixed */ protected function resolveVariadicClass(ReflectionParameter $parameter) { $className = Util::getParameterClassName($parameter); $abstract = $this->getAlias($className); if (! is_array($concrete = $this->getContextualConcrete($abstract))) { return $this->make($className); } return array_map(fn ($abstract) => $this->resolve($abstract), $concrete); } /** * Resolve a dependency based on an attribute. * * @param \ReflectionAttribute $attribute * @return mixed */ public function resolveFromAttribute(ReflectionAttribute $attribute) { $handler = $this->contextualAttributes[$attribute->getName()] ?? null; $instance = $attribute->newInstance(); if (is_null($handler) && method_exists($instance, 'resolve')) { $handler = $instance->resolve(...); } if (is_null($handler)) { throw new BindingResolutionException("Contextual binding attribute [{$attribute->getName()}] has no registered handler."); } return $handler($instance, $this); } /** * Throw an exception that the concrete is not instantiable. * * @param string $concrete * @return void * * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function notInstantiable($concrete) { if (! empty($this->buildStack)) { $previous = implode(', ', $this->buildStack); $message = "Target [$concrete] is not instantiable while building [$previous]."; } else { $message = "Target [$concrete] is not instantiable."; } throw new BindingResolutionException($message); } /** * Throw an exception for an unresolvable primitive. * * @param \ReflectionParameter $parameter * @return void * * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function unresolvablePrimitive(ReflectionParameter $parameter) { $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}"; throw new BindingResolutionException($message); }
195222
<?php namespace Illuminate\Container; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Container\ContextualBindingBuilder as ContextualBindingBuilderContract; class ContextualBindingBuilder implements ContextualBindingBuilderContract { /** * The underlying container instance. * * @var \Illuminate\Contracts\Container\Container */ protected $container; /** * The concrete instance. * * @var string|array */ protected $concrete; /** * The abstract target. * * @var string */ protected $needs; /** * Create a new contextual binding builder. * * @param \Illuminate\Contracts\Container\Container $container * @param string|array $concrete * @return void */ public function __construct(Container $container, $concrete) { $this->concrete = $concrete; $this->container = $container; } /** * Define the abstract target that depends on the context. * * @param string $abstract * @return $this */ public function needs($abstract) { $this->needs = $abstract; return $this; } /** * Define the implementation for the contextual binding. * * @param \Closure|string|array $implementation * @return void */ public function give($implementation) { foreach (Util::arrayWrap($this->concrete) as $concrete) { $this->container->addContextualBinding($concrete, $this->needs, $implementation); } } /** * Define tagged services to be used as the implementation for the contextual binding. * * @param string $tag * @return void */ public function giveTagged($tag) { $this->give(function ($container) use ($tag) { $taggedServices = $container->tagged($tag); return is_array($taggedServices) ? $taggedServices : iterator_to_array($taggedServices); }); } /** * Specify the configuration item to bind as a primitive. * * @param string $key * @param mixed $default * @return void */ public function giveConfig($key, $default = null) { $this->give(fn ($container) => $container->get('config')->get($key, $default)); } }
195278
class ValidatedInput implements ValidatedData { /** * The underlying input. * * @var array */ protected $input; /** * Create a new validated input container. * * @param array $input * @return void */ public function __construct(array $input) { $this->input = $input; } /** * Determine if the validated input has one or more keys. * * @param string|array $key * @return bool */ public function exists($key) { return $this->has($key); } /** * 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->all(), $key)) { return false; } } return true; } /** * Determine if the validated input contains any of the given keys. * * @param string|array $keys * @return bool */ public function hasAny($keys) { $keys = is_array($keys) ? $keys : func_get_args(); $input = $this->all(); return Arr::hasAny($input, $keys); } /** * Determine if the validated input is missing one or more keys. * * @param mixed $keys * @return bool */ public function missing($keys) { return ! $this->has($keys); } /** * Apply the callback if the validated input is missing the given input item key. * * @param string $key * @param callable $callback * @param callable|null $default * @return $this|mixed */ public function whenMissing($key, callable $callback, ?callable $default = null) { if ($this->missing($key)) { return $callback(data_get($this->all(), $key)) ?: $this; } if ($default) { return $default(); } return $this; } /** * Retrieve input from the validated input as a Stringable instance. * * @param string $key * @param mixed $default * @return \Illuminate\Support\Stringable */ public function str($key, $default = null) { return $this->string($key, $default); } /** * Retrieve input from the validated input as a Stringable instance. * * @param string $key * @param mixed $default * @return \Illuminate\Support\Stringable */ public function string($key, $default = null) { return str($this->input($key, $default)); } /** * 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->all(); $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->all(); 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->all(), $items)); } /** * Get the input as a collection. * * @param array|string|null $key * @return \Illuminate\Support\Collection */ public function collect($key = null) { return collect(is_array($key) ? $this->only($key) : $this->input($key)); } /** * Get the raw, underlying input array. * * @return array */ public function all() { return $this->input; } /** * Apply the callback if the validated inputs contains the given input item key. * * @param string $key * @param callable $callback * @param callable|null $default * @return $this|mixed */ public function whenHas($key, callable $callback, ?callable $default = null) { if ($this->has($key)) { return $callback(data_get($this->all(), $key)) ?: $this; } if ($default) { return $default(); } return $this; } /** * Determine if the validated inputs contains a non-empty value for an input item. * * @param string|array $key * @return bool */ public function filled($key) { $keys = is_array($key) ? $key : func_get_args(); foreach ($keys as $value) { if ($this->isEmptyString($value)) { return false; } } return true; } /** * Determine if the validated inputs contains an empty value for an input item. * * @param string|array $key * @return bool */ public function isNotFilled($key) { $keys = is_array($key) ? $key : func_get_args(); foreach ($keys as $value) { if (! $this->isEmptyString($value)) { return false; } } return true; } /** * Determine if the validated inputs contains a non-empty value for any of the given inputs. * * @param string|array $keys * @return bool */ public function anyFilled($keys) { $keys = is_array($keys) ? $keys : func_get_args(); foreach ($keys as $key) { if ($this->filled($key)) { return true; } } return false; } /** * Apply the callback if the validated inputs contains a non-empty value for the given input item key. * * @param string $key * @param callable $callback * @param callable|null $default * @return $this|mixed */ public function whenFilled($key, callable $callback, ?callable $default = null) { if ($this->filled($key)) { return $callback(data_get($this->all(), $key)) ?: $this; } if ($default) { return $default(); } return $this; } /** * Determine if the given input key is an empty string for "filled". * * @param string $key * @return bool */ protected function isEmptyString($key) { $value = $this->input($key); return ! is_bool($value) && ! is_array($value) && trim((string) $value) === ''; } /** * Get the keys for all of the input. * * @return array */ public function keys() { return array_keys($this->input()); } /** * Retrieve an input item from the validated inputs. * * @param string|null $key * @param mixed $default * @return mixed */ public function input($key = null, $default = null) { return data_get( $this->all(), $key, $default ); } /** * Retrieve input as a boolean value. * * Returns true when value is "1", "true", "on", and "yes". Otherwise, returns false. * * @param string|null $key * @param bool $default * @return bool */ public function boolean($key = null, $default = false) { return filter_var($this->input($key, $default), FILTER_VALIDATE_BOOLEAN); }
195280
<?php namespace Illuminate\Support; use Closure; use Illuminate\Filesystem\Filesystem; use RuntimeException; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\Process; class Composer { /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * The working path to regenerate from. * * @var string|null */ protected $workingPath; /** * Create a new Composer manager instance. * * @param \Illuminate\Filesystem\Filesystem $files * @param string|null $workingPath * @return void */ public function __construct(Filesystem $files, $workingPath = null) { $this->files = $files; $this->workingPath = $workingPath; } /** * Determine if the given Composer package is installed. * * @param string $package * @return bool * * @throw \RuntimeException */ protected function hasPackage($package) { $composer = json_decode(file_get_contents($this->findComposerFile()), true); return array_key_exists($package, $composer['require'] ?? []) || array_key_exists($package, $composer['require-dev'] ?? []); } /** * Install the given Composer packages into the application. * * @param array<int, string> $packages * @param bool $dev * @param \Closure|\Symfony\Component\Console\Output\OutputInterface|null $output * @param string|null $composerBinary * @return bool */ public function requirePackages(array $packages, bool $dev = false, Closure|OutputInterface|null $output = null, $composerBinary = null) { $command = collect([ ...$this->findComposer($composerBinary), 'require', ...$packages, ]) ->when($dev, function ($command) { $command->push('--dev'); })->all(); return 0 === $this->getProcess($command, ['COMPOSER_MEMORY_LIMIT' => '-1']) ->run( $output instanceof OutputInterface ? function ($type, $line) use ($output) { $output->write(' '.$line); } : $output ); } /** * Remove the given Composer packages from the application. * * @param array<int, string> $packages * @param bool $dev * @param \Closure|\Symfony\Component\Console\Output\OutputInterface|null $output * @param string|null $composerBinary * @return bool */ public function removePackages(array $packages, bool $dev = false, Closure|OutputInterface|null $output = null, $composerBinary = null) { $command = collect([ ...$this->findComposer($composerBinary), 'remove', ...$packages, ]) ->when($dev, function ($command) { $command->push('--dev'); })->all(); return 0 === $this->getProcess($command, ['COMPOSER_MEMORY_LIMIT' => '-1']) ->run( $output instanceof OutputInterface ? function ($type, $line) use ($output) { $output->write(' '.$line); } : $output ); } /** * Modify the "composer.json" file contents using the given callback. * * @param callable(array):array $callback * @return void * * @throw \RuntimeException */ public function modify(callable $callback) { $composerFile = $this->findComposerFile(); $composer = json_decode(file_get_contents($composerFile), true, 512, JSON_THROW_ON_ERROR); file_put_contents( $composerFile, json_encode( call_user_func($callback, $composer), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ); } /** * Regenerate the Composer autoloader files. * * @param string|array $extra * @param string|null $composerBinary * @return int */ public function dumpAutoloads($extra = '', $composerBinary = null) { $extra = $extra ? (array) $extra : []; $command = array_merge($this->findComposer($composerBinary), ['dump-autoload'], $extra); return $this->getProcess($command)->run(); } /** * Regenerate the optimized Composer autoloader files. * * @param string|null $composerBinary * @return int */ public function dumpOptimized($composerBinary = null) { return $this->dumpAutoloads('--optimize', $composerBinary); } /** * Get the Composer binary / command for the environment. * * @param string|null $composerBinary * @return array */ public function findComposer($composerBinary = null) { if (! is_null($composerBinary) && $this->files->exists($composerBinary)) { return [$this->phpBinary(), $composerBinary]; } elseif ($this->files->exists($this->workingPath.'/composer.phar')) { return [$this->phpBinary(), 'composer.phar']; } return ['composer']; } /** * Get the path to the "composer.json" file. * * @return string * * @throw \RuntimeException */ protected function findComposerFile() { $composerFile = "{$this->workingPath}/composer.json"; if (! file_exists($composerFile)) { throw new RuntimeException("Unable to locate `composer.json` file at [{$this->workingPath}]."); } return $composerFile; } /** * Get the PHP binary. * * @return string */ protected function phpBinary() { return php_binary(); } /** * Get a new Symfony process instance. * * @param array $command * @param array $env * @return \Symfony\Component\Process\Process */ protected function getProcess(array $command, array $env = []) { return (new Process($command, $this->workingPath, $env))->setTimeout(null); } /** * Set the working path used by the class. * * @param string $path * @return $this */ public function setWorkingPath($path) { $this->workingPath = realpath($path); return $this; } /** * Get the version of Composer. * * @return string|null */ public function getVersion() { $command = array_merge($this->findComposer(), ['-V', '--no-ansi']); $process = $this->getProcess($command); $process->run(); $output = $process->getOutput(); if (preg_match('/(\d+(\.\d+){2})/', $output, $version)) { return $version[1]; } return explode(' ', $output)[2] ?? null; } }
195284
<?php namespace Illuminate\Support; use Carbon\Factory; use InvalidArgumentException; /** * @see https://carbon.nesbot.com/docs/ * @see https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Factory.php * * @method \Illuminate\Support\Carbon create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null) * @method \Illuminate\Support\Carbon createFromDate($year = null, $month = null, $day = null, $tz = null) * @method \Illuminate\Support\Carbon|false createFromFormat($format, $time, $tz = null) * @method \Illuminate\Support\Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null) * @method \Illuminate\Support\Carbon createFromTimeString($time, $tz = null) * @method \Illuminate\Support\Carbon createFromTimestamp($timestamp, $tz = null) * @method \Illuminate\Support\Carbon createFromTimestampMs($timestamp, $tz = null) * @method \Illuminate\Support\Carbon createFromTimestampUTC($timestamp) * @method \Illuminate\Support\Carbon createMidnightDate($year = null, $month = null, $day = null, $tz = null) * @method \Illuminate\Support\Carbon|false createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) * @method void disableHumanDiffOption($humanDiffOption) * @method void enableHumanDiffOption($humanDiffOption) * @method mixed executeWithLocale($locale, $func) * @method \Illuminate\Support\Carbon fromSerialized($value) * @method array getAvailableLocales() * @method array getDays() * @method int getHumanDiffOptions() * @method array getIsoUnits() * @method array getLastErrors() * @method string getLocale() * @method int getMidDayAt() * @method \Illuminate\Support\Carbon|null getTestNow() * @method \Symfony\Component\Translation\TranslatorInterface getTranslator() * @method int getWeekEndsAt() * @method int getWeekStartsAt() * @method array getWeekendDays() * @method bool hasFormat($date, $format) * @method bool hasMacro($name) * @method bool hasRelativeKeywords($time) * @method bool hasTestNow() * @method \Illuminate\Support\Carbon instance($date) * @method bool isImmutable() * @method bool isModifiableUnit($unit) * @method bool isMutable() * @method bool isStrictModeEnabled() * @method bool localeHasDiffOneDayWords($locale) * @method bool localeHasDiffSyntax($locale) * @method bool localeHasDiffTwoDayWords($locale) * @method bool localeHasPeriodSyntax($locale) * @method bool localeHasShortUnits($locale) * @method void macro($name, $macro) * @method \Illuminate\Support\Carbon|null make($var) * @method \Illuminate\Support\Carbon maxValue() * @method \Illuminate\Support\Carbon minValue() * @method void mixin($mixin) * @method \Illuminate\Support\Carbon now($tz = null) * @method \Illuminate\Support\Carbon parse($time = null, $tz = null) * @method string pluralUnit(string $unit) * @method void resetMonthsOverflow() * @method void resetToStringFormat() * @method void resetYearsOverflow() * @method void serializeUsing($callback) * @method void setHumanDiffOptions($humanDiffOptions) * @method bool setLocale($locale) * @method void setMidDayAt($hour) * @method void setTestNow($testNow = null) * @method void setToStringFormat($format) * @method void setTranslator(\Symfony\Component\Translation\TranslatorInterface $translator) * @method void setUtf8($utf8) * @method void setWeekEndsAt($day) * @method void setWeekStartsAt($day) * @method void setWeekendDays($days) * @method bool shouldOverflowMonths() * @method bool shouldOverflowYears() * @method string singularUnit(string $unit) * @method \Illuminate\Support\Carbon today($tz = null) * @method \Illuminate\Support\Carbon tomorrow($tz = null) * @method void useMonthsOverflow($monthsOverflow = true) * @method void useStrictMode($strictModeEnabled = true) * @method void useYearsOverflow($yearsOverflow = true) * @method \Illuminate\Support\Carbon yesterday($tz = null) */ class DateFactory { /** * The default class that will be used for all created dates. * * @var string */ const DEFAULT_CLASS_NAME = Carbon::class; /** * The type (class) of dates that should be created. * * @var string */ protected static $dateClass; /** * This callable may be used to intercept date creation. * * @var callable */ protected static $callable; /** * The Carbon factory that should be used when creating dates. * * @var object */ protected static $factory; /** * Use the given handler when generating dates (class name, callable, or factory). * * @param mixed $handler * @return mixed * * @throws \InvalidArgumentException */ public static function use($handler) { if (is_callable($handler) && is_object($handler)) { return static::useCallable($handler); } elseif (is_string($handler)) { return static::useClass($handler); } elseif ($handler instanceof Factory) { return static::useFactory($handler); } throw new InvalidArgumentException('Invalid date creation handler. Please provide a class name, callable, or Carbon factory.'); } /** * Use the default date class when generating dates. * * @return void */ public static function useDefault() { static::$dateClass = null; static::$callable = null; static::$factory = null; } /** * Execute the given callable on each date creation. * * @param callable $callable * @return void */ public static function useCallable(callable $callable) { static::$callable = $callable; static::$dateClass = null; static::$factory = null; } /** * Use the given date type (class) when generating dates. * * @param string $dateClass * @return void */ public static function useClass($dateClass) { static::$dateClass = $dateClass; static::$factory = null; static::$callable = null; } /** * Use the given Carbon factory when generating dates. * * @param object $factory * @return void */ public static function useFactory($factory) { static::$factory = $factory; static::$dateClass = null; static::$callable = null; } /** * Handle dynamic calls to generate dates. * * @param string $method * @param array $parameters * @return mixed * * @throws \RuntimeException */ public function __call($method, $parameters) { $defaultClassName = static::DEFAULT_CLASS_NAME; // Using callable to generate dates... if (static::$callable) { return call_user_func(static::$callable, $defaultClassName::$method(...$parameters)); } // Using Carbon factory to generate dates... if (static::$factory) { return static::$factory->$method(...$parameters); } $dateClass = static::$dateClass ?: $defaultClassName; // Check if the date can be created using the public class method... if (method_exists($dateClass, $method) || method_exists($dateClass, 'hasMacro') && $dateClass::hasMacro($method)) { return $dateClass::$method(...$parameters); } // If that fails, create the date with the default class... $date = $defaultClassName::$method(...$parameters); // If the configured class has an "instance" method, we'll try to pass our date into there... if (method_exists($dateClass, 'instance')) { return $dateClass::instance($date); } // Otherwise, assume the configured class has a DateTime compatible constructor... return new $dateClass($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } }
195343
<?php namespace Illuminate\Support\Facades; use Laravel\Ui\UiServiceProvider; use RuntimeException; /** * @method static \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard guard(string|null $name = null) * @method static \Illuminate\Auth\SessionGuard createSessionDriver(string $name, array $config) * @method static \Illuminate\Auth\TokenGuard createTokenDriver(string $name, array $config) * @method static string getDefaultDriver() * @method static void shouldUse(string $name) * @method static void setDefaultDriver(string $name) * @method static \Illuminate\Auth\AuthManager viaRequest(string $driver, callable $callback) * @method static \Closure userResolver() * @method static \Illuminate\Auth\AuthManager resolveUsersUsing(\Closure $userResolver) * @method static \Illuminate\Auth\AuthManager extend(string $driver, \Closure $callback) * @method static \Illuminate\Auth\AuthManager provider(string $name, \Closure $callback) * @method static bool hasResolvedGuards() * @method static \Illuminate\Auth\AuthManager forgetGuards() * @method static \Illuminate\Auth\AuthManager setApplication(\Illuminate\Contracts\Foundation\Application $app) * @method static \Illuminate\Contracts\Auth\UserProvider|null createUserProvider(string|null $provider = null) * @method static string getDefaultUserProvider() * @method static bool check() * @method static bool guest() * @method static \Illuminate\Contracts\Auth\Authenticatable|null user() * @method static int|string|null id() * @method static bool validate(array $credentials = []) * @method static bool hasUser() * @method static \Illuminate\Contracts\Auth\Guard setUser(\Illuminate\Contracts\Auth\Authenticatable $user) * @method static bool attempt(array $credentials = [], bool $remember = false) * @method static bool once(array $credentials = []) * @method static void login(\Illuminate\Contracts\Auth\Authenticatable $user, bool $remember = false) * @method static \Illuminate\Contracts\Auth\Authenticatable|false loginUsingId(mixed $id, bool $remember = false) * @method static \Illuminate\Contracts\Auth\Authenticatable|false onceUsingId(mixed $id) * @method static bool viaRemember() * @method static void logout() * @method static \Symfony\Component\HttpFoundation\Response|null basic(string $field = 'email', array $extraConditions = []) * @method static \Symfony\Component\HttpFoundation\Response|null onceBasic(string $field = 'email', array $extraConditions = []) * @method static bool attemptWhen(array $credentials = [], array|callable|null $callbacks = null, bool $remember = false) * @method static void logoutCurrentDevice() * @method static \Illuminate\Contracts\Auth\Authenticatable|null logoutOtherDevices(string $password) * @method static void attempting(mixed $callback) * @method static \Illuminate\Contracts\Auth\Authenticatable getLastAttempted() * @method static string getName() * @method static string getRecallerName() * @method static \Illuminate\Auth\SessionGuard setRememberDuration(int $minutes) * @method static \Illuminate\Contracts\Cookie\QueueingFactory getCookieJar() * @method static void setCookieJar(\Illuminate\Contracts\Cookie\QueueingFactory $cookie) * @method static \Illuminate\Contracts\Events\Dispatcher getDispatcher() * @method static void setDispatcher(\Illuminate\Contracts\Events\Dispatcher $events) * @method static \Illuminate\Contracts\Session\Session getSession() * @method static \Illuminate\Contracts\Auth\Authenticatable|null getUser() * @method static \Symfony\Component\HttpFoundation\Request getRequest() * @method static \Illuminate\Auth\SessionGuard setRequest(\Symfony\Component\HttpFoundation\Request $request) * @method static \Illuminate\Support\Timebox getTimebox() * @method static \Illuminate\Contracts\Auth\Authenticatable authenticate() * @method static \Illuminate\Auth\SessionGuard forgetUser() * @method static \Illuminate\Contracts\Auth\UserProvider getProvider() * @method static void setProvider(\Illuminate\Contracts\Auth\UserProvider $provider) * @method static void macro(string $name, object|callable $macro) * @method static void mixin(object $mixin, bool $replace = true) * @method static bool hasMacro(string $name) * @method static void flushMacros() * * @see \Illuminate\Auth\AuthManager * @see \Illuminate\Auth\SessionGuard */ class Auth extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'auth'; } /** * Register the typical authentication routes for an application. * * @param array $options * @return void * * @throws \RuntimeException */ public static function routes(array $options = []) { if (! static::$app->providerIsLoaded(UiServiceProvider::class)) { throw new RuntimeException('In order to use the Auth::routes() method, please install the laravel/ui package.'); } static::$app->make('router')->auth($options); } }
195363
<?php namespace Illuminate\Support\Facades; use Illuminate\Database\Console\Migrations\FreshCommand; use Illuminate\Database\Console\Migrations\RefreshCommand; use Illuminate\Database\Console\Migrations\ResetCommand; use Illuminate\Database\Console\WipeCommand; /** * @method static \Illuminate\Database\Connection connection(string|null $name = null) * @method static \Illuminate\Database\ConnectionInterface connectUsing(string $name, array $config, bool $force = false) * @method static void purge(string|null $name = null) * @method static void disconnect(string|null $name = null) * @method static \Illuminate\Database\Connection reconnect(string|null $name = null) * @method static mixed usingConnection(string $name, callable $callback) * @method static string getDefaultConnection() * @method static void setDefaultConnection(string $name) * @method static string[] supportedDrivers() * @method static string[] availableDrivers() * @method static void extend(string $name, callable $resolver) * @method static void forgetExtension(string $name) * @method static array getConnections() * @method static void setReconnector(callable $reconnector) * @method static \Illuminate\Database\DatabaseManager setApplication(\Illuminate\Contracts\Foundation\Application $app) * @method static void macro(string $name, object|callable $macro) * @method static void mixin(object $mixin, bool $replace = true) * @method static bool hasMacro(string $name) * @method static void flushMacros() * @method static mixed macroCall(string $method, array $parameters) * @method static void useDefaultQueryGrammar() * @method static void useDefaultSchemaGrammar() * @method static void useDefaultPostProcessor() * @method static \Illuminate\Database\Schema\Builder getSchemaBuilder() * @method static \Illuminate\Database\Query\Builder table(\Closure|\Illuminate\Database\Query\Builder|\Illuminate\Contracts\Database\Query\Expression|string $table, string|null $as = null) * @method static \Illuminate\Database\Query\Builder query() * @method static mixed selectOne(string $query, array $bindings = [], bool $useReadPdo = true) * @method static mixed scalar(string $query, array $bindings = [], bool $useReadPdo = true) * @method static array selectFromWriteConnection(string $query, array $bindings = []) * @method static array select(string $query, array $bindings = [], bool $useReadPdo = true) * @method static array selectResultSets(string $query, array $bindings = [], bool $useReadPdo = true) * @method static \Generator cursor(string $query, array $bindings = [], bool $useReadPdo = true) * @method static bool insert(string $query, array $bindings = []) * @method static int update(string $query, array $bindings = []) * @method static int delete(string $query, array $bindings = []) * @method static bool statement(string $query, array $bindings = []) * @method static int affectingStatement(string $query, array $bindings = []) * @method static bool unprepared(string $query) * @method static int|null threadCount() * @method static array pretend(\Closure $callback) * @method static mixed withoutPretending(\Closure $callback) * @method static void bindValues(\PDOStatement $statement, array $bindings) * @method static array prepareBindings(array $bindings) * @method static void logQuery(string $query, array $bindings, float|null $time = null) * @method static void whenQueryingForLongerThan(\DateTimeInterface|\Carbon\CarbonInterval|float|int $threshold, callable $handler) * @method static void allowQueryDurationHandlersToRunAgain() * @method static float totalQueryDuration() * @method static void resetTotalQueryDuration() * @method static void reconnectIfMissingConnection() * @method static \Illuminate\Database\Connection beforeStartingTransaction(\Closure $callback) * @method static \Illuminate\Database\Connection beforeExecuting(\Closure $callback) * @method static void listen(\Closure $callback) * @method static \Illuminate\Contracts\Database\Query\Expression raw(mixed $value) * @method static string escape(string|float|int|bool|null $value, bool $binary = false) * @method static bool hasModifiedRecords() * @method static void recordsHaveBeenModified(bool $value = true) * @method static \Illuminate\Database\Connection setRecordModificationState(bool $value) * @method static void forgetRecordModificationState() * @method static \Illuminate\Database\Connection useWriteConnectionWhenReading(bool $value = true) * @method static \PDO getPdo() * @method static \PDO|\Closure|null getRawPdo() * @method static \PDO getReadPdo() * @method static \PDO|\Closure|null getRawReadPdo() * @method static \Illuminate\Database\Connection setPdo(\PDO|\Closure|null $pdo) * @method static \Illuminate\Database\Connection setReadPdo(\PDO|\Closure|null $pdo) * @method static string|null getName() * @method static string|null getNameWithReadWriteType() * @method static mixed getConfig(string|null $option = null) * @method static string getDriverName() * @method static string getDriverTitle() * @method static \Illuminate\Database\Query\Grammars\Grammar getQueryGrammar() * @method static \Illuminate\Database\Connection setQueryGrammar(\Illuminate\Database\Query\Grammars\Grammar $grammar) * @method static \Illuminate\Database\Schema\Grammars\Grammar getSchemaGrammar() * @method static \Illuminate\Database\Connection setSchemaGrammar(\Illuminate\Database\Schema\Grammars\Grammar $grammar) * @method static \Illuminate\Database\Query\Processors\Processor getPostProcessor() * @method static \Illuminate\Database\Connection setPostProcessor(\Illuminate\Database\Query\Processors\Processor $processor) * @method static \Illuminate\Contracts\Events\Dispatcher getEventDispatcher() * @method static \Illuminate\Database\Connection setEventDispatcher(\Illuminate\Contracts\Events\Dispatcher $events) * @method static void unsetEventDispatcher() * @method static \Illuminate\Database\Connection setTransactionManager(\Illuminate\Database\DatabaseTransactionsManager $manager) * @method static void unsetTransactionManager() * @method static bool pretending() * @method static array getQueryLog() * @method static array getRawQueryLog() * @method static void flushQueryLog() * @method static void enableQueryLog() * @method static void disableQueryLog() * @method static bool logging() * @method static string getDatabaseName() * @method static \Illuminate\Database\Connection setDatabaseName(string $database) * @method static \Illuminate\Database\Connection setReadWriteType(string|null $readWriteType) * @method static string getTablePrefix() * @method static \Illuminate\Database\Connection setTablePrefix(string $prefix) * @method static void withTablePrefix(\Illuminate\Database\Grammar $grammar) * @method static string getServerVersion() * @method static void resolverFor(string $driver, \Closure $callback) * @method static \Closure|null getResolver(string $driver) * @method static mixed transaction(\Closure $callback, int $attempts = 1) * @method static void beginTransaction() * @method static void commit() * @method static void rollBack(int|null $toLevel = null) * @method static int transactionLevel() * @method static void afterCommit(callable $callback) * * @see \Illuminate\Database\DatabaseManager */ class DB extends Facade { /** * Indicate if destructive Artisan commands should be prohibited. * * Prohibits: db:wipe, migrate:fresh, migrate:refresh, and migrate:reset * * @param bool $prohibit * @return void */ public static function prohibitDestructiveCommands(bool $prohibit = true) { FreshCommand::prohibit($prohibit); RefreshCommand::prohibit($prohibit); ResetCommand::prohibit($prohibit); WipeCommand::prohibit($prohibit); } /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'db'; } }
195383
abstract class Facade { /** * The application instance being facaded. * * @var \Illuminate\Contracts\Foundation\Application|null */ protected static $app; /** * The resolved object instances. * * @var array */ protected static $resolvedInstance; /** * Indicates if the resolved instance should be cached. * * @var bool */ protected static $cached = true; /** * Run a Closure when the facade has been resolved. * * @param \Closure $callback * @return void */ public static function resolved(Closure $callback) { $accessor = static::getFacadeAccessor(); if (static::$app->resolved($accessor) === true) { $callback(static::getFacadeRoot(), static::$app); } static::$app->afterResolving($accessor, function ($service, $app) use ($callback) { $callback($service, $app); }); } /** * Convert the facade into a Mockery spy. * * @return \Mockery\MockInterface */ public static function spy() { if (! static::isMock()) { $class = static::getMockableClass(); return tap($class ? Mockery::spy($class) : Mockery::spy(), function ($spy) { static::swap($spy); }); } } /** * Initiate a partial mock on the facade. * * @return \Mockery\MockInterface */ public static function partialMock() { $name = static::getFacadeAccessor(); $mock = static::isMock() ? static::$resolvedInstance[$name] : static::createFreshMockInstance(); return $mock->makePartial(); } /** * Initiate a mock expectation on the facade. * * @return \Mockery\Expectation */ public static function shouldReceive() { $name = static::getFacadeAccessor(); $mock = static::isMock() ? static::$resolvedInstance[$name] : static::createFreshMockInstance(); return $mock->shouldReceive(...func_get_args()); } /** * Initiate a mock expectation on the facade. * * @return \Mockery\Expectation */ public static function expects() { $name = static::getFacadeAccessor(); $mock = static::isMock() ? static::$resolvedInstance[$name] : static::createFreshMockInstance(); return $mock->expects(...func_get_args()); } /** * Create a fresh mock instance for the given class. * * @return \Mockery\MockInterface */ protected static function createFreshMockInstance() { return tap(static::createMock(), function ($mock) { static::swap($mock); $mock->shouldAllowMockingProtectedMethods(); }); } /** * Create a fresh mock instance for the given class. * * @return \Mockery\MockInterface */ protected static function createMock() { $class = static::getMockableClass(); return $class ? Mockery::mock($class) : Mockery::mock(); } /** * Determines whether a mock is set as the instance of the facade. * * @return bool */ protected static function isMock() { $name = static::getFacadeAccessor(); return isset(static::$resolvedInstance[$name]) && static::$resolvedInstance[$name] instanceof LegacyMockInterface; } /** * Get the mockable class for the bound instance. * * @return string|null */ protected static function getMockableClass() { if ($root = static::getFacadeRoot()) { return get_class($root); } } /** * Hotswap the underlying instance behind the facade. * * @param mixed $instance * @return void */ public static function swap($instance) { static::$resolvedInstance[static::getFacadeAccessor()] = $instance; if (isset(static::$app)) { static::$app->instance(static::getFacadeAccessor(), $instance); } } /** * Determines whether a "fake" has been set as the facade instance. * * @return bool */ public static function isFake() { $name = static::getFacadeAccessor(); return isset(static::$resolvedInstance[$name]) && static::$resolvedInstance[$name] instanceof Fake; } /** * Get the root object behind the facade. * * @return mixed */ public static function getFacadeRoot() { return static::resolveFacadeInstance(static::getFacadeAccessor()); } /** * Get the registered name of the component. * * @return string * * @throws \RuntimeException */ protected static function getFacadeAccessor() { throw new RuntimeException('Facade does not implement getFacadeAccessor method.'); } /** * Resolve the facade root instance from the container. * * @param string $name * @return mixed */ protected static function resolveFacadeInstance($name) { if (isset(static::$resolvedInstance[$name])) { return static::$resolvedInstance[$name]; } if (static::$app) { if (static::$cached) { return static::$resolvedInstance[$name] = static::$app[$name]; } return static::$app[$name]; } } /** * Clear a resolved facade instance. * * @param string $name * @return void */ public static function clearResolvedInstance($name) { unset(static::$resolvedInstance[$name]); } /** * Clear all of the resolved instances. * * @return void */ public static function clearResolvedInstances() { static::$resolvedInstance = []; } /** * Get the application default aliases. * * @return \Illuminate\Support\Collection */ public static function defaultAliases() { return 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, 'Concurrency' => Concurrency::class, 'Config' => Config::class, 'Context' => Context::class, 'Cookie' => Cookie::class, 'Crypt' => Crypt::class, 'Date' => Date::class, 'DB' => DB::class, 'Eloquent' => Model::class, 'Event' => Event::class, 'File' => File::class, 'Gate' => Gate::class, 'Hash' => Hash::class, 'Http' => Http::class, 'Js' => Js::class, 'Lang' => Lang::class, 'Log' => Log::class, 'Mail' => Mail::class, 'Notification' => Notification::class, 'Number' => Number::class, 'Password' => Password::class, 'Process' => Process::class, 'Queue' => Queue::class, 'RateLimiter' => RateLimiter::class, 'Redirect' => Redirect::class, 'Request' => Request::class, 'Response' => Response::class, 'Route' => Route::class, 'Schedule' => Schedule::class, 'Schema' => Schema::class, 'Session' => Session::class, 'Storage' => Storage::class, 'Str' => Str::class, 'URL' => URL::class, 'Validator' => Validator::class, 'View' => View::class, 'Vite' => Vite::class, ]); } /** * Get the application instance behind the facade. * * @return \Illuminate\Contracts\Foundation\Application|null */ public static function getFacadeApplication() { return static::$app; } /** * Set the application instance. * * @param \Illuminate\Contracts\Foundation\Application|null $app * @return void */ public static function setFacadeApplication($app) { static::$app = $app; } /** * Handle dynamic, static calls to the object. * * @param string $method * @param array $args * @return mixed * * @throws \RuntimeException */ public static function __callStatic($method, $args) { $instance = static::getFacadeRoot(); if (! $instance) { throw new RuntimeException('A facade root has not been set.'); } return $instance->$method(...$args); } }
195438
class PendingRequest { use Conditionable, Macroable; /** * The factory instance. * * @var \Illuminate\Http\Client\Factory|null */ protected $factory; /** * The Guzzle client instance. * * @var \GuzzleHttp\Client */ protected $client; /** * The Guzzle HTTP handler. * * @var callable */ protected $handler; /** * The base URL for the request. * * @var string */ protected $baseUrl = ''; /** * The parameters that can be substituted into the URL. * * @var array */ protected $urlParameters = []; /** * The request body format. * * @var string */ protected $bodyFormat; /** * The raw body for the request. * * @var \Psr\Http\Message\StreamInterface|string */ protected $pendingBody; /** * The pending files for the request. * * @var array */ protected $pendingFiles = []; /** * The request cookies. * * @var array */ protected $cookies; /** * The transfer stats for the request. * * @var \GuzzleHttp\TransferStats */ protected $transferStats; /** * The request options. * * @var array */ protected $options = []; /** * A callback to run when throwing if a server or client error occurs. * * @var \Closure */ protected $throwCallback; /** * A callback to check if an exception should be thrown when a server or client error occurs. * * @var \Closure */ protected $throwIfCallback; /** * The number of times to try the request. * * @var int */ protected $tries = 1; /** * The number of milliseconds to wait between retries. * * @var Closure|int */ protected $retryDelay = 100; /** * Whether to throw an exception when all retries fail. * * @var bool */ protected $retryThrow = true; /** * The callback that will determine if the request should be retried. * * @var callable|null */ protected $retryWhenCallback = null; /** * The callbacks that should execute before the request is sent. * * @var \Illuminate\Support\Collection */ protected $beforeSendingCallbacks; /** * The stub callables that will handle requests. * * @var \Illuminate\Support\Collection|null */ protected $stubCallbacks; /** * Indicates that an exception should be thrown if any request is not faked. * * @var bool */ protected $preventStrayRequests = false; /** * The middleware callables added by users that will handle requests. * * @var \Illuminate\Support\Collection */ protected $middleware; /** * Whether the requests should be asynchronous. * * @var bool */ protected $async = false; /** * The pending request promise. * * @var \GuzzleHttp\Promise\PromiseInterface */ protected $promise; /** * The sent request object, if a request has been made. * * @var \Illuminate\Http\Client\Request|null */ protected $request; /** * The Guzzle request options that are mergeable via array_merge_recursive. * * @var array */ protected $mergeableOptions = [ 'cookies', 'form_params', 'headers', 'json', 'multipart', 'query', ]; /** * Create a new HTTP Client instance. * * @param \Illuminate\Http\Client\Factory|null $factory * @param array $middleware * @return void */ public function __construct(?Factory $factory = null, $middleware = []) { $this->factory = $factory; $this->middleware = new Collection($middleware); $this->asJson(); $this->options = [ 'connect_timeout' => 10, 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, 'http_errors' => false, 'timeout' => 30, ]; $this->beforeSendingCallbacks = collect([function (Request $request, array $options, PendingRequest $pendingRequest) { $pendingRequest->request = $request; $pendingRequest->cookies = $options['cookies']; $pendingRequest->dispatchRequestSendingEvent(); }]); } /** * Set the base URL for the pending request. * * @param string $url * @return $this */ public function baseUrl(string $url) { $this->baseUrl = $url; return $this; } /** * Attach a raw body to the request. * * @param \Psr\Http\Message\StreamInterface|string $content * @param string $contentType * @return $this */ public function withBody($content, $contentType = 'application/json') { $this->bodyFormat('body'); $this->pendingBody = $content; $this->contentType($contentType); return $this; } /** * Indicate the request contains JSON. * * @return $this */ public function asJson() { return $this->bodyFormat('json')->contentType('application/json'); } /** * Indicate the request contains form parameters. * * @return $this */ public function asForm() { return $this->bodyFormat('form_params')->contentType('application/x-www-form-urlencoded'); } /** * Attach a file to the request. * * @param string|array $name * @param string|resource $contents * @param string|null $filename * @param array $headers * @return $this */ public function attach($name, $contents = '', $filename = null, array $headers = []) { if (is_array($name)) { foreach ($name as $file) { $this->attach(...$file); } return $this; } $this->asMultipart(); $this->pendingFiles[] = array_filter([ 'name' => $name, 'contents' => $contents, 'headers' => $headers, 'filename' => $filename, ]); return $this; } /** * Indicate the request is a multi-part form request. * * @return $this */ public function asMultipart() { return $this->bodyFormat('multipart'); } /** * Specify the body format of the request. * * @param string $format * @return $this */ public function bodyFormat(string $format) { return tap($this, function () use ($format) { $this->bodyFormat = $format; }); } /** * Set the given query parameters in the request URI. * * @param array $parameters * @return $this */ public function withQueryParameters(array $parameters) { return tap($this, function () use ($parameters) { $this->options = array_merge_recursive($this->options, [ 'query' => $parameters, ]); }); } /** * Specify the request's content type. * * @param string $contentType * @return $this */ public function contentType(string $contentType) { $this->options['headers']['Content-Type'] = $contentType; return $this; } /** * Indicate that JSON should be returned by the server. * * @return $this */ public function acceptJson() { return $this->accept('application/json'); } /** * Indicate the type of content that should be returned by the server. * * @param string $contentType * @return $this */ public function accept($contentType) { return $this->withHeaders(['Accept' => $contentType]); } /** * Add the given headers to the request. * * @param array $headers * @return $this */ public function withHeaders(array $headers) { return tap($this, function () use ($headers) { $this->options = array_merge_recursive($this->options, [ 'headers' => $headers, ]); }); }
195439
/** * Add the given header to the request. * * @param string $name * @param mixed $value * @return $this */ public function withHeader($name, $value) { return $this->withHeaders([$name => $value]); } /** * Replace the given headers on the request. * * @param array $headers * @return $this */ public function replaceHeaders(array $headers) { $this->options['headers'] = array_merge($this->options['headers'] ?? [], $headers); return $this; } /** * Specify the basic authentication username and password for the request. * * @param string $username * @param string $password * @return $this */ public function withBasicAuth(string $username, string $password) { return tap($this, function () use ($username, $password) { $this->options['auth'] = [$username, $password]; }); } /** * Specify the digest authentication username and password for the request. * * @param string $username * @param string $password * @return $this */ public function withDigestAuth($username, $password) { return tap($this, function () use ($username, $password) { $this->options['auth'] = [$username, $password, 'digest']; }); } /** * Specify an authorization token for the request. * * @param string $token * @param string $type * @return $this */ public function withToken($token, $type = 'Bearer') { return tap($this, function () use ($token, $type) { $this->options['headers']['Authorization'] = trim($type.' '.$token); }); } /** * Specify the user agent for the request. * * @param string|bool $userAgent * @return $this */ public function withUserAgent($userAgent) { return tap($this, function () use ($userAgent) { $this->options['headers']['User-Agent'] = trim($userAgent); }); } /** * Specify the URL parameters that can be substituted into the request URL. * * @param array $parameters * @return $this */ public function withUrlParameters(array $parameters = []) { return tap($this, function () use ($parameters) { $this->urlParameters = $parameters; }); } /** * Specify the cookies that should be included with the request. * * @param array $cookies * @param string $domain * @return $this */ public function withCookies(array $cookies, string $domain) { return tap($this, function () use ($cookies, $domain) { $this->options = array_merge_recursive($this->options, [ 'cookies' => CookieJar::fromArray($cookies, $domain), ]); }); } /** * Specify the maximum number of redirects to allow. * * @param int $max * @return $this */ public function maxRedirects(int $max) { return tap($this, function () use ($max) { $this->options['allow_redirects']['max'] = $max; }); } /** * Indicate that redirects should not be followed. * * @return $this */ public function withoutRedirecting() { return tap($this, function () { $this->options['allow_redirects'] = false; }); } /** * Indicate that TLS certificates should not be verified. * * @return $this */ public function withoutVerifying() { return tap($this, function () { $this->options['verify'] = false; }); } /** * Specify the path where the body of the response should be stored. * * @param string|resource $to * @return $this */ public function sink($to) { return tap($this, function () use ($to) { $this->options['sink'] = $to; }); } /** * Specify the timeout (in seconds) for the request. * * @param int $seconds * @return $this */ public function timeout(int $seconds) { return tap($this, function () use ($seconds) { $this->options['timeout'] = $seconds; }); } /** * Specify the connect timeout (in seconds) for the request. * * @param int $seconds * @return $this */ public function connectTimeout(int $seconds) { return tap($this, function () use ($seconds) { $this->options['connect_timeout'] = $seconds; }); } /** * Specify the number of times the request should be attempted. * * @param array|int $times * @param Closure|int $sleepMilliseconds * @param callable|null $when * @param bool $throw * @return $this */ public function retry(array|int $times, Closure|int $sleepMilliseconds = 0, ?callable $when = null, bool $throw = true) { $this->tries = $times; $this->retryDelay = $sleepMilliseconds; $this->retryThrow = $throw; $this->retryWhenCallback = $when; return $this; } /** * Replace the specified options on the request. * * @param array $options * @return $this */ public function withOptions(array $options) { return tap($this, function () use ($options) { $this->options = array_replace_recursive( array_merge_recursive($this->options, Arr::only($options, $this->mergeableOptions)), $options ); }); } /** * Add new middleware the client handler stack. * * @param callable $middleware * @return $this */ public function withMiddleware(callable $middleware) { $this->middleware->push($middleware); return $this; } /** * Add new request middleware the client handler stack. * * @param callable $middleware * @return $this */ public function withRequestMiddleware(callable $middleware) { $this->middleware->push(Middleware::mapRequest($middleware)); return $this; } /** * Add new response middleware the client handler stack. * * @param callable $middleware * @return $this */ public function withResponseMiddleware(callable $middleware) { $this->middleware->push(Middleware::mapResponse($middleware)); return $this; } /** * Add a new "before sending" callback to the request. * * @param callable $callback * @return $this */ public function beforeSending($callback) { return tap($this, function () use ($callback) { $this->beforeSendingCallbacks[] = $callback; }); } /** * Throw an exception if a server or client error occurs. * * @param callable|null $callback * @return $this */ public function throw(?callable $callback = null) { $this->throwCallback = $callback ?: fn () => null; return $this; } /** * Throw an exception if a server or client error occurred and the given condition evaluates to true. * * @param callable|bool $condition * @return $this */ public function throwIf($condition) { if (is_callable($condition)) { $this->throwIfCallback = $condition; } return $condition ? $this->throw(func_get_args()[1] ?? null) : $this; } /** * Throw an exception if a server or client error occurred and the given condition evaluates to false. * * @param callable|bool $condition * @return $this */ public function throwUnless($condition) { return $this->throwIf(! $condition); } /** * Dump the request before sending. * * @return $this */
195440
public function dump() { $values = func_get_args(); return $this->beforeSending(function (Request $request, array $options) use ($values) { foreach (array_merge($values, [$request, $options]) as $value) { VarDumper::dump($value); } }); } /** * Dump the request before sending and end the script. * * @return $this */ public function dd() { $values = func_get_args(); return $this->beforeSending(function (Request $request, array $options) use ($values) { foreach (array_merge($values, [$request, $options]) as $value) { VarDumper::dump($value); } exit(1); }); } /** * Issue a GET request to the given URL. * * @param string $url * @param array|string|null $query * @return \Illuminate\Http\Client\Response * * @throws \Illuminate\Http\Client\ConnectionException */ public function get(string $url, $query = null) { return $this->send('GET', $url, func_num_args() === 1 ? [] : [ 'query' => $query, ]); } /** * Issue a HEAD request to the given URL. * * @param string $url * @param array|string|null $query * @return \Illuminate\Http\Client\Response * * @throws \Illuminate\Http\Client\ConnectionException */ public function head(string $url, $query = null) { return $this->send('HEAD', $url, func_num_args() === 1 ? [] : [ 'query' => $query, ]); } /** * Issue a POST request to the given URL. * * @param string $url * @param array $data * @return \Illuminate\Http\Client\Response * * @throws \Illuminate\Http\Client\ConnectionException */ public function post(string $url, $data = []) { return $this->send('POST', $url, [ $this->bodyFormat => $data, ]); } /** * Issue a PATCH request to the given URL. * * @param string $url * @param array $data * @return \Illuminate\Http\Client\Response * * @throws \Illuminate\Http\Client\ConnectionException */ public function patch(string $url, $data = []) { return $this->send('PATCH', $url, [ $this->bodyFormat => $data, ]); } /** * Issue a PUT request to the given URL. * * @param string $url * @param array $data * @return \Illuminate\Http\Client\Response * * @throws \Illuminate\Http\Client\ConnectionException */ public function put(string $url, $data = []) { return $this->send('PUT', $url, [ $this->bodyFormat => $data, ]); } /** * Issue a DELETE request to the given URL. * * @param string $url * @param array $data * @return \Illuminate\Http\Client\Response * * @throws \Illuminate\Http\Client\ConnectionException */ public function delete(string $url, $data = []) { return $this->send('DELETE', $url, empty($data) ? [] : [ $this->bodyFormat => $data, ]); } /** * Send a pool of asynchronous requests concurrently. * * @param callable $callback * @return array<array-key, \Illuminate\Http\Client\Response> */ public function pool(callable $callback) { $results = []; $requests = tap(new Pool($this->factory), $callback)->getRequests(); foreach ($requests as $key => $item) { $results[$key] = $item instanceof static ? $item->getPromise()->wait() : $item->wait(); } return $results; } /** * Send the request to the given URL. * * @param string $method * @param string $url * @param array $options * @return \Illuminate\Http\Client\Response * * @throws \Exception * @throws \Illuminate\Http\Client\ConnectionException */ public function send(string $method, string $url, array $options = []) { if (! Str::startsWith($url, ['http://', 'https://'])) { $url = ltrim(rtrim($this->baseUrl, '/').'/'.ltrim($url, '/'), '/'); } $url = $this->expandUrlParameters($url); $options = $this->parseHttpOptions($options); [$this->pendingBody, $this->pendingFiles] = [null, []]; if ($this->async) { return $this->makePromise($method, $url, $options); } $shouldRetry = null; return retry($this->tries ?? 1, function ($attempt) use ($method, $url, $options, &$shouldRetry) { try { return tap($this->newResponse($this->sendRequest($method, $url, $options)), function ($response) use ($attempt, &$shouldRetry) { $this->populateResponse($response); $this->dispatchResponseReceivedEvent($response); if (! $response->successful()) { try { $shouldRetry = $this->retryWhenCallback ? call_user_func($this->retryWhenCallback, $response->toException(), $this) : true; } catch (Exception $exception) { $shouldRetry = false; throw $exception; } if ($this->throwCallback && ($this->throwIfCallback === null || call_user_func($this->throwIfCallback, $response))) { $response->throw($this->throwCallback); } $potentialTries = is_array($this->tries) ? count($this->tries) + 1 : $this->tries; if ($attempt < $potentialTries && $shouldRetry) { $response->throw(); } if ($potentialTries > 1 && $this->retryThrow) { $response->throw(); } } }); } catch (ConnectException $e) { $exception = new ConnectionException($e->getMessage(), 0, $e); $this->dispatchConnectionFailedEvent(new Request($e->getRequest()), $exception); throw $exception; } }, $this->retryDelay ?? 100, function ($exception) use (&$shouldRetry) { $result = $shouldRetry ?? ($this->retryWhenCallback ? call_user_func($this->retryWhenCallback, $exception, $this) : true); $shouldRetry = null; return $result; }); } /** * Substitute the URL parameters in the given URL. * * @param string $url * @return string */ protected function expandUrlParameters(string $url) { return UriTemplate::expand($url, $this->urlParameters); } /** * Parse the given HTTP options and set the appropriate additional options. * * @param array $options * @return array */ protected function parseHttpOptions(array $options) { if (isset($options[$this->bodyFormat])) { if ($this->bodyFormat === 'multipart') { $options[$this->bodyFormat] = $this->parseMultipartBodyFormat($options[$this->bodyFormat]); } elseif ($this->bodyFormat === 'body') { $options[$this->bodyFormat] = $this->pendingBody; } if (is_array($options[$this->bodyFormat])) { $options[$this->bodyFormat] = array_merge( $options[$this->bodyFormat], $this->pendingFiles ); } } else { $options[$this->bodyFormat] = $this->pendingBody; } return collect($options)->map(function ($value, $key) { if ($key === 'json' && $value instanceof JsonSerializable) { return $value; } return $value instanceof Arrayable ? $value->toArray() : $value; })->all(); } /** * Parse multi-part form data. * * @param array $data * @return array|array[] */
195441
protected function parseMultipartBodyFormat(array $data) { return collect($data)->map(function ($value, $key) { return is_array($value) ? $value : ['name' => $key, 'contents' => $value]; })->values()->all(); } /** * Send an asynchronous request to the given URL. * * @param string $method * @param string $url * @param array $options * @param int $attempt * @return \GuzzleHttp\Promise\PromiseInterface */ protected function makePromise(string $method, string $url, array $options = [], int $attempt = 1) { return $this->promise = $this->sendRequest($method, $url, $options) ->then(function (MessageInterface $message) { return tap($this->newResponse($message), function ($response) { $this->populateResponse($response); $this->dispatchResponseReceivedEvent($response); }); }) ->otherwise(function (OutOfBoundsException|TransferException $e) { if ($e instanceof ConnectException || ($e instanceof RequestException && ! $e->hasResponse())) { $exception = new ConnectionException($e->getMessage(), 0, $e); $this->dispatchConnectionFailedEvent(new Request($e->getRequest()), $exception); return $exception; } return $e instanceof RequestException && $e->hasResponse() ? $this->populateResponse($this->newResponse($e->getResponse())) : $e; }) ->then(function (Response|ConnectionException|TransferException $response) use ($method, $url, $options, $attempt) { return $this->handlePromiseResponse($response, $method, $url, $options, $attempt); }); } /** * Handle the response of an asynchronous request. * * @param \Illuminate\Http\Client\Response $response * @param string $method * @param string $url * @param array $options * @param int $attempt * @return mixed */ protected function handlePromiseResponse(Response|ConnectionException|TransferException $response, $method, $url, $options, $attempt) { if ($response instanceof Response && $response->successful()) { return $response; } if ($response instanceof RequestException) { $response = $this->populateResponse($this->newResponse($response->getResponse())); } try { $shouldRetry = $this->retryWhenCallback ? call_user_func( $this->retryWhenCallback, $response instanceof Response ? $response->toException() : $response, $this ) : true; } catch (Exception $exception) { return $exception; } if ($attempt < $this->tries && $shouldRetry) { $options['delay'] = value( $this->retryDelay, $attempt, $response instanceof Response ? $response->toException() : $response ); return $this->makePromise($method, $url, $options, $attempt + 1); } if ($response instanceof Response && $this->throwCallback && ($this->throwIfCallback === null || call_user_func($this->throwIfCallback, $response))) { try { $response->throw($this->throwCallback); } catch (Exception $exception) { return $exception; } } if ($this->tries > 1 && $this->retryThrow) { return $response instanceof Response ? $response->toException() : $response; } return $response; } /** * Send a request either synchronously or asynchronously. * * @param string $method * @param string $url * @param array $options * @return \Psr\Http\Message\MessageInterface|\GuzzleHttp\Promise\PromiseInterface * * @throws \Exception */ protected function sendRequest(string $method, string $url, array $options = []) { $clientMethod = $this->async ? 'requestAsync' : 'request'; $laravelData = $this->parseRequestData($method, $url, $options); $onStats = function ($transferStats) { if (($callback = ($this->options['on_stats'] ?? false)) instanceof Closure) { $transferStats = $callback($transferStats) ?: $transferStats; } $this->transferStats = $transferStats; }; $mergedOptions = $this->normalizeRequestOptions($this->mergeOptions([ 'laravel_data' => $laravelData, 'on_stats' => $onStats, ], $options)); return $this->buildClient()->$clientMethod($method, $url, $mergedOptions); } /** * Get the request data as an array so that we can attach it to the request for convenient assertions. * * @param string $method * @param string $url * @param array $options * @return array */ protected function parseRequestData($method, $url, array $options) { if ($this->bodyFormat === 'body') { return []; } $laravelData = $options[$this->bodyFormat] ?? $options['query'] ?? []; $urlString = Str::of($url); if (empty($laravelData) && $method === 'GET' && $urlString->contains('?')) { $laravelData = (string) $urlString->after('?'); } if (is_string($laravelData)) { parse_str($laravelData, $parsedData); $laravelData = is_array($parsedData) ? $parsedData : []; } if ($laravelData instanceof JsonSerializable) { $laravelData = $laravelData->jsonSerialize(); } return is_array($laravelData) ? $laravelData : []; } /** * Normalize the given request options. * * @param array $options * @return array */ protected function normalizeRequestOptions(array $options) { foreach ($options as $key => $value) { $options[$key] = match (true) { is_array($value) => $this->normalizeRequestOptions($value), $value instanceof Stringable => $value->toString(), default => $value, }; } return $options; } /** * Populate the given response with additional data. * * @param \Illuminate\Http\Client\Response $response * @return \Illuminate\Http\Client\Response */ protected function populateResponse(Response $response) { $response->cookies = $this->cookies; $response->transferStats = $this->transferStats; return $response; } /** * Build the Guzzle client. * * @return \GuzzleHttp\Client */ public function buildClient() { return $this->client ?? $this->createClient($this->buildHandlerStack()); } /** * Determine if a reusable client is required. * * @return bool */ protected function requestsReusableClient() { return ! is_null($this->client) || $this->async; } /** * Retrieve a reusable Guzzle client. * * @return \GuzzleHttp\Client */ protected function getReusableClient() { return $this->client ??= $this->createClient($this->buildHandlerStack()); } /** * Create new Guzzle client. * * @param \GuzzleHttp\HandlerStack $handlerStack * @return \GuzzleHttp\Client */ public function createClient($handlerStack) { return new Client([ 'handler' => $handlerStack, 'cookies' => true, ]); } /** * Build the Guzzle client handler stack. * * @return \GuzzleHttp\HandlerStack */ public function buildHandlerStack() { return $this->pushHandlers(HandlerStack::create($this->handler)); } /** * Add the necessary handlers to the given handler stack. * * @param \GuzzleHttp\HandlerStack $handlerStack * @return \GuzzleHttp\HandlerStack */ public function pushHandlers($handlerStack) { return tap($handlerStack, function ($stack) { $this->middleware->each(function ($middleware) use ($stack) { $stack->push($middleware); }); $stack->push($this->buildBeforeSendingHandler()); $stack->push($this->buildRecorderHandler()); $stack->push($this->buildStubHandler()); }); }
195473
{ use Macroable { __call as macroCall; } /** * The view factory instance. * * @var \Illuminate\View\Factory */ protected $factory; /** * The engine implementation. * * @var \Illuminate\Contracts\View\Engine */ protected $engine; /** * The name of the view. * * @var string */ protected $view; /** * The array of view data. * * @var array */ protected $data; /** * The path to the view file. * * @var string */ protected $path; /** * Create a new view instance. * * @param \Illuminate\View\Factory $factory * @param \Illuminate\Contracts\View\Engine $engine * @param string $view * @param string $path * @param mixed $data * @return void */ public function __construct(Factory $factory, Engine $engine, $view, $path, $data = []) { $this->view = $view; $this->path = $path; $this->engine = $engine; $this->factory = $factory; $this->data = $data instanceof Arrayable ? $data->toArray() : (array) $data; } /** * Get the evaluated contents of a given fragment. * * @param string $fragment * @return string */ public function fragment($fragment) { return $this->render(function () use ($fragment) { return $this->factory->getFragment($fragment); }); } /** * Get the evaluated contents for a given array of fragments or return all fragments. * * @param array|null $fragments * @return string */ public function fragments(?array $fragments = null) { return is_null($fragments) ? $this->allFragments() : collect($fragments)->map(fn ($f) => $this->fragment($f))->implode(''); } /** * Get the evaluated contents of a given fragment if the given condition is true. * * @param bool $boolean * @param string $fragment * @return string */ public function fragmentIf($boolean, $fragment) { if (value($boolean)) { return $this->fragment($fragment); } return $this->render(); } /** * Get the evaluated contents for a given array of fragments if the given condition is true. * * @param bool $boolean * @param array|null $fragments * @return string */ public function fragmentsIf($boolean, ?array $fragments = null) { if (value($boolean)) { return $this->fragments($fragments); } return $this->render(); } /** * Get all fragments as a single string. * * @return string */ protected function allFragments() { return collect($this->render(fn () => $this->factory->getFragments()))->implode(''); } /** * Get the string contents of the view. * * @param callable|null $callback * @return string * * @throws \Throwable */ public function render(?callable $callback = null) { try { $contents = $this->renderContents(); $response = isset($callback) ? $callback($this, $contents) : null; // Once we have the contents of the view, we will flush the sections if we are // done rendering all views so that there is nothing left hanging over when // another view gets rendered in the future by the application developer. $this->factory->flushStateIfDoneRendering(); return ! is_null($response) ? $response : $contents; } catch (Throwable $e) { $this->factory->flushState(); throw $e; } } /** * Get the contents of the view instance. * * @return string */ protected function renderContents() { // We will keep track of the number of views being rendered so we can flush // the section after the complete rendering operation is done. This will // clear out the sections for any separate views that may be rendered. $this->factory->incrementRender(); $this->factory->callComposer($this); $contents = $this->getContents(); // Once we've finished rendering the view, we'll decrement the render count // so that each section gets flushed out next time a view is created and // no old sections are staying around in the memory of an environment. $this->factory->decrementRender(); return $contents; } /** * Get the evaluated contents of the view. * * @return string */ protected function getContents() { return $this->engine->get($this->path, $this->gatherData()); } /** * Get the data bound to the view instance. * * @return array */ public function gatherData() { $data = array_merge($this->factory->getShared(), $this->data); foreach ($data as $key => $value) { if ($value instanceof Renderable) { $data[$key] = $value->render(); } } return $data; } /** * Get the sections of the rendered view. * * @return array * * @throws \Throwable */ public function renderSections() { return $this->render(function () { return $this->factory->getSections(); }); } /** * Add a piece of data to the view. * * @param string|array $key * @param mixed $value * @return $this */ public function with($key, $value = null) { if (is_array($key)) { $this->data = array_merge($this->data, $key); } else { $this->data[$key] = $value; } return $this; } /** * Add a view instance to the view data. * * @param string $key * @param string $view * @param array $data * @return $this */ public function nest($key, $view, array $data = []) { return $this->with($key, $this->factory->make($view, $data)); } /** * Add validation errors to the view. * * @param \Illuminate\Contracts\Support\MessageProvider|array $provider * @param string $bag * @return $this */ public function withErrors($provider, $bag = 'default') { return $this->with('errors', (new ViewErrorBag)->put( $bag, $this->formatErrors($provider) )); } /** * Parse the given errors into an appropriate value. * * @param \Illuminate\Contracts\Support\MessageProvider|array|string $provider * @return \Illuminate\Support\MessageBag */ protected function formatErrors($provider) { return $provider instanceof MessageProvider ? $provider->getMessageBag() : new MessageBag((array) $provider); } /** * Get the name of the view. * * @return string */ public function name() { return $this->getName(); } /** * Get the name of the view. * * @return string */ public function getName() { return $this->view; } /** * Get the array of view data. * * @return array */ public function getData() { return $this->data; } /** * Get the path to the view file. * * @return string */ public function getPath() { return $this->path; } /** * Set the path to the view. * * @param string $path * @return void */ public function setPath($path) { $this->path = $path; } /** * Get the view factory instance. * * @return \Illuminate\View\Factory */ public function getFactory() { return $this->factory; } /** * Get the view's rendering engine. * * @return \Illuminate\Contracts\View\Engine */ public function getEngine() { return $this->engine; }
195474
/** * Determine if a piece of data is bound. * * @param string $key * @return bool */ public function offsetExists($key): bool { return array_key_exists($key, $this->data); } /** * Get a piece of bound data to the view. * * @param string $key * @return mixed */ public function offsetGet($key): mixed { return $this->data[$key]; } /** * Set a piece of data on the view. * * @param string $key * @param mixed $value * @return void */ public function offsetSet($key, $value): void { $this->with($key, $value); } /** * Unset a piece of data from the view. * * @param string $key * @return void */ public function offsetUnset($key): void { unset($this->data[$key]); } /** * Get a piece of data from the view. * * @param string $key * @return mixed */ public function &__get($key) { return $this->data[$key]; } /** * Set a piece of data on the view. * * @param string $key * @param mixed $value * @return void */ public function __set($key, $value) { $this->with($key, $value); } /** * Check if a piece of data is bound to the view. * * @param string $key * @return bool */ public function __isset($key) { return isset($this->data[$key]); } /** * Remove a piece of bound data from the view. * * @param string $key * @return void */ public function __unset($key) { unset($this->data[$key]); } /** * Dynamically bind parameters to the view. * * @param string $method * @param array $parameters * @return \Illuminate\View\View * * @throws \BadMethodCallException */ public function __call($method, $parameters) { if (static::hasMacro($method)) { return $this->macroCall($method, $parameters); } if (! str_starts_with($method, 'with')) { throw new BadMethodCallException(sprintf( 'Method %s::%s does not exist.', static::class, $method )); } return $this->with(Str::camel(substr($method, 4)), $parameters[0]); } /** * Get content as a string of HTML. * * @return string */ public function toHtml() { return $this->render(); } /** * Get the string contents of the view. * * @return string * * @throws \Throwable */ public function __toString() { return $this->render(); } }
195478
<?php namespace Illuminate\View\Middleware; use Closure; use Illuminate\Contracts\View\Factory as ViewFactory; use Illuminate\Support\ViewErrorBag; class ShareErrorsFromSession { /** * The view factory implementation. * * @var \Illuminate\Contracts\View\Factory */ protected $view; /** * Create a new error binder instance. * * @param \Illuminate\Contracts\View\Factory $view * @return void */ public function __construct(ViewFactory $view) { $this->view = $view; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // If the current session has an "errors" variable bound to it, we will share // its value with all view instances so the views can easily access errors // without having to bind. An empty bag is set when there aren't errors. $this->view->share( 'errors', $request->session()->get('errors') ?: new ViewErrorBag ); // Putting the errors in the view for every view allows the developer to just // assume that some errors are always available, which is convenient since // they don't have to continually run checks for the presence of errors. return $next($request); } }
195542
class Worker { use DetectsLostConnections; const EXIT_SUCCESS = 0; const EXIT_ERROR = 1; const EXIT_MEMORY_LIMIT = 12; /** * The name of the worker. * * @var string */ protected $name; /** * The queue manager instance. * * @var \Illuminate\Contracts\Queue\Factory */ protected $manager; /** * The event dispatcher instance. * * @var \Illuminate\Contracts\Events\Dispatcher */ protected $events; /** * The cache repository implementation. * * @var \Illuminate\Contracts\Cache\Repository */ protected $cache; /** * The exception handler instance. * * @var \Illuminate\Contracts\Debug\ExceptionHandler */ protected $exceptions; /** * The callback used to determine if the application is in maintenance mode. * * @var callable */ protected $isDownForMaintenance; /** * The callback used to reset the application's scope. * * @var callable */ protected $resetScope; /** * Indicates if the worker should exit. * * @var bool */ public $shouldQuit = false; /** * Indicates if the worker is paused. * * @var bool */ public $paused = false; /** * The callbacks used to pop jobs from queues. * * @var callable[] */ protected static $popCallbacks = []; /** * Create a new queue worker. * * @param \Illuminate\Contracts\Queue\Factory $manager * @param \Illuminate\Contracts\Events\Dispatcher $events * @param \Illuminate\Contracts\Debug\ExceptionHandler $exceptions * @param callable $isDownForMaintenance * @param callable|null $resetScope * @return void */ public function __construct(QueueManager $manager, Dispatcher $events, ExceptionHandler $exceptions, callable $isDownForMaintenance, ?callable $resetScope = null) { $this->events = $events; $this->manager = $manager; $this->exceptions = $exceptions; $this->isDownForMaintenance = $isDownForMaintenance; $this->resetScope = $resetScope; } /** * Listen to the given queue in a loop. * * @param string $connectionName * @param string $queue * @param \Illuminate\Queue\WorkerOptions $options * @return int */ public function daemon($connectionName, $queue, WorkerOptions $options) { if ($supportsAsyncSignals = $this->supportsAsyncSignals()) { $this->listenForSignals(); } $lastRestart = $this->getTimestampOfLastQueueRestart(); [$startTime, $jobsProcessed] = [hrtime(true) / 1e9, 0]; while (true) { // Before reserving any jobs, we will make sure this queue is not paused and // if it is we will just pause this worker for a given amount of time and // make sure we do not need to kill this worker process off completely. if (! $this->daemonShouldRun($options, $connectionName, $queue)) { $status = $this->pauseWorker($options, $lastRestart); if (! is_null($status)) { return $this->stop($status, $options); } continue; } if (isset($this->resetScope)) { ($this->resetScope)(); } // First, we will attempt to get the next job off of the queue. We will also // register the timeout handler and reset the alarm for this job so it is // not stuck in a frozen state forever. Then, we can fire off this job. $job = $this->getNextJob( $this->manager->connection($connectionName), $queue ); if ($supportsAsyncSignals) { $this->registerTimeoutHandler($job, $options); } // If the daemon should run (not in maintenance mode, etc.), then we can run // fire off this job for processing. Otherwise, we will need to sleep the // worker so no more jobs are processed until they should be processed. if ($job) { $jobsProcessed++; $this->runJob($job, $connectionName, $options); if ($options->rest > 0) { $this->sleep($options->rest); } } else { $this->sleep($options->sleep); } if ($supportsAsyncSignals) { $this->resetTimeoutHandler(); } // Finally, we will check to see if we have exceeded our memory limits or if // the queue should restart based on other indications. If so, we'll stop // this worker and let whatever is "monitoring" it restart the process. $status = $this->stopIfNecessary( $options, $lastRestart, $startTime, $jobsProcessed, $job ); if (! is_null($status)) { return $this->stop($status, $options); } } } /** * Register the worker timeout handler. * * @param \Illuminate\Contracts\Queue\Job|null $job * @param \Illuminate\Queue\WorkerOptions $options * @return void */ protected function registerTimeoutHandler($job, WorkerOptions $options) { // We will register a signal handler for the alarm signal so that we can kill this // process if it is running too long because it has frozen. This uses the async // signals supported in recent versions of PHP to accomplish it conveniently. pcntl_signal(SIGALRM, function () use ($job, $options) { if ($job) { $this->markJobAsFailedIfWillExceedMaxAttempts( $job->getConnectionName(), $job, (int) $options->maxTries, $e = $this->timeoutExceededException($job) ); $this->markJobAsFailedIfWillExceedMaxExceptions( $job->getConnectionName(), $job, $e ); $this->markJobAsFailedIfItShouldFailOnTimeout( $job->getConnectionName(), $job, $e ); $this->events->dispatch(new JobTimedOut( $job->getConnectionName(), $job )); } $this->kill(static::EXIT_ERROR, $options); }, true); pcntl_alarm( max($this->timeoutForJob($job, $options), 0) ); } /** * Reset the worker timeout handler. * * @return void */ protected function resetTimeoutHandler() { pcntl_alarm(0); } /** * Get the appropriate timeout for the given job. * * @param \Illuminate\Contracts\Queue\Job|null $job * @param \Illuminate\Queue\WorkerOptions $options * @return int */ protected function timeoutForJob($job, WorkerOptions $options) { return $job && ! is_null($job->timeout()) ? $job->timeout() : $options->timeout; } /** * Determine if the daemon should process on this iteration. * * @param \Illuminate\Queue\WorkerOptions $options * @param string $connectionName * @param string $queue * @return bool */ protected function daemonShouldRun(WorkerOptions $options, $connectionName, $queue) { return ! ((($this->isDownForMaintenance)() && ! $options->force) || $this->paused || $this->events->until(new Looping($connectionName, $queue)) === false); } /** * Pause the worker for the current loop. * * @param \Illuminate\Queue\WorkerOptions $options * @param int $lastRestart * @return int|null */ protected function pauseWorker(WorkerOptions $options, $lastRestart) { $this->sleep($options->sleep > 0 ? $options->sleep : 1); return $this->stopIfNecessary($options, $lastRestart); } /** * Determine the exit code to stop the process if necessary. * * @param \Illuminate\Queue\WorkerOptions $options * @param int $lastRestart * @param int $startTime * @param int $jobsProcessed * @param mixed $job * @return int|null */
195543
protected function stopIfNecessary(WorkerOptions $options, $lastRestart, $startTime = 0, $jobsProcessed = 0, $job = null) { return match (true) { $this->shouldQuit => static::EXIT_SUCCESS, $this->memoryExceeded($options->memory) => static::EXIT_MEMORY_LIMIT, $this->queueShouldRestart($lastRestart) => static::EXIT_SUCCESS, $options->stopWhenEmpty && is_null($job) => static::EXIT_SUCCESS, $options->maxTime && hrtime(true) / 1e9 - $startTime >= $options->maxTime => static::EXIT_SUCCESS, $options->maxJobs && $jobsProcessed >= $options->maxJobs => static::EXIT_SUCCESS, default => null }; } /** * Process the next job on the queue. * * @param string $connectionName * @param string $queue * @param \Illuminate\Queue\WorkerOptions $options * @return void */ public function runNextJob($connectionName, $queue, WorkerOptions $options) { $job = $this->getNextJob( $this->manager->connection($connectionName), $queue ); // If we're able to pull a job off of the stack, we will process it and then return // from this method. If there is no job on the queue, we will "sleep" the worker // for the specified number of seconds, then keep processing jobs after sleep. if ($job) { return $this->runJob($job, $connectionName, $options); } $this->sleep($options->sleep); } /** * Get the next job from the queue connection. * * @param \Illuminate\Contracts\Queue\Queue $connection * @param string $queue * @return \Illuminate\Contracts\Queue\Job|null */ protected function getNextJob($connection, $queue) { $popJobCallback = function ($queue, $index = 0) use ($connection) { return $connection->pop($queue, $index); }; $this->raiseBeforeJobPopEvent($connection->getConnectionName()); try { if (isset(static::$popCallbacks[$this->name])) { return tap( (static::$popCallbacks[$this->name])($popJobCallback, $queue), fn ($job) => $this->raiseAfterJobPopEvent($connection->getConnectionName(), $job) ); } foreach (explode(',', $queue) as $index => $queue) { if (! is_null($job = $popJobCallback($queue, $index))) { $this->raiseAfterJobPopEvent($connection->getConnectionName(), $job); return $job; } } } catch (Throwable $e) { $this->exceptions->report($e); $this->stopWorkerIfLostConnection($e); $this->sleep(1); } } /** * Process the given job. * * @param \Illuminate\Contracts\Queue\Job $job * @param string $connectionName * @param \Illuminate\Queue\WorkerOptions $options * @return void */ protected function runJob($job, $connectionName, WorkerOptions $options) { try { return $this->process($connectionName, $job, $options); } catch (Throwable $e) { $this->exceptions->report($e); $this->stopWorkerIfLostConnection($e); } } /** * Stop the worker if we have lost connection to a database. * * @param \Throwable $e * @return void */ protected function stopWorkerIfLostConnection($e) { if ($this->causedByLostConnection($e)) { $this->shouldQuit = true; } } /** * Process the given job from the queue. * * @param string $connectionName * @param \Illuminate\Contracts\Queue\Job $job * @param \Illuminate\Queue\WorkerOptions $options * @return void * * @throws \Throwable */ public function process($connectionName, $job, WorkerOptions $options) { try { // First we will raise the before job event and determine if the job has already run // over its maximum attempt limits, which could primarily happen when this job is // continually timing out and not actually throwing any exceptions from itself. $this->raiseBeforeJobEvent($connectionName, $job); $this->markJobAsFailedIfAlreadyExceedsMaxAttempts( $connectionName, $job, (int) $options->maxTries ); if ($job->isDeleted()) { return $this->raiseAfterJobEvent($connectionName, $job); } // Here we will fire off the job and let it process. We will catch any exceptions, so // they can be reported to the developer's logs, etc. Once the job is finished the // proper events will be fired to let any listeners know this job has completed. $job->fire(); $this->raiseAfterJobEvent($connectionName, $job); } catch (Throwable $e) { $exceptionOccurred = true; $this->handleJobException($connectionName, $job, $options, $e); } finally { $this->events->dispatch(new JobAttempted( $connectionName, $job, $exceptionOccurred ?? false )); } } /** * Handle an exception that occurred while the job was running. * * @param string $connectionName * @param \Illuminate\Contracts\Queue\Job $job * @param \Illuminate\Queue\WorkerOptions $options * @param \Throwable $e * @return void * * @throws \Throwable */ protected function handleJobException($connectionName, $job, WorkerOptions $options, Throwable $e) { try { // First, we will go ahead and mark the job as failed if it will exceed the maximum // attempts it is allowed to run the next time we process it. If so we will just // go ahead and mark it as failed now so we do not have to release this again. if (! $job->hasFailed()) { $this->markJobAsFailedIfWillExceedMaxAttempts( $connectionName, $job, (int) $options->maxTries, $e ); $this->markJobAsFailedIfWillExceedMaxExceptions( $connectionName, $job, $e ); } $this->raiseExceptionOccurredJobEvent( $connectionName, $job, $e ); } finally { // If we catch an exception, we will attempt to release the job back onto the queue // so it is not lost entirely. This'll let the job be retried at a later time by // another listener (or this same one). We will re-throw this exception after. if (! $job->isDeleted() && ! $job->isReleased() && ! $job->hasFailed()) { $job->release($this->calculateBackoff($job, $options)); $this->events->dispatch(new JobReleasedAfterException( $connectionName, $job )); } } throw $e; } /** * Mark the given job as failed if it has exceeded the maximum allowed attempts. * * This will likely be because the job previously exceeded a timeout. * * @param string $connectionName * @param \Illuminate\Contracts\Queue\Job $job * @param int $maxTries * @return void * * @throws \Throwable */ protected function markJobAsFailedIfAlreadyExceedsMaxAttempts($connectionName, $job, $maxTries) { $maxTries = ! is_null($job->maxTries()) ? $job->maxTries() : $maxTries; $retryUntil = $job->retryUntil(); if ($retryUntil && Carbon::now()->getTimestamp() <= $retryUntil) { return; } if (! $retryUntil && ($maxTries === 0 || $job->attempts() <= $maxTries)) { return; } $this->failJob($job, $e = $this->maxAttemptsExceededException($job)); throw $e; }
195621
#[AsCommand(name: 'queue:work')] class WorkCommand extends Command { use InteractsWithTime; /** * The console command name. * * @var string */ protected $signature = 'queue:work {connection? : The name of the queue connection to work} {--name=default : The name of the worker} {--queue= : The names of the queues to work} {--daemon : Run the worker in daemon mode (Deprecated)} {--once : Only process the next job on the queue} {--stop-when-empty : Stop when the queue is empty} {--delay=0 : The number of seconds to delay failed jobs (Deprecated)} {--backoff=0 : The number of seconds to wait before retrying a job that encountered an uncaught exception} {--max-jobs=0 : The number of jobs to process before stopping} {--max-time=0 : The maximum number of seconds the worker should run} {--force : Force the worker to run even in maintenance mode} {--memory=128 : The memory limit in megabytes} {--sleep=3 : Number of seconds to sleep when no job is available} {--rest=0 : Number of seconds to rest between jobs} {--timeout=60 : The number of seconds a child process can run} {--tries=1 : Number of times to attempt a job before logging it failed} {--json : Output the queue worker information as JSON}'; /** * The console command description. * * @var string */ protected $description = 'Start processing jobs on the queue as a daemon'; /** * The queue worker instance. * * @var \Illuminate\Queue\Worker */ protected $worker; /** * The cache store implementation. * * @var \Illuminate\Contracts\Cache\Repository */ protected $cache; /** * Holds the start time of the last processed job, if any. * * @var float|null */ protected $latestStartedAt; /** * Create a new queue work command. * * @param \Illuminate\Queue\Worker $worker * @param \Illuminate\Contracts\Cache\Repository $cache * @return void */ public function __construct(Worker $worker, Cache $cache) { parent::__construct(); $this->cache = $cache; $this->worker = $worker; } /** * Execute the console command. * * @return int|null */ public function handle() { if ($this->downForMaintenance() && $this->option('once')) { return $this->worker->sleep($this->option('sleep')); } // We'll listen to the processed and failed events so we can write information // to the console as jobs are processed, which will let the developer watch // which jobs are coming through a queue and be informed on its progress. $this->listenForEvents(); $connection = $this->argument('connection') ?: $this->laravel['config']['queue.default']; // We need to get the right queue for the connection which is set in the queue // configuration file for the application. We will pull it based on the set // connection being run for the queue operation currently being executed. $queue = $this->getQueue($connection); if (! $this->outputUsingJson() && Terminal::hasSttyAvailable()) { $this->components->info( sprintf('Processing jobs from the [%s] %s.', $queue, str('queue')->plural(explode(',', $queue))) ); } return $this->runWorker( $connection, $queue ); } /** * Run the worker instance. * * @param string $connection * @param string $queue * @return int|null */ protected function runWorker($connection, $queue) { return $this->worker ->setName($this->option('name')) ->setCache($this->cache) ->{$this->option('once') ? 'runNextJob' : 'daemon'}( $connection, $queue, $this->gatherWorkerOptions() ); } /** * Gather all of the queue worker options as a single object. * * @return \Illuminate\Queue\WorkerOptions */ protected function gatherWorkerOptions() { return new WorkerOptions( $this->option('name'), max($this->option('backoff'), $this->option('delay')), $this->option('memory'), $this->option('timeout'), $this->option('sleep'), $this->option('tries'), $this->option('force'), $this->option('stop-when-empty'), $this->option('max-jobs'), $this->option('max-time'), $this->option('rest') ); } /** * Listen for the queue events in order to update the console output. * * @return void */ protected function listenForEvents() { $this->laravel['events']->listen(JobProcessing::class, function ($event) { $this->writeOutput($event->job, 'starting'); }); $this->laravel['events']->listen(JobProcessed::class, function ($event) { $this->writeOutput($event->job, 'success'); }); $this->laravel['events']->listen(JobReleasedAfterException::class, function ($event) { $this->writeOutput($event->job, 'released_after_exception'); }); $this->laravel['events']->listen(JobFailed::class, function ($event) { $this->writeOutput($event->job, 'failed', $event->exception); $this->logFailedJob($event); }); } /** * Write the status output for the queue worker for JSON or TTY. * * @param Job $job * @param string $status * @param Throwable|null $exception * @return void */ protected function writeOutput(Job $job, $status, ?Throwable $exception = null) { $this->outputUsingJson() ? $this->writeOutputAsJson($job, $status, $exception) : $this->writeOutputForCli($job, $status); } /** * Write the status output for the queue worker. * * @param \Illuminate\Contracts\Queue\Job $job * @param string $status * @return void */ protected function writeOutputForCli(Job $job, $status) { $this->output->write(sprintf( ' <fg=gray>%s</> %s%s', $this->now()->format('Y-m-d H:i:s'), $job->resolveName(), $this->output->isVerbose() ? sprintf(' <fg=gray>%s</>', $job->getJobId()) : '' )); if ($status == 'starting') { $this->latestStartedAt = microtime(true); $dots = max(terminal()->width() - mb_strlen($job->resolveName()) - ( $this->output->isVerbose() ? (mb_strlen($job->getJobId()) + 1) : 0 ) - 33, 0); $this->output->write(' '.str_repeat('<fg=gray>.</>', $dots)); return $this->output->writeln(' <fg=yellow;options=bold>RUNNING</>'); } $runTime = $this->runTimeForHumans($this->latestStartedAt); $dots = max(terminal()->width() - mb_strlen($job->resolveName()) - ( $this->output->isVerbose() ? (mb_strlen($job->getJobId()) + 1) : 0 ) - mb_strlen($runTime) - 31, 0); $this->output->write(' '.str_repeat('<fg=gray>.</>', $dots)); $this->output->write(" <fg=gray>$runTime</>"); $this->output->writeln(match ($status) { 'success' => ' <fg=green;options=bold>DONE</>', 'released_after_exception' => ' <fg=yellow;options=bold>FAIL</>', default => ' <fg=red;options=bold>FAIL</>', }); } /** * Write the status output for the queue worker in JSON format. * * @param \Illuminate\Contracts\Queue\Job $job * @param string $status * @param Throwable|null $exception * @return void */
195633
class LogManager implements LoggerInterface { use ParsesLogConfiguration; /** * The application instance. * * @var \Illuminate\Contracts\Foundation\Application */ protected $app; /** * The array of resolved channels. * * @var array */ protected $channels = []; /** * The context shared across channels and stacks. * * @var array */ protected $sharedContext = []; /** * The registered custom driver creators. * * @var array */ protected $customCreators = []; /** * The standard date format to use when writing logs. * * @var string */ protected $dateFormat = 'Y-m-d H:i:s'; /** * Create a new Log manager instance. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function __construct($app) { $this->app = $app; } /** * Build an on-demand log channel. * * @param array $config * @return \Psr\Log\LoggerInterface */ public function build(array $config) { unset($this->channels['ondemand']); return $this->get('ondemand', $config); } /** * Create a new, on-demand aggregate logger instance. * * @param array $channels * @param string|null $channel * @return \Psr\Log\LoggerInterface */ public function stack(array $channels, $channel = null) { return (new Logger( $this->createStackDriver(compact('channels', 'channel')), $this->app['events'] ))->withContext($this->sharedContext); } /** * Get a log channel instance. * * @param string|null $channel * @return \Psr\Log\LoggerInterface */ public function channel($channel = null) { return $this->driver($channel); } /** * Get a log driver instance. * * @param string|null $driver * @return \Psr\Log\LoggerInterface */ public function driver($driver = null) { return $this->get($this->parseDriver($driver)); } /** * Attempt to get the log from the local cache. * * @param string $name * @param array|null $config * @return \Psr\Log\LoggerInterface */ protected function get($name, ?array $config = null) { try { return $this->channels[$name] ?? with($this->resolve($name, $config), function ($logger) use ($name) { $loggerWithContext = $this->tap( $name, new Logger($logger, $this->app['events']) )->withContext($this->sharedContext); if (method_exists($loggerWithContext->getLogger(), 'pushProcessor')) { $loggerWithContext->pushProcessor(function ($record) { if (! $this->app->bound(ContextRepository::class)) { return $record; } return $record->with(extra: [ ...$record->extra, ...$this->app[ContextRepository::class]->all(), ]); }); } return $this->channels[$name] = $loggerWithContext; }); } catch (Throwable $e) { return tap($this->createEmergencyLogger(), function ($logger) use ($e) { $logger->emergency('Unable to create configured logger. Using emergency logger.', [ 'exception' => $e, ]); }); } } /** * Apply the configured taps for the logger. * * @param string $name * @param \Illuminate\Log\Logger $logger * @return \Illuminate\Log\Logger */ protected function tap($name, Logger $logger) { foreach ($this->configurationFor($name)['tap'] ?? [] as $tap) { [$class, $arguments] = $this->parseTap($tap); $this->app->make($class)->__invoke($logger, ...explode(',', $arguments)); } return $logger; } /** * Parse the given tap class string into a class name and arguments string. * * @param string $tap * @return array */ protected function parseTap($tap) { return str_contains($tap, ':') ? explode(':', $tap, 2) : [$tap, '']; } /** * Create an emergency log handler to avoid white screens of death. * * @return \Psr\Log\LoggerInterface */ protected function createEmergencyLogger() { $config = $this->configurationFor('emergency'); $handler = new StreamHandler( $config['path'] ?? $this->app->storagePath().'/logs/laravel.log', $this->level(['level' => 'debug']) ); return new Logger( new Monolog('laravel', $this->prepareHandlers([$handler])), $this->app['events'] ); } /** * Resolve the given log instance by name. * * @param string $name * @param array|null $config * @return \Psr\Log\LoggerInterface * * @throws \InvalidArgumentException */ protected function resolve($name, ?array $config = null) { $config ??= $this->configurationFor($name); if (is_null($config)) { throw new InvalidArgumentException("Log [{$name}] is not defined."); } if (isset($this->customCreators[$config['driver']])) { return $this->callCustomCreator($config); } $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; if (method_exists($this, $driverMethod)) { return $this->{$driverMethod}($config); } throw new InvalidArgumentException("Driver [{$config['driver']}] is not supported."); } /** * Call a custom driver creator. * * @param array $config * @return mixed */ protected function callCustomCreator(array $config) { return $this->customCreators[$config['driver']]($this->app, $config); } /** * Create a custom log driver instance. * * @param array $config * @return \Psr\Log\LoggerInterface */ protected function createCustomDriver(array $config) { $factory = is_callable($via = $config['via']) ? $via : $this->app->make($via); return $factory($config); } /** * Create an aggregate log driver instance. * * @param array $config * @return \Psr\Log\LoggerInterface */ protected function createStackDriver(array $config) { if (is_string($config['channels'])) { $config['channels'] = explode(',', $config['channels']); } $handlers = collect($config['channels'])->flatMap(function ($channel) { return $channel instanceof LoggerInterface ? $channel->getHandlers() : $this->channel($channel)->getHandlers(); })->all(); $processors = collect($config['channels'])->flatMap(function ($channel) { return $channel instanceof LoggerInterface ? $channel->getProcessors() : $this->channel($channel)->getProcessors(); })->all(); if ($config['ignore_exceptions'] ?? false) { $handlers = [new WhatFailureGroupHandler($handlers)]; } return new Monolog($this->parseChannel($config), $handlers, $processors); } /** * Create an instance of the single file log driver. * * @param array $config * @return \Psr\Log\LoggerInterface */ protected function createSingleDriver(array $config) { return new Monolog($this->parseChannel($config), [ $this->prepareHandler( new StreamHandler( $config['path'], $this->level($config), $config['bubble'] ?? true, $config['permission'] ?? null, $config['locking'] ?? false ), $config ), ], $config['replace_placeholders'] ?? false ? [new PsrLogMessageProcessor()] : []); } /** * Create an instance of the daily file log driver. * * @param array $config * @return \Psr\Log\LoggerInterface */
195634
protected function createDailyDriver(array $config) { return new Monolog($this->parseChannel($config), [ $this->prepareHandler(new RotatingFileHandler( $config['path'], $config['days'] ?? 7, $this->level($config), $config['bubble'] ?? true, $config['permission'] ?? null, $config['locking'] ?? false ), $config), ], $config['replace_placeholders'] ?? false ? [new PsrLogMessageProcessor()] : []); } /** * Create an instance of the Slack log driver. * * @param array $config * @return \Psr\Log\LoggerInterface */ protected function createSlackDriver(array $config) { return new Monolog($this->parseChannel($config), [ $this->prepareHandler(new SlackWebhookHandler( $config['url'], $config['channel'] ?? null, $config['username'] ?? 'Laravel', $config['attachment'] ?? true, $config['emoji'] ?? ':boom:', $config['short'] ?? false, $config['context'] ?? true, $this->level($config), $config['bubble'] ?? true, $config['exclude_fields'] ?? [] ), $config), ], $config['replace_placeholders'] ?? false ? [new PsrLogMessageProcessor()] : []); } /** * Create an instance of the syslog log driver. * * @param array $config * @return \Psr\Log\LoggerInterface */ protected function createSyslogDriver(array $config) { return new Monolog($this->parseChannel($config), [ $this->prepareHandler(new SyslogHandler( Str::snake($this->app['config']['app.name'], '-'), $config['facility'] ?? LOG_USER, $this->level($config) ), $config), ], $config['replace_placeholders'] ?? false ? [new PsrLogMessageProcessor()] : []); } /** * Create an instance of the "error log" log driver. * * @param array $config * @return \Psr\Log\LoggerInterface */ protected function createErrorlogDriver(array $config) { return new Monolog($this->parseChannel($config), [ $this->prepareHandler(new ErrorLogHandler( $config['type'] ?? ErrorLogHandler::OPERATING_SYSTEM, $this->level($config) )), ], $config['replace_placeholders'] ?? false ? [new PsrLogMessageProcessor()] : []); } /** * Create an instance of any handler available in Monolog. * * @param array $config * @return \Psr\Log\LoggerInterface * * @throws \InvalidArgumentException * @throws \Illuminate\Contracts\Container\BindingResolutionException */ protected function createMonologDriver(array $config) { if (! is_a($config['handler'], HandlerInterface::class, true)) { throw new InvalidArgumentException( $config['handler'].' must be an instance of '.HandlerInterface::class ); } collect($config['processors'] ?? [])->each(function ($processor) { $processor = $processor['processor'] ?? $processor; if (! is_a($processor, ProcessorInterface::class, true)) { throw new InvalidArgumentException( $processor.' must be an instance of '.ProcessorInterface::class ); } }); $with = array_merge( ['level' => $this->level($config)], $config['with'] ?? [], $config['handler_with'] ?? [] ); $handler = $this->prepareHandler( $this->app->make($config['handler'], $with), $config ); $processors = collect($config['processors'] ?? []) ->map(fn ($processor) => $this->app->make($processor['processor'] ?? $processor, $processor['with'] ?? [])) ->toArray(); return new Monolog( $this->parseChannel($config), [$handler], $processors, ); } /** * Prepare the handlers for usage by Monolog. * * @param array $handlers * @return array */ protected function prepareHandlers(array $handlers) { foreach ($handlers as $key => $handler) { $handlers[$key] = $this->prepareHandler($handler); } return $handlers; } /** * Prepare the handler for usage by Monolog. * * @param \Monolog\Handler\HandlerInterface $handler * @param array $config * @return \Monolog\Handler\HandlerInterface */ protected function prepareHandler(HandlerInterface $handler, array $config = []) { if (isset($config['action_level'])) { $handler = new FingersCrossedHandler( $handler, $this->actionLevel($config), 0, true, $config['stop_buffering'] ?? true ); } if (! $handler instanceof FormattableHandlerInterface) { return $handler; } if (! isset($config['formatter'])) { $handler->setFormatter($this->formatter()); } elseif ($config['formatter'] !== 'default') { $handler->setFormatter($this->app->make($config['formatter'], $config['formatter_with'] ?? [])); } return $handler; } /** * Get a Monolog formatter instance. * * @return \Monolog\Formatter\FormatterInterface */ protected function formatter() { return new LineFormatter(null, $this->dateFormat, true, true, true); } /** * Share context across channels and stacks. * * @param array $context * @return $this */ public function shareContext(array $context) { foreach ($this->channels as $channel) { $channel->withContext($context); } $this->sharedContext = array_merge($this->sharedContext, $context); return $this; } /** * The context shared across channels and stacks. * * @return array */ public function sharedContext() { return $this->sharedContext; } /** * Flush the log context on all currently resolved channels. * * @return $this */ public function withoutContext() { foreach ($this->channels as $channel) { if (method_exists($channel, 'withoutContext')) { $channel->withoutContext(); } } return $this; } /** * Flush the shared context. * * @return $this */ public function flushSharedContext() { $this->sharedContext = []; return $this; } /** * Get fallback log channel name. * * @return string */ protected function getFallbackChannelName() { return $this->app->bound('env') ? $this->app->environment() : 'production'; } /** * Get the log connection configuration. * * @param string $name * @return array */ protected function configurationFor($name) { return $this->app['config']["logging.channels.{$name}"]; } /** * Get the default log driver name. * * @return string|null */ public function getDefaultDriver() { return $this->app['config']['logging.default']; } /** * Set the default log driver name. * * @param string $name * @return void */ public function setDefaultDriver($name) { $this->app['config']['logging.default'] = $name; } /** * Register a custom driver creator Closure. * * @param string $driver * @param \Closure $callback * @return $this */ public function extend($driver, Closure $callback) { $this->customCreators[$driver] = $callback->bindTo($this, $this); return $this; } /** * Unset the given channel instance. * * @param string|null $driver * @return void */ public function forgetChannel($driver = null) { $driver = $this->parseDriver($driver); if (isset($this->channels[$driver])) { unset($this->channels[$driver]); } } /** * Parse the driver name. * * @param string|null $driver * @return string|null */
195659
<?php namespace Illuminate\Routing; use BadMethodCallException; abstract class Controller { /** * The middleware registered on the controller. * * @var array */ protected $middleware = []; /** * Register middleware on the controller. * * @param \Closure|array|string $middleware * @param array $options * @return \Illuminate\Routing\ControllerMiddlewareOptions */ public function middleware($middleware, array $options = []) { foreach ((array) $middleware as $m) { $this->middleware[] = [ 'middleware' => $m, 'options' => &$options, ]; } return new ControllerMiddlewareOptions($options); } /** * Get the middleware assigned to the controller. * * @return array */ public function getMiddleware() { return $this->middleware; } /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { return $this->{$method}(...array_values($parameters)); } /** * Handle calls to missing methods on the controller. * * @param string $method * @param array $parameters * @return mixed * * @throws \BadMethodCallException */ public function __call($method, $parameters) { throw new BadMethodCallException(sprintf( 'Method %s::%s does not exist.', static::class, $method )); } }
195666
<?php namespace Illuminate\Routing; use Illuminate\Contracts\Routing\UrlRoutable; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException; use Illuminate\Support\Reflector; use Illuminate\Support\Str; class ImplicitRouteBinding { /** * Resolve the implicit route bindings for the given route. * * @param \Illuminate\Container\Container $container * @param \Illuminate\Routing\Route $route * @return void * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> * @throws \Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException */ public static function resolveForRoute($container, $route) { $parameters = $route->parameters(); $route = static::resolveBackedEnumsForRoute($route, $parameters); foreach ($route->signatureParameters(['subClass' => UrlRoutable::class]) as $parameter) { if (! $parameterName = static::getParameterName($parameter->getName(), $parameters)) { continue; } $parameterValue = $parameters[$parameterName]; if ($parameterValue instanceof UrlRoutable) { continue; } $instance = $container->make(Reflector::getParameterClassName($parameter)); $parent = $route->parentOfParameter($parameterName); $routeBindingMethod = $route->allowsTrashedBindings() && in_array(SoftDeletes::class, class_uses_recursive($instance)) ? 'resolveSoftDeletableRouteBinding' : 'resolveRouteBinding'; if ($parent instanceof UrlRoutable && ! $route->preventsScopedBindings() && ($route->enforcesScopedBindings() || array_key_exists($parameterName, $route->bindingFields()))) { $childRouteBindingMethod = $route->allowsTrashedBindings() && in_array(SoftDeletes::class, class_uses_recursive($instance)) ? 'resolveSoftDeletableChildRouteBinding' : 'resolveChildRouteBinding'; if (! $model = $parent->{$childRouteBindingMethod}( $parameterName, $parameterValue, $route->bindingFieldFor($parameterName) )) { throw (new ModelNotFoundException)->setModel(get_class($instance), [$parameterValue]); } } elseif (! $model = $instance->{$routeBindingMethod}($parameterValue, $route->bindingFieldFor($parameterName))) { throw (new ModelNotFoundException)->setModel(get_class($instance), [$parameterValue]); } $route->setParameter($parameterName, $model); } } /** * Resolve the Backed Enums route bindings for the route. * * @param \Illuminate\Routing\Route $route * @param array $parameters * @return \Illuminate\Routing\Route * * @throws \Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException */ protected static function resolveBackedEnumsForRoute($route, $parameters) { foreach ($route->signatureParameters(['backedEnum' => true]) as $parameter) { if (! $parameterName = static::getParameterName($parameter->getName(), $parameters)) { continue; } $parameterValue = $parameters[$parameterName]; if ($parameterValue === null) { continue; } $backedEnumClass = $parameter->getType()?->getName(); $backedEnum = $parameterValue instanceof $backedEnumClass ? $parameterValue : $backedEnumClass::tryFrom((string) $parameterValue); if (is_null($backedEnum)) { throw new BackedEnumCaseNotFoundException($backedEnumClass, $parameterValue); } $route->setParameter($parameterName, $backedEnum); } return $route; } /** * Return the parameter name if it exists in the given parameters. * * @param string $name * @param array $parameters * @return string|null */ protected static function getParameterName($name, $parameters) { if (array_key_exists($name, $parameters)) { return $name; } if (array_key_exists($snakedName = Str::snake($name), $parameters)) { return $snakedName; } } }
195671
class UrlGenerator implements UrlGeneratorContract { use InteractsWithTime, Macroable; /** * The route collection. * * @var \Illuminate\Routing\RouteCollectionInterface */ protected $routes; /** * The request instance. * * @var \Illuminate\Http\Request */ protected $request; /** * The asset root URL. * * @var string */ protected $assetRoot; /** * The forced URL root. * * @var string */ protected $forcedRoot; /** * The forced scheme for URLs. * * @var string */ protected $forceScheme; /** * A cached copy of the URL root for the current request. * * @var string|null */ protected $cachedRoot; /** * A cached copy of the URL scheme for the current request. * * @var string|null */ protected $cachedScheme; /** * The root namespace being applied to controller actions. * * @var string */ protected $rootNamespace; /** * The session resolver callable. * * @var callable */ protected $sessionResolver; /** * The encryption key resolver callable. * * @var callable */ protected $keyResolver; /** * The missing named route resolver callable. * * @var callable */ protected $missingNamedRouteResolver; /** * The callback to use to format hosts. * * @var \Closure */ protected $formatHostUsing; /** * The callback to use to format paths. * * @var \Closure */ protected $formatPathUsing; /** * The route URL generator instance. * * @var \Illuminate\Routing\RouteUrlGenerator|null */ protected $routeGenerator; /** * Create a new URL Generator instance. * * @param \Illuminate\Routing\RouteCollectionInterface $routes * @param \Illuminate\Http\Request $request * @param string|null $assetRoot * @return void */ public function __construct(RouteCollectionInterface $routes, Request $request, $assetRoot = null) { $this->routes = $routes; $this->assetRoot = $assetRoot; $this->setRequest($request); } /** * Get the full URL for the current request. * * @return string */ public function full() { return $this->request->fullUrl(); } /** * Get the current URL for the request. * * @return string */ public function current() { return $this->to($this->request->getPathInfo()); } /** * Get the URL for the previous request. * * @param mixed $fallback * @return string */ public function previous($fallback = false) { $referrer = $this->request->headers->get('referer'); $url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession(); if ($url) { return $url; } elseif ($fallback) { return $this->to($fallback); } return $this->to('/'); } /** * Get the previous path info for the request. * * @param mixed $fallback * @return string */ public function previousPath($fallback = false) { $previousPath = str_replace($this->to('/'), '', rtrim(preg_replace('/\?.*/', '', $this->previous($fallback)), '/')); return $previousPath === '' ? '/' : $previousPath; } /** * Get the previous URL from the session if possible. * * @return string|null */ protected function getPreviousUrlFromSession() { return $this->getSession()?->previousUrl(); } /** * Generate an absolute URL to the given path. * * @param string $path * @param mixed $extra * @param bool|null $secure * @return string */ public function to($path, $extra = [], $secure = null) { // First we will check if the URL is already a valid URL. If it is we will not // try to generate a new one but will simply return the URL as is, which is // convenient since developers do not always have to check if it's valid. if ($this->isValidUrl($path)) { return $path; } $tail = implode('/', array_map( 'rawurlencode', (array) $this->formatParameters($extra)) ); // Once we have the scheme we will compile the "tail" by collapsing the values // into a single string delimited by slashes. This just makes it convenient // for passing the array of parameters to this URL as a list of segments. $root = $this->formatRoot($this->formatScheme($secure)); [$path, $query] = $this->extractQueryString($path); return $this->format( $root, '/'.trim($path.'/'.$tail, '/') ).$query; } /** * Generate an absolute URL with the given query parameters. * * @param string $path * @param array $query * @param mixed $extra * @param bool|null $secure * @return string */ public function query($path, $query = [], $extra = [], $secure = null) { [$path, $existingQueryString] = $this->extractQueryString($path); parse_str(Str::after($existingQueryString, '?'), $existingQueryArray); return rtrim($this->to($path.'?'.Arr::query( array_merge($existingQueryArray, $query) ), $extra, $secure), '?'); } /** * Generate a secure, absolute URL to the given path. * * @param string $path * @param array $parameters * @return string */ public function secure($path, $parameters = []) { return $this->to($path, $parameters, true); } /** * Generate the URL to an application asset. * * @param string $path * @param bool|null $secure * @return string */ public function asset($path, $secure = null) { if ($this->isValidUrl($path)) { return $path; } // Once we get the root URL, we will check to see if it contains an index.php // file in the paths. If it does, we will remove it since it is not needed // for asset paths, but only for routes to endpoints in the application. $root = $this->assetRoot ?: $this->formatRoot($this->formatScheme($secure)); return Str::finish($this->removeIndex($root), '/').trim($path, '/'); } /** * Generate the URL to a secure asset. * * @param string $path * @return string */ public function secureAsset($path) { return $this->asset($path, true); } /** * Generate the URL to an asset from a custom root domain such as CDN, etc. * * @param string $root * @param string $path * @param bool|null $secure * @return string */ public function assetFrom($root, $path, $secure = null) { // Once we get the root URL, we will check to see if it contains an index.php // file in the paths. If it does, we will remove it since it is not needed // for asset paths, but only for routes to endpoints in the application. $root = $this->formatRoot($this->formatScheme($secure), $root); return $this->removeIndex($root).'/'.trim($path, '/'); } /** * Remove the index.php file from a path. * * @param string $root * @return string */ protected function removeIndex($root) { $i = 'index.php'; return str_contains($root, $i) ? str_replace('/'.$i, '', $root) : $root; } /** * Get the default scheme for a raw URL. * * @param bool|null $secure * @return string */
195674
<?php namespace Illuminate\Routing; use Illuminate\Support\Arr; use function Illuminate\Support\enum_value; trait CreatesRegularExpressionRouteConstraints { /** * Specify that the given route parameters must be alphabetic. * * @param array|string $parameters * @return $this */ public function whereAlpha($parameters) { return $this->assignExpressionToParameters($parameters, '[a-zA-Z]+'); } /** * Specify that the given route parameters must be alphanumeric. * * @param array|string $parameters * @return $this */ public function whereAlphaNumeric($parameters) { return $this->assignExpressionToParameters($parameters, '[a-zA-Z0-9]+'); } /** * Specify that the given route parameters must be numeric. * * @param array|string $parameters * @return $this */ public function whereNumber($parameters) { return $this->assignExpressionToParameters($parameters, '[0-9]+'); } /** * Specify that the given route parameters must be ULIDs. * * @param array|string $parameters * @return $this */ public function whereUlid($parameters) { return $this->assignExpressionToParameters($parameters, '[0-7][0-9a-hjkmnp-tv-zA-HJKMNP-TV-Z]{25}'); } /** * Specify that the given route parameters must be UUIDs. * * @param array|string $parameters * @return $this */ public function whereUuid($parameters) { return $this->assignExpressionToParameters($parameters, '[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}'); } /** * Specify that the given route parameters must be one of the given values. * * @param array|string $parameters * @param array $values * @return $this */ public function whereIn($parameters, array $values) { return $this->assignExpressionToParameters( $parameters, collect($values) ->map(fn ($value) => enum_value($value)) ->implode('|') ); } /** * Apply the given regular expression to the given parameters. * * @param array|string $parameters * @param string $expression * @return $this */ protected function assignExpressionToParameters($parameters, $expression) { return $this->where(collect(Arr::wrap($parameters)) ->mapWithKeys(fn ($parameter) => [$parameter => $expression]) ->all()); } }
195680
public function parameter($name, $default = null) { return Arr::get($this->parameters(), $name, $default); } /** * Get original value of a given parameter from the route. * * @param string $name * @param string|null $default * @return string|null */ public function originalParameter($name, $default = null) { return Arr::get($this->originalParameters(), $name, $default); } /** * Set a parameter to the given value. * * @param string $name * @param string|object|null $value * @return void */ public function setParameter($name, $value) { $this->parameters(); $this->parameters[$name] = $value; } /** * Unset a parameter on the route if it is set. * * @param string $name * @return void */ public function forgetParameter($name) { $this->parameters(); unset($this->parameters[$name]); } /** * Get the key / value list of parameters for the route. * * @return array * * @throws \LogicException */ public function parameters() { if (isset($this->parameters)) { return $this->parameters; } throw new LogicException('Route is not bound.'); } /** * Get the key / value list of original parameters for the route. * * @return array * * @throws \LogicException */ public function originalParameters() { if (isset($this->originalParameters)) { return $this->originalParameters; } throw new LogicException('Route is not bound.'); } /** * Get the key / value list of parameters without null values. * * @return array */ public function parametersWithoutNulls() { return array_filter($this->parameters(), fn ($p) => ! is_null($p)); } /** * Get all of the parameter names for the route. * * @return array */ public function parameterNames() { if (isset($this->parameterNames)) { return $this->parameterNames; } return $this->parameterNames = $this->compileParameterNames(); } /** * Get the parameter names for the route. * * @return array */ protected function compileParameterNames() { preg_match_all('/\{(.*?)\}/', $this->getDomain().$this->uri, $matches); return array_map(fn ($m) => trim($m, '?'), $matches[1]); } /** * Get the parameters that are listed in the route / controller signature. * * @param array $conditions * @return array */ public function signatureParameters($conditions = []) { if (is_string($conditions)) { $conditions = ['subClass' => $conditions]; } return RouteSignatureParameters::fromAction($this->action, $conditions); } /** * Get the binding field for the given parameter. * * @param string|int $parameter * @return string|null */ public function bindingFieldFor($parameter) { $fields = is_int($parameter) ? array_values($this->bindingFields) : $this->bindingFields; return $fields[$parameter] ?? null; } /** * Get the binding fields for the route. * * @return array */ public function bindingFields() { return $this->bindingFields ?? []; } /** * Set the binding fields for the route. * * @param array $bindingFields * @return $this */ public function setBindingFields(array $bindingFields) { $this->bindingFields = $bindingFields; return $this; } /** * Get the parent parameter of the given parameter. * * @param string $parameter * @return string|null */ public function parentOfParameter($parameter) { $key = array_search($parameter, array_keys($this->parameters)); if ($key === 0 || $key === false) { return; } return array_values($this->parameters)[$key - 1]; } /** * Allow "trashed" models to be retrieved when resolving implicit model bindings for this route. * * @param bool $withTrashed * @return $this */ public function withTrashed($withTrashed = true) { $this->withTrashedBindings = $withTrashed; return $this; } /** * Determines if the route allows "trashed" models to be retrieved when resolving implicit model bindings. * * @return bool */ public function allowsTrashedBindings() { return $this->withTrashedBindings; } /** * Set a default value for the route. * * @param string $key * @param mixed $value * @return $this */ public function defaults($key, $value) { $this->defaults[$key] = $value; return $this; } /** * Set the default values for the route. * * @param array $defaults * @return $this */ public function setDefaults(array $defaults) { $this->defaults = $defaults; return $this; } /** * Set a regular expression requirement on the route. * * @param array|string $name * @param string|null $expression * @return $this */ public function where($name, $expression = null) { foreach ($this->parseWhere($name, $expression) as $name => $expression) { $this->wheres[$name] = $expression; } return $this; } /** * Parse arguments to the where method into an array. * * @param array|string $name * @param string $expression * @return array */ protected function parseWhere($name, $expression) { return is_array($name) ? $name : [$name => $expression]; } /** * Set a list of regular expression requirements on the route. * * @param array $wheres * @return $this */ public function setWheres(array $wheres) { foreach ($wheres as $name => $expression) { $this->where($name, $expression); } return $this; } /** * Mark this route as a fallback route. * * @return $this */ public function fallback() { $this->isFallback = true; return $this; } /** * Set the fallback value. * * @param bool $isFallback * @return $this */ public function setFallback($isFallback) { $this->isFallback = $isFallback; return $this; } /** * Get the HTTP verbs the route responds to. * * @return array */ public function methods() { return $this->methods; } /** * Determine if the route only responds to HTTP requests. * * @return bool */ public function httpOnly() { return in_array('http', $this->action, true); } /** * Determine if the route only responds to HTTPS requests. * * @return bool */ public function httpsOnly() { return $this->secure(); } /** * Determine if the route only responds to HTTPS requests. * * @return bool */ public function secure() { return in_array('https', $this->action, true); } /** * Get or set the domain for the route. * * @param \BackedEnum|string|null $domain * @return $this|string|null * * @throws \InvalidArgumentException */ public function domain($domain = null) { if (is_null($domain)) { return $this->getDomain(); } if ($domain instanceof BackedEnum && ! is_string($domain = $domain->value)) { throw new InvalidArgumentException('Enum must be string backed.'); } $parsed = RouteUri::parse($domain); $this->action['domain'] = $parsed->uri; $this->bindingFields = array_merge( $this->bindingFields, $parsed->bindingFields ); return $this; }
195684
<?php namespace Illuminate\Routing; use Illuminate\Support\Str; class ResourceRegistrar { /** * The router instance. * * @var \Illuminate\Routing\Router */ protected $router; /** * The default actions for a resourceful controller. * * @var string[] */ protected $resourceDefaults = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy']; /** * The default actions for a singleton resource controller. * * @var string[] */ protected $singletonResourceDefaults = ['show', 'edit', 'update']; /** * The parameters set for this resource instance. * * @var array|string */ protected $parameters; /** * The global parameter mapping. * * @var array */ protected static $parameterMap = []; /** * Singular global parameters. * * @var bool */ protected static $singularParameters = true; /** * The verbs used in the resource URIs. * * @var array */ protected static $verbs = [ 'create' => 'create', 'edit' => 'edit', ]; /** * Create a new resource registrar instance. * * @param \Illuminate\Routing\Router $router * @return void */ public function __construct(Router $router) { $this->router = $router; } /** * Route a resource to a controller. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\RouteCollection */ public function register($name, $controller, array $options = []) { if (isset($options['parameters']) && ! isset($this->parameters)) { $this->parameters = $options['parameters']; } // If the resource name contains a slash, we will assume the developer wishes to // register these resource routes with a prefix so we will set that up out of // the box so they don't have to mess with it. Otherwise, we will continue. if (str_contains($name, '/')) { $this->prefixedResource($name, $controller, $options); return; } // We need to extract the base resource from the resource name. Nested resources // are supported in the framework, but we need to know what name to use for a // place-holder on the route parameters, which should be the base resources. $base = $this->getResourceWildcard(last(explode('.', $name))); $defaults = $this->resourceDefaults; $collection = new RouteCollection; $resourceMethods = $this->getResourceMethods($defaults, $options); foreach ($resourceMethods as $m) { $route = $this->{'addResource'.ucfirst($m)}( $name, $base, $controller, $options ); if (isset($options['bindingFields'])) { $this->setResourceBindingFields($route, $options['bindingFields']); } if (isset($options['trashed']) && in_array($m, ! empty($options['trashed']) ? $options['trashed'] : array_intersect($resourceMethods, ['show', 'edit', 'update']))) { $route->withTrashed(); } $collection->add($route); } return $collection; } /** * Route a singleton resource to a controller. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\RouteCollection */ public function singleton($name, $controller, array $options = []) { if (isset($options['parameters']) && ! isset($this->parameters)) { $this->parameters = $options['parameters']; } // If the resource name contains a slash, we will assume the developer wishes to // register these singleton routes with a prefix so we will set that up out of // the box so they don't have to mess with it. Otherwise, we will continue. if (str_contains($name, '/')) { $this->prefixedSingleton($name, $controller, $options); return; } $defaults = $this->singletonResourceDefaults; if (isset($options['creatable'])) { $defaults = array_merge($defaults, ['create', 'store', 'destroy']); } elseif (isset($options['destroyable'])) { $defaults = array_merge($defaults, ['destroy']); } $collection = new RouteCollection; $resourceMethods = $this->getResourceMethods($defaults, $options); foreach ($resourceMethods as $m) { $route = $this->{'addSingleton'.ucfirst($m)}( $name, $controller, $options ); if (isset($options['bindingFields'])) { $this->setResourceBindingFields($route, $options['bindingFields']); } $collection->add($route); } return $collection; } /** * Build a set of prefixed resource routes. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Router */ protected function prefixedResource($name, $controller, array $options) { [$name, $prefix] = $this->getResourcePrefix($name); // We need to extract the base resource from the resource name. Nested resources // are supported in the framework, but we need to know what name to use for a // place-holder on the route parameters, which should be the base resources. $callback = function ($me) use ($name, $controller, $options) { $me->resource($name, $controller, $options); }; return $this->router->group(compact('prefix'), $callback); } /** * Build a set of prefixed singleton routes. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Router */ protected function prefixedSingleton($name, $controller, array $options) { [$name, $prefix] = $this->getResourcePrefix($name); // We need to extract the base resource from the resource name. Nested resources // are supported in the framework, but we need to know what name to use for a // place-holder on the route parameters, which should be the base resources. $callback = function ($me) use ($name, $controller, $options) { $me->singleton($name, $controller, $options); }; return $this->router->group(compact('prefix'), $callback); } /** * Extract the resource and prefix from a resource name. * * @param string $name * @return array */ protected function getResourcePrefix($name) { $segments = explode('/', $name); // To get the prefix, we will take all of the name segments and implode them on // a slash. This will generate a proper URI prefix for us. Then we take this // last segment, which will be considered the final resources name we use. $prefix = implode('/', array_slice($segments, 0, -1)); return [end($segments), $prefix]; } /** * Get the applicable resource methods. * * @param array $defaults * @param array $options * @return array */ protected function getResourceMethods($defaults, $options) { $methods = $defaults; if (isset($options['only'])) { $methods = array_intersect($methods, (array) $options['only']); } if (isset($options['except'])) { $methods = array_diff($methods, (array) $options['except']); } return array_values($methods); } /** * Add the index method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceIndex($name, $base, $controller, $options) { $uri = $this->getResourceUri($name); unset($options['missing']); $action = $this->getResourceAction($name, $controller, 'index', $options); return $this->router->get($uri, $action); }
195685
/** * Add the create method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceCreate($name, $base, $controller, $options) { $uri = $this->getResourceUri($name).'/'.static::$verbs['create']; unset($options['missing']); $action = $this->getResourceAction($name, $controller, 'create', $options); return $this->router->get($uri, $action); } /** * Add the store method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceStore($name, $base, $controller, $options) { $uri = $this->getResourceUri($name); unset($options['missing']); $action = $this->getResourceAction($name, $controller, 'store', $options); return $this->router->post($uri, $action); } /** * Add the show method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceShow($name, $base, $controller, $options) { $name = $this->getShallowName($name, $options); $uri = $this->getResourceUri($name).'/{'.$base.'}'; $action = $this->getResourceAction($name, $controller, 'show', $options); return $this->router->get($uri, $action); } /** * Add the edit method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceEdit($name, $base, $controller, $options) { $name = $this->getShallowName($name, $options); $uri = $this->getResourceUri($name).'/{'.$base.'}/'.static::$verbs['edit']; $action = $this->getResourceAction($name, $controller, 'edit', $options); return $this->router->get($uri, $action); } /** * Add the update method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceUpdate($name, $base, $controller, $options) { $name = $this->getShallowName($name, $options); $uri = $this->getResourceUri($name).'/{'.$base.'}'; $action = $this->getResourceAction($name, $controller, 'update', $options); return $this->router->match(['PUT', 'PATCH'], $uri, $action); } /** * Add the destroy method for a resourceful route. * * @param string $name * @param string $base * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addResourceDestroy($name, $base, $controller, $options) { $name = $this->getShallowName($name, $options); $uri = $this->getResourceUri($name).'/{'.$base.'}'; $action = $this->getResourceAction($name, $controller, 'destroy', $options); return $this->router->delete($uri, $action); } /** * Add the create method for a singleton route. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addSingletonCreate($name, $controller, $options) { $uri = $this->getResourceUri($name).'/'.static::$verbs['create']; unset($options['missing']); $action = $this->getResourceAction($name, $controller, 'create', $options); return $this->router->get($uri, $action); } /** * Add the store method for a singleton route. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addSingletonStore($name, $controller, $options) { $uri = $this->getResourceUri($name); unset($options['missing']); $action = $this->getResourceAction($name, $controller, 'store', $options); return $this->router->post($uri, $action); } /** * Add the show method for a singleton route. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addSingletonShow($name, $controller, $options) { $uri = $this->getResourceUri($name); unset($options['missing']); $action = $this->getResourceAction($name, $controller, 'show', $options); return $this->router->get($uri, $action); } /** * Add the edit method for a singleton route. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addSingletonEdit($name, $controller, $options) { $name = $this->getShallowName($name, $options); $uri = $this->getResourceUri($name).'/'.static::$verbs['edit']; $action = $this->getResourceAction($name, $controller, 'edit', $options); return $this->router->get($uri, $action); } /** * Add the update method for a singleton route. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addSingletonUpdate($name, $controller, $options) { $name = $this->getShallowName($name, $options); $uri = $this->getResourceUri($name); $action = $this->getResourceAction($name, $controller, 'update', $options); return $this->router->match(['PUT', 'PATCH'], $uri, $action); } /** * Add the destroy method for a singleton route. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\Route */ protected function addSingletonDestroy($name, $controller, $options) { $name = $this->getShallowName($name, $options); $uri = $this->getResourceUri($name); $action = $this->getResourceAction($name, $controller, 'destroy', $options); return $this->router->delete($uri, $action); } /** * Get the name for a given resource with shallowness applied when applicable. * * @param string $name * @param array $options * @return string */ protected function getShallowName($name, $options) { return isset($options['shallow']) && $options['shallow'] ? last(explode('.', $name)) : $name; } /** * Set the route's binding fields if the resource is scoped. * * @param \Illuminate\Routing\Route $route * @param array $bindingFields * @return void */
195686
protected function setResourceBindingFields($route, $bindingFields) { preg_match_all('/(?<={).*?(?=})/', $route->uri, $matches); $fields = array_fill_keys($matches[0], null); $route->setBindingFields(array_replace( $fields, array_intersect_key($bindingFields, $fields) )); } /** * Get the base resource URI for a given resource. * * @param string $resource * @return string */ public function getResourceUri($resource) { if (! str_contains($resource, '.')) { return $resource; } // Once we have built the base URI, we'll remove the parameter holder for this // base resource name so that the individual route adders can suffix these // paths however they need to, as some do not have any parameters at all. $segments = explode('.', $resource); $uri = $this->getNestedResourceUri($segments); return str_replace('/{'.$this->getResourceWildcard(end($segments)).'}', '', $uri); } /** * Get the URI for a nested resource segment array. * * @param array $segments * @return string */ protected function getNestedResourceUri(array $segments) { // We will spin through the segments and create a place-holder for each of the // resource segments, as well as the resource itself. Then we should get an // entire string for the resource URI that contains all nested resources. return implode('/', array_map(function ($s) { return $s.'/{'.$this->getResourceWildcard($s).'}'; }, $segments)); } /** * Format a resource parameter for usage. * * @param string $value * @return string */ public function getResourceWildcard($value) { if (isset($this->parameters[$value])) { $value = $this->parameters[$value]; } elseif (isset(static::$parameterMap[$value])) { $value = static::$parameterMap[$value]; } elseif ($this->parameters === 'singular' || static::$singularParameters) { $value = Str::singular($value); } return str_replace('-', '_', $value); } /** * Get the action array for a resource route. * * @param string $resource * @param string $controller * @param string $method * @param array $options * @return array */ protected function getResourceAction($resource, $controller, $method, $options) { $name = $this->getResourceRouteName($resource, $method, $options); $action = ['as' => $name, 'uses' => $controller.'@'.$method]; if (isset($options['middleware'])) { $action['middleware'] = $options['middleware']; } if (isset($options['excluded_middleware'])) { $action['excluded_middleware'] = $options['excluded_middleware']; } if (isset($options['wheres'])) { $action['where'] = $options['wheres']; } if (isset($options['missing'])) { $action['missing'] = $options['missing']; } return $action; } /** * Get the name for a given resource. * * @param string $resource * @param string $method * @param array $options * @return string */ protected function getResourceRouteName($resource, $method, $options) { $name = $resource; // If the names array has been provided to us we will check for an entry in the // array first. We will also check for the specific method within this array // so the names may be specified on a more "granular" level using methods. if (isset($options['names'])) { if (is_string($options['names'])) { $name = $options['names']; } elseif (isset($options['names'][$method])) { return $options['names'][$method]; } } // If a global prefix has been assigned to all names for this resource, we will // grab that so we can prepend it onto the name when we create this name for // the resource action. Otherwise we'll just use an empty string for here. $prefix = isset($options['as']) ? $options['as'].'.' : ''; return trim(sprintf('%s%s.%s', $prefix, $name, $method), '.'); } /** * Set or unset the unmapped global parameters to singular. * * @param bool $singular * @return void */ public static function singularParameters($singular = true) { static::$singularParameters = (bool) $singular; } /** * Get the global parameter map. * * @return array */ public static function getParameters() { return static::$parameterMap; } /** * Set the global parameter mapping. * * @param array $parameters * @return void */ public static function setParameters(array $parameters = []) { static::$parameterMap = $parameters; } /** * Get or set the action verbs used in the resource URIs. * * @param array $verbs * @return array */ public static function verbs(array $verbs = []) { if (empty($verbs)) { return static::$verbs; } static::$verbs = array_merge(static::$verbs, $verbs); } }
195691
class Router implements BindingRegistrar, RegistrarContract { use Macroable { __call as macroCall; } use Tappable; /** * The event dispatcher instance. * * @var \Illuminate\Contracts\Events\Dispatcher */ protected $events; /** * The IoC container instance. * * @var \Illuminate\Container\Container */ protected $container; /** * The route collection instance. * * @var \Illuminate\Routing\RouteCollectionInterface */ protected $routes; /** * The currently dispatched route instance. * * @var \Illuminate\Routing\Route|null */ protected $current; /** * The request currently being dispatched. * * @var \Illuminate\Http\Request */ protected $currentRequest; /** * All of the short-hand keys for middlewares. * * @var array */ protected $middleware = []; /** * All of the middleware groups. * * @var array */ protected $middlewareGroups = []; /** * The priority-sorted list of middleware. * * Forces the listed middleware to always be in the given order. * * @var array */ public $middlewarePriority = []; /** * The registered route value binders. * * @var array */ protected $binders = []; /** * The globally available parameter patterns. * * @var array */ protected $patterns = []; /** * The route group attribute stack. * * @var array */ protected $groupStack = []; /** * The registered custom implicit binding callback. * * @var array */ protected $implicitBindingCallback; /** * All of the verbs supported by the router. * * @var string[] */ public static $verbs = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']; /** * Create a new Router instance. * * @param \Illuminate\Contracts\Events\Dispatcher $events * @param \Illuminate\Container\Container|null $container * @return void */ public function __construct(Dispatcher $events, ?Container $container = null) { $this->events = $events; $this->routes = new RouteCollection; $this->container = $container ?: new Container; } /** * Register a new GET route with the router. * * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function get($uri, $action = null) { return $this->addRoute(['GET', 'HEAD'], $uri, $action); } /** * Register a new POST route with the router. * * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function post($uri, $action = null) { return $this->addRoute('POST', $uri, $action); } /** * Register a new PUT route with the router. * * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function put($uri, $action = null) { return $this->addRoute('PUT', $uri, $action); } /** * Register a new PATCH route with the router. * * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function patch($uri, $action = null) { return $this->addRoute('PATCH', $uri, $action); } /** * Register a new DELETE route with the router. * * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function delete($uri, $action = null) { return $this->addRoute('DELETE', $uri, $action); } /** * Register a new OPTIONS route with the router. * * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function options($uri, $action = null) { return $this->addRoute('OPTIONS', $uri, $action); } /** * Register a new route responding to all verbs. * * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function any($uri, $action = null) { return $this->addRoute(self::$verbs, $uri, $action); } /** * Register a new fallback route with the router. * * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function fallback($action) { $placeholder = 'fallbackPlaceholder'; return $this->addRoute( 'GET', "{{$placeholder}}", $action )->where($placeholder, '.*')->fallback(); } /** * Create a redirect from one URI to another. * * @param string $uri * @param string $destination * @param int $status * @return \Illuminate\Routing\Route */ public function redirect($uri, $destination, $status = 302) { return $this->any($uri, '\Illuminate\Routing\RedirectController') ->defaults('destination', $destination) ->defaults('status', $status); } /** * Create a permanent redirect from one URI to another. * * @param string $uri * @param string $destination * @return \Illuminate\Routing\Route */ public function permanentRedirect($uri, $destination) { return $this->redirect($uri, $destination, 301); } /** * Register a new route that returns a view. * * @param string $uri * @param string $view * @param array $data * @param int|array $status * @param array $headers * @return \Illuminate\Routing\Route */ public function view($uri, $view, $data = [], $status = 200, array $headers = []) { return $this->match(['GET', 'HEAD'], $uri, '\Illuminate\Routing\ViewController') ->setDefaults([ 'view' => $view, 'data' => $data, 'status' => is_array($status) ? 200 : $status, 'headers' => is_array($status) ? $status : $headers, ]); } /** * Register a new route with the given verbs. * * @param array|string $methods * @param string $uri * @param array|string|callable|null $action * @return \Illuminate\Routing\Route */ public function match($methods, $uri, $action = null) { return $this->addRoute(array_map('strtoupper', (array) $methods), $uri, $action); } /** * Register an array of resource controllers. * * @param array $resources * @param array $options * @return void */ public function resources(array $resources, array $options = []) { foreach ($resources as $name => $controller) { $this->resource($name, $controller, $options); } } /** * Route a resource to a controller. * * @param string $name * @param string $controller * @param array $options * @return \Illuminate\Routing\PendingResourceRegistration */ public function resource($name, $controller, array $options = []) { if ($this->container && $this->container->bound(ResourceRegistrar::class)) { $registrar = $this->container->make(ResourceRegistrar::class); } else { $registrar = new ResourceRegistrar($this); } return new PendingResourceRegistration( $registrar, $name, $controller, $options ); } /** * Register an array of API resource controllers. * * @param array $resources * @param array $options * @return void */
195728
<?php namespace Illuminate\Routing\Controllers; interface HasMiddleware { /** * Get the middleware that should be assigned to the controller. * * @return \Illuminate\Routing\Controllers\Middleware[] */ public static function middleware(); }
195730
<?php namespace Illuminate\Routing\Console; use Illuminate\Console\Concerns\CreatesMatchingTest; use Illuminate\Console\GeneratorCommand; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'make:middleware')] class MiddlewareMakeCommand extends GeneratorCommand { use CreatesMatchingTest; /** * The console command name. * * @var string */ protected $name = 'make:middleware'; /** * The console command description. * * @var string */ protected $description = 'Create a new HTTP middleware class'; /** * The type of class being generated. * * @var string */ protected $type = 'Middleware'; /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return $this->resolveStubPath('/stubs/middleware.stub'); } /** * Resolve the fully-qualified path to the stub. * * @param string $stub * @return string */ protected function resolveStubPath($stub) { return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath : __DIR__.$stub; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Http\Middleware'; } }
195735
<?php namespace {{ namespace }}; use {{ rootNamespace }}Http\Controllers\Controller; use Illuminate\Http\Request; class {{ class }} extends Controller { /** * Display a listing of the resource. */ public function index() { // } /** * Show the form for creating a new resource. */ public function create() { // } /** * Store a newly created resource in storage. */ public function store(Request $request) { // } /** * Display the specified resource. */ public function show(string $id) { // } /** * Show the form for editing the specified resource. */ public function edit(string $id) { // } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { // } /** * Remove the specified resource from storage. */ public function destroy(string $id) { // } }
195741
<?php namespace {{ namespace }}; use {{ rootNamespace }}Http\Controllers\Controller; use Illuminate\Http\Request; class {{ class }} extends Controller { /** * Display a listing of the resource. */ public function index() { // } /** * Store a newly created resource in storage. */ public function store(Request $request) { // } /** * Display the specified resource. */ public function show(string $id) { // } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { // } /** * Remove the specified resource from storage. */ public function destroy(string $id) { // } }
195773
public function has($key); /** * Determine if any of the keys exist in the collection. * * @param mixed $key * @return bool */ public function hasAny($key); /** * Concatenate values of a given key as a string. * * @param (callable(TValue, TKey): mixed)|string $value * @param string|null $glue * @return string */ public function implode($value, $glue = null); /** * Intersect the collection with the given items. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function intersect($items); /** * Intersect the collection with the given items, using the callback. * * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items * @param callable(TValue, TValue): int $callback * @return static */ public function intersectUsing($items, callable $callback); /** * Intersect the collection with the given items with additional index check. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function intersectAssoc($items); /** * Intersect the collection with the given items with additional index check, using the callback. * * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items * @param callable(TValue, TValue): int $callback * @return static */ public function intersectAssocUsing($items, callable $callback); /** * Intersect the collection with the given items by key. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function intersectByKeys($items); /** * Determine if the collection is empty or not. * * @return bool */ public function isEmpty(); /** * Determine if the collection is not empty. * * @return bool */ public function isNotEmpty(); /** * Determine if the collection contains a single item. * * @return bool */ public function containsOneItem(); /** * Join all items from the collection using a string. The final items can use a separate glue string. * * @param string $glue * @param string $finalGlue * @return string */ public function join($glue, $finalGlue = ''); /** * Get the keys of the collection items. * * @return static<int, TKey> */ public function keys(); /** * Get the last item from the collection. * * @template TLastDefault * * @param (callable(TValue, TKey): bool)|null $callback * @param TLastDefault|(\Closure(): TLastDefault) $default * @return TValue|TLastDefault */ public function last(?callable $callback = null, $default = null); /** * Run a map over each of the items. * * @template TMapValue * * @param callable(TValue, TKey): TMapValue $callback * @return static<TKey, TMapValue> */ public function map(callable $callback); /** * Run a map over each nested chunk of items. * * @param callable $callback * @return static */ public function mapSpread(callable $callback); /** * Run a dictionary map over the items. * * The callback should return an associative array with a single key/value pair. * * @template TMapToDictionaryKey of array-key * @template TMapToDictionaryValue * * @param callable(TValue, TKey): array<TMapToDictionaryKey, TMapToDictionaryValue> $callback * @return static<TMapToDictionaryKey, array<int, TMapToDictionaryValue>> */ public function mapToDictionary(callable $callback); /** * Run a grouping map over the items. * * The callback should return an associative array with a single key/value pair. * * @template TMapToGroupsKey of array-key * @template TMapToGroupsValue * * @param callable(TValue, TKey): array<TMapToGroupsKey, TMapToGroupsValue> $callback * @return static<TMapToGroupsKey, static<int, TMapToGroupsValue>> */ public function mapToGroups(callable $callback); /** * Run an associative map over each of the items. * * The callback should return an associative array with a single key/value pair. * * @template TMapWithKeysKey of array-key * @template TMapWithKeysValue * * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback * @return static<TMapWithKeysKey, TMapWithKeysValue> */ public function mapWithKeys(callable $callback); /** * Map a collection and flatten the result by a single level. * * @template TFlatMapKey of array-key * @template TFlatMapValue * * @param callable(TValue, TKey): (\Illuminate\Support\Collection<TFlatMapKey, TFlatMapValue>|array<TFlatMapKey, TFlatMapValue>) $callback * @return static<TFlatMapKey, TFlatMapValue> */ public function flatMap(callable $callback); /** * Map the values into a new class. * * @template TMapIntoValue * * @param class-string<TMapIntoValue> $class * @return static<TKey, TMapIntoValue> */ public function mapInto($class); /** * Merge the collection with the given items. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function merge($items); /** * Recursively merge the collection with the given items. * * @template TMergeRecursiveValue * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TMergeRecursiveValue>|iterable<TKey, TMergeRecursiveValue> $items * @return static<TKey, TValue|TMergeRecursiveValue> */ public function mergeRecursive($items); /** * Create a collection by using this collection for keys and another for its values. * * @template TCombineValue * * @param \Illuminate\Contracts\Support\Arrayable<array-key, TCombineValue>|iterable<array-key, TCombineValue> $values * @return static<TValue, TCombineValue> */ public function combine($values); /** * Union the collection with the given items. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function union($items); /** * Get the min value of a given key. * * @param (callable(TValue):mixed)|string|null $callback * @return mixed */ public function min($callback = null); /** * Get the max value of a given key. * * @param (callable(TValue):mixed)|string|null $callback * @return mixed */ public function max($callback = null); /** * Create a new collection consisting of every n-th element. * * @param int $step * @param int $offset * @return static */ public function nth($step, $offset = 0); /** * Get the items with the specified keys. * * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|string $keys * @return static */ public function only($keys); /** * "Paginate" the collection by slicing it into a smaller collection. * * @param int $page * @param int $perPage * @return static */ public function forPage($page, $perPage);
195774
/** * Partition the collection into two arrays using the given callback or key. * * @param (callable(TValue, TKey): bool)|TValue|string $key * @param mixed $operator * @param mixed $value * @return static<int<0, 1>, static<TKey, TValue>> */ public function partition($key, $operator = null, $value = null); /** * Push all of the given items onto the collection. * * @template TConcatKey of array-key * @template TConcatValue * * @param iterable<TConcatKey, TConcatValue> $source * @return static<TKey|TConcatKey, TValue|TConcatValue> */ public function concat($source); /** * Get one or a specified number of items randomly from the collection. * * @param int|null $number * @return static<int, TValue>|TValue * * @throws \InvalidArgumentException */ public function random($number = null); /** * Reduce the collection to a single value. * * @template TReduceInitial * @template TReduceReturnType * * @param callable(TReduceInitial|TReduceReturnType, TValue, TKey): TReduceReturnType $callback * @param TReduceInitial $initial * @return TReduceReturnType */ public function reduce(callable $callback, $initial = null); /** * Reduce the collection to multiple aggregate values. * * @param callable $callback * @param mixed ...$initial * @return array * * @throws \UnexpectedValueException */ public function reduceSpread(callable $callback, ...$initial); /** * Replace the collection items with the given items. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function replace($items); /** * Recursively replace the collection items with the given items. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function replaceRecursive($items); /** * Reverse items order. * * @return static */ public function reverse(); /** * Search the collection for a given value and return the corresponding key if successful. * * @param TValue|callable(TValue,TKey): bool $value * @param bool $strict * @return TKey|bool */ public function search($value, $strict = false); /** * Get the item before the given item. * * @param TValue|(callable(TValue,TKey): bool) $value * @param bool $strict * @return TValue|null */ public function before($value, $strict = false); /** * Get the item after the given item. * * @param TValue|(callable(TValue,TKey): bool) $value * @param bool $strict * @return TValue|null */ public function after($value, $strict = false); /** * Shuffle the items in the collection. * * @return static */ public function shuffle(); /** * Create chunks representing a "sliding window" view of the items in the collection. * * @param int $size * @param int $step * @return static<int, static> */ public function sliding($size = 2, $step = 1); /** * Skip the first {$count} items. * * @param int $count * @return static */ public function skip($count); /** * Skip items in the collection until the given condition is met. * * @param TValue|callable(TValue,TKey): bool $value * @return static */ public function skipUntil($value); /** * Skip items in the collection while the given condition is met. * * @param TValue|callable(TValue,TKey): bool $value * @return static */ public function skipWhile($value); /** * Get a slice of items from the enumerable. * * @param int $offset * @param int|null $length * @return static */ public function slice($offset, $length = null); /** * Split a collection into a certain number of groups. * * @param int $numberOfGroups * @return static<int, static> */ public function split($numberOfGroups); /** * Get the first item in the collection, but only if exactly one item exists. Otherwise, throw an exception. * * @param (callable(TValue, TKey): bool)|string $key * @param mixed $operator * @param mixed $value * @return TValue * * @throws \Illuminate\Support\ItemNotFoundException * @throws \Illuminate\Support\MultipleItemsFoundException */ public function sole($key = null, $operator = null, $value = null); /** * Get the first item in the collection but throw an exception if no matching items exist. * * @param (callable(TValue, TKey): bool)|string $key * @param mixed $operator * @param mixed $value * @return TValue * * @throws \Illuminate\Support\ItemNotFoundException */ public function firstOrFail($key = null, $operator = null, $value = null); /** * Chunk the collection into chunks of the given size. * * @param int $size * @return static<int, static> */ public function chunk($size); /** * Chunk the collection into chunks with a callback. * * @param callable(TValue, TKey, static<int, TValue>): bool $callback * @return static<int, static<int, TValue>> */ public function chunkWhile(callable $callback); /** * Split a collection into a certain number of groups, and fill the first groups completely. * * @param int $numberOfGroups * @return static<int, static> */ public function splitIn($numberOfGroups); /** * Sort through each item with a callback. * * @param (callable(TValue, TValue): int)|null|int $callback * @return static */ public function sort($callback = null); /** * Sort items in descending order. * * @param int $options * @return static */ public function sortDesc($options = SORT_REGULAR); /** * Sort the collection using the given callback. * * @param array<array-key, (callable(TValue, TValue): mixed)|(callable(TValue, TKey): mixed)|string|array{string, string}>|(callable(TValue, TKey): mixed)|string $callback * @param int $options * @param bool $descending * @return static */ public function sortBy($callback, $options = SORT_REGULAR, $descending = false); /** * Sort the collection in descending order using the given callback. * * @param array<array-key, (callable(TValue, TValue): mixed)|(callable(TValue, TKey): mixed)|string|array{string, string}>|(callable(TValue, TKey): mixed)|string $callback * @param int $options * @return static */ public function sortByDesc($callback, $options = SORT_REGULAR); /** * Sort the collection keys. * * @param int $options * @param bool $descending * @return static */ public function sortKeys($options = SORT_REGULAR, $descending = false); /** * Sort the collection keys in descending order. * * @param int $options * @return static */ public function sortKeysDesc($options = SORT_REGULAR); /** * Sort the collection keys using a callback. * * @param callable(TKey, TKey): int $callback * @return static */ public function sortKeysUsing(callable $callback); /** * Get the sum of the given values. * * @param (callable(TValue): mixed)|string|null $callback * @return mixed */ public function sum($callback = null);
195778
public function diffKeysUsing($items, callable $callback) { return new static(array_diff_ukey($this->items, $this->getArrayableItems($items), $callback)); } /** * Retrieve duplicate items from the collection. * * @param (callable(TValue): bool)|string|null $callback * @param bool $strict * @return static */ public function duplicates($callback = null, $strict = false) { $items = $this->map($this->valueRetriever($callback)); $uniqueItems = $items->unique(null, $strict); $compare = $this->duplicateComparator($strict); $duplicates = new static; foreach ($items as $key => $value) { if ($uniqueItems->isNotEmpty() && $compare($value, $uniqueItems->first())) { $uniqueItems->shift(); } else { $duplicates[$key] = $value; } } return $duplicates; } /** * Retrieve duplicate items from the collection using strict comparison. * * @param (callable(TValue): bool)|string|null $callback * @return static */ public function duplicatesStrict($callback = null) { return $this->duplicates($callback, true); } /** * Get the comparison function to detect duplicates. * * @param bool $strict * @return callable(TValue, TValue): bool */ protected function duplicateComparator($strict) { if ($strict) { return fn ($a, $b) => $a === $b; } return fn ($a, $b) => $a == $b; } /** * Get all items except for those with the specified keys. * * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|string $keys * @return static */ public function except($keys) { if (is_null($keys)) { return new static($this->items); } if ($keys instanceof Enumerable) { $keys = $keys->all(); } elseif (! is_array($keys)) { $keys = func_get_args(); } return new static(Arr::except($this->items, $keys)); } /** * Run a filter over each of the items. * * @param (callable(TValue, TKey): bool)|null $callback * @return static */ public function filter(?callable $callback = null) { if ($callback) { return new static(Arr::where($this->items, $callback)); } return new static(array_filter($this->items)); } /** * Get the first item from the collection passing the given truth test. * * @template TFirstDefault * * @param (callable(TValue, TKey): bool)|null $callback * @param TFirstDefault|(\Closure(): TFirstDefault) $default * @return TValue|TFirstDefault */ public function first(?callable $callback = null, $default = null) { return Arr::first($this->items, $callback, $default); } /** * Get a flattened array of the items in the collection. * * @param int $depth * @return static<int, mixed> */ public function flatten($depth = INF) { return new static(Arr::flatten($this->items, $depth)); } /** * Flip the items in the collection. * * @return static<TValue, TKey> */ public function flip() { return new static(array_flip($this->items)); } /** * Remove an item from the collection by key. * * \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TKey>|TKey $keys * * @return $this */ public function forget($keys) { foreach ($this->getArrayableItems($keys) as $key) { $this->offsetUnset($key); } return $this; } /** * Get an item from the collection by key. * * @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->items)) { return $this->items[$key]; } return value($default); } /** * Get an item from the collection by key or add it to collection if it does not exist. * * @template TGetOrPutValue * * @param mixed $key * @param TGetOrPutValue|(\Closure(): TGetOrPutValue) $value * @return TValue|TGetOrPutValue */ public function getOrPut($key, $value) { if (array_key_exists($key, $this->items)) { return $this->items[$key]; } $this->offsetSet($key, $value = value($value)); return $value; } /** * Group an associative array by a field or using a callback. * * @template TGroupKey of array-key * * @param (callable(TValue, TKey): TGroupKey)|array|string $groupBy * @param bool $preserveKeys * @return static<($groupBy is string ? array-key : ($groupBy is array ? array-key : TGroupKey)), static<($preserveKeys is true ? TKey : int), TValue>> */ public function groupBy($groupBy, $preserveKeys = false) { if (! $this->useAsCallable($groupBy) && is_array($groupBy)) { $nextGroups = $groupBy; $groupBy = array_shift($nextGroups); } $groupBy = $this->valueRetriever($groupBy); $results = []; foreach ($this->items as $key => $value) { $groupKeys = $groupBy($value, $key); if (! is_array($groupKeys)) { $groupKeys = [$groupKeys]; } foreach ($groupKeys as $groupKey) { $groupKey = match (true) { is_bool($groupKey) => (int) $groupKey, $groupKey instanceof \BackedEnum => $groupKey->value, $groupKey instanceof \Stringable => (string) $groupKey, default => $groupKey, }; if (! array_key_exists($groupKey, $results)) { $results[$groupKey] = new static; } $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value); } } $result = new static($results); if (! empty($nextGroups)) { return $result->map->groupBy($nextGroups, $preserveKeys); } return $result; } /** * Key an associative array by a field or using a callback. * * @template TNewKey of array-key * * @param (callable(TValue, TKey): TNewKey)|array|string $keyBy * @return static<($keyBy is string ? array-key : ($keyBy is array ? array-key : TNewKey)), TValue> */ public function keyBy($keyBy) { $keyBy = $this->valueRetriever($keyBy); $results = []; foreach ($this->items as $key => $item) { $resolvedKey = $keyBy($item, $key); if (is_object($resolvedKey)) { $resolvedKey = (string) $resolvedKey; } $results[$resolvedKey] = $item; } return new static($results); } /** * Determine if an item exists in the collection by key. * * @param TKey|array<array-key, TKey> $key * @return bool */ public function has($key) { $keys = is_array($key) ? $key : func_get_args(); foreach ($keys as $value) { if (! array_key_exists($value, $this->items)) { return false; } } return true; } /** * Determine if any of the keys exist in the collection. * * @param mixed $key * @return bool */
195779
public function hasAny($key) { if ($this->isEmpty()) { return false; } $keys = is_array($key) ? $key : func_get_args(); foreach ($keys as $value) { if ($this->has($value)) { return true; } } return false; } /** * Concatenate values of a given key as a string. * * @param (callable(TValue, TKey): mixed)|string|null $value * @param string|null $glue * @return string */ public function implode($value, $glue = null) { if ($this->useAsCallable($value)) { return implode($glue ?? '', $this->map($value)->all()); } $first = $this->first(); if (is_array($first) || (is_object($first) && ! $first instanceof Stringable)) { return implode($glue ?? '', $this->pluck($value)->all()); } return implode($value ?? '', $this->items); } /** * Intersect the collection with the given items. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function intersect($items) { return new static(array_intersect($this->items, $this->getArrayableItems($items))); } /** * Intersect the collection with the given items, using the callback. * * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items * @param callable(TValue, TValue): int $callback * @return static */ public function intersectUsing($items, callable $callback) { return new static(array_uintersect($this->items, $this->getArrayableItems($items), $callback)); } /** * Intersect the collection with the given items with additional index check. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function intersectAssoc($items) { return new static(array_intersect_assoc($this->items, $this->getArrayableItems($items))); } /** * Intersect the collection with the given items with additional index check, using the callback. * * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items * @param callable(TValue, TValue): int $callback * @return static */ public function intersectAssocUsing($items, callable $callback) { return new static(array_intersect_uassoc($this->items, $this->getArrayableItems($items), $callback)); } /** * Intersect the collection with the given items by key. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function intersectByKeys($items) { return new static(array_intersect_key( $this->items, $this->getArrayableItems($items) )); } /** * Determine if the collection is empty or not. * * @phpstan-assert-if-true null $this->first() * @phpstan-assert-if-true null $this->last() * * @phpstan-assert-if-false TValue $this->first() * @phpstan-assert-if-false TValue $this->last() * * @return bool */ public function isEmpty() { return empty($this->items); } /** * Determine if the collection contains a single item. * * @return bool */ public function containsOneItem() { return $this->count() === 1; } /** * Join all items from the collection using a string. The final items can use a separate glue string. * * @param string $glue * @param string $finalGlue * @return string */ public function join($glue, $finalGlue = '') { if ($finalGlue === '') { return $this->implode($glue); } $count = $this->count(); if ($count === 0) { return ''; } if ($count === 1) { return $this->last(); } $collection = new static($this->items); $finalItem = $collection->pop(); return $collection->implode($glue).$finalGlue.$finalItem; } /** * Get the keys of the collection items. * * @return static<int, TKey> */ public function keys() { return new static(array_keys($this->items)); } /** * Get the last item from the collection. * * @template TLastDefault * * @param (callable(TValue, TKey): bool)|null $callback * @param TLastDefault|(\Closure(): TLastDefault) $default * @return TValue|TLastDefault */ public function last(?callable $callback = null, $default = null) { return Arr::last($this->items, $callback, $default); } /** * Get the values of a given key. * * @param string|int|array<array-key, string>|null $value * @param string|null $key * @return static<array-key, mixed> */ public function pluck($value, $key = null) { return new static(Arr::pluck($this->items, $value, $key)); } /** * Run a map over each of the items. * * @template TMapValue * * @param callable(TValue, TKey): TMapValue $callback * @return static<TKey, TMapValue> */ public function map(callable $callback) { return new static(Arr::map($this->items, $callback)); } /** * Run a dictionary map over the items. * * The callback should return an associative array with a single key/value pair. * * @template TMapToDictionaryKey of array-key * @template TMapToDictionaryValue * * @param callable(TValue, TKey): array<TMapToDictionaryKey, TMapToDictionaryValue> $callback * @return static<TMapToDictionaryKey, array<int, TMapToDictionaryValue>> */ public function mapToDictionary(callable $callback) { $dictionary = []; foreach ($this->items as $key => $item) { $pair = $callback($item, $key); $key = key($pair); $value = reset($pair); if (! isset($dictionary[$key])) { $dictionary[$key] = []; } $dictionary[$key][] = $value; } return new static($dictionary); } /** * Run an associative map over each of the items. * * The callback should return an associative array with a single key/value pair. * * @template TMapWithKeysKey of array-key * @template TMapWithKeysValue * * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback * @return static<TMapWithKeysKey, TMapWithKeysValue> */ public function mapWithKeys(callable $callback) { return new static(Arr::mapWithKeys($this->items, $callback)); } /** * Merge the collection with the given items. * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items * @return static */ public function merge($items) { return new static(array_merge($this->items, $this->getArrayableItems($items))); } /** * Recursively merge the collection with the given items. * * @template TMergeRecursiveValue * * @param \Illuminate\Contracts\Support\Arrayable<TKey, TMergeRecursiveValue>|iterable<TKey, TMergeRecursiveValue> $items * @return static<TKey, TValue|TMergeRecursiveValue> */ public function mergeRecursive($items) { return new static(array_merge_recursive($this->items, $this->getArrayableItems($items))); } /** * Multiply the items in the collection by the multiplier. * * @param int $multiplier * @return static */
195782
public function sortBy($callback, $options = SORT_REGULAR, $descending = false) { if (is_array($callback) && ! is_callable($callback)) { return $this->sortByMany($callback, $options); } $results = []; $callback = $this->valueRetriever($callback); // First we will loop through the items and get the comparator from a callback // function which we were given. Then, we will sort the returned values and // grab all the corresponding values for the sorted keys from this array. foreach ($this->items as $key => $value) { $results[$key] = $callback($value, $key); } $descending ? arsort($results, $options) : asort($results, $options); // Once we have sorted all of the keys in the array, we will loop through them // and grab the corresponding model so we can set the underlying items list // to the sorted version. Then we'll just return the collection instance. foreach (array_keys($results) as $key) { $results[$key] = $this->items[$key]; } return new static($results); } /** * Sort the collection using multiple comparisons. * * @param array<array-key, (callable(TValue, TValue): mixed)|(callable(TValue, TKey): mixed)|string|array{string, string}> $comparisons * @param int $options * @return static */ protected function sortByMany(array $comparisons = [], int $options = SORT_REGULAR) { $items = $this->items; uasort($items, function ($a, $b) use ($comparisons, $options) { foreach ($comparisons as $comparison) { $comparison = Arr::wrap($comparison); $prop = $comparison[0]; $ascending = Arr::get($comparison, 1, true) === true || Arr::get($comparison, 1, true) === 'asc'; if (! is_string($prop) && is_callable($prop)) { $result = $prop($a, $b); } else { $values = [data_get($a, $prop), data_get($b, $prop)]; if (! $ascending) { $values = array_reverse($values); } if (($options & SORT_FLAG_CASE) === SORT_FLAG_CASE) { if (($options & SORT_NATURAL) === SORT_NATURAL) { $result = strnatcasecmp($values[0], $values[1]); } else { $result = strcasecmp($values[0], $values[1]); } } else { $result = match ($options) { SORT_NUMERIC => intval($values[0]) <=> intval($values[1]), SORT_STRING => strcmp($values[0], $values[1]), SORT_NATURAL => strnatcmp((string) $values[0], (string) $values[1]), SORT_LOCALE_STRING => strcoll($values[0], $values[1]), default => $values[0] <=> $values[1], }; } } if ($result === 0) { continue; } return $result; } }); return new static($items); } /** * Sort the collection in descending order using the given callback. * * @param array<array-key, (callable(TValue, TValue): mixed)|(callable(TValue, TKey): mixed)|string|array{string, string}>|(callable(TValue, TKey): mixed)|string $callback * @param int $options * @return static */ public function sortByDesc($callback, $options = SORT_REGULAR) { if (is_array($callback) && ! is_callable($callback)) { foreach ($callback as $index => $key) { $comparison = Arr::wrap($key); $comparison[1] = 'desc'; $callback[$index] = $comparison; } } return $this->sortBy($callback, $options, true); } /** * Sort the collection keys. * * @param int $options * @param bool $descending * @return static */ public function sortKeys($options = SORT_REGULAR, $descending = false) { $items = $this->items; $descending ? krsort($items, $options) : ksort($items, $options); return new static($items); } /** * Sort the collection keys in descending order. * * @param int $options * @return static */ public function sortKeysDesc($options = SORT_REGULAR) { return $this->sortKeys($options, true); } /** * Sort the collection keys using a callback. * * @param callable(TKey, TKey): int $callback * @return static */ public function sortKeysUsing(callable $callback) { $items = $this->items; uksort($items, $callback); return new static($items); } /** * Splice a portion of the underlying collection array. * * @param int $offset * @param int|null $length * @param array<array-key, TValue> $replacement * @return static */ public function splice($offset, $length = null, $replacement = []) { if (func_num_args() === 1) { return new static(array_splice($this->items, $offset)); } return new static(array_splice($this->items, $offset, $length, $this->getArrayableItems($replacement))); } /** * Take the first or last {$limit} items. * * @param int $limit * @return static */ public function take($limit) { if ($limit < 0) { return $this->slice($limit, abs($limit)); } return $this->slice(0, $limit); } /** * Take items in the collection until the given condition is met. * * @param TValue|callable(TValue,TKey): bool $value * @return static */ public function takeUntil($value) { return new static($this->lazy()->takeUntil($value)->all()); } /** * Take items in the collection while the given condition is met. * * @param TValue|callable(TValue,TKey): bool $value * @return static */ public function takeWhile($value) { return new static($this->lazy()->takeWhile($value)->all()); } /** * Transform each item in the collection using a callback. * * @param callable(TValue, TKey): TValue $callback * @return $this */ public function transform(callable $callback) { $this->items = $this->map($callback)->all(); return $this; } /** * Flatten a multi-dimensional associative array with dots. * * @return static */ public function dot() { return new static(Arr::dot($this->all())); } /** * Convert a flatten "dot" notation array into an expanded array. * * @return static */ public function undot() { return new static(Arr::undot($this->all())); } /** * Return only unique items from the collection array. * * @param (callable(TValue, TKey): mixed)|string|null $key * @param bool $strict * @return static */ public function unique($key = null, $strict = false) { if (is_null($key) && $strict === false) { return new static(array_unique($this->items, SORT_REGULAR)); } $callback = $this->valueRetriever($key); $exists = []; return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) { if (in_array($id = $callback($item, $key), $exists, $strict)) { return true; } $exists[] = $id; }); } /** * Reset the keys on the underlying array. * * @return static<int, TValue> */ public function values() { return new static(array_values($this->items)); }
195786
public static function get($array, $key, $default = null) { if (! static::accessible($array)) { return value($default); } if (is_null($key)) { return $array; } if (static::exists($array, $key)) { return $array[$key]; } if (! str_contains($key, '.')) { return $array[$key] ?? value($default); } foreach (explode('.', $key) as $segment) { if (static::accessible($array) && static::exists($array, $segment)) { $array = $array[$segment]; } else { return value($default); } } return $array; } /** * Check if an item or items exist in an array using "dot" notation. * * @param \ArrayAccess|array $array * @param string|array $keys * @return bool */ public static function has($array, $keys) { $keys = (array) $keys; if (! $array || $keys === []) { return false; } foreach ($keys as $key) { $subKeyArray = $array; if (static::exists($array, $key)) { continue; } foreach (explode('.', $key) as $segment) { if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) { $subKeyArray = $subKeyArray[$segment]; } else { return false; } } } return true; } /** * Determine if any of the keys exist in an array using "dot" notation. * * @param \ArrayAccess|array $array * @param string|array $keys * @return bool */ public static function hasAny($array, $keys) { if (is_null($keys)) { return false; } $keys = (array) $keys; if (! $array) { return false; } if ($keys === []) { return false; } foreach ($keys as $key) { if (static::has($array, $key)) { return true; } } return false; } /** * Determines if an array is associative. * * An array is "associative" if it doesn't have sequential numerical keys beginning with zero. * * @param array $array * @return bool */ public static function isAssoc(array $array) { return ! array_is_list($array); } /** * Determines if an array is a list. * * An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between. * * @param array $array * @return bool */ public static function isList($array) { return array_is_list($array); } /** * Join all items using a string. The final items can use a separate glue string. * * @param array $array * @param string $glue * @param string $finalGlue * @return string */ public static function join($array, $glue, $finalGlue = '') { if ($finalGlue === '') { return implode($glue, $array); } if (count($array) === 0) { return ''; } if (count($array) === 1) { return end($array); } $finalItem = array_pop($array); return implode($glue, $array).$finalGlue.$finalItem; } /** * Key an associative array by a field or using a callback. * * @param array $array * @param callable|array|string $keyBy * @return array */ public static function keyBy($array, $keyBy) { return Collection::make($array)->keyBy($keyBy)->all(); } /** * Prepend the key names of an associative array. * * @param array $array * @param string $prependWith * @return array */ public static function prependKeysWith($array, $prependWith) { return static::mapWithKeys($array, fn ($item, $key) => [$prependWith.$key => $item]); } /** * Get a subset of the items from the given array. * * @param array $array * @param array|string $keys * @return array */ public static function only($array, $keys) { return array_intersect_key($array, array_flip((array) $keys)); } /** * Select an array of values from an array. * * @param array $array * @param array|string $keys * @return array */ public static function select($array, $keys) { $keys = static::wrap($keys); return static::map($array, function ($item) use ($keys) { $result = []; foreach ($keys as $key) { if (Arr::accessible($item) && Arr::exists($item, $key)) { $result[$key] = $item[$key]; } elseif (is_object($item) && isset($item->{$key})) { $result[$key] = $item->{$key}; } } return $result; }); } /** * Pluck an array of values from an array. * * @param iterable $array * @param string|array|int|null $value * @param string|array|null $key * @return array */ public static function pluck($array, $value, $key = null) { $results = []; [$value, $key] = static::explodePluckParameters($value, $key); foreach ($array as $item) { $itemValue = data_get($item, $value); // If the key is "null", we will just append the value to the array and keep // looping. Otherwise we will key the array using the value of the key we // received from the developer. Then we'll return the final array form. if (is_null($key)) { $results[] = $itemValue; } else { $itemKey = data_get($item, $key); if (is_object($itemKey) && method_exists($itemKey, '__toString')) { $itemKey = (string) $itemKey; } $results[$itemKey] = $itemValue; } } return $results; } /** * Explode the "value" and "key" arguments passed to "pluck". * * @param string|array $value * @param string|array|null $key * @return array */ protected static function explodePluckParameters($value, $key) { $value = is_string($value) ? explode('.', $value) : $value; $key = is_null($key) || is_array($key) ? $key : explode('.', $key); return [$value, $key]; } /** * Run a map over each of the items in the array. * * @param array $array * @param callable $callback * @return array */ public static function map(array $array, callable $callback) { $keys = array_keys($array); try { $items = array_map($callback, $array, $keys); } catch (ArgumentCountError) { $items = array_map($callback, $array); } return array_combine($keys, $items); } /** * Run an associative map over each of the items. * * The callback should return an associative array with a single key/value pair. * * @template TKey * @template TValue * @template TMapWithKeysKey of array-key * @template TMapWithKeysValue * * @param array<TKey, TValue> $array * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback * @return array */
195791
/** * Determine if the collection is not empty. * * @phpstan-assert-if-true TValue $this->first() * @phpstan-assert-if-true TValue $this->last() * * @phpstan-assert-if-false null $this->first() * @phpstan-assert-if-false null $this->last() * * @return bool */ public function isNotEmpty() { return ! $this->isEmpty(); } /** * Run a map over each nested chunk of items. * * @template TMapSpreadValue * * @param callable(mixed...): TMapSpreadValue $callback * @return static<TKey, TMapSpreadValue> */ public function mapSpread(callable $callback) { return $this->map(function ($chunk, $key) use ($callback) { $chunk[] = $key; return $callback(...$chunk); }); } /** * Run a grouping map over the items. * * The callback should return an associative array with a single key/value pair. * * @template TMapToGroupsKey of array-key * @template TMapToGroupsValue * * @param callable(TValue, TKey): array<TMapToGroupsKey, TMapToGroupsValue> $callback * @return static<TMapToGroupsKey, static<int, TMapToGroupsValue>> */ public function mapToGroups(callable $callback) { $groups = $this->mapToDictionary($callback); return $groups->map([$this, 'make']); } /** * Map a collection and flatten the result by a single level. * * @template TFlatMapKey of array-key * @template TFlatMapValue * * @param callable(TValue, TKey): (\Illuminate\Support\Collection<TFlatMapKey, TFlatMapValue>|array<TFlatMapKey, TFlatMapValue>) $callback * @return static<TFlatMapKey, TFlatMapValue> */ public function flatMap(callable $callback) { return $this->map($callback)->collapse(); } /** * Map the values into a new class. * * @template TMapIntoValue * * @param class-string<TMapIntoValue> $class * @return static<TKey, TMapIntoValue> */ public function mapInto($class) { if (is_subclass_of($class, BackedEnum::class)) { return $this->map(fn ($value, $key) => $class::from($value)); } return $this->map(fn ($value, $key) => new $class($value, $key)); } /** * Get the min value of a given key. * * @param (callable(TValue):mixed)|string|null $callback * @return mixed */ public function min($callback = null) { $callback = $this->valueRetriever($callback); return $this->map(fn ($value) => $callback($value)) ->filter(fn ($value) => ! is_null($value)) ->reduce(fn ($result, $value) => is_null($result) || $value < $result ? $value : $result); } /** * Get the max value of a given key. * * @param (callable(TValue):mixed)|string|null $callback * @return mixed */ public function max($callback = null) { $callback = $this->valueRetriever($callback); return $this->filter(fn ($value) => ! is_null($value))->reduce(function ($result, $item) use ($callback) { $value = $callback($item); return is_null($result) || $value > $result ? $value : $result; }); } /** * "Paginate" the collection by slicing it into a smaller collection. * * @param int $page * @param int $perPage * @return static */ public function forPage($page, $perPage) { $offset = max(0, ($page - 1) * $perPage); return $this->slice($offset, $perPage); } /** * Partition the collection into two arrays using the given callback or key. * * @param (callable(TValue, TKey): bool)|TValue|string $key * @param TValue|string|null $operator * @param TValue|null $value * @return static<int<0, 1>, static<TKey, TValue>> */ public function partition($key, $operator = null, $value = null) { $passed = []; $failed = []; $callback = func_num_args() === 1 ? $this->valueRetriever($key) : $this->operatorForWhere(...func_get_args()); foreach ($this as $key => $item) { if ($callback($item, $key)) { $passed[$key] = $item; } else { $failed[$key] = $item; } } return new static([new static($passed), new static($failed)]); } /** * Calculate the percentage of items that pass a given truth test. * * @param (callable(TValue, TKey): bool) $callback * @param int $precision * @return float|null */ public function percentage(callable $callback, int $precision = 2) { if ($this->isEmpty()) { return null; } return round( $this->filter($callback)->count() / $this->count() * 100, $precision ); } /** * Get the sum of the given values. * * @param (callable(TValue): mixed)|string|null $callback * @return mixed */ public function sum($callback = null) { $callback = is_null($callback) ? $this->identity() : $this->valueRetriever($callback); return $this->reduce(fn ($result, $item) => $result + $callback($item), 0); } /** * Apply the callback if the collection is empty. * * @template TWhenEmptyReturnType * * @param (callable($this): TWhenEmptyReturnType) $callback * @param (callable($this): TWhenEmptyReturnType)|null $default * @return $this|TWhenEmptyReturnType */ public function whenEmpty(callable $callback, ?callable $default = null) { return $this->when($this->isEmpty(), $callback, $default); } /** * Apply the callback if the collection is not empty. * * @template TWhenNotEmptyReturnType * * @param callable($this): TWhenNotEmptyReturnType $callback * @param (callable($this): TWhenNotEmptyReturnType)|null $default * @return $this|TWhenNotEmptyReturnType */ public function whenNotEmpty(callable $callback, ?callable $default = null) { return $this->when($this->isNotEmpty(), $callback, $default); } /** * Apply the callback unless the collection is empty. * * @template TUnlessEmptyReturnType * * @param callable($this): TUnlessEmptyReturnType $callback * @param (callable($this): TUnlessEmptyReturnType)|null $default * @return $this|TUnlessEmptyReturnType */ public function unlessEmpty(callable $callback, ?callable $default = null) { return $this->whenNotEmpty($callback, $default); } /** * Apply the callback unless the collection is not empty. * * @template TUnlessNotEmptyReturnType * * @param callable($this): TUnlessNotEmptyReturnType $callback * @param (callable($this): TUnlessNotEmptyReturnType)|null $default * @return $this|TUnlessNotEmptyReturnType */ public function unlessNotEmpty(callable $callback, ?callable $default = null) { return $this->whenEmpty($callback, $default); } /** * Filter items by the given key value pair. * * @param callable|string $key * @param mixed $operator * @param mixed $value * @return static */ public function where($key, $operator = null, $value = null) { return $this->filter($this->operatorForWhere(...func_get_args())); }
195832
public function after($callback) { if (is_array($callback) && ! is_callable($callback)) { foreach ($callback as $rule) { $this->after(method_exists($rule, 'after') ? $rule->after(...) : $rule); } return $this; } $this->after[] = fn () => $callback($this); return $this; } /** * Determine if the data passes the validation rules. * * @return bool */ public function passes() { $this->messages = new MessageBag; [$this->distinctValues, $this->failedRules] = [[], []]; // We'll spin through each rule, validating the attributes attached to that // rule. Any error messages will be added to the containers with each of // the other error messages, returning true if we don't have messages. foreach ($this->rules as $attribute => $rules) { if ($this->shouldBeExcluded($attribute)) { $this->removeAttribute($attribute); continue; } if ($this->stopOnFirstFailure && $this->messages->isNotEmpty()) { break; } foreach ($rules as $rule) { $this->validateAttribute($attribute, $rule); if ($this->shouldBeExcluded($attribute)) { break; } if ($this->shouldStopValidating($attribute)) { break; } } } foreach ($this->rules as $attribute => $rules) { if ($this->shouldBeExcluded($attribute)) { $this->removeAttribute($attribute); } } // Here we will spin through all of the "after" hooks on this validator and // fire them off. This gives the callbacks a chance to perform all kinds // of other validation that needs to get wrapped up in this operation. foreach ($this->after as $after) { $after(); } return $this->messages->isEmpty(); } /** * Determine if the data fails the validation rules. * * @return bool */ public function fails() { return ! $this->passes(); } /** * Determine if the attribute should be excluded. * * @param string $attribute * @return bool */ protected function shouldBeExcluded($attribute) { foreach ($this->excludeAttributes as $excludeAttribute) { if ($attribute === $excludeAttribute || Str::startsWith($attribute, $excludeAttribute.'.')) { return true; } } return false; } /** * Remove the given attribute. * * @param string $attribute * @return void */ protected function removeAttribute($attribute) { Arr::forget($this->data, $attribute); Arr::forget($this->rules, $attribute); } /** * Run the validator's rules against its data. * * @return array * * @throws \Illuminate\Validation\ValidationException */ public function validate() { throw_if($this->fails(), $this->exception, $this); return $this->validated(); } /** * Run the validator's rules against its data. * * @param string $errorBag * @return array * * @throws \Illuminate\Validation\ValidationException */ public function validateWithBag(string $errorBag) { try { return $this->validate(); } catch (ValidationException $e) { $e->errorBag = $errorBag; throw $e; } } /** * Get a validated input container for the validated input. * * @param array|null $keys * @return \Illuminate\Support\ValidatedInput|array */ public function safe(?array $keys = null) { return is_array($keys) ? (new ValidatedInput($this->validated()))->only($keys) : new ValidatedInput($this->validated()); } /** * Get the attributes and values that were validated. * * @return array * * @throws \Illuminate\Validation\ValidationException */ public function validated() { if (! $this->messages) { $this->passes(); } throw_if($this->messages->isNotEmpty(), $this->exception, $this); $results = []; $missingValue = new stdClass; foreach ($this->getRules() as $key => $rules) { $value = data_get($this->getData(), $key, $missingValue); if ($this->excludeUnvalidatedArrayKeys && (in_array('array', $rules) || in_array('list', $rules)) && $value !== null && ! empty(preg_grep('/^'.preg_quote($key, '/').'\.+/', array_keys($this->getRules())))) { continue; } if ($value !== $missingValue) { Arr::set($results, $key, $value); } } return $this->replacePlaceholders($results); } /** * Validate a given attribute against a rule. * * @param string $attribute * @param string $rule * @return void */ protected function validateAttribute($attribute, $rule) { $this->currentRule = $rule; [$rule, $parameters] = ValidationRuleParser::parse($rule); if ($rule === '') { return; } // First we will get the correct keys for the given attribute in case the field is nested in // an array. Then we determine if the given rule accepts other field names as parameters. // If so, we will replace any asterisks found in the parameters with the correct keys. if ($this->dependsOnOtherFields($rule)) { $parameters = $this->replaceDotInParameters($parameters); if ($keys = $this->getExplicitKeys($attribute)) { $parameters = $this->replaceAsterisksInParameters($parameters, $keys); } } $value = $this->getValue($attribute); // If the attribute is a file, we will verify that the file upload was actually successful // and if it wasn't we will add a failure for the attribute. Files may not successfully // upload if they are too large based on PHP's settings so we will bail in this case. if ($value instanceof UploadedFile && ! $value->isValid() && $this->hasRule($attribute, array_merge($this->fileRules, $this->implicitRules)) ) { return $this->addFailure($attribute, 'uploaded', []); } // If we have made it this far we will make sure the attribute is validatable and if it is // we will call the validation method with the attribute. If a method returns false the // attribute is invalid and we will add a failure message for this failing attribute. $validatable = $this->isValidatable($rule, $attribute, $value); if ($rule instanceof RuleContract) { return $validatable ? $this->validateUsingCustomRule($attribute, $value, $rule) : null; } $method = "validate{$rule}"; $this->numericRules = $this->defaultNumericRules; if ($validatable && ! $this->$method($attribute, $value, $parameters, $this)) { $this->addFailure($attribute, $rule, $parameters); } } /** * Determine if the given rule depends on other fields. * * @param string $rule * @return bool */ protected function dependsOnOtherFields($rule) { return in_array($rule, $this->dependentRules); } /** * Get the explicit keys from an attribute flattened with dot notation. * * E.g. 'foo.1.bar.spark.baz' -> [1, 'spark'] for 'foo.*.bar.*.baz' * * @param string $attribute * @return array */ protected function getExplicitKeys($attribute) { $pattern = str_replace('\*', '([^\.]+)', preg_quote($this->getPrimaryAttribute($attribute), '/')); if (preg_match('/^'.$pattern.'/', $attribute, $keys)) { array_shift($keys); return $keys; } return []; } /** * Get the primary attribute name. * * For example, if "name.0" is given, "name.*" will be returned. * * @param string $attribute * @return string */ protected function getPrimaryAttribute($attribute) { foreach ($this->implicitAttributes as $unparsed => $parsed) { if (in_array($attribute, $parsed, true)) { return $unparsed; } } return $attribute; }
195840
<?php namespace Illuminate\Validation; use Illuminate\Foundation\Precognition; /** * Provides default implementation of ValidatesWhenResolved contract. */ trait ValidatesWhenResolvedTrait { /** * Validate the class instance. * * @return void */ public function validateResolved() { $this->prepareForValidation(); if (! $this->passesAuthorization()) { $this->failedAuthorization(); } $instance = $this->getValidatorInstance(); if ($this->isPrecognitive()) { $instance->after(Precognition::afterValidationHook($this)); } if ($instance->fails()) { $this->failedValidation($instance); } $this->passedValidation(); } /** * Prepare the data for validation. * * @return void */ protected function prepareForValidation() { // } /** * Get the validator instance for the request. * * @return \Illuminate\Validation\Validator */ protected function getValidatorInstance() { return $this->validator(); } /** * Handle a passed validation attempt. * * @return void */ protected function passedValidation() { // } /** * Handle a failed validation attempt. * * @param \Illuminate\Validation\Validator $validator * @return void * * @throws \Illuminate\Validation\ValidationException */ protected function failedValidation(Validator $validator) { $exception = $validator->getException(); throw new $exception($validator); } /** * Determine if the request passes the authorization check. * * @return bool */ protected function passesAuthorization() { if (method_exists($this, 'authorize')) { return $this->authorize(); } return true; } /** * Handle a failed authorization attempt. * * @return void * * @throws \Illuminate\Validation\UnauthorizedException */ protected function failedAuthorization() { throw new UnauthorizedException; } }
195868
trait ValidatesAttributes { /** * Validate that an attribute was "accepted". * * This validation rule implies the attribute is "required". * * @param string $attribute * @param mixed $value * @return bool */ public function validateAccepted($attribute, $value) { $acceptable = ['yes', 'on', '1', 1, true, 'true']; return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true); } /** * Validate that an attribute was "accepted" when another attribute has a given value. * * @param string $attribute * @param mixed $value * @param mixed $parameters * @return bool */ public function validateAcceptedIf($attribute, $value, $parameters) { $acceptable = ['yes', 'on', '1', 1, true, 'true']; $this->requireParameterCount(2, $parameters, 'accepted_if'); [$values, $other] = $this->parseDependentRuleParameters($parameters); if (in_array($other, $values, is_bool($other) || is_null($other))) { return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true); } return true; } /** * Validate that an attribute was "declined". * * This validation rule implies the attribute is "required". * * @param string $attribute * @param mixed $value * @return bool */ public function validateDeclined($attribute, $value) { $acceptable = ['no', 'off', '0', 0, false, 'false']; return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true); } /** * Validate that an attribute was "declined" when another attribute has a given value. * * @param string $attribute * @param mixed $value * @param mixed $parameters * @return bool */ public function validateDeclinedIf($attribute, $value, $parameters) { $acceptable = ['no', 'off', '0', 0, false, 'false']; $this->requireParameterCount(2, $parameters, 'declined_if'); [$values, $other] = $this->parseDependentRuleParameters($parameters); if (in_array($other, $values, is_bool($other) || is_null($other))) { return $this->validateRequired($attribute, $value) && in_array($value, $acceptable, true); } return true; } /** * Validate that an attribute is an active URL. * * @param string $attribute * @param mixed $value * @return bool */ public function validateActiveUrl($attribute, $value) { if (! is_string($value)) { return false; } if ($url = parse_url($value, PHP_URL_HOST)) { try { $records = $this->getDnsRecords($url.'.', DNS_A | DNS_AAAA); if (is_array($records) && count($records) > 0) { return true; } } catch (Exception) { return false; } } return false; } /** * Get the DNS records for the given hostname. * * @param string $hostname * @param int $type * @return array|false */ protected function getDnsRecords($hostname, $type) { return dns_get_record($hostname, $type); } /** * Validate that an attribute is 7 bit ASCII. * * @param string $attribute * @param mixed $value * @return bool */ public function validateAscii($attribute, $value) { return Str::isAscii($value); } /** * "Break" on first validation fail. * * Always returns true, just lets us put "bail" in rules. * * @return bool */ public function validateBail() { return true; } /** * Validate the date is before a given date. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateBefore($attribute, $value, $parameters) { $this->requireParameterCount(1, $parameters, 'before'); return $this->compareDates($attribute, $value, $parameters, '<'); } /** * Validate the date is before or equal a given date. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateBeforeOrEqual($attribute, $value, $parameters) { $this->requireParameterCount(1, $parameters, 'before_or_equal'); return $this->compareDates($attribute, $value, $parameters, '<='); } /** * Validate the date is after a given date. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateAfter($attribute, $value, $parameters) { $this->requireParameterCount(1, $parameters, 'after'); return $this->compareDates($attribute, $value, $parameters, '>'); } /** * Validate the date is equal or after a given date. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateAfterOrEqual($attribute, $value, $parameters) { $this->requireParameterCount(1, $parameters, 'after_or_equal'); return $this->compareDates($attribute, $value, $parameters, '>='); } /** * Compare a given date against another using an operator. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @param string $operator * @return bool */ protected function compareDates($attribute, $value, $parameters, $operator) { if (! is_string($value) && ! is_numeric($value) && ! $value instanceof DateTimeInterface) { return false; } if ($format = $this->getDateFormat($attribute)) { return $this->checkDateTimeOrder($format, $value, $parameters[0], $operator); } if (is_null($date = $this->getDateTimestamp($parameters[0]))) { $date = $this->getDateTimestamp($this->getValue($parameters[0])); } return $this->compare($this->getDateTimestamp($value), $date, $operator); } /** * Get the date format for an attribute if it has one. * * @param string $attribute * @return string|null */ protected function getDateFormat($attribute) { if ($result = $this->getRule($attribute, 'DateFormat')) { return $result[1][0]; } } /** * Get the date timestamp. * * @param mixed $value * @return int */ protected function getDateTimestamp($value) { $date = is_null($value) ? null : $this->getDateTime($value); return $date ? $date->getTimestamp() : null; } /** * Given two date/time strings, check that one is after the other. * * @param string $format * @param string $first * @param string $second * @param string $operator * @return bool */
195871
/** * Validate an attribute is unique among other values. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateDistinct($attribute, $value, $parameters) { $data = Arr::except($this->getDistinctValues($attribute), $attribute); if (in_array('ignore_case', $parameters)) { return empty(preg_grep('/^'.preg_quote($value, '/').'$/iu', $data)); } return ! in_array($value, array_values($data), in_array('strict', $parameters)); } /** * Get the values to distinct between. * * @param string $attribute * @return array */ protected function getDistinctValues($attribute) { $attributeName = $this->getPrimaryAttribute($attribute); if (! property_exists($this, 'distinctValues')) { return $this->extractDistinctValues($attributeName); } if (! array_key_exists($attributeName, $this->distinctValues)) { $this->distinctValues[$attributeName] = $this->extractDistinctValues($attributeName); } return $this->distinctValues[$attributeName]; } /** * Extract the distinct values from the data. * * @param string $attribute * @return array */ protected function extractDistinctValues($attribute) { $attributeData = ValidationData::extractDataFromPath( ValidationData::getLeadingExplicitAttributePath($attribute), $this->data ); $pattern = str_replace('\*', '[^.]+', preg_quote($attribute, '#')); return Arr::where(Arr::dot($attributeData), function ($value, $key) use ($pattern) { return (bool) preg_match('#^'.$pattern.'\z#u', $key); }); } /** * Validate that an attribute is a valid e-mail address. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateEmail($attribute, $value, $parameters) { if (! is_string($value) && ! (is_object($value) && method_exists($value, '__toString'))) { return false; } $validations = collect($parameters) ->unique() ->map(fn ($validation) => match (true) { $validation === 'strict' => new NoRFCWarningsValidation(), $validation === 'dns' => new DNSCheckValidation(), $validation === 'spoof' => new SpoofCheckValidation(), $validation === 'filter' => new FilterEmailValidation(), $validation === 'filter_unicode' => FilterEmailValidation::unicode(), is_string($validation) && class_exists($validation) => $this->container->make($validation), default => new RFCValidation(), }) ->values() ->all() ?: [new RFCValidation]; $emailValidator = Container::getInstance()->make(EmailValidator::class); return $emailValidator->isValid($value, new MultipleValidationWithAnd($validations)); } /** * Validate the existence of an attribute value in a database table. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateExists($attribute, $value, $parameters) { $this->requireParameterCount(1, $parameters, 'exists'); [$connection, $table] = $this->parseTable($parameters[0]); // The second parameter position holds the name of the column that should be // verified as existing. If this parameter is not specified we will guess // that the columns being "verified" shares the given attribute's name. $column = $this->getQueryColumn($parameters, $attribute); $expected = is_array($value) ? count(array_unique($value)) : 1; if ($expected === 0) { return true; } return $this->getExistCount( $connection, $table, $column, $value, $parameters ) >= $expected; } /** * Get the number of records that exist in storage. * * @param mixed $connection * @param string $table * @param string $column * @param mixed $value * @param array<int, int|string> $parameters * @return int */ protected function getExistCount($connection, $table, $column, $value, $parameters) { $verifier = $this->getPresenceVerifier($connection); $extra = $this->getExtraConditions( array_values(array_slice($parameters, 2)) ); if ($this->currentRule instanceof Exists) { $extra = array_merge($extra, $this->currentRule->queryCallbacks()); } return is_array($value) ? $verifier->getMultiCount($table, $column, $value, $extra) : $verifier->getCount($table, $column, $value, null, null, $extra); } /** * Validate the uniqueness of an attribute value on a given database table. * * If a database column is not specified, the attribute will be used. * * @param string $attribute * @param mixed $value * @param array<int, int|string> $parameters * @return bool */ public function validateUnique($attribute, $value, $parameters) { $this->requireParameterCount(1, $parameters, 'unique'); [$connection, $table, $idColumn] = $this->parseTable($parameters[0]); // The second parameter position holds the name of the column that needs to // be verified as unique. If this parameter isn't specified we will just // assume that this column to be verified shares the attribute's name. $column = $this->getQueryColumn($parameters, $attribute); $id = null; if (isset($parameters[2])) { [$idColumn, $id] = $this->getUniqueIds($idColumn, $parameters); if (! is_null($id)) { $id = stripslashes($id); } } // The presence verifier is responsible for counting rows within this store // mechanism which might be a relational database or any other permanent // data store like Redis, etc. We will use it to determine uniqueness. $verifier = $this->getPresenceVerifier($connection); $extra = $this->getUniqueExtra($parameters); if ($this->currentRule instanceof Unique) { $extra = array_merge($extra, $this->currentRule->queryCallbacks()); } return $verifier->getCount( $table, $column, $value, $id, $idColumn, $extra ) == 0; } /** * Get the excluded ID column and value for the unique rule. * * @param string|null $idColumn * @param array<int, int|string> $parameters * @return array */ protected function getUniqueIds($idColumn, $parameters) { $idColumn ??= $parameters[3] ?? 'id'; return [$idColumn, $this->prepareUniqueId($parameters[2])]; } /** * Prepare the given ID for querying. * * @param mixed $id * @return int */ protected function prepareUniqueId($id) { if (preg_match('/\[(.*)\]/', $id, $matches)) { $id = $this->getValue($matches[1]); } if (strtolower($id) === 'null') { $id = null; } if (filter_var($id, FILTER_VALIDATE_INT) !== false) { $id = (int) $id; } return $id; } /** * Get the extra conditions for a unique rule. * * @param array<int, int|string> $parameters * @return array */ protected function getUniqueExtra($parameters) { if (isset($parameters[4])) { return $this->getExtraConditions(array_slice($parameters, 4)); } return []; } /** * Parse the connection / table for the unique / exists rules. * * @param string $table * @return array */
195993
<?php namespace Illuminate\Session; use Illuminate\Contracts\Cache\Factory as CacheFactory; use Illuminate\Session\Middleware\StartSession; use Illuminate\Support\ServiceProvider; class SessionServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->registerSessionManager(); $this->registerSessionDriver(); $this->app->singleton(StartSession::class, function ($app) { return new StartSession($app->make(SessionManager::class), function () use ($app) { return $app->make(CacheFactory::class); }); }); } /** * Register the session manager instance. * * @return void */ protected function registerSessionManager() { $this->app->singleton('session', function ($app) { return new SessionManager($app); }); } /** * Register the session driver instance. * * @return void */ protected function registerSessionDriver() { $this->app->singleton('session.store', function ($app) { // First, we will create the session manager which is responsible for the // creation of the various session drivers when they are needed by the // application instance, and will resolve them on a lazy load basis. return $app->make('session')->driver(); }); } }
195994
<?php namespace Illuminate\Session; use Exception; class TokenMismatchException extends Exception { // }
195995
<?php namespace Illuminate\Session; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Carbon; use SessionHandlerInterface; use Symfony\Component\Finder\Finder; class FileSessionHandler implements SessionHandlerInterface { /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * The path where sessions should be stored. * * @var string */ protected $path; /** * The number of minutes the session should be valid. * * @var int */ protected $minutes; /** * Create a new file driven handler instance. * * @param \Illuminate\Filesystem\Filesystem $files * @param string $path * @param int $minutes * @return void */ public function __construct(Filesystem $files, $path, $minutes) { $this->path = $path; $this->files = $files; $this->minutes = $minutes; } /** * {@inheritdoc} * * @return bool */ public function open($savePath, $sessionName): bool { return true; } /** * {@inheritdoc} * * @return bool */ public function close(): bool { return true; } /** * {@inheritdoc} * * @return string|false */ public function read($sessionId): string|false { if ($this->files->isFile($path = $this->path.'/'.$sessionId) && $this->files->lastModified($path) >= Carbon::now()->subMinutes($this->minutes)->getTimestamp()) { return $this->files->sharedGet($path); } return ''; } /** * {@inheritdoc} * * @return bool */ public function write($sessionId, $data): bool { $this->files->put($this->path.'/'.$sessionId, $data, true); return true; } /** * {@inheritdoc} * * @return bool */ public function destroy($sessionId): bool { $this->files->delete($this->path.'/'.$sessionId); return true; } /** * {@inheritdoc} * * @return int */ public function gc($lifetime): int { $files = Finder::create() ->in($this->path) ->files() ->ignoreDotFiles(true) ->date('<= now - '.$lifetime.' seconds'); $deletedSessions = 0; foreach ($files as $file) { $this->files->delete($file->getRealPath()); $deletedSessions++; } return $deletedSessions; } }
196000
<?php namespace Illuminate\Session; use Illuminate\Support\Manager; /** * @mixin \Illuminate\Session\Store */ class SessionManager extends Manager { /** * Call a custom driver creator. * * @param string $driver * @return \Illuminate\Session\Store */ protected function callCustomCreator($driver) { return $this->buildSession(parent::callCustomCreator($driver)); } /** * Create an instance of the "null" session driver. * * @return \Illuminate\Session\Store */ protected function createNullDriver() { return $this->buildSession(new NullSessionHandler); } /** * Create an instance of the "array" session driver. * * @return \Illuminate\Session\Store */ protected function createArrayDriver() { return $this->buildSession(new ArraySessionHandler( $this->config->get('session.lifetime') )); } /** * Create an instance of the "cookie" session driver. * * @return \Illuminate\Session\Store */ protected function createCookieDriver() { return $this->buildSession(new CookieSessionHandler( $this->container->make('cookie'), $this->config->get('session.lifetime'), $this->config->get('session.expire_on_close') )); } /** * Create an instance of the file session driver. * * @return \Illuminate\Session\Store */ protected function createFileDriver() { return $this->createNativeDriver(); } /** * Create an instance of the file session driver. * * @return \Illuminate\Session\Store */ protected function createNativeDriver() { $lifetime = $this->config->get('session.lifetime'); return $this->buildSession(new FileSessionHandler( $this->container->make('files'), $this->config->get('session.files'), $lifetime )); } /** * Create an instance of the database session driver. * * @return \Illuminate\Session\Store */ protected function createDatabaseDriver() { $table = $this->config->get('session.table'); $lifetime = $this->config->get('session.lifetime'); return $this->buildSession(new DatabaseSessionHandler( $this->getDatabaseConnection(), $table, $lifetime, $this->container )); } /** * Get the database connection for the database driver. * * @return \Illuminate\Database\Connection */ protected function getDatabaseConnection() { $connection = $this->config->get('session.connection'); return $this->container->make('db')->connection($connection); } /** * Create an instance of the APC session driver. * * @return \Illuminate\Session\Store */ protected function createApcDriver() { return $this->createCacheBased('apc'); } /** * Create an instance of the Memcached session driver. * * @return \Illuminate\Session\Store */ protected function createMemcachedDriver() { return $this->createCacheBased('memcached'); } /** * Create an instance of the Redis session driver. * * @return \Illuminate\Session\Store */ protected function createRedisDriver() { $handler = $this->createCacheHandler('redis'); $handler->getCache()->getStore()->setConnection( $this->config->get('session.connection') ); return $this->buildSession($handler); } /** * Create an instance of the DynamoDB session driver. * * @return \Illuminate\Session\Store */ protected function createDynamodbDriver() { return $this->createCacheBased('dynamodb'); } /** * Create an instance of a cache driven driver. * * @param string $driver * @return \Illuminate\Session\Store */ protected function createCacheBased($driver) { return $this->buildSession($this->createCacheHandler($driver)); } /** * Create the cache based session handler instance. * * @param string $driver * @return \Illuminate\Session\CacheBasedSessionHandler */ protected function createCacheHandler($driver) { $store = $this->config->get('session.store') ?: $driver; return new CacheBasedSessionHandler( clone $this->container->make('cache')->store($store), $this->config->get('session.lifetime') ); } /** * Build the session instance. * * @param \SessionHandlerInterface $handler * @return \Illuminate\Session\Store */ protected function buildSession($handler) { return $this->config->get('session.encrypt') ? $this->buildEncryptedSession($handler) : new Store( $this->config->get('session.cookie'), $handler, $id = null, $this->config->get('session.serialization', 'php') ); } /** * Build the encrypted session instance. * * @param \SessionHandlerInterface $handler * @return \Illuminate\Session\EncryptedStore */ protected function buildEncryptedSession($handler) { return new EncryptedStore( $this->config->get('session.cookie'), $handler, $this->container['encrypter'], $id = null, $this->config->get('session.serialization', 'php'), ); } /** * Determine if requests for the same session should wait for each to finish before executing. * * @return bool */ public function shouldBlock() { return $this->config->get('session.block', false); } /** * Get the name of the cache store / driver that should be used to acquire session locks. * * @return string|null */ public function blockDriver() { return $this->config->get('session.block_store'); } /** * Get the maximum number of seconds the session lock should be held for. * * @return int */ public function defaultRouteBlockLockSeconds() { return $this->config->get('session.block_lock_seconds', 10); } /** * Get the maximum number of seconds to wait while attempting to acquire a route block session lock. * * @return int */ public function defaultRouteBlockWaitSeconds() { return $this->config->get('session.block_wait_seconds', 10); } /** * Get the session configuration. * * @return array */ public function getSessionConfig() { return $this->config->get('session'); } /** * Get the default session driver name. * * @return string */ public function getDefaultDriver() { return $this->config->get('session.driver'); } /** * Set the default session driver name. * * @param string $name * @return void */ public function setDefaultDriver($name) { $this->config->set('session.driver', $name); } }