Pressroom template verwijderd, website naar root van repo

This commit is contained in:
2020-03-22 15:30:52 +01:00
parent 2cb6a77425
commit f3d1c41e91
7620 changed files with 0 additions and 186900 deletions

View File

@@ -0,0 +1,242 @@
<?php
namespace Illuminate\Foundation;
class AliasLoader
{
/**
* The array of class aliases.
*
* @var array
*/
protected $aliases;
/**
* Indicates if a loader has been registered.
*
* @var bool
*/
protected $registered = false;
/**
* The namespace for all real-time facades.
*
* @var string
*/
protected static $facadeNamespace = 'Facades\\';
/**
* The singleton instance of the loader.
*
* @var \Illuminate\Foundation\AliasLoader
*/
protected static $instance;
/**
* Create a new AliasLoader instance.
*
* @param array $aliases
*/
private function __construct($aliases)
{
$this->aliases = $aliases;
}
/**
* Get or create the singleton alias loader instance.
*
* @param array $aliases
* @return \Illuminate\Foundation\AliasLoader
*/
public static function getInstance(array $aliases = [])
{
if (is_null(static::$instance)) {
return static::$instance = new static($aliases);
}
$aliases = array_merge(static::$instance->getAliases(), $aliases);
static::$instance->setAliases($aliases);
return static::$instance;
}
/**
* Load a class alias if it is registered.
*
* @param string $alias
* @return bool|null
*/
public function load($alias)
{
if (static::$facadeNamespace && strpos($alias, static::$facadeNamespace) === 0) {
$this->loadFacade($alias);
return true;
}
if (isset($this->aliases[$alias])) {
return class_alias($this->aliases[$alias], $alias);
}
}
/**
* Load a real-time facade for the given alias.
*
* @param string $alias
* @return void
*/
protected function loadFacade($alias)
{
require $this->ensureFacadeExists($alias);
}
/**
* Ensure that the given alias has an existing real-time facade class.
*
* @param string $alias
* @return string
*/
protected function ensureFacadeExists($alias)
{
if (file_exists($path = storage_path('framework/cache/facade-'.sha1($alias).'.php'))) {
return $path;
}
file_put_contents($path, $this->formatFacadeStub(
$alias, file_get_contents(__DIR__.'/stubs/facade.stub')
));
return $path;
}
/**
* Format the facade stub with the proper namespace and class.
*
* @param string $alias
* @param string $stub
* @return string
*/
protected function formatFacadeStub($alias, $stub)
{
$replacements = [
str_replace('/', '\\', dirname(str_replace('\\', '/', $alias))),
class_basename($alias),
substr($alias, strlen(static::$facadeNamespace)),
];
return str_replace(
['DummyNamespace', 'DummyClass', 'DummyTarget'], $replacements, $stub
);
}
/**
* Add an alias to the loader.
*
* @param string $class
* @param string $alias
* @return void
*/
public function alias($class, $alias)
{
$this->aliases[$class] = $alias;
}
/**
* Register the loader on the auto-loader stack.
*
* @return void
*/
public function register()
{
if (! $this->registered) {
$this->prependToLoaderStack();
$this->registered = true;
}
}
/**
* Prepend the load method to the auto-loader stack.
*
* @return void
*/
protected function prependToLoaderStack()
{
spl_autoload_register([$this, 'load'], true, true);
}
/**
* Get the registered aliases.
*
* @return array
*/
public function getAliases()
{
return $this->aliases;
}
/**
* Set the registered aliases.
*
* @param array $aliases
* @return void
*/
public function setAliases(array $aliases)
{
$this->aliases = $aliases;
}
/**
* Indicates if the loader has been registered.
*
* @return bool
*/
public function isRegistered()
{
return $this->registered;
}
/**
* Set the "registered" state of the loader.
*
* @param bool $value
* @return void
*/
public function setRegistered($value)
{
$this->registered = $value;
}
/**
* Set the real-time facade namespace.
*
* @param string $namespace
* @return void
*/
public static function setFacadeNamespace($namespace)
{
static::$facadeNamespace = rtrim($namespace, '\\').'\\';
}
/**
* Set the value of the singleton alias loader.
*
* @param \Illuminate\Foundation\AliasLoader $loader
* @return void
*/
public static function setInstance($loader)
{
static::$instance = $loader;
}
/**
* Clone method.
*
* @return void
*/
private function __clone()
{
//
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,44 @@
<?php
namespace Illuminate\Foundation\Auth\Access;
use Illuminate\Contracts\Auth\Access\Gate;
trait Authorizable
{
/**
* Determine if the entity has a given ability.
*
* @param string $ability
* @param array|mixed $arguments
* @return bool
*/
public function can($ability, $arguments = [])
{
return app(Gate::class)->forUser($this)->check($ability, $arguments);
}
/**
* Determine if the entity does not have a given ability.
*
* @param string $ability
* @param array|mixed $arguments
* @return bool
*/
public function cant($ability, $arguments = [])
{
return ! $this->can($ability, $arguments);
}
/**
* Determine if the entity does not have a given ability.
*
* @param string $ability
* @param array|mixed $arguments
* @return bool
*/
public function cannot($ability, $arguments = [])
{
return $this->cant($ability, $arguments);
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Illuminate\Foundation\Auth\Access;
use Illuminate\Contracts\Auth\Access\Gate;
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 = [])
{
list($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 = [])
{
list($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) && strpos($ability, '\\') === false) {
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 isset($map[$ability]) ? $map[$ability] : $ability;
}
/**
* Authorize a resource action based on the incoming request.
*
* @param string $model
* @param string|null $parameter
* @param array $options
* @param \Illuminate\Http\Request|null $request
* @return void
*/
public function authorizeResource($model, $parameter = null, array $options = [], $request = null)
{
$parameter = $parameter ?: lcfirst(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 [
'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'];
}
}

View File

@@ -0,0 +1,172 @@
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait AuthenticatesUsers
{
use RedirectsUsers, ThrottlesLogins;
/**
* Show the application's login form.
*
* @return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('auth.login');
}
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
/**
* Attempt to log the user into the application.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->has('remember')
);
}
/**
* Get the needed authorization credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password');
}
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
//
}
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function username()
{
return 'email';
}
/**
* Log the user out of the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/');
}
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Illuminate\Foundation\Auth;
trait RedirectsUsers
{
/**
* Get the post register / login redirect path.
*
* @return string
*/
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
trait RegistersUsers
{
use RedirectsUsers;
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
return view('auth.register');
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* Get the guard to be used during registration.
*
* @return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
/**
* The user has been registered.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function registered(Request $request, $user)
{
//
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
trait ResetsPasswords
{
use RedirectsUsers;
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* @param \Illuminate\Http\Request $request
* @param string|null $token
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
/**
* Reset the given user's password.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function reset(Request $request)
{
$this->validate($request, $this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
/**
* Get the password reset validation rules.
*
* @return array
*/
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
];
}
/**
* Get the password reset validation error messages.
*
* @return array
*/
protected function validationErrorMessages()
{
return [];
}
/**
* Get the password reset credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function credentials(Request $request)
{
return $request->only(
'email', 'password', 'password_confirmation', 'token'
);
}
/**
* Reset the given user's password.
*
* @param \Illuminate\Contracts\Auth\CanResetPassword $user
* @param string $password
* @return void
*/
protected function resetPassword($user, $password)
{
$user->forceFill([
'password' => bcrypt($password),
'remember_token' => Str::random(60),
])->save();
$this->guard()->login($user);
}
/**
* Get the response for a successful password reset.
*
* @param string $response
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendResetResponse($response)
{
return redirect($this->redirectPath())
->with('status', trans($response));
}
/**
* Get the response for a failed password reset.
*
* @param \Illuminate\Http\Request
* @param string $response
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendResetFailedResponse(Request $request, $response)
{
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
/**
* Get the broker to be used during password reset.
*
* @return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}
/**
* Get the guard to be used during password reset.
*
* @return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
trait SendsPasswordResetEmails
{
/**
* Display the form to request a password reset link.
*
* @return \Illuminate\Http\Response
*/
public function showLinkRequestForm()
{
return view('auth.passwords.email');
}
/**
* Send a reset link to the given user.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validateEmail($request);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
/**
* Validate the email for the given request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function validateEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
}
/**
* Get the response for a successful password reset link.
*
* @param string $response
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendResetLinkResponse($response)
{
return back()->with('status', trans($response));
}
/**
* Get the response for a failed password reset link.
*
* @param \Illuminate\Http\Request
* @param string $response
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendResetLinkFailedResponse(Request $request, $response)
{
return back()->withErrors(
['email' => trans($response)]
);
}
/**
* Get the broker to be used during password reset.
*
* @return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Cache\RateLimiter;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Support\Facades\Lang;
trait ThrottlesLogins
{
/**
* Determine if the user has too many failed login attempts.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function hasTooManyLoginAttempts(Request $request)
{
return $this->limiter()->tooManyAttempts(
$this->throttleKey($request), $this->maxAttempts(), $this->decayMinutes()
);
}
/**
* Increment the login attempts for the user.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function incrementLoginAttempts(Request $request)
{
$this->limiter()->hit($this->throttleKey($request));
}
/**
* Redirect the user after determining they are locked out.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendLockoutResponse(Request $request)
{
$seconds = $this->limiter()->availableIn(
$this->throttleKey($request)
);
$message = Lang::get('auth.throttle', ['seconds' => $seconds]);
$errors = [$this->username() => $message];
if ($request->expectsJson()) {
return response()->json($errors, 423);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* Clear the login locks for the given user credentials.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function clearLoginAttempts(Request $request)
{
$this->limiter()->clear($this->throttleKey($request));
}
/**
* Fire an event when a lockout occurs.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function fireLockoutEvent(Request $request)
{
event(new Lockout($request));
}
/**
* Get the throttle key for the given request.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function throttleKey(Request $request)
{
return Str::lower($request->input($this->username())).'|'.$request->ip();
}
/**
* Get the rate limiter instance.
*
* @return \Illuminate\Cache\RateLimiter
*/
protected function limiter()
{
return app(RateLimiter::class);
}
/**
* Get the maximum number of attempts to allow.
*
* @return int
*/
public function maxAttempts()
{
return property_exists($this, 'maxAttempts') ? $this->maxAttempts : 5;
}
/**
* Get the number of minutes to throttle for.
*
* @return int
*/
public function decayMinutes()
{
return property_exists($this, 'decayMinutes') ? $this->decayMinutes : 1;
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Illuminate\Contracts\Foundation\Application;
class BootProviders
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
$app->boot();
}
}

View File

@@ -0,0 +1,161 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Exception;
use ErrorException;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Foundation\Application;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
class HandleExceptions
{
/**
* The application instance.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
$this->app = $app;
error_reporting(-1);
set_error_handler([$this, 'handleError']);
set_exception_handler([$this, 'handleException']);
register_shutdown_function([$this, 'handleShutdown']);
if (! $app->environment('testing')) {
ini_set('display_errors', 'Off');
}
}
/**
* Convert PHP errors to ErrorException instances.
*
* @param int $level
* @param string $message
* @param string $file
* @param int $line
* @param array $context
* @return void
*
* @throws \ErrorException
*/
public function handleError($level, $message, $file = '', $line = 0, $context = [])
{
if (error_reporting() & $level) {
throw new ErrorException($message, 0, $level, $file, $line);
}
}
/**
* Handle an uncaught exception from the application.
*
* Note: Most exceptions can be handled via the try / catch block in
* the HTTP and Console kernels. But, fatal error exceptions must
* be handled differently since they are not normal exceptions.
*
* @param \Throwable $e
* @return void
*/
public function handleException($e)
{
if (! $e instanceof Exception) {
$e = new FatalThrowableError($e);
}
try {
$this->getExceptionHandler()->report($e);
} catch (Exception $e) {
//
}
if ($this->app->runningInConsole()) {
$this->renderForConsole($e);
} else {
$this->renderHttpResponse($e);
}
}
/**
* Render an exception to the console.
*
* @param \Exception $e
* @return void
*/
protected function renderForConsole(Exception $e)
{
$this->getExceptionHandler()->renderForConsole(new ConsoleOutput, $e);
}
/**
* Render an exception as an HTTP response and send it.
*
* @param \Exception $e
* @return void
*/
protected function renderHttpResponse(Exception $e)
{
$this->getExceptionHandler()->render($this->app['request'], $e)->send();
}
/**
* Handle the PHP shutdown event.
*
* @return void
*/
public function handleShutdown()
{
if (! is_null($error = error_get_last()) && $this->isFatal($error['type'])) {
$this->handleException($this->fatalExceptionFromError($error, 0));
}
}
/**
* Create a new fatal exception instance from an error array.
*
* @param array $error
* @param int|null $traceOffset
* @return \Symfony\Component\Debug\Exception\FatalErrorException
*/
protected function fatalExceptionFromError(array $error, $traceOffset = null)
{
return new FatalErrorException(
$error['message'], $error['type'], 0, $error['file'], $error['line'], $traceOffset
);
}
/**
* Determine if the error type is fatal.
*
* @param int $type
* @return bool
*/
protected function isFatal($type)
{
return in_array($type, [E_COMPILE_ERROR, E_CORE_ERROR, E_ERROR, E_PARSE]);
}
/**
* Get an instance of the exception handler.
*
* @return \Illuminate\Contracts\Debug\ExceptionHandler
*/
protected function getExceptionHandler()
{
return $this->app->make(ExceptionHandler::class);
}
}

View File

@@ -0,0 +1,113 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Exception;
use SplFileInfo;
use Illuminate\Config\Repository;
use Symfony\Component\Finder\Finder;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Config\Repository as RepositoryContract;
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;
$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(function () use ($config) {
return $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);
if (! isset($files['app'])) {
throw new Exception('Unable to load the "app" configuration file.');
}
foreach ($files as $key => $path) {
$repository->set($key, require $path);
}
}
/**
* 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());
foreach (Finder::create()->files()->name('*.php')->in($configPath) as $file) {
$directory = $this->getNestedDirectory($file, $configPath);
$files[$directory.basename($file->getRealPath(), '.php')] = $file->getRealPath();
}
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;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Symfony\Component\Console\Input\ArgvInput;
use Illuminate\Contracts\Foundation\Application;
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 {
(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
} catch (InvalidPathException $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 (php_sapi_name() == 'cli' && with($input = new ArgvInput)->hasParameterOption('--env')) {
$this->setEnvironmentFilePath(
$app, $app->environmentFile().'.'.$input->getParameterOption('--env')
);
}
if (! env('APP_ENV')) {
return;
}
$this->setEnvironmentFilePath(
$app, $app->environmentFile().'.'.env('APP_ENV')
);
}
/**
* Load a custom environment file.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param string $file
* @return void
*/
protected function setEnvironmentFilePath($app, $file)
{
if (file_exists($app->environmentPath().'/'.$file)) {
$app->loadEnvironmentFrom($file);
}
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\Facades\Facade;
use Illuminate\Contracts\Foundation\Application;
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($app->make('config')->get('app.aliases', []))->register();
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Illuminate\Contracts\Foundation\Application;
class RegisterProviders
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
$app->registerConfiguredProviders();
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Illuminate\Http\Request;
use Illuminate\Contracts\Foundation\Application;
class SetRequestForConsole
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
$app->instance('request', Request::create(
$app->make('config')->get('app.url', 'http://localhost'), 'GET', [], [], [], $_SERVER
));
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Illuminate\Foundation\Bus;
trait Dispatchable
{
/**
* Dispatch the job with the given arguments.
*
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public static function dispatch()
{
return new PendingDispatch(new static(...func_get_args()));
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Illuminate\Foundation\Bus;
use Illuminate\Contracts\Bus\Dispatcher;
trait DispatchesJobs
{
/**
* Dispatch a job to its appropriate handler.
*
* @param mixed $job
* @return mixed
*/
protected function dispatch($job)
{
return app(Dispatcher::class)->dispatch($job);
}
/**
* Dispatch a command to its appropriate handler in the current process.
*
* @param mixed $job
* @return mixed
*/
public function dispatchNow($job)
{
return app(Dispatcher::class)->dispatchNow($job);
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace Illuminate\Foundation\Bus;
class PendingDispatch
{
/**
* Create a new pending job dispatch.
*
* @param mixed $job
* @return void
*/
public function __construct($job)
{
$this->job = $job;
}
/**
* Set the desired connection for the job.
*
* @param string|null $connection
* @return $this
*/
public function onConnection($connection)
{
$this->job->onConnection($connection);
return $this;
}
/**
* Set the desired queue for the job.
*
* @param string|null $queue
* @return $this
*/
public function onQueue($queue)
{
$this->job->onQueue($queue);
return $this;
}
/**
* Set the desired delay for the job.
*
* @param \DateTime|int|null $delay
* @return $this
*/
public function delay($delay)
{
$this->job->delay($delay);
return $this;
}
/**
* Handle the object's destruction.
*
* @return void
*/
public function __destruct()
{
dispatch($this->job);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Illuminate\Foundation;
use Composer\Script\Event;
class ComposerScripts
{
/**
* Handle the post-install Composer event.
*
* @param \Composer\Script\Event $event
* @return void
*/
public static function postInstall(Event $event)
{
require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php';
static::clearCompiled();
}
/**
* Handle the post-update Composer event.
*
* @param \Composer\Script\Event $event
* @return void
*/
public static function postUpdate(Event $event)
{
require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php';
static::clearCompiled();
}
/**
* Clear the cached Laravel bootstrapping files.
*
* @return void
*/
protected static function clearCompiled()
{
$laravel = new Application(getcwd());
if (file_exists($servicesPath = $laravel->getCachedServicesPath())) {
@unlink($servicesPath);
}
}
}

View File

@@ -0,0 +1,289 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Composer;
use Symfony\Component\Finder\Finder;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
class AppNameCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'app:name';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set the application namespace';
/**
* The Composer class instance.
*
* @var \Illuminate\Support\Composer
*/
protected $composer;
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Current root application namespace.
*
* @var string
*/
protected $currentRoot;
/**
* Create a new key generator command.
*
* @param \Illuminate\Support\Composer $composer
* @param \Illuminate\Filesystem\Filesystem $files
* @return void
*/
public function __construct(Composer $composer, Filesystem $files)
{
parent::__construct();
$this->files = $files;
$this->composer = $composer;
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$this->currentRoot = trim($this->laravel->getNamespace(), '\\');
$this->setAppDirectoryNamespace();
$this->setBootstrapNamespaces();
$this->setConfigNamespaces();
$this->setComposerNamespace();
$this->setDatabaseFactoryNamespaces();
$this->info('Application namespace set!');
$this->composer->dumpAutoloads();
$this->call('clear-compiled');
}
/**
* Set the namespace on the files in the app directory.
*
* @return void
*/
protected function setAppDirectoryNamespace()
{
$files = Finder::create()
->in($this->laravel['path'])
->contains($this->currentRoot)
->name('*.php');
foreach ($files as $file) {
$this->replaceNamespace($file->getRealPath());
}
}
/**
* Replace the App namespace at the given path.
*
* @param string $path
* @return void
*/
protected function replaceNamespace($path)
{
$search = [
'namespace '.$this->currentRoot.';',
$this->currentRoot.'\\',
];
$replace = [
'namespace '.$this->argument('name').';',
$this->argument('name').'\\',
];
$this->replaceIn($path, $search, $replace);
}
/**
* Set the bootstrap namespaces.
*
* @return void
*/
protected function setBootstrapNamespaces()
{
$search = [
$this->currentRoot.'\\Http',
$this->currentRoot.'\\Console',
$this->currentRoot.'\\Exceptions',
];
$replace = [
$this->argument('name').'\\Http',
$this->argument('name').'\\Console',
$this->argument('name').'\\Exceptions',
];
$this->replaceIn($this->getBootstrapPath(), $search, $replace);
}
/**
* Set the namespace in the appropriate configuration files.
*
* @return void
*/
protected function setConfigNamespaces()
{
$this->setAppConfigNamespaces();
$this->setAuthConfigNamespace();
$this->setServicesConfigNamespace();
}
/**
* Set the application provider namespaces.
*
* @return void
*/
protected function setAppConfigNamespaces()
{
$search = [
$this->currentRoot.'\\Providers',
$this->currentRoot.'\\Http\\Controllers\\',
];
$replace = [
$this->argument('name').'\\Providers',
$this->argument('name').'\\Http\\Controllers\\',
];
$this->replaceIn($this->getConfigPath('app'), $search, $replace);
}
/**
* Set the authentication User namespace.
*
* @return void
*/
protected function setAuthConfigNamespace()
{
$this->replaceIn(
$this->getConfigPath('auth'),
$this->currentRoot.'\\User',
$this->argument('name').'\\User'
);
}
/**
* Set the services User namespace.
*
* @return void
*/
protected function setServicesConfigNamespace()
{
$this->replaceIn(
$this->getConfigPath('services'),
$this->currentRoot.'\\User',
$this->argument('name').'\\User'
);
}
/**
* Set the PSR-4 namespace in the Composer file.
*
* @return void
*/
protected function setComposerNamespace()
{
$this->replaceIn(
$this->getComposerPath(),
str_replace('\\', '\\\\', $this->currentRoot).'\\\\',
str_replace('\\', '\\\\', $this->argument('name')).'\\\\'
);
}
/**
* Set the namespace in database factory files.
*
* @return void
*/
protected function setDatabaseFactoryNamespaces()
{
$this->replaceIn(
$this->laravel->databasePath().'/factories/ModelFactory.php',
$this->currentRoot, $this->argument('name')
);
}
/**
* Replace the given string in the given file.
*
* @param string $path
* @param string|array $search
* @param string|array $replace
* @return void
*/
protected function replaceIn($path, $search, $replace)
{
if ($this->files->exists($path)) {
$this->files->put($path, str_replace($search, $replace, $this->files->get($path)));
}
}
/**
* Get the path to the bootstrap/app.php file.
*
* @return string
*/
protected function getBootstrapPath()
{
return $this->laravel->bootstrapPath().'/app.php';
}
/**
* Get the path to the Composer.json file.
*
* @return string
*/
protected function getComposerPath()
{
return $this->laravel->basePath().'/composer.json';
}
/**
* Get the path to the given configuration file.
*
* @param string $name
* @return string
*/
protected function getConfigPath($name)
{
return $this->laravel['path.config'].'/'.$name.'.php';
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The desired namespace.'],
];
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
class ClearCompiledCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'clear-compiled';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Remove the compiled class file';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$servicesPath = $this->laravel->getCachedServicesPath();
if (file_exists($servicesPath)) {
@unlink($servicesPath);
}
$this->info('The compiled services file has been removed.');
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Illuminate\Foundation\Console;
use Closure;
use ReflectionFunction;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ClosureCommand extends Command
{
/**
* The command callback.
*
* @var \Closure
*/
protected $callback;
/**
* Create a new command instance.
*
* @param string $signature
* @param Closure $callback
* @return void
*/
public function __construct($signature, Closure $callback)
{
$this->callback = $callback;
$this->signature = $signature;
parent::__construct();
}
/**
* Execute the console command.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return mixed
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$inputs = array_merge($input->getArguments(), $input->getOptions());
$parameters = [];
foreach ((new ReflectionFunction($this->callback))->getParameters() as $parameter) {
if (isset($inputs[$parameter->name])) {
$parameters[$parameter->name] = $inputs[$parameter->name];
}
}
return $this->laravel->call(
$this->callback->bindTo($this, $this), $parameters
);
}
/**
* Set the description for the command.
*
* @param string $description
* @return $this
*/
public function describe($description)
{
$this->setDescription($description);
return $this;
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
class ConfigCacheCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'config:cache';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a cache file for faster configuration loading';
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new config cache 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 fire()
{
$this->call('config:clear');
$config = $this->getFreshConfiguration();
$this->files->put(
$this->laravel->getCachedConfigPath(), '<?php return '.var_export($config, true).';'.PHP_EOL
);
$this->info('Configuration cached successfully!');
}
/**
* Boot a fresh copy of the application configuration.
*
* @return array
*/
protected function getFreshConfiguration()
{
$app = require $this->laravel->bootstrapPath().'/app.php';
$app->make(ConsoleKernelContract::class)->bootstrap();
return $app['config']->all();
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
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 fire()
{
$this->files->delete($this->laravel->getCachedConfigPath());
$this->info('Configuration cache cleared!');
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class ConsoleMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:command';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Artisan command';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Console command';
/**
* Replace the class name for the given stub.
*
* @param string $stub
* @param string $name
* @return string
*/
protected function replaceClass($stub, $name)
{
$stub = parent::replaceClass($stub, $name);
return str_replace('dummy:command', $this->option('command'), $stub);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/console.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Console\Commands';
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the command.'],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['command', null, InputOption::VALUE_OPTIONAL, 'The terminal command that should be assigned.', 'command:name'],
];
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Illuminate\Foundation\Console;
use Carbon\Carbon;
use Illuminate\Console\Command;
class DownCommand extends Command
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'down {--message= : The message for the maintenance mode. }
{--retry= : The number of seconds after which the request may be retried.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Put the application into maintenance mode';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
file_put_contents(
$this->laravel->storagePath().'/framework/down',
json_encode($this->getDownFilePayload(), JSON_PRETTY_PRINT)
);
$this->comment('Application is now in maintenance mode.');
}
/**
* Get the payload to be placed in the "down" file.
*
* @return array
*/
protected function getDownFilePayload()
{
return [
'time' => Carbon::now()->getTimestamp(),
'message' => $this->option('message'),
'retry' => $this->getRetryTime(),
];
}
/**
* Get the number of seconds the client should wait before retrying their request.
*
* @return int|null
*/
protected function getRetryTime()
{
$retry = $this->option('retry');
return is_numeric($retry) && $retry > 0 ? (int) $retry : null;
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
class EnvironmentCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'env';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Display the current framework environment';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$this->line('<info>Current application environment:</info> <comment>'.$this->laravel['env'].'</comment>');
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Illuminate\Foundation\Support\Providers\EventServiceProvider;
class EventGenerateCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'event:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate the missing events and listeners based on registration';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$provider = $this->laravel->getProvider(EventServiceProvider::class);
foreach ($provider->listens() as $event => $listeners) {
$this->makeEventAndListeners($event, $listeners);
}
$this->info('Events and listeners generated successfully!');
}
/**
* Make the event and listeners for the given event.
*
* @param string $event
* @param array $listeners
* @return void
*/
protected function makeEventAndListeners($event, $listeners)
{
if (! Str::contains($event, '\\')) {
return;
}
$this->callSilent('make:event', ['name' => $event]);
$this->makeListeners($event, $listeners);
}
/**
* Make the listeners for the given event.
*
* @param string $event
* @param array $listeners
* @return void
*/
protected function makeListeners($event, $listeners)
{
foreach ($listeners as $listener) {
$listener = preg_replace('/@.+$/', '', $listener);
$this->callSilent('make:listener', ['name' => $listener, '--event' => $event]);
}
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
class EventMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:event';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new event class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Event';
/**
* Determine if the class already exists.
*
* @param string $rawName
* @return bool
*/
protected function alreadyExists($rawName)
{
return class_exists($rawName);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/event.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Events';
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class JobMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:job';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new job class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Job';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->option('sync')
? __DIR__.'/stubs/job.stub'
: __DIR__.'/stubs/job-queued.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Jobs';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['sync', null, InputOption::VALUE_NONE, 'Indicates that job should be synchronous.'],
];
}
}

View File

@@ -0,0 +1,334 @@
<?php
namespace Illuminate\Foundation\Console;
use Closure;
use Exception;
use Throwable;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Console\Application as Artisan;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Console\Kernel as KernelContract;
use Symfony\Component\Debug\Exception\FatalThrowableError;
class Kernel implements KernelContract
{
/**
* The application implementation.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* The event dispatcher implementation.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected $events;
/**
* The Artisan application instance.
*
* @var \Illuminate\Console\Application
*/
protected $artisan;
/**
* The Artisan commands provided by the application.
*
* @var array
*/
protected $commands = [];
/**
* Indicates if the Closure commands have been loaded.
*
* @var bool
*/
protected $commandsLoaded = false;
/**
* The bootstrap classes for the application.
*
* @var array
*/
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\SetRequestForConsole::class,
\Illuminate\Foundation\Bootstrap\RegisterProviders::class,
\Illuminate\Foundation\Bootstrap\BootProviders::class,
];
/**
* Create a new console kernel instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function __construct(Application $app, Dispatcher $events)
{
if (! defined('ARTISAN_BINARY')) {
define('ARTISAN_BINARY', 'artisan');
}
$this->app = $app;
$this->events = $events;
$this->app->booted(function () {
$this->defineConsoleSchedule();
});
}
/**
* Define the application's command schedule.
*
* @return void
*/
protected function defineConsoleSchedule()
{
$this->app->instance(
Schedule::class, $schedule = new Schedule($this->app[Cache::class])
);
$this->schedule($schedule);
}
/**
* Run the console application.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return int
*/
public function handle($input, $output = null)
{
try {
$this->bootstrap();
if (! $this->commandsLoaded) {
$this->commands();
$this->commandsLoaded = true;
}
return $this->getArtisan()->run($input, $output);
} catch (Exception $e) {
$this->reportException($e);
$this->renderException($output, $e);
return 1;
} catch (Throwable $e) {
$e = new FatalThrowableError($e);
$this->reportException($e);
$this->renderException($output, $e);
return 1;
}
}
/**
* Terminate the application.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param int $status
* @return void
*/
public function terminate($input, $status)
{
$this->app->terminate();
}
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
//
}
/**
* Register a Closure based command with the application.
*
* @param string $signature
* @param Closure $callback
* @return \Illuminate\Foundation\Console\ClosureCommand
*/
public function command($signature, Closure $callback)
{
$command = new ClosureCommand($signature, $callback);
Artisan::starting(function ($artisan) use ($command) {
$artisan->add($command);
});
return $command;
}
/**
* Register the given command with the console application.
*
* @param \Symfony\Component\Console\Command\Command $command
* @return void
*/
public function registerCommand($command)
{
$this->getArtisan()->add($command);
}
/**
* Run an Artisan console command by name.
*
* @param string $command
* @param array $parameters
* @param \Symfony\Component\Console\Output\OutputInterface $outputBuffer
* @return int
*/
public function call($command, array $parameters = [], $outputBuffer = null)
{
$this->bootstrap();
if (! $this->commandsLoaded) {
$this->commands();
$this->commandsLoaded = true;
}
return $this->getArtisan()->call($command, $parameters, $outputBuffer);
}
/**
* Queue the given console command.
*
* @param string $command
* @param array $parameters
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public function queue($command, array $parameters = [])
{
return QueuedCommand::dispatch(func_get_args());
}
/**
* Get all of the commands registered with the console.
*
* @return array
*/
public function all()
{
$this->bootstrap();
return $this->getArtisan()->all();
}
/**
* Get the output for the last run command.
*
* @return string
*/
public function output()
{
$this->bootstrap();
return $this->getArtisan()->output();
}
/**
* Bootstrap the application for artisan commands.
*
* @return void
*/
public function bootstrap()
{
if (! $this->app->hasBeenBootstrapped()) {
$this->app->bootstrapWith($this->bootstrappers());
}
// If we are calling an arbitrary command from within the application, we'll load
// all of the available deferred providers which will make all of the commands
// available to an application. Otherwise the command will not be available.
$this->app->loadDeferredProviders();
}
/**
* Get the Artisan application instance.
*
* @return \Illuminate\Console\Application
*/
protected function getArtisan()
{
if (is_null($this->artisan)) {
return $this->artisan = (new Artisan($this->app, $this->events, $this->app->version()))
->resolveCommands($this->commands);
}
return $this->artisan;
}
/**
* Set the Artisan application instance.
*
* @param \Illuminate\Console\Application $artisan
* @return void
*/
public function setArtisan($artisan)
{
$this->artisan = $artisan;
}
/**
* Get the bootstrap classes for the application.
*
* @return array
*/
protected function bootstrappers()
{
return $this->bootstrappers;
}
/**
* Report the exception to the exception handler.
*
* @param \Exception $e
* @return void
*/
protected function reportException(Exception $e)
{
$this->app[ExceptionHandler::class]->report($e);
}
/**
* Report the exception to the exception handler.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $e
* @return void
*/
protected function renderException($output, Exception $e)
{
$this->app[ExceptionHandler::class]->renderForConsole($output, $e);
}
}

View File

@@ -0,0 +1,110 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class KeyGenerateCommand extends Command
{
use ConfirmableTrait;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'key:generate
{--show : Display the key instead of modifying files}
{--force : Force the operation to run when in production}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set the application key';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->generateRandomKey();
if ($this->option('show')) {
return $this->line('<comment>'.$key.'</comment>');
}
// Next, we will replace the application key in the environment file so it is
// automatically setup for this developer. This key gets generated using a
// secure random byte generator and is later base64 encoded for storage.
if (! $this->setKeyInEnvironmentFile($key)) {
return;
}
$this->laravel['config']['app.key'] = $key;
$this->info("Application key [$key] set successfully.");
}
/**
* Generate a random key for the application.
*
* @return string
*/
protected function generateRandomKey()
{
return 'base64:'.base64_encode(random_bytes(
$this->laravel['config']['app.cipher'] == 'AES-128-CBC' ? 16 : 32
));
}
/**
* Set the application key in the environment file.
*
* @param string $key
* @return bool
*/
protected function setKeyInEnvironmentFile($key)
{
$currentKey = $this->laravel['config']['app.key'];
if (strlen($currentKey) !== 0 && (! $this->confirmToProceed())) {
return false;
}
$this->writeNewEnvironmentFileWith($key);
return true;
}
/**
* Write a new environment file with the given key.
*
* @param string $key
* @return void
*/
protected function writeNewEnvironmentFileWith($key)
{
file_put_contents($this->laravel->environmentFilePath(), preg_replace(
$this->keyReplacementPattern(),
'APP_KEY='.$key,
file_get_contents($this->laravel->environmentFilePath())
));
}
/**
* Get a regex pattern that will match env APP_KEY with any random key.
*
* @return string
*/
protected function keyReplacementPattern()
{
$escaped = preg_quote('='.$this->laravel['config']['app.key'], '/');
return "/^APP_KEY{$escaped}/m";
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Support\Str;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class ListenerMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:listener';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new event listener class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Listener';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
if (! $this->option('event')) {
return $this->error('Missing required option: --event');
}
parent::fire();
}
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
$event = $this->option('event');
if (! Str::startsWith($event, $this->laravel->getNamespace()) &&
! Str::startsWith($event, 'Illuminate')) {
$event = $this->laravel->getNamespace().'Events\\'.$event;
}
$stub = str_replace(
'DummyEvent', class_basename($event), parent::buildClass($name)
);
return str_replace(
'DummyFullEvent', $event, $stub
);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('queued')) {
return __DIR__.'/stubs/listener-queued.stub';
} else {
return __DIR__.'/stubs/listener.stub';
}
}
/**
* Determine if the class already exists.
*
* @param string $rawName
* @return bool
*/
protected function alreadyExists($rawName)
{
return class_exists($rawName);
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Listeners';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['event', 'e', InputOption::VALUE_REQUIRED, 'The event class being listened for.'],
['queued', null, InputOption::VALUE_NONE, 'Indicates the event listener should be queued.'],
];
}
}

View File

@@ -0,0 +1,116 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class MailMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:mail';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new email class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Mail';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
if (parent::fire() === false && ! $this->option('force')) {
return;
}
if ($this->option('markdown')) {
$this->writeMarkdownTemplate();
}
}
/**
* Write the Markdown template for the mailable.
*
* @return void
*/
protected function writeMarkdownTemplate()
{
$path = resource_path('views/'.str_replace('.', '/', $this->option('markdown'))).'.blade.php';
if (! $this->files->isDirectory(dirname($path))) {
$this->files->makeDirectory(dirname($path), 0755, true);
}
$this->files->put($path, file_get_contents(__DIR__.'/stubs/markdown.stub'));
}
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
$class = parent::buildClass($name);
if ($this->option('markdown')) {
$class = str_replace('DummyView', $this->option('markdown'), $class);
}
return $class;
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->option('markdown')
? __DIR__.'/stubs/markdown-mail.stub'
: __DIR__.'/stubs/mail.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Mail';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['force', 'f', InputOption::VALUE_NONE, 'Create the class even if the mailable already exists.'],
['markdown', 'm', InputOption::VALUE_OPTIONAL, 'Create a new Markdown template for the mailable.'],
];
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Support\Str;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class ModelMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Eloquent model class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Model';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
if (parent::fire() === false && ! $this->option('force')) {
return;
}
if ($this->option('migration')) {
$this->createMigration();
}
if ($this->option('controller') || $this->option('resource')) {
$this->createController();
}
}
/**
* Create a migration file for the model.
*
* @return void
*/
protected function createMigration()
{
$table = Str::plural(Str::snake(class_basename($this->argument('name'))));
$this->call('make:migration', [
'name' => "create_{$table}_table",
'--create' => $table,
]);
}
/**
* Create a controller for the model.
*
* @return void
*/
protected function createController()
{
$controller = Str::studly(class_basename($this->argument('name')));
$modelName = $this->qualifyClass($this->getNameInput());
$this->call('make:controller', [
'name' => "{$controller}Controller",
'--model' => $this->option('resource') ? $modelName : null,
]);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/model.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace;
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['force', 'f', InputOption::VALUE_NONE, 'Create the class even if the model already exists.'],
['migration', 'm', InputOption::VALUE_NONE, 'Create a new migration file for the model.'],
['controller', 'c', InputOption::VALUE_NONE, 'Create a new controller for the model.'],
['resource', 'r', InputOption::VALUE_NONE, 'Indicates if the generated controller should be a resource controller.'],
];
}
}

View File

@@ -0,0 +1,116 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class NotificationMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:notification';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new notification class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Notification';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
if (parent::fire() === false && ! $this->option('force')) {
return;
}
if ($this->option('markdown')) {
$this->writeMarkdownTemplate();
}
}
/**
* Write the Markdown template for the mailable.
*
* @return void
*/
protected function writeMarkdownTemplate()
{
$path = resource_path('views/'.str_replace('.', '/', $this->option('markdown'))).'.blade.php';
if (! $this->files->isDirectory(dirname($path))) {
$this->files->makeDirectory(dirname($path), 0755, true);
}
$this->files->put($path, file_get_contents(__DIR__.'/stubs/markdown.stub'));
}
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
$class = parent::buildClass($name);
if ($this->option('markdown')) {
$class = str_replace('DummyView', $this->option('markdown'), $class);
}
return $class;
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->option('markdown')
? __DIR__.'/stubs/markdown-notification.stub'
: __DIR__.'/stubs/notification.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Notifications';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['force', 'f', InputOption::VALUE_NONE, 'Create the class even if the notification already exists.'],
['markdown', 'm', InputOption::VALUE_OPTIONAL, 'Create a new Markdown template for the notification.'],
];
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Composer;
use Symfony\Component\Console\Input\InputOption;
class OptimizeCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'optimize';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Optimize the framework for better performance';
/**
* The composer instance.
*
* @var \Illuminate\Support\Composer
*/
protected $composer;
/**
* Create a new optimize command instance.
*
* @param \Illuminate\Support\Composer $composer
* @return void
*/
public function __construct(Composer $composer)
{
parent::__construct();
$this->composer = $composer;
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$this->info('Generating optimized class loader');
if ($this->option('psr')) {
$this->composer->dumpAutoloads();
} else {
$this->composer->dumpOptimized();
}
$this->call('clear-compiled');
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['force', null, InputOption::VALUE_NONE, 'Force the compiled class file to be written (deprecated).'],
['psr', null, InputOption::VALUE_NONE, 'Do not optimize Composer dump-autoload.'],
];
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Support\Str;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class PolicyMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:policy';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new policy class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Policy';
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
$stub = $this->replaceUserNamespace(
parent::buildClass($name)
);
$model = $this->option('model');
return $model ? $this->replaceModel($stub, $model) : $stub;
}
/**
* Replace the User model namespace.
*
* @param string $stub
* @return string
*/
protected function replaceUserNamespace($stub)
{
if (! config('auth.providers.users.model')) {
return $stub;
}
return str_replace(
$this->rootNamespace().'User',
config('auth.providers.users.model'),
$stub
);
}
/**
* Replace the model for the given stub.
*
* @param string $stub
* @param string $model
* @return string
*/
protected function replaceModel($stub, $model)
{
$model = str_replace('/', '\\', $model);
if (Str::startsWith($model, '\\')) {
$stub = str_replace('NamespacedDummyModel', trim($model, '\\'), $stub);
} else {
$stub = str_replace('NamespacedDummyModel', $this->laravel->getNamespace().$model, $stub);
}
$model = class_basename(trim($model, '\\'));
$stub = str_replace('DummyModel', $model, $stub);
$stub = str_replace('dummyModel', Str::camel($model), $stub);
return str_replace('dummyPluralModel', Str::plural(Str::camel($model)), $stub);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->option('model')
? __DIR__.'/stubs/policy.stub'
: __DIR__.'/stubs/policy.plain.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Policies';
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getOptions()
{
return [
['model', 'm', InputOption::VALUE_OPTIONAL, 'The model that the policy applies to.'],
];
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
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';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/provider.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Providers';
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Console\Kernel as KernelContract;
class QueuedCommand implements ShouldQueue
{
use Dispatchable, Queueable;
/**
* The data to pass to the Artisan command.
*
* @var array
*/
protected $data;
/**
* Create a new job instance.
*
* @param array $data
* @return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Handle the job.
*
* @param \Illuminate\Contracts\Console\Kernel $kernel
* @return void
*/
public function handle(KernelContract $kernel)
{
call_user_func_array([$kernel, 'call'], $this->data);
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
class RequestMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:request';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new form request class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Request';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/request.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Http\Requests';
}
}

View File

@@ -0,0 +1,109 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Routing\RouteCollection;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
class RouteCacheCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'route:cache';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a route cache file for faster route registration';
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new route 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 fire()
{
$this->call('route:clear');
$routes = $this->getFreshApplicationRoutes();
if (count($routes) == 0) {
return $this->error("Your application doesn't have any routes.");
}
foreach ($routes as $route) {
$route->prepareForSerialization();
}
$this->files->put(
$this->laravel->getCachedRoutesPath(), $this->buildRouteCacheFile($routes)
);
$this->info('Routes cached successfully!');
}
/**
* Boot a fresh copy of the application and get the routes.
*
* @return \Illuminate\Routing\RouteCollection
*/
protected function getFreshApplicationRoutes()
{
return tap($this->getFreshApplication()['router']->getRoutes(), function ($routes) {
$routes->refreshNameLookups();
$routes->refreshActionLookups();
});
}
/**
* Get a fresh application instance.
*
* @return \Illuminate\Foundation\Application
*/
protected function getFreshApplication()
{
return tap(require $this->laravel->bootstrapPath().'/app.php', function ($app) {
$app->make(ConsoleKernelContract::class)->bootstrap();
});
}
/**
* Build the route cache file.
*
* @param \Illuminate\Routing\RouteCollection $routes
* @return string
*/
protected function buildRouteCacheFile(RouteCollection $routes)
{
$stub = $this->files->get(__DIR__.'/stubs/routes.stub');
return str_replace('{{routes}}', base64_encode(serialize($routes)), $stub);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class RouteClearCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'route:clear';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Remove the route cache file';
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new route 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 fire()
{
$this->files->delete($this->laravel->getCachedRoutesPath());
$this->info('Route cache cleared!');
}
}

View File

@@ -0,0 +1,192 @@
<?php
namespace Illuminate\Foundation\Console;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class RouteListCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'route:list';
/**
* The console command description.
*
* @var string
*/
protected $description = 'List all registered routes';
/**
* The router instance.
*
* @var \Illuminate\Routing\Router
*/
protected $router;
/**
* An array of all the registered routes.
*
* @var \Illuminate\Routing\RouteCollection
*/
protected $routes;
/**
* The table headers for the command.
*
* @var array
*/
protected $headers = ['Domain', 'Method', 'URI', 'Name', 'Action', 'Middleware'];
/**
* Create a new route command instance.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function __construct(Router $router)
{
parent::__construct();
$this->router = $router;
$this->routes = $router->getRoutes();
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
if (count($this->routes) == 0) {
return $this->error("Your application doesn't have any routes.");
}
$this->displayRoutes($this->getRoutes());
}
/**
* Compile the routes into a displayable format.
*
* @return array
*/
protected function getRoutes()
{
$routes = collect($this->routes)->map(function ($route) {
return $this->getRouteInformation($route);
})->all();
if ($sort = $this->option('sort')) {
$routes = $this->sortRoutes($sort, $routes);
}
if ($this->option('reverse')) {
$routes = array_reverse($routes);
}
return array_filter($routes);
}
/**
* Get the route information for a given route.
*
* @param \Illuminate\Routing\Route $route
* @return array
*/
protected function getRouteInformation(Route $route)
{
return $this->filterRoute([
'host' => $route->domain(),
'method' => implode('|', $route->methods()),
'uri' => $route->uri(),
'name' => $route->getName(),
'action' => $route->getActionName(),
'middleware' => $this->getMiddleware($route),
]);
}
/**
* Sort the routes by a given element.
*
* @param string $sort
* @param array $routes
* @return array
*/
protected function sortRoutes($sort, $routes)
{
return Arr::sort($routes, function ($route) use ($sort) {
return $route[$sort];
});
}
/**
* Display the route information on the console.
*
* @param array $routes
* @return void
*/
protected function displayRoutes(array $routes)
{
$this->table($this->headers, $routes);
}
/**
* Get before filters.
*
* @param \Illuminate\Routing\Route $route
* @return string
*/
protected function getMiddleware($route)
{
return collect($route->gatherMiddleware())->map(function ($middleware) {
return $middleware instanceof Closure ? 'Closure' : $middleware;
})->implode(',');
}
/**
* Filter the route by URI and / or name.
*
* @param array $route
* @return array|null
*/
protected function filterRoute(array $route)
{
if (($this->option('name') && ! Str::contains($route['name'], $this->option('name'))) ||
$this->option('path') && ! Str::contains($route['uri'], $this->option('path')) ||
$this->option('method') && ! Str::contains($route['method'], $this->option('method'))) {
return;
}
return $route;
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['method', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by method.'],
['name', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by name.'],
['path', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by path.'],
['reverse', 'r', InputOption::VALUE_NONE, 'Reverse the ordering of the routes.'],
['sort', null, InputOption::VALUE_OPTIONAL, 'The column (host, method, uri, name, action, middleware) to sort by.', 'uri'],
];
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Symfony\Component\Process\ProcessUtils;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Process\PhpExecutableFinder;
class ServeCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'serve';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Serve the application on the PHP development server';
/**
* Execute the console command.
*
* @return void
*
* @throws \Exception
*/
public function fire()
{
chdir($this->laravel->publicPath());
$this->line("<info>Laravel development server started:</info> <http://{$this->host()}:{$this->port()}>");
passthru($this->serverCommand());
}
/**
* Get the full server command.
*
* @return string
*/
protected function serverCommand()
{
return sprintf('%s -S %s:%s %s/server.php',
ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)),
$this->host(),
$this->port(),
ProcessUtils::escapeArgument($this->laravel->basePath())
);
}
/**
* Get the host for the command.
*
* @return string
*/
protected function host()
{
return $this->input->getOption('host');
}
/**
* Get the port for the command.
*
* @return string
*/
protected function port()
{
return $this->input->getOption('port');
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '127.0.0.1'],
['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000],
];
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
class StorageLinkCommand extends Command
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'storage:link';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a symbolic link from "public/storage" to "storage/app/public"';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
if (file_exists(public_path('storage'))) {
return $this->error('The "public/storage" directory already exists.');
}
$this->laravel->make('files')->link(
storage_path('app/public'), public_path('storage')
);
$this->info('The [public/storage] directory has been linked.');
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
class TestMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'make:test {name : The name of the class} {--unit : Create a unit test}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new test class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Test';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('unit')) {
return __DIR__.'/stubs/unit-test.stub';
} else {
return __DIR__.'/stubs/test.stub';
}
}
/**
* Get the destination class path.
*
* @param string $name
* @return string
*/
protected function getPath($name)
{
$name = str_replace_first($this->rootNamespace(), '', $name);
return $this->laravel->basePath().'/tests'.str_replace('\\', '/', $name).'.php';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
if ($this->option('unit')) {
return $rootNamespace.'\Unit';
} else {
return $rootNamespace.'\Feature';
}
}
/**
* Get the root namespace for the class.
*
* @return string
*/
protected function rootNamespace()
{
return 'Tests';
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
class UpCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'up';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Bring the application out of maintenance mode';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
@unlink($this->laravel->storagePath().'/framework/down');
$this->info('Application is now live.');
}
}

View File

@@ -0,0 +1,189 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use League\Flysystem\MountManager;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem as Flysystem;
use League\Flysystem\Adapter\Local as LocalAdapter;
class VendorPublishCommand extends Command
{
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'vendor:publish {--force : Overwrite any existing files.}
{--provider= : The service provider that has assets you want to publish.}
{--tag=* : One or many tags that have assets you want to publish.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish any publishable assets from vendor packages';
/**
* Create a new 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 fire()
{
$tags = $this->option('tag') ?: [null];
foreach ((array) $tags as $tag) {
$this->publishTag($tag);
}
}
/**
* Publishes the assets for a tag.
*
* @param string $tag
* @return mixed
*/
protected function publishTag($tag)
{
foreach ($this->pathsToPublish($tag) as $from => $to) {
$this->publishItem($from, $to);
}
$this->info('Publishing complete.');
}
/**
* Get all of the paths to publish.
*
* @param string $tag
* @return array
*/
protected function pathsToPublish($tag)
{
return ServiceProvider::pathsToPublish(
$this->option('provider'), $tag
);
}
/**
* Publish the given item from and to the given location.
*
* @param string $from
* @param string $to
* @return void
*/
protected function publishItem($from, $to)
{
if ($this->files->isFile($from)) {
return $this->publishFile($from, $to);
} elseif ($this->files->isDirectory($from)) {
return $this->publishDirectory($from, $to);
}
$this->error("Can't locate path: <{$from}>");
}
/**
* Publish the file to the given path.
*
* @param string $from
* @param string $to
* @return void
*/
protected function publishFile($from, $to)
{
if (! $this->files->exists($to) || $this->option('force')) {
$this->createParentDirectory(dirname($to));
$this->files->copy($from, $to);
$this->status($from, $to, 'File');
}
}
/**
* Publish the directory to the given directory.
*
* @param string $from
* @param string $to
* @return void
*/
protected function publishDirectory($from, $to)
{
$this->moveManagedFiles(new MountManager([
'from' => new Flysystem(new LocalAdapter($from)),
'to' => new Flysystem(new LocalAdapter($to)),
]));
$this->status($from, $to, 'Directory');
}
/**
* Move all the files in the given MountManager.
*
* @param \League\Flysystem\MountManager $manager
* @return void
*/
protected function moveManagedFiles($manager)
{
foreach ($manager->listContents('from://', true) as $file) {
if ($file['type'] === 'file' && (! $manager->has('to://'.$file['path']) || $this->option('force'))) {
$manager->put('to://'.$file['path'], $manager->read('from://'.$file['path']));
}
}
}
/**
* Create the directory to house the published files if needed.
*
* @param string $directory
* @return void
*/
protected function createParentDirectory($directory)
{
if (! $this->files->isDirectory($directory)) {
$this->files->makeDirectory($directory, 0755, true);
}
}
/**
* Write a status message to the console.
*
* @param string $from
* @param string $to
* @param string $type
* @return void
*/
protected function status($from, $to, $type)
{
$from = str_replace(base_path(), '', realpath($from));
$to = str_replace(base_path(), '', realpath($to));
$this->line('<info>Copied '.$type.'</info> <comment>['.$from.']</comment> <info>To</info> <comment>['.$to.']</comment>');
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace Illuminate\Foundation\Console;
use RuntimeException;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class ViewClearCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'view:clear';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clear all compiled view files';
/**
* 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 fire()
{
$path = $this->laravel['config']['view.compiled'];
if (! $path) {
throw new RuntimeException('View path not found.');
}
foreach ($this->files->glob("{$path}/*") as $view) {
$this->files->delete($view);
}
$this->info('Compiled views cleared!');
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace DummyNamespace;
use Illuminate\Console\Command;
class DummyClass extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'dummy:command';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace DummyNamespace;
use DummyFullEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class DummyClass implements ShouldQueue
{
use InteractsWithQueue;
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param DummyEvent $event
* @return void
*/
public function handle(DummyEvent $event)
{
//
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace DummyNamespace;
use DummyFullEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class DummyClass
{
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param DummyEvent $event
* @return void
*/
public function handle(DummyEvent $event)
{
//
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace DummyNamespace;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class DummyClass
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace DummyNamespace;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class DummyClass implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace DummyNamespace;
use Illuminate\Bus\Queueable;
use Illuminate\Foundation\Bus\Dispatchable;
class DummyClass
{
use Dispatchable, Queueable;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace DummyNamespace;
use DummyFullEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class DummyClass implements ShouldQueue
{
use InteractsWithQueue;
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param DummyEvent $event
* @return void
*/
public function handle(DummyEvent $event)
{
//
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace DummyNamespace;
use DummyFullEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class DummyClass
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param DummyEvent $event
* @return void
*/
public function handle(DummyEvent $event)
{
//
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace DummyNamespace;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class DummyClass extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('view.name');
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace DummyNamespace;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class DummyClass extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('DummyView');
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace DummyNamespace;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class DummyClass extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)->markdown('DummyView');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}

View File

@@ -0,0 +1,12 @@
@component('mail::message')
# Introduction
The body of your message.
@component('mail::button', ['url' => ''])
Button Text
@endcomponent
Thanks,<br>
{{ config('app.name') }}
@endcomponent

View File

@@ -0,0 +1,10 @@
<?php
namespace DummyNamespace;
use Illuminate\Database\Eloquent\Model;
class DummyClass extends Model
{
//
}

View File

@@ -0,0 +1,61 @@
<?php
namespace DummyNamespace;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class DummyClass extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace DummyNamespace;
use DummyRootNamespaceUser;
use Illuminate\Auth\Access\HandlesAuthorization;
class DummyClass
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* @return void
*/
public function __construct()
{
//
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace DummyNamespace;
use DummyRootNamespaceUser;
use NamespacedDummyModel;
use Illuminate\Auth\Access\HandlesAuthorization;
class DummyClass
{
use HandlesAuthorization;
/**
* Determine whether the user can view the dummyModel.
*
* @param \DummyRootNamespaceUser $user
* @param \NamespacedDummyModel $dummyModel
* @return mixed
*/
public function view(User $user, DummyModel $dummyModel)
{
//
}
/**
* Determine whether the user can create dummyPluralModel.
*
* @param \DummyRootNamespaceUser $user
* @return mixed
*/
public function create(User $user)
{
//
}
/**
* Determine whether the user can update the dummyModel.
*
* @param \DummyRootNamespaceUser $user
* @param \NamespacedDummyModel $dummyModel
* @return mixed
*/
public function update(User $user, DummyModel $dummyModel)
{
//
}
/**
* Determine whether the user can delete the dummyModel.
*
* @param \DummyRootNamespaceUser $user
* @param \NamespacedDummyModel $dummyModel
* @return mixed
*/
public function delete(User $user, DummyModel $dummyModel)
{
//
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace DummyNamespace;
use Illuminate\Support\ServiceProvider;
class DummyClass extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace DummyNamespace;
use Illuminate\Foundation\Http\FormRequest;
class DummyClass extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}

View File

@@ -0,0 +1,16 @@
<?php
/*
|--------------------------------------------------------------------------
| Load The Cached Routes
|--------------------------------------------------------------------------
|
| Here we will decode and unserialize the RouteCollection instance that
| holds all of the route information for an application. This allows
| us to instantaneously load the entire route map into the router.
|
*/
app('router')->setRoutes(
unserialize(base64_decode('{{routes}}'))
);

View File

@@ -0,0 +1,21 @@
<?php
namespace DummyNamespace;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DummyClass extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace DummyNamespace;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DummyClass extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Illuminate\Foundation;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class EnvironmentDetector
{
/**
* Detect the application's current environment.
*
* @param \Closure $callback
* @param array|null $consoleArgs
* @return string
*/
public function detect(Closure $callback, $consoleArgs = null)
{
if ($consoleArgs) {
return $this->detectConsoleEnvironment($callback, $consoleArgs);
}
return $this->detectWebEnvironment($callback);
}
/**
* Set the application environment for a web request.
*
* @param \Closure $callback
* @return string
*/
protected function detectWebEnvironment(Closure $callback)
{
return call_user_func($callback);
}
/**
* Set the application environment from command-line arguments.
*
* @param \Closure $callback
* @param array $args
* @return string
*/
protected function detectConsoleEnvironment(Closure $callback, array $args)
{
// First we will check if an environment argument was passed via console arguments
// and if it was that automatically overrides as the environment. Otherwise, we
// will check the environment as a "web" request like a typical HTTP request.
if (! is_null($value = $this->getEnvironmentArgument($args))) {
return head(array_slice(explode('=', $value), 1));
}
return $this->detectWebEnvironment($callback);
}
/**
* Get the environment argument from the console.
*
* @param array $args
* @return string|null
*/
protected function getEnvironmentArgument(array $args)
{
return Arr::first($args, function ($value) {
return Str::startsWith($value, '--env');
});
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Illuminate\Foundation\Events;
trait Dispatchable
{
/**
* Dispatch the event with the given arguments.
*
* @return void
*/
public static function dispatch()
{
return event(new static(...func_get_args()));
}
/**
* Broadcast the event with the given arguments.
*
* @return \Illuminate\Broadcasting\PendingBroadcast
*/
public static function broadcast()
{
return broadcast(new static(...func_get_args()));
}
}

View File

@@ -0,0 +1,24 @@
<?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;
}
}

View File

@@ -0,0 +1,256 @@
<?php
namespace Illuminate\Foundation\Exceptions;
use Exception;
use Psr\Log\LoggerInterface;
use Illuminate\Http\Response;
use Illuminate\Http\RedirectResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Container\Container;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Symfony\Component\Debug\Exception\FlattenException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
use Illuminate\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract;
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirectResponse;
class Handler implements ExceptionHandlerContract
{
/**
* The container implementation.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [];
/**
* Create a new exception handler instance.
*
* @param \Illuminate\Contracts\Container\Container $container
* @return void
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Report or log an exception.
*
* @param \Exception $e
* @return void
*
* @throws \Exception
*/
public function report(Exception $e)
{
if ($this->shouldntReport($e)) {
return;
}
try {
$logger = $this->container->make(LoggerInterface::class);
} catch (Exception $ex) {
throw $e; // throw the original exception
}
$logger->error($e);
}
/**
* Determine if the exception should be reported.
*
* @param \Exception $e
* @return bool
*/
public function shouldReport(Exception $e)
{
return ! $this->shouldntReport($e);
}
/**
* Determine if the exception is in the "do not report" list.
*
* @param \Exception $e
* @return bool
*/
protected function shouldntReport(Exception $e)
{
$dontReport = array_merge($this->dontReport, [HttpResponseException::class]);
return ! is_null(collect($dontReport)->first(function ($type) use ($e) {
return $e instanceof $type;
}));
}
/**
* Render an exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Symfony\Component\HttpFoundation\Response
*/
public function render($request, Exception $e)
{
$e = $this->prepareException($e);
if ($e instanceof HttpResponseException) {
return $e->getResponse();
} elseif ($e instanceof AuthenticationException) {
return $this->unauthenticated($request, $e);
} elseif ($e instanceof ValidationException) {
return $this->convertValidationExceptionToResponse($e, $request);
}
return $this->prepareResponse($request, $e);
}
/**
* Prepare exception for rendering.
*
* @param \Exception $e
* @return \Exception
*/
protected function prepareException(Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
} elseif ($e instanceof AuthorizationException) {
$e = new HttpException(403, $e->getMessage());
}
return $e;
}
/**
* 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;
}
$errors = $e->validator->errors()->getMessages();
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()->withInput(
$request->input()
)->withErrors($errors);
}
/**
* Prepare response containing exception render.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function prepareResponse($request, Exception $e)
{
if ($this->isHttpException($e)) {
return $this->toIlluminateResponse($this->renderHttpException($e), $e);
} else {
return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
}
}
/**
* Render the given HttpException.
*
* @param \Symfony\Component\HttpKernel\Exception\HttpException $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function renderHttpException(HttpException $e)
{
$status = $e->getStatusCode();
view()->replaceNamespace('errors', [
resource_path('views/errors'),
__DIR__.'/views',
]);
if (view()->exists("errors::{$status}")) {
return response()->view("errors::{$status}", ['exception' => $e], $status, $e->getHeaders());
} else {
return $this->convertExceptionToResponse($e);
}
}
/**
* Create a Symfony response for the given exception.
*
* @param \Exception $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function convertExceptionToResponse(Exception $e)
{
$e = FlattenException::create($e);
$handler = new SymfonyExceptionHandler(config('app.debug', false));
return SymfonyResponse::create($handler->getHtml($e), $e->getStatusCode(), $e->getHeaders());
}
/**
* Map the given exception into an Illuminate response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
protected function toIlluminateResponse($response, Exception $e)
{
if ($response instanceof SymfonyRedirectResponse) {
$response = new RedirectResponse($response->getTargetUrl(), $response->getStatusCode(), $response->headers->all());
} else {
$response = new Response($response->getContent(), $response->getStatusCode(), $response->headers->all());
}
return $response->withException($e);
}
/**
* Render an exception to the console.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $e
* @return void
*/
public function renderForConsole($output, Exception $e)
{
(new ConsoleApplication)->renderException($e, $output);
}
/**
* Determine if the given exception is an HTTP exception.
*
* @param \Exception $e
* @return bool
*/
protected function isHttpException(Exception $e)
{
return $e instanceof HttpException;
}
}

View File

@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Service Unavailable</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Raleway', sans-serif;
font-weight: 100;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.content {
text-align: center;
}
.title {
font-size: 84px;
}
</style>
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title">
Be right back.
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,33 @@
<?php
namespace Illuminate\Foundation\Http\Events;
class RequestHandled
{
/**
* The request instance.
*
* @var \Illuminate\Http\Request
*/
public $request;
/**
* The response instance.
*
* @var \Illuminate\Http\Response
*/
public $response;
/**
* Create a new event instance.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Response $response
* @return void
*/
public function __construct($request, $response)
{
$this->request = $request;
$this->response = $response;
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Illuminate\Foundation\Http\Exceptions;
use Exception;
use Carbon\Carbon;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class MaintenanceModeException extends ServiceUnavailableHttpException
{
/**
* When the application was put in maintenance mode.
*
* @var \Carbon\Carbon
*/
public $wentDownAt;
/**
* The number of seconds to wait before retrying.
*
* @var int
*/
public $retryAfter;
/**
* When the application should next be available.
*
* @var \Carbon\Carbon
*/
public $willBeAvailableAt;
/**
* Create a new exception instance.
*
* @param int $time
* @param int $retryAfter
* @param string $message
* @param \Exception $previous
* @param int $code
* @return void
*/
public function __construct($time, $retryAfter = null, $message = null, Exception $previous = null, $code = 0)
{
parent::__construct($retryAfter, $message, $previous, $code);
$this->wentDownAt = Carbon::createFromTimestamp($time);
if ($retryAfter) {
$this->retryAfter = $retryAfter;
$this->willBeAvailableAt = Carbon::createFromTimestamp($time)->addSeconds($this->retryAfter);
}
}
}

View File

@@ -0,0 +1,249 @@
<?php
namespace Illuminate\Foundation\Http;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Validation\ValidatesWhenResolvedTrait;
use Illuminate\Contracts\Validation\ValidatesWhenResolved;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
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';
/**
* The input keys that should not be flashed on redirect.
*
* @var array
*/
protected $dontFlash = ['password', 'password_confirmation'];
/**
* Get the validator instance for the request.
*
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function getValidatorInstance()
{
$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);
}
return $validator;
}
/**
* Create the default validator instance.
*
* @param \Illuminate\Contracts\Validation\Factory $factory
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function createDefaultValidator(ValidationFactory $factory)
{
return $factory->make(
$this->validationData(), $this->container->call([$this, 'rules']),
$this->messages(), $this->attributes()
);
}
/**
* Get data to be validated from the request.
*
* @return array
*/
protected function validationData()
{
return $this->all();
}
/**
* Handle a failed validation attempt.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function failedValidation(Validator $validator)
{
throw new ValidationException($validator, $this->response(
$this->formatErrors($validator)
));
}
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
if ($this->expectsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
/**
* Format the errors from the given Validator instance.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return array
*/
protected function formatErrors(Validator $validator)
{
return $validator->getMessageBag()->toArray();
}
/**
* 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
*/
protected function passesAuthorization()
{
if (method_exists($this, 'authorize')) {
return $this->container->call([$this, 'authorize']);
}
return false;
}
/**
* Handle a failed authorization attempt.
*
* @return void
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function failedAuthorization()
{
throw new AuthorizationException('This action is unauthorized.');
}
/**
* 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 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;
}
}

View File

@@ -0,0 +1,338 @@
<?php
namespace Illuminate\Foundation\Http;
use Exception;
use Throwable;
use Illuminate\Routing\Router;
use Illuminate\Routing\Pipeline;
use Illuminate\Support\Facades\Facade;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Http\Kernel as KernelContract;
use Symfony\Component\Debug\Exception\FatalThrowableError;
class Kernel implements KernelContract
{
/**
* 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 array
*/
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
*/
protected $middleware = [];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [];
/**
* The priority-sorted list of middleware.
*
* Forces the listed middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::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;
$router->middlewarePriority = $this->middlewarePriority;
foreach ($this->middlewareGroups as $key => $middleware) {
$router->middlewareGroup($key, $middleware);
}
foreach ($this->routeMiddleware as $key => $middleware) {
$router->aliasMiddleware($key, $middleware);
}
}
/**
* Handle an incoming HTTP request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function handle($request)
{
try {
$request->enableHttpMethodParameterOverride();
$response = $this->sendRequestThroughRouter($request);
} catch (Exception $e) {
$this->reportException($e);
$response = $this->renderException($request, $e);
} catch (Throwable $e) {
$this->reportException($e = new FatalThrowableError($e));
$response = $this->renderException($request, $e);
}
$this->app['events']->dispatch(
new Events\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->terminateMiddleware($request, $response);
$this->app->terminate();
}
/**
* 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;
}
list($name, $parameters) = $this->parseMiddleware($middleware);
$instance = $this->app->make($name);
if (method_exists($instance, 'terminate')) {
$instance->terminate($request, $response);
}
}
}
/**
* 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)
{
list($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 beginning of the stack if it does not already exist.
*
* @param string $middleware
* @return $this
*/
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;
}
/**
* Get the bootstrap classes for the application.
*
* @return array
*/
protected function bootstrappers()
{
return $this->bootstrappers;
}
/**
* Report the exception to the exception handler.
*
* @param \Exception $e
* @return void
*/
protected function reportException(Exception $e)
{
$this->app[ExceptionHandler::class]->report($e);
}
/**
* Render the exception to a response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function renderException($request, Exception $e)
{
return $this->app[ExceptionHandler::class]->render($request, $e);
}
/**
* Get the Laravel application instance.
*
* @return \Illuminate\Contracts\Foundation\Application
*/
public function getApplication()
{
return $this->app;
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Illuminate\Foundation\Http\Middleware;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
class CheckForMaintenanceMode
{
/**
* The application implementation.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function handle($request, Closure $next)
{
if ($this->app->isDownForMaintenance()) {
$data = json_decode(file_get_contents($this->app->storagePath().'/framework/down'), true);
throw new MaintenanceModeException($data['time'], $data['retry'], $data['message']);
}
return $next($request);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Illuminate\Foundation\Http\Middleware;
class ConvertEmptyStringsToNull extends TransformsRequest
{
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return is_string($value) && $value === '' ? null : $value;
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Illuminate\Foundation\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\ParameterBag;
class TransformsRequest
{
/**
* The additional attributes passed to the middleware.
*
* @var array
*/
protected $attributes = [];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, ...$attributes)
{
$this->attributes = $attributes;
$this->clean($request);
return $next($request);
}
/**
* Clean the request's data.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function clean($request)
{
$this->cleanParameterBag($request->query);
if ($request->isJson()) {
$this->cleanParameterBag($request->json());
} else {
$this->cleanParameterBag($request->request);
}
}
/**
* Clean the data in the parameter bag.
*
* @param \Symfony\Component\HttpFoundation\ParameterBag $bag
* @return void
*/
protected function cleanParameterBag(ParameterBag $bag)
{
$bag->replace($this->cleanArray($bag->all()));
}
/**
* Clean the data in the given array.
*
* @param array $data
* @return array
*/
protected function cleanArray(array $data)
{
return collect($data)->map(function ($value, $key) {
return $this->cleanValue($key, $value);
})->all();
}
/**
* Clean the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function cleanValue($key, $value)
{
if (is_array($value)) {
return $this->cleanArray($value);
}
return $this->transform($key, $value);
}
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return $value;
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace Illuminate\Foundation\Http\Middleware;
class TrimStrings extends TransformsRequest
{
/**
* The attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
//
];
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
if (in_array($key, $this->except, true)) {
return $value;
}
return is_string($value) ? trim($value) : $value;
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Illuminate\Foundation\Http\Middleware;
use Closure;
use Illuminate\Http\Exceptions\PostTooLargeException;
class ValidatePostSize
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Illuminate\Http\Exceptions\PostTooLargeException
*/
public function handle($request, Closure $next)
{
$max = $this->getPostMaxSize();
if ($max > 0 && $request->server('CONTENT_LENGTH') > $max) {
throw new PostTooLargeException;
}
return $next($request);
}
/**
* Determine the server 'post_max_size' as bytes.
*
* @return int
*/
protected function getPostMaxSize()
{
if (is_numeric($postMaxSize = ini_get('post_max_size'))) {
return (int) $postMaxSize;
}
$metric = strtoupper(substr($postMaxSize, -1));
switch ($metric) {
case 'K':
return (int) $postMaxSize * 1024;
case 'M':
return (int) $postMaxSize * 1048576;
case 'G':
return (int) $postMaxSize * 1073741824;
default:
return (int) $postMaxSize;
}
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace Illuminate\Foundation\Http\Middleware;
use Closure;
use Carbon\Carbon;
use Illuminate\Foundation\Application;
use Symfony\Component\HttpFoundation\Cookie;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Session\TokenMismatchException;
class VerifyCsrfToken
{
/**
* The application instance.
*
* @var \Illuminate\Foundation\Application
*/
protected $app;
/**
* The encrypter implementation.
*
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
protected $encrypter;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [];
/**
* Create a new middleware instance.
*
* @param \Illuminate\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 $this->addCookieToResponse($request, $next($request));
}
throw new TokenMismatchException;
}
/**
* 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();
}
/**
* Determine if the request has a URI that should pass through CSRF verification.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function inExceptArray($request)
{
foreach ($this->except as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}
if ($request->is($except)) {
return true;
}
}
return false;
}
/**
* 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
*/
protected function getTokenFromRequest($request)
{
$token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
$token = $this->encrypter->decrypt($header);
}
return $token;
}
/**
* 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');
$response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), Carbon::now()->getTimestamp() + 60 * $config['lifetime'],
$config['path'], $config['domain'], $config['secure'], false
)
);
return $response;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Illuminate\Foundation;
use Illuminate\Support\Collection;
class Inspiring
{
/**
* Get an inspiring quote.
*
* Taylor & Dayle made this commit from Jungfraujoch. (11,333 ft.)
*
* May McGinnis always control the board. #LaraconUS2015
*
* @return string
*/
public static function quote()
{
return Collection::make([
'When there is no desire, all things are at peace. - Laozi',
'Simplicity is the ultimate sophistication. - Leonardo da Vinci',
'Simplicity is the essence of happiness. - Cedric Bledsoe',
'Smile, breathe, and go slowly. - Thich Nhat Hanh',
'Simplicity is an acquired taste. - Katharine Gerould',
'Well begun is half done. - Aristotle',
'He who is contented is rich. - Laozi',
'Very little is needed to make a happy life. - Marcus Antoninus',
'It is quality rather than quantity that matters. - Lucius Annaeus Seneca',
'Genius is one percent inspiration and ninety-nine percent perspiration. - Thomas Edison',
'Computer science is no more about computers than astronomy is about telescopes. - Edsger Dijkstra',
])->random();
}
}

View File

@@ -0,0 +1,210 @@
<?php
namespace Illuminate\Foundation;
use Exception;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Contracts\Foundation\Application as ApplicationContract;
class ProviderRepository
{
/**
* The application implementation.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* The path to the manifest file.
*
* @var string
*/
protected $manifestPath;
/**
* Create a new service repository instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Filesystem\Filesystem $files
* @param string $manifestPath
* @return void
*/
public function __construct(ApplicationContract $app, Filesystem $files, $manifestPath)
{
$this->app = $app;
$this->files = $files;
$this->manifestPath = $manifestPath;
}
/**
* Register the application service providers.
*
* @param array $providers
* @return void
*/
public function load(array $providers)
{
$manifest = $this->loadManifest();
// First we will load the service manifest, which contains information on all
// service providers registered with the application and which services it
// provides. This is used to know which services are "deferred" loaders.
if ($this->shouldRecompile($manifest, $providers)) {
$manifest = $this->compileManifest($providers);
}
// Next, we will register events to load the providers for each of the events
// that it has requested. This allows the service provider to defer itself
// while still getting automatically loaded when a certain event occurs.
foreach ($manifest['when'] as $provider => $events) {
$this->registerLoadEvents($provider, $events);
}
// We will go ahead and register all of the eagerly loaded providers with the
// application so their services can be registered with the application as
// a provided service. Then we will set the deferred service list on it.
foreach ($manifest['eager'] as $provider) {
$this->app->register($provider);
}
$this->app->addDeferredServices($manifest['deferred']);
}
/**
* Load the service provider manifest JSON file.
*
* @return array|null
*/
public function loadManifest()
{
// The service manifest is a file containing a JSON representation of every
// service provided by the application and whether its provider is using
// deferred loading or should be eagerly loaded on each request to us.
if ($this->files->exists($this->manifestPath)) {
$manifest = $this->files->getRequire($this->manifestPath);
if ($manifest) {
return array_merge(['when' => []], $manifest);
}
}
}
/**
* Determine if the manifest should be compiled.
*
* @param array $manifest
* @param array $providers
* @return bool
*/
public function shouldRecompile($manifest, $providers)
{
return is_null($manifest) || $manifest['providers'] != $providers;
}
/**
* Register the load events for the given provider.
*
* @param string $provider
* @param array $events
* @return void
*/
protected function registerLoadEvents($provider, array $events)
{
if (count($events) < 1) {
return;
}
$this->app->make('events')->listen($events, function () use ($provider) {
$this->app->register($provider);
});
}
/**
* Compile the application service manifest file.
*
* @param array $providers
* @return array
*/
protected function compileManifest($providers)
{
// The service manifest should contain a list of all of the providers for
// the application so we can compare it on each request to the service
// and determine if the manifest should be recompiled or is current.
$manifest = $this->freshManifest($providers);
foreach ($providers as $provider) {
$instance = $this->createProvider($provider);
// When recompiling the service manifest, we will spin through each of the
// providers and check if it's a deferred provider or not. If so we'll
// add it's provided services to the manifest and note the provider.
if ($instance->isDeferred()) {
foreach ($instance->provides() as $service) {
$manifest['deferred'][$service] = $provider;
}
$manifest['when'][$provider] = $instance->when();
}
// If the service providers are not deferred, we will simply add it to an
// array of eagerly loaded providers that will get registered on every
// request to this application instead of "lazy" loading every time.
else {
$manifest['eager'][] = $provider;
}
}
return $this->writeManifest($manifest);
}
/**
* Create a fresh service manifest data structure.
*
* @param array $providers
* @return array
*/
protected function freshManifest(array $providers)
{
return ['providers' => $providers, 'eager' => [], 'deferred' => []];
}
/**
* Write the service manifest file to disk.
*
* @param array $manifest
* @return array
*
* @throws \Exception
*/
public function writeManifest($manifest)
{
if (! is_writable(dirname($this->manifestPath))) {
throw new Exception('The bootstrap/cache directory must be present and writable.');
}
$this->files->put(
$this->manifestPath, '<?php return '.var_export($manifest, true).';'
);
return array_merge(['when' => []], $manifest);
}
/**
* Create a new provider instance.
*
* @param string $provider
* @return \Illuminate\Support\ServiceProvider
*/
public function createProvider($provider)
{
return new $provider($this->app);
}
}

View File

@@ -0,0 +1,869 @@
<?php
namespace Illuminate\Foundation\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Queue\Console\TableCommand;
use Illuminate\Auth\Console\MakeAuthCommand;
use Illuminate\Foundation\Console\UpCommand;
use Illuminate\Foundation\Console\DownCommand;
use Illuminate\Auth\Console\ClearResetsCommand;
use Illuminate\Cache\Console\CacheTableCommand;
use Illuminate\Foundation\Console\ServeCommand;
use Illuminate\Queue\Console\FailedTableCommand;
use Illuminate\Foundation\Console\AppNameCommand;
use Illuminate\Foundation\Console\JobMakeCommand;
use Illuminate\Database\Console\Seeds\SeedCommand;
use Illuminate\Foundation\Console\MailMakeCommand;
use Illuminate\Foundation\Console\OptimizeCommand;
use Illuminate\Foundation\Console\TestMakeCommand;
use Illuminate\Foundation\Console\EventMakeCommand;
use Illuminate\Foundation\Console\ModelMakeCommand;
use Illuminate\Foundation\Console\RouteListCommand;
use Illuminate\Foundation\Console\ViewClearCommand;
use Illuminate\Session\Console\SessionTableCommand;
use Illuminate\Foundation\Console\PolicyMakeCommand;
use Illuminate\Foundation\Console\RouteCacheCommand;
use Illuminate\Foundation\Console\RouteClearCommand;
use Illuminate\Console\Scheduling\ScheduleRunCommand;
use Illuminate\Foundation\Console\ConfigCacheCommand;
use Illuminate\Foundation\Console\ConfigClearCommand;
use Illuminate\Foundation\Console\ConsoleMakeCommand;
use Illuminate\Foundation\Console\EnvironmentCommand;
use Illuminate\Foundation\Console\KeyGenerateCommand;
use Illuminate\Foundation\Console\RequestMakeCommand;
use Illuminate\Foundation\Console\StorageLinkCommand;
use Illuminate\Routing\Console\ControllerMakeCommand;
use Illuminate\Routing\Console\MiddlewareMakeCommand;
use Illuminate\Foundation\Console\ListenerMakeCommand;
use Illuminate\Foundation\Console\ProviderMakeCommand;
use Illuminate\Foundation\Console\ClearCompiledCommand;
use Illuminate\Foundation\Console\EventGenerateCommand;
use Illuminate\Foundation\Console\VendorPublishCommand;
use Illuminate\Console\Scheduling\ScheduleFinishCommand;
use Illuminate\Database\Console\Seeds\SeederMakeCommand;
use Illuminate\Database\Console\Migrations\MigrateCommand;
use Illuminate\Foundation\Console\NotificationMakeCommand;
use Illuminate\Queue\Console\WorkCommand as QueueWorkCommand;
use Illuminate\Database\Console\Migrations\MigrateMakeCommand;
use Illuminate\Notifications\Console\NotificationTableCommand;
use Illuminate\Cache\Console\ClearCommand as CacheClearCommand;
use Illuminate\Queue\Console\RetryCommand as QueueRetryCommand;
use Illuminate\Cache\Console\ForgetCommand as CacheForgetCommand;
use Illuminate\Queue\Console\ListenCommand as QueueListenCommand;
use Illuminate\Queue\Console\RestartCommand as QueueRestartCommand;
use Illuminate\Queue\Console\ListFailedCommand as ListFailedQueueCommand;
use Illuminate\Queue\Console\FlushFailedCommand as FlushFailedQueueCommand;
use Illuminate\Queue\Console\ForgetFailedCommand as ForgetFailedQueueCommand;
use Illuminate\Database\Console\Migrations\ResetCommand as MigrateResetCommand;
use Illuminate\Database\Console\Migrations\StatusCommand as MigrateStatusCommand;
use Illuminate\Database\Console\Migrations\InstallCommand as MigrateInstallCommand;
use Illuminate\Database\Console\Migrations\RefreshCommand as MigrateRefreshCommand;
use Illuminate\Database\Console\Migrations\RollbackCommand as MigrateRollbackCommand;
class ArtisanServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* The commands to be registered.
*
* @var array
*/
protected $commands = [
'CacheClear' => 'command.cache.clear',
'CacheForget' => 'command.cache.forget',
'ClearCompiled' => 'command.clear-compiled',
'ClearResets' => 'command.auth.resets.clear',
'ConfigCache' => 'command.config.cache',
'ConfigClear' => 'command.config.clear',
'Down' => 'command.down',
'Environment' => 'command.environment',
'KeyGenerate' => 'command.key.generate',
'Migrate' => 'command.migrate',
'MigrateInstall' => 'command.migrate.install',
'MigrateRefresh' => 'command.migrate.refresh',
'MigrateReset' => 'command.migrate.reset',
'MigrateRollback' => 'command.migrate.rollback',
'MigrateStatus' => 'command.migrate.status',
'Optimize' => 'command.optimize',
'QueueFailed' => 'command.queue.failed',
'QueueFlush' => 'command.queue.flush',
'QueueForget' => 'command.queue.forget',
'QueueListen' => 'command.queue.listen',
'QueueRestart' => 'command.queue.restart',
'QueueRetry' => 'command.queue.retry',
'QueueWork' => 'command.queue.work',
'RouteCache' => 'command.route.cache',
'RouteClear' => 'command.route.clear',
'RouteList' => 'command.route.list',
'Seed' => 'command.seed',
'ScheduleFinish' => ScheduleFinishCommand::class,
'ScheduleRun' => ScheduleRunCommand::class,
'StorageLink' => 'command.storage.link',
'Up' => 'command.up',
'ViewClear' => 'command.view.clear',
];
/**
* The commands to be registered.
*
* @var array
*/
protected $devCommands = [
'AppName' => 'command.app.name',
'AuthMake' => 'command.auth.make',
'CacheTable' => 'command.cache.table',
'ConsoleMake' => 'command.console.make',
'ControllerMake' => 'command.controller.make',
'EventGenerate' => 'command.event.generate',
'EventMake' => 'command.event.make',
'JobMake' => 'command.job.make',
'ListenerMake' => 'command.listener.make',
'MailMake' => 'command.mail.make',
'MiddlewareMake' => 'command.middleware.make',
'MigrateMake' => 'command.migrate.make',
'ModelMake' => 'command.model.make',
'NotificationMake' => 'command.notification.make',
'NotificationTable' => 'command.notification.table',
'PolicyMake' => 'command.policy.make',
'ProviderMake' => 'command.provider.make',
'QueueFailedTable' => 'command.queue.failed-table',
'QueueTable' => 'command.queue.table',
'RequestMake' => 'command.request.make',
'SeederMake' => 'command.seeder.make',
'SessionTable' => 'command.session.table',
'Serve' => 'command.serve',
'TestMake' => 'command.test.make',
'VendorPublish' => 'command.vendor.publish',
];
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerCommands(array_merge(
$this->commands, $this->devCommands
));
}
/**
* Register the given commands.
*
* @param array $commands
* @return void
*/
protected function registerCommands(array $commands)
{
foreach (array_keys($commands) as $command) {
call_user_func_array([$this, "register{$command}Command"], []);
}
$this->commands(array_values($commands));
}
/**
* Register the command.
*
* @return void
*/
protected function registerAppNameCommand()
{
$this->app->singleton('command.app.name', function ($app) {
return new AppNameCommand($app['composer'], $app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerAuthMakeCommand()
{
$this->app->singleton('command.auth.make', function ($app) {
return new MakeAuthCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerCacheClearCommand()
{
$this->app->singleton('command.cache.clear', function ($app) {
return new CacheClearCommand($app['cache']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerCacheForgetCommand()
{
$this->app->singleton('command.cache.forget', function ($app) {
return new CacheForgetCommand($app['cache']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerCacheTableCommand()
{
$this->app->singleton('command.cache.table', function ($app) {
return new CacheTableCommand($app['files'], $app['composer']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerClearCompiledCommand()
{
$this->app->singleton('command.clear-compiled', function () {
return new ClearCompiledCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerClearResetsCommand()
{
$this->app->singleton('command.auth.resets.clear', function () {
return new ClearResetsCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerConfigCacheCommand()
{
$this->app->singleton('command.config.cache', function ($app) {
return new ConfigCacheCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerConfigClearCommand()
{
$this->app->singleton('command.config.clear', function ($app) {
return new ConfigClearCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerConsoleMakeCommand()
{
$this->app->singleton('command.console.make', function ($app) {
return new ConsoleMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerControllerMakeCommand()
{
$this->app->singleton('command.controller.make', function ($app) {
return new ControllerMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerEventGenerateCommand()
{
$this->app->singleton('command.event.generate', function () {
return new EventGenerateCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerEventMakeCommand()
{
$this->app->singleton('command.event.make', function ($app) {
return new EventMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerDownCommand()
{
$this->app->singleton('command.down', function () {
return new DownCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerEnvironmentCommand()
{
$this->app->singleton('command.environment', function () {
return new EnvironmentCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerJobMakeCommand()
{
$this->app->singleton('command.job.make', function ($app) {
return new JobMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerKeyGenerateCommand()
{
$this->app->singleton('command.key.generate', function () {
return new KeyGenerateCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerListenerMakeCommand()
{
$this->app->singleton('command.listener.make', function ($app) {
return new ListenerMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMailMakeCommand()
{
$this->app->singleton('command.mail.make', function ($app) {
return new MailMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMiddlewareMakeCommand()
{
$this->app->singleton('command.middleware.make', function ($app) {
return new MiddlewareMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMigrateCommand()
{
$this->app->singleton('command.migrate', function ($app) {
return new MigrateCommand($app['migrator']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMigrateInstallCommand()
{
$this->app->singleton('command.migrate.install', function ($app) {
return new MigrateInstallCommand($app['migration.repository']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMigrateMakeCommand()
{
$this->app->singleton('command.migrate.make', function ($app) {
// Once we have the migration creator registered, we will create the command
// and inject the creator. The creator is responsible for the actual file
// creation of the migrations, and may be extended by these developers.
$creator = $app['migration.creator'];
$composer = $app['composer'];
return new MigrateMakeCommand($creator, $composer);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMigrateRefreshCommand()
{
$this->app->singleton('command.migrate.refresh', function () {
return new MigrateRefreshCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMigrateResetCommand()
{
$this->app->singleton('command.migrate.reset', function ($app) {
return new MigrateResetCommand($app['migrator']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMigrateRollbackCommand()
{
$this->app->singleton('command.migrate.rollback', function ($app) {
return new MigrateRollbackCommand($app['migrator']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerMigrateStatusCommand()
{
$this->app->singleton('command.migrate.status', function ($app) {
return new MigrateStatusCommand($app['migrator']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerModelMakeCommand()
{
$this->app->singleton('command.model.make', function ($app) {
return new ModelMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerNotificationMakeCommand()
{
$this->app->singleton('command.notification.make', function ($app) {
return new NotificationMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerOptimizeCommand()
{
$this->app->singleton('command.optimize', function ($app) {
return new OptimizeCommand($app['composer']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerProviderMakeCommand()
{
$this->app->singleton('command.provider.make', function ($app) {
return new ProviderMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueFailedCommand()
{
$this->app->singleton('command.queue.failed', function () {
return new ListFailedQueueCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueForgetCommand()
{
$this->app->singleton('command.queue.forget', function () {
return new ForgetFailedQueueCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueFlushCommand()
{
$this->app->singleton('command.queue.flush', function () {
return new FlushFailedQueueCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueListenCommand()
{
$this->app->singleton('command.queue.listen', function ($app) {
return new QueueListenCommand($app['queue.listener']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueRestartCommand()
{
$this->app->singleton('command.queue.restart', function () {
return new QueueRestartCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueRetryCommand()
{
$this->app->singleton('command.queue.retry', function () {
return new QueueRetryCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueWorkCommand()
{
$this->app->singleton('command.queue.work', function ($app) {
return new QueueWorkCommand($app['queue.worker']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueFailedTableCommand()
{
$this->app->singleton('command.queue.failed-table', function ($app) {
return new FailedTableCommand($app['files'], $app['composer']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerQueueTableCommand()
{
$this->app->singleton('command.queue.table', function ($app) {
return new TableCommand($app['files'], $app['composer']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerRequestMakeCommand()
{
$this->app->singleton('command.request.make', function ($app) {
return new RequestMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerSeederMakeCommand()
{
$this->app->singleton('command.seeder.make', function ($app) {
return new SeederMakeCommand($app['files'], $app['composer']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerSessionTableCommand()
{
$this->app->singleton('command.session.table', function ($app) {
return new SessionTableCommand($app['files'], $app['composer']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerStorageLinkCommand()
{
$this->app->singleton('command.storage.link', function () {
return new StorageLinkCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerRouteCacheCommand()
{
$this->app->singleton('command.route.cache', function ($app) {
return new RouteCacheCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerRouteClearCommand()
{
$this->app->singleton('command.route.clear', function ($app) {
return new RouteClearCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerRouteListCommand()
{
$this->app->singleton('command.route.list', function ($app) {
return new RouteListCommand($app['router']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerSeedCommand()
{
$this->app->singleton('command.seed', function ($app) {
return new SeedCommand($app['db']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerScheduleFinishCommand()
{
$this->app->singleton(ScheduleFinishCommand::class);
}
/**
* Register the command.
*
* @return void
*/
protected function registerScheduleRunCommand()
{
$this->app->singleton(ScheduleRunCommand::class);
}
/**
* Register the command.
*
* @return void
*/
protected function registerServeCommand()
{
$this->app->singleton('command.serve', function () {
return new ServeCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerTestMakeCommand()
{
$this->app->singleton('command.test.make', function ($app) {
return new TestMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerUpCommand()
{
$this->app->singleton('command.up', function () {
return new UpCommand;
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerVendorPublishCommand()
{
$this->app->singleton('command.vendor.publish', function ($app) {
return new VendorPublishCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerViewClearCommand()
{
$this->app->singleton('command.view.clear', function ($app) {
return new ViewClearCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerPolicyMakeCommand()
{
$this->app->singleton('command.policy.make', function ($app) {
return new PolicyMakeCommand($app['files']);
});
}
/**
* Register the command.
*
* @return void
*/
protected function registerNotificationTableCommand()
{
$this->app->singleton('command.notification.table', function ($app) {
return new NotificationTableCommand($app['files'], $app['composer']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array_merge(array_values($this->commands), array_values($this->devCommands));
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Illuminate\Foundation\Providers;
use Illuminate\Support\Composer;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('composer', function ($app) {
return new Composer($app['files'], $app->basePath());
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['composer'];
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Illuminate\Foundation\Providers;
use Illuminate\Support\AggregateServiceProvider;
use Illuminate\Database\MigrationServiceProvider;
class ConsoleSupportServiceProvider extends AggregateServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* The provider class names.
*
* @var array
*/
protected $providers = [
ArtisanServiceProvider::class,
MigrationServiceProvider::class,
ComposerServiceProvider::class,
];
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Illuminate\Foundation\Providers;
use Illuminate\Routing\Redirector;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\Http\FormRequest;
use Symfony\Component\HttpFoundation\Request;
use Illuminate\Contracts\Validation\ValidatesWhenResolved;
class FormRequestServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->app->afterResolving(ValidatesWhenResolved::class, function ($resolved) {
$resolved->validate();
});
$this->app->resolving(FormRequest::class, function ($request, $app) {
$this->initializeRequest($request, $app['request']);
$request->setContainer($app)->setRedirector($app->make(Redirector::class));
});
}
/**
* Initialize the form request with data from the given request.
*
* @param \Illuminate\Foundation\Http\FormRequest $form
* @param \Symfony\Component\HttpFoundation\Request $current
* @return void
*/
protected function initializeRequest(FormRequest $form, Request $current)
{
$files = $current->files->all();
$files = is_array($files) ? array_filter($files) : $files;
$form->initialize(
$current->query->all(), $current->request->all(), $current->attributes->all(),
$current->cookies->all(), $files, $current->server->all(), $current->getContent()
);
$form->setJson($current->json());
if ($session = $current->getSession()) {
$form->setLaravelSession($session);
}
$form->setUserResolver($current->getUserResolver());
$form->setRouteResolver($current->getRouteResolver());
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Illuminate\Foundation\Providers;
use Illuminate\Support\AggregateServiceProvider;
class FoundationServiceProvider extends AggregateServiceProvider
{
/**
* The provider class names.
*
* @var array
*/
protected $providers = [
FormRequestServiceProvider::class,
];
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Illuminate\Foundation\Support\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [];
/**
* Register the application's policies.
*
* @return void
*/
public function registerPolicies()
{
foreach ($this->policies as $key => $value) {
Gate::policy($key, $value);
}
}
/**
* {@inheritdoc}
*/
public function register()
{
//
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace Illuminate\Foundation\Support\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event handler mappings for the application.
*
* @var array
*/
protected $listen = [];
/**
* The subscriber classes to register.
*
* @var array
*/
protected $subscribe = [];
/**
* Register the application's event listeners.
*
* @return void
*/
public function boot()
{
foreach ($this->listens() as $event => $listeners) {
foreach ($listeners as $listener) {
Event::listen($event, $listener);
}
}
foreach ($this->subscribe as $subscriber) {
Event::subscribe($subscriber);
}
}
/**
* {@inheritdoc}
*/
public function register()
{
//
}
/**
* Get the events and handlers.
*
* @return array
*/
public function listens()
{
return $this->listen;
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Illuminate\Foundation\Support\Providers;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Routing\UrlGenerator;
class RouteServiceProvider extends ServiceProvider
{
/**
* The controller namespace for the application.
*
* @var string|null
*/
protected $namespace;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->setRootControllerNamespace();
if ($this->app->routesAreCached()) {
$this->loadCachedRoutes();
} else {
$this->loadRoutes();
$this->app->booted(function () {
$this->app['router']->getRoutes()->refreshNameLookups();
$this->app['router']->getRoutes()->refreshActionLookups();
});
}
}
/**
* Set the root controller namespace for the application.
*
* @return void
*/
protected function setRootControllerNamespace()
{
if (! is_null($this->namespace)) {
$this->app[UrlGenerator::class]->setRootControllerNamespace($this->namespace);
}
}
/**
* Load the cached routes for the application.
*
* @return void
*/
protected function loadCachedRoutes()
{
$this->app->booted(function () {
require $this->app->getCachedRoutesPath();
});
}
/**
* Load the application routes.
*
* @return void
*/
protected function loadRoutes()
{
if (method_exists($this, 'map')) {
$this->app->call([$this, 'map']);
}
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
/**
* Pass dynamic methods onto the router instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return call_user_func_array(
[$this->app->make(Router::class), $method], $parameters
);
}
}

View File

@@ -0,0 +1,145 @@
<?php
namespace Illuminate\Foundation\Testing\Concerns;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
trait InteractsWithAuthentication
{
/**
* Set the currently logged in user for the application.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string|null $driver
* @return $this
*/
public function actingAs(UserContract $user, $driver = null)
{
$this->be($user, $driver);
return $this;
}
/**
* Set the currently logged in user for the application.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string|null $driver
* @return void
*/
public function be(UserContract $user, $driver = null)
{
$this->app['auth']->guard($driver)->setUser($user);
$this->app['auth']->shouldUse($driver);
}
/**
* Assert that the user is authenticated.
*
* @param string|null $guard
* @return $this
*/
public function seeIsAuthenticated($guard = null)
{
$this->assertTrue($this->isAuthenticated($guard), 'The user is not authenticated');
return $this;
}
/**
* Assert that the user is not authenticated.
*
* @param string|null $guard
* @return $this
*/
public function dontSeeIsAuthenticated($guard = null)
{
$this->assertFalse($this->isAuthenticated($guard), 'The user is authenticated');
return $this;
}
/**
* Return true if the user is authenticated, false otherwise.
*
* @param string|null $guard
* @return bool
*/
protected function isAuthenticated($guard = null)
{
return $this->app->make('auth')->guard($guard)->check();
}
/**
* Assert that the user is authenticated as the given user.
*
* @param $user
* @param string|null $guard
* @return $this
*/
public function seeIsAuthenticatedAs($user, $guard = null)
{
$expected = $this->app->make('auth')->guard($guard)->user();
$this->assertInstanceOf(
get_class($expected), $user,
'The currently authenticated user is not who was expected'
);
$this->assertSame(
$expected->getAuthIdentifier(), $user->getAuthIdentifier(),
'The currently authenticated user is not who was expected'
);
return $this;
}
/**
* Assert that the given credentials are valid.
*
* @param array $credentials
* @param string|null $guard
* @return $this
*/
public function seeCredentials(array $credentials, $guard = null)
{
$this->assertTrue(
$this->hasCredentials($credentials, $guard), 'The given credentials are invalid.'
);
return $this;
}
/**
* Assert that the given credentials are invalid.
*
* @param array $credentials
* @param string|null $guard
* @return $this
*/
public function dontSeeCredentials(array $credentials, $guard = null)
{
$this->assertFalse(
$this->hasCredentials($credentials, $guard), 'The given credentials are valid.'
);
return $this;
}
/**
* Return true if the credentials are valid, false otherwise.
*
* @param array $credentials
* @param string|null $guard
* @return bool
*/
protected function hasCredentials(array $credentials, $guard = null)
{
$provider = $this->app->make('auth')->guard($guard)->getProvider();
$user = $provider->retrieveByCredentials($credentials);
return $user && $provider->validateCredentials($user, $credentials);
}
}

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